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/// Metrics and monitoring.
38#[cfg(feature = "metrics")]
39pub mod metrics;
40/// Core traits and types for database models.
41pub mod model;
42pub use model::{FastRow, Model, ModelHooks, ModelValidation, UpdateResult, ValidationError};
43/// Type-safe SQL query builder.
44pub mod query;
45pub use query::QueryBuilder;
46/// Database schema introspection and diffing utilities.
47pub mod schema;
48pub use schema::ModelSchema;
49/// Cache helpers for SQL snippets/placeholders.
50pub mod sql_cache;
51pub use sql_cache::{cached_placeholders, cached_placeholders_from};
52
53/// Main entry point for the Premix ORM helpers.
54#[derive(Debug, Clone, Copy, Default)]
55pub struct Premix;
56
57impl Premix {
58    /// Creates a smart SQLite pool with optimized settings for performance.
59    #[cfg(feature = "sqlite")]
60    pub async fn smart_sqlite_pool(url: &str) -> Result<sqlx::SqlitePool, sqlx::Error> {
61        use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous};
62        use std::str::FromStr;
63        let options = SqliteConnectOptions::from_str(url)?
64            .create_if_missing(true)
65            .journal_mode(SqliteJournalMode::Wal)
66            .synchronous(SqliteSynchronous::Normal)
67            .statement_cache_capacity(200);
68        sqlx::SqlitePool::connect_with(options).await
69    }
70
71    /// Synchronizes the database schema for a specific model.
72    pub async fn sync<DB, T>(pool: &sqlx::Pool<DB>) -> Result<(), sqlx::Error>
73    where
74        DB: crate::dialect::SqlDialect,
75        T: crate::model::Model<DB> + crate::schema::ModelSchema,
76        for<'c> &'c sqlx::Pool<DB>: sqlx::Executor<'c, Database = DB>,
77    {
78        let schema = T::schema();
79        let sql = schema.to_create_sql();
80        use sqlx::Executor;
81        pool.execute(sql.as_str()).await?;
82        Ok(())
83    }
84}
85
86/// Helper to build a comma-separated list of placeholders for a given database.
87pub fn build_placeholders<DB: crate::dialect::SqlDialect>(start: usize, count: usize) -> String {
88    (start..start + count)
89        .map(DB::placeholder)
90        .collect::<Vec<_>>()
91        .join(", ")
92}
93
94pub use dialect::SqlDialect;
95pub use executor::{Executor, IntoExecutor};
96
97// Prelude
98/// The Premix prelude, re-exporting commonly used traits and types.
99pub mod prelude {
100    pub use crate::Premix;
101    pub use crate::build_placeholders;
102    pub use crate::dialect::SqlDialect;
103    pub use crate::executor::{Executor, IntoExecutor};
104    pub use crate::migrator::{Migration, Migrator};
105    pub use crate::model::{
106        FastRow, Model, ModelHooks, ModelValidation, UpdateResult, ValidationError,
107    };
108    pub use crate::query::QueryBuilder;
109    pub use crate::schema::ModelSchema;
110    pub use crate::sql_cache::{cached_placeholders, cached_placeholders_from};
111}