Skip to main content

karbon_framework/db/
mod.rs

1mod database;
2mod builder;
3mod pagination;
4mod query;
5mod repository;
6mod paginated_query;
7mod select_builder;
8#[cfg(test)]
9mod pagination_test;
10pub mod filter_value;
11pub mod seeder;
12
13pub use database::Database;
14pub use builder::{InsertBuilder, UpdateBuilder, DeleteBuilder, CountBuilder};
15pub use pagination::{Paginated, PaginationParams};
16pub use query::QueryBuilder;
17pub use repository::{CrudRepository, WhereValue};
18pub use paginated_query::PaginatedQuery;
19pub use select_builder::{SelectBuilder, Order};
20
21// ─── Database driver type aliases ───
22
23#[cfg(feature = "mysql")]
24pub type Db = sqlx::MySql;
25#[cfg(feature = "mysql")]
26pub type DbPool = sqlx::MySqlPool;
27#[cfg(feature = "mysql")]
28pub type DbPoolOptions = sqlx::mysql::MySqlPoolOptions;
29#[cfg(feature = "mysql")]
30pub type DbRow = sqlx::mysql::MySqlRow;
31#[cfg(feature = "mysql")]
32pub type DbArguments = sqlx::mysql::MySqlArguments;
33
34#[cfg(feature = "postgres")]
35pub type Db = sqlx::Postgres;
36#[cfg(feature = "postgres")]
37pub type DbPool = sqlx::PgPool;
38#[cfg(feature = "postgres")]
39pub type DbPoolOptions = sqlx::postgres::PgPoolOptions;
40#[cfg(feature = "postgres")]
41pub type DbRow = sqlx::postgres::PgRow;
42#[cfg(feature = "postgres")]
43pub type DbArguments = sqlx::postgres::PgArguments;
44
45// ─── SQL dialect helpers ───
46
47/// Returns a SQL placeholder for the given 1-based parameter index.
48/// MySQL: always `?`. PostgreSQL: `$1`, `$2`, etc.
49#[cfg(feature = "mysql")]
50pub fn placeholder(_n: usize) -> String {
51    "?".to_string()
52}
53
54#[cfg(feature = "postgres")]
55pub fn placeholder(n: usize) -> String {
56    format!("${}", n)
57}
58
59/// Generates an INSERT SQL string with the correct placeholder syntax.
60/// For PostgreSQL, appends `RETURNING id`.
61pub fn insert_sql(table: &str, columns: &[&str]) -> String {
62    let placeholders: Vec<String> = (1..=columns.len())
63        .map(placeholder)
64        .collect();
65
66    let base = format!(
67        "INSERT INTO {} ({}) VALUES ({})",
68        table,
69        columns.join(", "),
70        placeholders.join(", ")
71    );
72
73    #[cfg(feature = "mysql")]
74    { return base; }
75
76    #[cfg(feature = "postgres")]
77    { return format!("{} RETURNING id", base); }
78}
79
80/// Extracts the last insert ID from a query result.
81#[cfg(feature = "mysql")]
82pub fn last_insert_id(result: &<Db as sqlx::Database>::QueryResult) -> u64 {
83    result.last_insert_id()
84}
85
86#[cfg(feature = "postgres")]
87pub fn last_insert_id(_result: &<Db as sqlx::Database>::QueryResult) -> u64 {
88    // For PostgreSQL, use RETURNING id in the query instead
89    0
90}