Skip to main content

bottle_orm/
database.rs

1//! # Database Module
2//!
3//! This module provides the core database connection and management functionality for Bottle ORM.
4//! It handles connection pooling, driver detection, table creation, and foreign key management
5//! across PostgreSQL, MySQL, and SQLite.
6
7// ============================================================================
8// External Crate Imports
9// ============================================================================
10
11use futures::future::BoxFuture;
12use heck::ToSnakeCase;
13use sqlx::{any::AnyArguments, AnyPool, Row, Arguments};
14use std::sync::Arc;
15
16// ============================================================================
17// Internal Crate Imports
18// ============================================================================
19
20use crate::{migration::Migrator, Error, Model, QueryBuilder};
21
22// ============================================================================
23// Database Driver Enum
24// ============================================================================
25
26/// Supported database drivers for Bottle ORM.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Drivers {
29    /// PostgreSQL driver
30    Postgres,
31    /// MySQL driver
32    MySQL,
33    /// SQLite driver
34    SQLite,
35}
36
37// ============================================================================
38// Database Struct
39// ============================================================================
40
41/// The main entry point for Bottle ORM database operations.
42///
43/// `Database` manages a connection pool and provides methods for starting
44/// transactions, creating tables, and building queries for models.
45///
46/// It is designed to be thread-safe and easily shared across an application
47/// (internally uses an `Arc` for the connection pool).
48#[derive(Debug, Clone)]
49pub struct Database {
50    /// The underlying SQLx connection pool
51    pub(crate) pool: AnyPool,
52    /// The detected database driver
53    pub(crate) driver: Drivers,
54}
55
56// ============================================================================
57// Database Implementation
58// ============================================================================
59
60impl Database {
61    /// Creates a new DatabaseBuilder for configuring the connection.
62    pub fn builder() -> DatabaseBuilder {
63        DatabaseBuilder::new()
64    }
65
66    /// Connects to a database using the provided connection string.
67    ///
68    /// This is a convenience method that uses default builder settings.
69    ///
70    /// # Arguments
71    ///
72    /// * `url` - A database connection URL (e.g., "postgres://user:pass@localhost/db")
73    pub async fn connect(url: &str) -> Result<Self, Error> {
74        DatabaseBuilder::new().connect(url).await
75    }
76
77    /// Returns a new Migrator instance for managing schema changes.
78    pub fn migrator(&self) -> Migrator<'_> {
79        Migrator::new(self)
80    }
81
82    /// Starts building a query for the specified model.
83    ///
84    /// # Type Parameters
85    ///
86    /// * `T` - The Model type to query.
87    pub fn model<T: Model + Send + Sync + Unpin>(&self) -> QueryBuilder<T, Self> {
88        let active_columns = T::active_columns();
89        let mut columns: Vec<String> = Vec::with_capacity(active_columns.capacity());
90
91        for col in active_columns {
92            columns.push(col.strip_prefix("r#").unwrap_or(col).to_snake_case());
93        }
94
95        QueryBuilder::new(self.clone(), self.driver, T::table_name(), T::columns(), columns)
96    }
97
98    /// Creates a raw SQL query builder.
99    pub fn raw<'a>(&self, sql: &'a str) -> RawQuery<'a, Self> {
100        RawQuery::new(self.clone(), sql)
101    }
102
103    /// Starts a new database transaction.
104    pub async fn begin(&self) -> Result<crate::transaction::Transaction<'_>, Error> {
105        let tx = self.pool.begin().await?;
106        Ok(crate::transaction::Transaction {
107            tx: Arc::new(tokio::sync::Mutex::new(Some(tx))),
108            driver: self.driver,
109        })
110    }
111
112    /// Checks if a table exists in the database.
113    pub async fn table_exists(&self, table_name: &str) -> Result<bool, Error> {
114        let table_name_snake = table_name.to_snake_case();
115        let query = match self.driver {
116            Drivers::Postgres => {
117                "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1 AND table_schema = 'public')".to_string()
118            }
119            Drivers::MySQL => {
120                "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = ? AND table_schema = DATABASE())".to_string()
121            }
122            Drivers::SQLite => {
123                "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?".to_string()
124            }
125        };
126
127        let row = sqlx::query(&query).bind(&table_name_snake).fetch_one(&self.pool).await?;
128
129        match self.driver {
130            Drivers::SQLite => {
131                let count: i64 = row.try_get(0)?;
132                Ok(count > 0)
133            }
134            _ => {
135                let exists: bool = row.try_get(0)?;
136                Ok(exists)
137            }
138        }
139    }
140
141    /// Creates a table based on the provided Model metadata.
142    pub async fn create_table<T: Model>(&self) -> Result<(), Error> {
143        let table_name = T::table_name().to_snake_case();
144        let columns = T::columns();
145
146        let mut query = format!("CREATE TABLE IF NOT EXISTS \"{}\" (", table_name);
147        let mut column_defs = Vec::new();
148        let mut indexes = Vec::new();
149
150        for col in columns {
151            let col_name_clean = col.name.strip_prefix("r#").unwrap_or(col.name).to_snake_case();
152            let mut def = format!("\"{}\" {}", col_name_clean, col.sql_type);
153
154            if col.is_primary_key {
155                def.push_str(" PRIMARY KEY");
156            } else if !col.is_nullable {
157                def.push_str(" NOT NULL");
158            }
159
160            if col.unique && !col.is_primary_key {
161                def.push_str(" UNIQUE");
162            }
163
164            if col.index && !col.is_primary_key && !col.unique {
165                indexes.push(format!(
166                    "CREATE INDEX IF NOT EXISTS \"idx_{}_{}\" ON \"{}\" (\"{}\")",
167                    table_name, col_name_clean, table_name, col_name_clean
168                ));
169            }
170
171            column_defs.push(def);
172        }
173
174        query.push_str(&column_defs.join(", "));
175        query.push(')');
176
177        sqlx::query(&query).execute(&self.pool).await?;
178
179        for idx_query in indexes {
180            sqlx::query(&idx_query).execute(&self.pool).await?;
181        }
182
183        Ok(())
184    }
185
186    /// Synchronizes a table schema by adding missing columns or indexes.
187    pub async fn sync_table<T: Model>(&self) -> Result<(), Error> {
188        if !self.table_exists(T::table_name()).await? {
189            return self.create_table::<T>().await;
190        }
191
192        let table_name = T::table_name().to_snake_case();
193        let model_columns = T::columns();
194        let existing_columns = self.get_table_columns(&table_name).await?;
195
196        for col in model_columns {
197            let col_name_clean = col.name.strip_prefix("r#").unwrap_or(col.name).to_snake_case();
198            if !existing_columns.contains(&col_name_clean) {
199                let mut alter_query = format!("ALTER TABLE \"{}\" ADD COLUMN \"{}\" {}", table_name, col_name_clean, col.sql_type);
200                if !col.is_nullable {
201                    alter_query.push_str(" DEFAULT ");
202                    match col.sql_type {
203                        "INTEGER" | "INT" | "BIGINT" => alter_query.push('0'),
204                        "BOOLEAN" | "BOOL" => alter_query.push_str("FALSE"),
205                        _ => alter_query.push_str("''"),
206                    }
207                }
208                sqlx::query(&alter_query).execute(&self.pool).await?;
209            }
210
211            if col.index || col.unique {
212                let existing_indexes = self.get_table_indexes(&table_name).await?;
213                let idx_name = format!("idx_{}_{}", table_name, col_name_clean);
214                let uniq_name = format!("unique_{}_{}", table_name, col_name_clean);
215
216                if col.unique && !existing_indexes.contains(&uniq_name) {
217                    let mut query = format!("CREATE UNIQUE INDEX \"{}\" ON \"{}\" (\"{}\")", uniq_name, table_name, col_name_clean);
218                    if matches!(self.driver, Drivers::SQLite) {
219                        query = format!("CREATE UNIQUE INDEX IF NOT EXISTS \"{}\" ON \"{}\" (\"{}\")", uniq_name, table_name, col_name_clean);
220                    }
221                    sqlx::query(&query).execute(&self.pool).await?;
222                } else if col.index && !existing_indexes.contains(&idx_name) && !col.unique {
223                    let mut query = format!("CREATE INDEX \"{}\" ON \"{}\" (\"{}\")", idx_name, table_name, col_name_clean);
224                    if matches!(self.driver, Drivers::SQLite) {
225                        query = format!("CREATE INDEX IF NOT EXISTS \"{}\" ON \"{}\" (\"{}\")", idx_name, table_name, col_name_clean);
226                    }
227                    sqlx::query(&query).execute(&self.pool).await?;
228                }
229            }
230        }
231
232        Ok(())
233    }
234
235    /// Returns the current columns of a table.
236    pub async fn get_table_columns(&self, table_name: &str) -> Result<Vec<String>, Error> {
237        let table_name_snake = table_name.to_snake_case();
238        let query = match self.driver {
239            Drivers::Postgres => "SELECT column_name::TEXT FROM information_schema.columns WHERE table_name = $1 AND table_schema = 'public'".to_string(),
240            Drivers::MySQL => "SELECT column_name FROM information_schema.columns WHERE table_name = ? AND table_schema = DATABASE()".to_string(),
241            Drivers::SQLite => format!("PRAGMA table_info(\"{}\")", table_name_snake),
242        };
243
244        let rows = if let Drivers::SQLite = self.driver {
245            sqlx::query(&query).fetch_all(&self.pool).await?
246        } else {
247            sqlx::query(&query).bind(&table_name_snake).fetch_all(&self.pool).await?
248        };
249
250        let mut columns = Vec::new();
251        for row in rows {
252            let col_name: String = if let Drivers::SQLite = self.driver {
253                row.try_get("name")?
254            } else {
255                row.try_get(0)?
256            };
257            columns.push(col_name);
258        }
259        Ok(columns)
260    }
261
262    /// Returns the current indexes of a table.
263    pub async fn get_table_indexes(&self, table_name: &str) -> Result<Vec<String>, Error> {
264        let table_name_snake = table_name.to_snake_case();
265        let query = match self.driver {
266            Drivers::Postgres => "SELECT indexname::TEXT FROM pg_indexes WHERE tablename = $1 AND schemaname = 'public'".to_string(),
267            Drivers::MySQL => "SELECT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = DATABASE()".to_string(),
268            Drivers::SQLite => format!("PRAGMA index_list(\"{}\")", table_name_snake),
269        };
270
271        let rows = if let Drivers::SQLite = self.driver {
272            sqlx::query(&query).fetch_all(&self.pool).await?
273        } else {
274            sqlx::query(&query).bind(&table_name_snake).fetch_all(&self.pool).await?
275        };
276
277        let mut indexes = Vec::new();
278        for row in rows {
279            let idx_name: String = if let Drivers::SQLite = self.driver {
280                row.try_get("name")?
281            } else {
282                row.try_get(0)?
283            };
284            indexes.push(idx_name);
285        }
286        Ok(indexes)
287    }
288
289    /// Assigns foreign keys to a table.
290    pub async fn assign_foreign_keys<T: Model>(&self) -> Result<(), Error> {
291        let table_name = T::table_name().to_snake_case();
292        let columns = T::columns();
293
294        for col in columns {
295            if let (Some(f_table), Some(f_key)) = (col.foreign_table, col.foreign_key) {
296                if matches!(self.driver, Drivers::SQLite) { continue; }
297                let constraint_name = format!("fk_{}_{}_{}", table_name, f_table.to_snake_case(), col.name.to_snake_case());
298                let query = format!(
299                    "ALTER TABLE \"{}\" ADD CONSTRAINT \"{}\" FOREIGN KEY (\"{}\") REFERENCES \"{}\"(\"{}\")",
300                    table_name, constraint_name, col.name.to_snake_case(), f_table.to_snake_case(), f_key.to_snake_case()
301                );
302                let _ = sqlx::query(&query).execute(&self.pool).await;
303            }
304        }
305        Ok(())
306    }
307}
308
309// ============================================================================
310// DatabaseBuilder Struct
311// ============================================================================
312
313pub struct DatabaseBuilder {
314    max_connections: u32,
315}
316
317impl DatabaseBuilder {
318    pub fn new() -> Self { Self { max_connections: 5 } }
319    pub fn max_connections(mut self, max: u32) -> Self { self.max_connections = max; self }
320    pub async fn connect(self, url: &str) -> Result<Database, Error> {
321        // Ensure sqlx drivers are registered for Any driver support
322        let _ = sqlx::any::install_default_drivers();
323
324        let pool = sqlx::any::AnyPoolOptions::new().max_connections(self.max_connections).connect(url).await?;
325        let driver = if url.starts_with("postgres") { Drivers::Postgres }
326                    else if url.starts_with("mysql") { Drivers::MySQL }
327                    else { Drivers::SQLite };
328        Ok(Database { pool, driver })
329    }
330}
331
332// ============================================================================
333// Connection Trait
334// ============================================================================
335
336pub trait Connection: Send + Sync {
337    fn execute<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<sqlx::any::AnyQueryResult, sqlx::Error>>;
338    fn fetch_all<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<Vec<sqlx::any::AnyRow>, sqlx::Error>>;
339    fn fetch_one<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<sqlx::any::AnyRow, sqlx::Error>>;
340    fn fetch_optional<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<Option<sqlx::any::AnyRow>, sqlx::Error>>;
341}
342
343impl Connection for Database {
344    fn execute<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<sqlx::any::AnyQueryResult, sqlx::Error>> {
345        Box::pin(async move { sqlx::query_with(sql, args).execute(&self.pool).await })
346    }
347    fn fetch_all<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<Vec<sqlx::any::AnyRow>, sqlx::Error>> {
348        Box::pin(async move { sqlx::query_with(sql, args).fetch_all(&self.pool).await })
349    }
350    fn fetch_one<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<sqlx::any::AnyRow, sqlx::Error>> {
351        Box::pin(async move { sqlx::query_with(sql, args).fetch_one(&self.pool).await })
352    }
353    fn fetch_optional<'a, 'q: 'a>(&'a self, sql: &'q str, args: AnyArguments<'q>) -> BoxFuture<'a, Result<Option<sqlx::any::AnyRow>, sqlx::Error>> {
354        Box::pin(async move { sqlx::query_with(sql, args).fetch_optional(&self.pool).await })
355    }
356}
357
358// ============================================================================
359// Raw SQL Query Builder
360// ============================================================================
361
362pub struct RawQuery<'a, C> {
363    conn: C,
364    sql: &'a str,
365    args: AnyArguments<'a>,
366}
367
368impl<'a, C> RawQuery<'a, C> where C: Connection {
369    pub(crate) fn new(conn: C, sql: &'a str) -> Self {
370        Self { conn, sql, args: AnyArguments::default() }
371    }
372    pub fn bind<T>(mut self, value: T) -> Self where T: 'a + sqlx::Encode<'a, sqlx::Any> + sqlx::Type<sqlx::Any> + Send + Sync {
373        let _ = self.args.add(value);
374        self
375    }
376    pub async fn fetch_all<T>(self) -> Result<Vec<T>, Error> where T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin {
377        let rows = self.conn.fetch_all(self.sql, self.args).await?;
378        Ok(rows.iter().map(|r| T::from_row(r).unwrap()).collect())
379    }
380    pub async fn fetch_one<T>(self) -> Result<T, Error> where T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin {
381        let row = self.conn.fetch_one(self.sql, self.args).await?;
382        Ok(T::from_row(&row)?)
383    }
384    pub async fn fetch_optional<T>(self) -> Result<Option<T>, Error> where T: for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Send + Unpin {
385        let row = self.conn.fetch_optional(self.sql, self.args).await?;
386        Ok(row.map(|r| T::from_row(&r).unwrap()))
387    }
388    pub async fn execute(self) -> Result<u64, Error> {
389        let result = self.conn.execute(self.sql, self.args).await?;
390        Ok(result.rows_affected())
391    }
392}