Skip to main content

premix_core/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![deny(missing_debug_implementations)]
3#![deny(missing_docs)]
4#![warn(rust_2018_idioms)]
5
6//! # Premix ORM Core
7//!
8//! Core definitions and traits for the Premix ORM ecosystem.
9//! Provides the `Model` trait, `Executor` abstraction, and `QueryBuilder`.
10//!
11//! ## Architecture
12//!
13//! - **Model**: The core trait that all database entities must implement.
14//! - **Executor**: Abstracts over connection pools and transactions.
15//! - **QueryBuilder**: A type-safe SQL query generator with support for:
16//!   - Filtering (eq, ne, gt, lt, in)
17//!   - Pagination (limit, offset)
18//!   - Relations (eager loading)
19//!   - Soft Deletes
20//!
21//! This crate is designed to be used with `premix-macros` for compile-time SQL generation overrides.
22
23// Re-export common types
24pub use chrono;
25pub use sqlx;
26pub use tracing;
27pub use uuid;
28
29// New Modules
30/// SQL dialect abstractions for multi-database support.
31pub mod dialect;
32/// Database executor abstraction for connection pools and transactions.
33pub mod executor;
34/// Database migration engine.
35pub mod migrator;
36pub use migrator::{Migration, Migrator};
37/// Premix error types and helpers.
38pub mod error;
39pub use error::{PremixError, PremixResult, map_sqlx_error};
40/// Metrics and monitoring.
41#[cfg(feature = "metrics")]
42pub mod metrics;
43/// Core traits and types for database models.
44pub mod model;
45pub use model::{FastRow, Model, ModelHooks, ModelValidation, UpdateResult, ValidationError};
46/// Type-safe SQL query builder.
47pub mod query;
48pub use query::QueryBuilder;
49/// Database schema introspection and diffing utilities.
50pub mod schema;
51pub use schema::ModelSchema;
52/// Cache helpers for SQL snippets/placeholders.
53pub mod sql_cache;
54pub use sql_cache::{cached_placeholders, cached_placeholders_from};
55
56/// Main entry point for the Premix ORM helpers.
57#[derive(Debug, Clone, Copy, Default)]
58pub struct Premix;
59
60impl Premix {
61    /// Creates a smart SQLite pool with optimized settings for performance.
62    #[cfg(feature = "sqlite")]
63    pub async fn smart_sqlite_pool(url: &str) -> Result<sqlx::SqlitePool, sqlx::Error> {
64        use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous};
65        use std::str::FromStr;
66        let options = SqliteConnectOptions::from_str(url)?
67            .create_if_missing(true)
68            .journal_mode(SqliteJournalMode::Wal)
69            .synchronous(SqliteSynchronous::Normal)
70            .statement_cache_capacity(200);
71        sqlx::SqlitePool::connect_with(options).await
72    }
73
74    /// Synchronizes the database schema for a specific model.
75    pub async fn sync<DB, T>(pool: &sqlx::Pool<DB>) -> Result<(), sqlx::Error>
76    where
77        DB: crate::dialect::SqlDialect,
78        T: crate::model::Model<DB> + crate::schema::ModelSchema,
79        for<'c> &'c sqlx::Pool<DB>: sqlx::Executor<'c, Database = DB>,
80    {
81        let schema = T::schema();
82        let sql = schema.to_create_sql();
83        use sqlx::Executor;
84        pool.execute(sql.as_str()).await?;
85        Ok(())
86    }
87}
88
89/// Helper to build a comma-separated list of placeholders for a given database.
90pub fn build_placeholders<DB: crate::dialect::SqlDialect>(start: usize, count: usize) -> String {
91    (start..start + count)
92        .map(DB::placeholder)
93        .collect::<Vec<_>>()
94        .join(", ")
95}
96
97pub use dialect::SqlDialect;
98pub use executor::{Executor, IntoExecutor};
99
100// Prelude
101/// The Premix prelude, re-exporting commonly used traits and types.
102pub mod prelude {
103    pub use crate::Premix;
104    pub use crate::build_placeholders;
105    pub use crate::dialect::SqlDialect;
106    pub use crate::error::{PremixError, PremixResult, map_sqlx_error};
107    pub use crate::executor::{Executor, IntoExecutor};
108    pub use crate::migrator::{Migration, Migrator};
109    pub use crate::model::{
110        FastRow, Model, ModelHooks, ModelResultExt, ModelValidation, UpdateResult, ValidationError,
111    };
112    pub use crate::query::QueryBuilder;
113    pub use crate::schema::ModelSchema;
114    pub use crate::schema_models;
115    pub use crate::sql_cache::{cached_placeholders, cached_placeholders_from};
116}