lume 0.13.1

A simple and intuitive Query Builder inspired by Drizzle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#![warn(missing_docs)]

//! # Database Module
//!
//! This module provides database connection and management functionality.
//! It includes the `Database` struct for managing MySQL connections and
//! executing database operations.

use sqlx::Executor;
#[cfg(feature = "mysql")]
use sqlx::MySqlPool;
#[cfg(feature = "postgres")]
use sqlx::PgPool;
#[cfg(feature = "sqlite")]
use sqlx::SqlitePool;
use std::{fmt::Debug, sync::Arc};

/// Error types for database operations.
pub mod error;

use crate::{
    database::error::DatabaseError,
    dialects::get_dialect,
    operations::{
        delete::Delete,
        insert::{Insert, InsertMany},
        query::Query,
        update::Update,
    },
    row::Row,
    schema::{ColumnInfo, Schema, Select, UpdateTrait},
    table::get_all_tables,
};

/// A database connection manager that provides type-safe access to MySQL databases.
///
/// The `Database` struct manages a connection pool and provides methods for
/// executing queries, registering tables, and managing database schema.
///
/// # Features
///
/// - **Connection Pooling**: Efficient management of database connections
/// - **Type-Safe Queries**: Compile-time type checking for all database operations
/// - **Schema Management**: Automatic table creation and migration support
/// - **Error Handling**: Comprehensive error handling with custom error types
///
/// # Example
///
/// ```no_run
/// use lume::database::Database;
/// use lume::define_schema;
/// use lume::schema::Schema;
/// use lume::schema::ColumnInfo;
/// use lume::database::error::DatabaseError;
///
/// define_schema! {
///     User {
///         id: i32 [primary_key()],
///         name: String [not_null()],
///     }
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), DatabaseError> {
///     // Connect to database
///     let db = Database::connect("mysql://user:password@localhost/database").await?;
///     
///     // Register and create tables
///     db.register_table::<User>().await?;
///     
///     // Execute type-safe queries
///     let users = db.query::<User, SelectUser>().execute().await?;
///     
///     Ok(())
/// }
/// ```
pub struct Database {
    /// The MySQL connection pool
    #[cfg(feature = "mysql")]
    pub(crate) connection: Arc<MySqlPool>,

    #[cfg(feature = "postgres")]
    pub(crate) connection: Arc<PgPool>,

    #[cfg(feature = "sqlite")]
    pub(crate) connection: Arc<SqlitePool>,
}

impl Database {
    /// Creates a new type-safe query builder for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `T`: The schema type to query (must implement `Schema + Debug`)
    ///
    /// # Returns
    ///
    /// A `Query<T>` instance that can be used to build and execute database queries
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     Users {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let query = db.query::<Users, SelectUsers>();
    ///     Ok(())
    /// }
    /// ```
    pub fn query<T: Schema + Debug, S: Select + Debug>(&self) -> Query<T, S> {
        Query::new(Arc::clone(&self.connection))
    }

    /// Creates a new type-safe insert for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `T`: The schema type to insert (must implement `Schema + Debug`)
    ///
    /// # Returns
    ///
    /// A `Insert<T>` instance that can be used to insert data into the database
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     Users {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///
    ///     db.insert(Users {
    ///         id: 1,
    ///         name: "guru".to_string(),
    ///     })
    ///     .execute()
    ///     .await
    ///     .unwrap();
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn insert<T: Schema + Debug>(&self, data: T) -> Insert<T> {
        Insert::new(data, Arc::clone(&self.connection))
    }

    /// Creates a new type-safe delete operation for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `T`: The schema type to delete from (must implement [`Schema`] + [`Debug`])
    ///
    /// # Returns
    ///
    /// A [`Delete<T>`] instance that can be used to build and execute a delete query.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     Users {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///
    ///     db.delete::<Users>()
    ///         .filter(lume::filter::eq_value(Users::name(), "guru"))
    ///         .execute()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn delete<T: Schema + Debug>(&self) -> Delete<T> {
        Delete::new(Arc::clone(&self.connection))
    }

    /// Creates a new type-safe update operation for the specified schema type.
    ///
    /// # Arguments
    ///
    /// - `T`: The schema type to update (must implement [`Schema`] + [`Debug`])
    ///
    /// # Returns
    ///
    /// An [`Update<T>`] instance that can be used to build and execute an update query.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     Users {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///         age: i32,
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), lume::database::error::DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///
    ///     db.update::<Users, UpdateUsers>()
    ///         .set(UpdateUsers {
    ///             age: Some(2),
    ///             ..Default::default()
    ///         })
    ///         .filter(lume::filter::eq_value(Users::name(), "guru"))
    ///         .execute()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn update<T: Schema + Debug, U: UpdateTrait + Debug>(&self) -> Update<T, U> {
        Update::new(Arc::clone(&self.connection))
    }

    /// Creates a new type-safe insert-many for the specified schema type.
    ///
    /// Accepts any iterable of schema values, enabling println!-style multiple values.
    pub fn insert_many<T: Schema + Debug, I>(&self, data: I) -> InsertMany<T>
    where
        I: IntoIterator<Item = T>,
    {
        InsertMany::new(data.into_iter().collect(), Arc::clone(&self.connection))
    }

    /// Executes a raw SQL query and returns typed rows.
    ///
    /// # Safety
    ///
    /// This method bypasses the query builder's type safety. Ensure the SQL
    /// query returns columns that match the schema type `T`.
    ///
    /// # Arguments
    ///
    /// - `sql`: The raw SQL query to execute
    ///
    /// # Returns
    ///
    /// - `Ok(Vec<Row<T>>)`: A vector of typed rows
    /// - `Err(DatabaseError)`: If there was an error executing the query
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::database::error::DatabaseError;
    /// use lume::define_schema;
    /// use lume::schema::ColumnInfo;
    /// use lume::schema::Schema;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key().not_null()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     let users = db.sql::<User>("SELECT * FROM User WHERE age > 18").await?;
    ///
    ///     Ok(())
    /// }
    /// ```

    pub async fn sql<T: Schema + Debug>(&self, sql: &str) -> Result<Vec<Row<T>>, DatabaseError> {
        let conn = self.connection.acquire().await;

        if let Err(e) = conn {
            return Err(DatabaseError::ConnectionError(e));
        }

        let mut conn = conn.unwrap();

        let rows = conn.fetch_all(sql).await;

        if let Err(e) = rows {
            return Err(DatabaseError::QueryError(e.to_string()));
        }

        let rows = rows.unwrap();

        #[cfg(feature = "mysql")]
        let rows = Row::from_mysql_row(rows, None);

        #[cfg(feature = "postgres")]
        let rows = Row::from_postgres_row(rows, None);

        #[cfg(feature = "sqlite")]
        let rows = Row::from_sqlite_row(rows, None);

        Ok(rows)
    }

    /// Registers a schema type and creates its corresponding database table.
    ///
    /// This method ensures the schema is registered and then executes the
    /// CREATE TABLE statements to create the table in the database.
    ///
    /// # Arguments
    ///
    /// - `T`: The schema type to register (must implement `Schema`)
    ///
    /// # Returns
    ///
    /// - `Ok(())`: If the table was successfully created
    /// - `Err(DatabaseError)`: If there was an error creating the table
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    /// use lume::database::error::DatabaseError;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), DatabaseError> {
    ///     let db = Database::connect("mysql://...").await?;
    ///     db.register_table::<User>().await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn register_table<T: Schema>(&self) -> Result<(), DatabaseError> {
        T::ensure_registered();
        let sql = Database::generate_migration_sql();
        for stmt in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
            sqlx::query(stmt)
                .execute(&*self.connection)
                .await
                .map_err(|e| DatabaseError::ExecutionError(e.to_string()))?;
        }
        Ok(())
    }

    /// Generates SQL migration statements for all registered tables.
    ///
    /// This method creates CREATE TABLE statements for all tables that have
    /// been registered in the global table registry.
    ///
    /// # Returns
    ///
    /// A string containing all CREATE TABLE statements, separated by newlines
    pub(crate) fn generate_migration_sql() -> String {
        let tables = get_all_tables();

        #[allow(unused_mut)]
        let mut statements: Vec<String> =
            tables.iter().map(|table| table.to_create_sql()).collect();

        let sql = statements.join("\n\n");
        get_dialect().adapt_sql(sql)
    }

    /// Retrieves column information for a specific table.
    ///
    /// # Arguments
    ///
    /// - `table_name`: The name of the table to get information for
    ///
    /// # Returns
    ///
    /// - `Some(Vec<ColumnInfo>)`: Column information if the table exists
    /// - `None`: If the table is not registered
    ///
    /// # Example
    ///
    /// ```rust
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///         name: String [not_null()],
    ///     }
    /// }
    ///
    /// User::ensure_registered();
    /// let columns = Database::get_table_info("User");
    /// if let Some(cols) = columns {
    ///     println!("User table has {} columns", cols.len());
    /// }
    /// ```
    pub fn get_table_info<'a>(table_name: &str) -> Option<Vec<ColumnInfo<'a>>> {
        // Avoid returning references to local data: fully copy the columns out.
        for table in get_all_tables() {
            if table.table_name() == table_name {
                let columns = table.get_columns();
                return Some(columns);
            }
        }
        None
    }

    /// Returns a list of all registered table names.
    ///
    /// # Returns
    ///
    /// A vector containing the names of all registered tables
    ///
    /// # Example
    ///
    /// ```rust
    /// use lume::database::Database;
    /// use lume::define_schema;
    /// use lume::schema::Schema;
    /// use lume::schema::ColumnInfo;
    ///
    /// define_schema! {
    ///     User {
    ///         id: i32 [primary_key()],
    ///     }
    /// }
    ///
    /// User::ensure_registered();
    /// let tables = Database::list_tables();
    /// assert!(tables.contains(&"User".to_string()));
    /// ```
    pub fn list_tables() -> Vec<String> {
        let tables = get_all_tables();
        tables
            .iter()
            .map(|table| table.table_name().to_string())
            .collect()
    }

    /// Establishes a connection to a MySQL database.
    ///
    /// # Arguments
    ///
    /// - `url`: The MySQL connection URL (e.g., "mysql://user:password@localhost/database")
    ///
    /// # Returns
    ///
    /// - `Ok(Database)`: If the connection was successful
    /// - `Err(DatabaseError)`: If there was an error connecting
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lume::database::Database;
    /// use lume::database::error::DatabaseError;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), DatabaseError> {
    ///     let db = Database::connect("mysql://user:password@localhost/mydb").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect(url: &str) -> Result<Database, DatabaseError> {
        #[cfg(feature = "mysql")]
        let conn = MySqlPool::connect(url)
            .await
            .map_err(|e| DatabaseError::ConnectionError(e))?;

        #[cfg(feature = "postgres")]
        let conn = PgPool::connect(url)
            .await
            .map_err(|e| DatabaseError::ConnectionError(e))?;

        #[cfg(feature = "sqlite")]
        let conn = SqlitePool::connect(url)
            .await
            .map_err(|e| DatabaseError::ConnectionError(e))?;

        Ok(Database {
            connection: Arc::new(conn),
        })
    }
}