rusql-alchemy 0.5.8

Rust Alchemy is Django ORM like lib for Rust
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! RusQL Alchemy: A Rust ORM library for SQL databases
//!
//! This module provides traits and implementations for database operations,
//! including querying, inserting, updating, and deleting records.

use super::query::{Arg, builder, condition::Kwargs};
use super::{Connection, PLACEHOLDER};
use crate::{Error, FutureResult, utils};
use serde::Serialize;

/// `Model` is a foundational trait in `rusql-alchemy` that provides an interface
/// for Rust structs to interact with a database table. By deriving or implementing
/// this trait, your struct gains capabilities for schema management (migrations)
/// and CRUD operations (Create, Read, Update, Delete).
///
/// This trait is typically implemented automatically using the `#[derive(Model)]`
/// procedural macro from `rusql_alchemy_derive`.
///
/// # Provided Methods
///
/// The `Model` trait provides default implementations for `up` and `down` methods
/// which execute the SQL defined in `Self::UP` and `Self::DOWN` respectively.
/// It also defines other asynchronous methods for CRUD operations which must be
/// implemented for the specific model.
///
/// # Examples
///
/// Below is an example of a `User` struct deriving the `Model` trait.
/// This automatically provides the `UP`, `DOWN`, `NAME`, `PK` constants
/// and implements the necessary methods.
///
/// ```rust
/// use rusql_alchemy::prelude::*;
/// use sqlx::FromRow;
///
/// #[derive(Model, Clone, FromRow, Debug)]
/// struct User {
///     #[field(primary_key = true, auto = true)]
///     id: Option<Integer>,
///     name: String,
///     #[field(default = "user")]
///     role: String,
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), rusql_alchemy::Error> {
///     let database = Database::new("sqlite::memory:").await?;
///     let conn = &database.conn;
///
///     User::up(conn).await?;
///     User::down(conn).await?;
///
///     Ok(())
/// }
/// ```
#[async_trait::async_trait]
pub trait Model {
    const UP: &'static str;
    const DOWN: &'static str;
    const NAME: &'static str;
    const PK: &'static str;

    /// Executes the `UP` SQL statement for this model, creating its table or
    /// applying schema changes.
    ///
    /// This method provides a default implementation that executes the SQL
    /// defined in `Self::UP`. It is typically called as part of a larger
    /// migration process orchestrated by `Database::up()`.
    ///
    /// # Arguments
    ///
    /// *   `conn` - A reference to the database connection.
    ///
    /// # Returns
    ///
    /// A `FutureResult` indicating success (`Ok(())`) or an `Error` on failure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rusql_alchemy::prelude::*;
    /// use sqlx::FromRow;
    ///
    /// #[derive(Model, Clone, FromRow, Debug)]
    /// struct User {
    ///     #[field(primary_key = true, auto = true)]
    ///     id: Option<Integer>,
    ///     name: String,
    ///     #[field(default = "user")]
    ///     role: String,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rusql_alchemy::Error> {
    ///     let database = Database::new("sqlite::memory:").await?;
    ///     let conn = &database.conn;
    ///
    ///     User::up(conn).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    fn up(conn: &'_ Connection) -> FutureResult<'_, ()>
    where
        Self: Sized,
    {
        Box::pin(async move {
            #[cfg(debug_assertions)]
            {
                let formatted_sql = sqlformat::format(
                    Self::UP,
                    &sqlformat::QueryParams::None,
                    &sqlformat::FormatOptions::default(),
                );
                println!("{formatted_sql}");
            }

            #[cfg(not(feature = "turso"))]
            sqlx::query(Self::UP).execute(conn).await?;

            #[cfg(feature = "turso")]
            conn.execute(Self::UP, ()).await?;

            Ok(())
        })
    }

    /// Executes the `DOWN` SQL statement for this model, typically dropping its table.
    ///
    /// This method provides a default implementation that executes the SQL
    /// defined in `Self::DOWN`. It is typically called as part of a larger
    /// migration rollback process orchestrated by `Database::down()`.
    ///
    /// # Arguments
    ///
    /// *   `conn` - A reference to the database connection.
    ///
    /// # Returns
    ///
    /// A `FutureResult` indicating success (`Ok(())`) or an `Error` on failure.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rusql_alchemy::prelude::*;
    /// use sqlx::FromRow;
    ///
    /// #[derive(Model, Clone, FromRow, Debug)]
    /// struct User {
    ///     #[field(primary_key = true, auto = true)]
    ///     id: Option<Integer>,
    ///     name: String,
    ///     #[field(default = "user")]
    ///     role: String,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rusql_alchemy::Error> {
    ///     let database = Database::new("sqlite::memory:").await?;
    ///     let conn = &database.conn;
    ///
    ///     User::down(conn).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    fn down(conn: &'_ Connection) -> FutureResult<'_, ()>
    where
        Self: Sized,
    {
        Box::pin(async move {
            #[cfg(debug_assertions)]
            {
                let formatted_sql = sqlformat::format(
                    Self::DOWN,
                    &sqlformat::QueryParams::None,
                    &sqlformat::FormatOptions::default(),
                );
                println!("{formatted_sql}");
            }

            #[cfg(not(feature = "turso"))]
            sqlx::query(Self::DOWN).execute(conn).await?;

            #[cfg(feature = "turso")]
            conn.execute(Self::DOWN, ()).await?;

            Ok(())
        })
    }

    /// Saves the current model instance to the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if save is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// let user = User {
    ///     name: "johnDoe@gmail.com".to_string(),
    ///     email: "21john@gmail.com".to_string(),
    ///     password: "p455w0rd".to_string(),
    ///     age: 18,
    ///     weight: 60.0,
    ///     ..Default::default()
    /// };
    /// let success = user.save(&conn).await;
    /// println!("Save success: {}", success);
    /// ```
    async fn save(&self, conn: &Connection) -> Result<(), Error>
    where
        Self: Sized;

    /// Creates a new model instance with the specified parameters.
    ///
    /// # Arguments
    /// * `kw` - The key-value arguments for the new instance.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if creation is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// let success = User::create(
    ///     kwargs!(
    ///         name = "joe",
    ///         email = "24nomeniavo@gmail.com",
    ///         password = "strongpassword",
    ///         age = 19,
    ///         weight = 80.1
    ///     ),
    ///     &conn,
    /// ).await;
    /// println!("Create success: {}", success);
    /// ```
    async fn create(kw: Vec<Kwargs>, conn: &Connection) -> Result<(), Error>
    where
        Self: Sized,
    {
        let insert_query = builder::to_insert_query(kw);

        let query = format!(
            "insert into {name} ({fields}) values ({placeholders});",
            name = Self::NAME,
            fields = insert_query.fields,
            placeholders = insert_query.placeholders,
        );

        #[cfg(not(feature = "turso"))]
        {
            let mut stream = sqlx::query(&query);
            binds!(insert_query.args.iter(), stream);
            stream.execute(conn).await?;
        }

        #[cfg(feature = "turso")]
        {
            let params = binds!(insert_query.args.iter());
            conn.execute(&query, params).await?;
        }
        Ok(())
    }

    /// Updates the current model instance in the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if update is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// if let Some(mut user) = User::get(
    ///     kwargs!(email == "24nomeniavo@gmail.com").and(kwargs!(password == "strongpassword")),
    ///     &conn,
    /// ).await {
    ///     user.role = "admin".to_string();
    ///     let success = user.update(&conn).await;
    ///     println!("Update success: {}", success);
    /// }
    /// ```
    async fn update(&self, conn: &Connection) -> Result<(), Error>
    where
        Self: Sized;

    /// Updates a specific model instance identified by its primary key with the given parameters.
    ///
    /// # Arguments
    /// * `id_value` - The value of the primary key.
    /// * `kw` - The key-value arguments for the update.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if update is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// let success = User::set(
    ///     user_id,
    ///     kwargs!(role = "admin"),
    ///     &conn,
    /// ).await;
    /// println!("Set success: {}", success);
    /// ```
    async fn set<T: Serialize + Clone + Send + Sync>(
        id: T,
        kw: Vec<Kwargs>,
        conn: &Connection,
    ) -> Result<(), Error> {
        let mut update_query = builder::to_update_query(kw);

        update_query.args = update_query
            .args
            .into_iter()
            .chain([Arg {
                value: serde_json::json!(id.clone()).to_string(),
                ty: utils::get_type_name(id).to_string(),
            }])
            .collect();

        let index_id = update_query.args.len();
        let query = format!(
            "update {name} set {placeholders} where {id}={PLACEHOLDER}{index_id};",
            id = Self::PK,
            name = Self::NAME,
            placeholders = update_query.placeholders,
        );

        #[cfg(not(feature = "turso"))]
        {
            let mut stream = sqlx::query(&query);
            binds!(update_query.args, stream);
            stream.execute(conn).await?;
        }

        #[cfg(feature = "turso")]
        {
            let params = binds!(update_query.args.iter());
            conn.execute(&query, params).await?;
        }
        Ok(())
    }

    /// Deletes the current model instance from the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if delete is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// let success = user.delete(&conn).await;
    /// println!("Delete success: {}", success);
    /// ```
    async fn delete(&self, conn: &Connection) -> Result<(), Error>
    where
        Self: Sized;

    #[cfg(not(feature = "turso"))]
    /// Retrieves all instances of the model from the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// A vector of all instances of the model.
    ///
    /// # Example
    /// ```
    /// let users = User::all(&conn).await;
    /// println!("{:#?}", users);
    /// ```
    async fn all(conn: &Connection) -> Result<Vec<Self>, Error>
    where
        Self: Sized + Unpin + for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Clone,
    {
        let query = format!("select * from {name}", name = Self::NAME);
        Ok(sqlx::query_as::<_, Self>(&query).fetch_all(conn).await?)
    }

    #[cfg(feature = "turso")]
    /// Retrieves all instances of the model from the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// A vector of all instances of the model.
    ///
    /// # Example
    /// ```
    /// let users = User::all(&conn).await;
    /// println!("{:#?}", users);
    /// ```
    async fn all(conn: &Connection) -> Result<Vec<Self>, Error>
    where
        Self: Sized + for<'de> serde::Deserialize<'de>,
    {
        let query = format!("select * from {name}", name = Self::NAME);
        let rows = conn.query(&query, ()).await?;
        let results = utils::libsql_from_row(rows).await?;
        Ok(results)
    }

    #[cfg(not(feature = "turso"))]
    /// Filters instances of the model based on the provided parameters.
    ///
    /// # Arguments
    /// * `kw` - The key-value arguments for filtering.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// A vector of instances matching the filter criteria.
    ///
    /// # Example
    /// ```
    /// let users = User::filter(
    ///     kwargs!(age <= 18).and(kwargs!(weight == 80.0)),
    ///     &conn,
    /// ).await;
    /// println!("{:#?}", users);
    /// ```
    async fn filter(kw: Vec<Kwargs>, conn: &Connection) -> Result<Vec<Self>, Error>
    where
        Self: Sized + Unpin + for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Clone,
    {
        let select_query = builder::to_select_query(kw);

        let query = format!(
            "SELECT * FROM {name} WHERE {placeholders};",
            name = Self::NAME,
            placeholders = select_query.placeholders,
        );

        let mut stream = sqlx::query_as::<_, Self>(&query);
        binds!(select_query.args, stream);
        Ok(stream.fetch_all(conn).await?)
    }

    #[cfg(feature = "turso")]
    /// Filters instances of the model based on the provided parameters.
    ///
    /// # Arguments
    /// * `kw` - The key-value arguments for filtering.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// A vector of instances matching the filter criteria.
    ///
    /// # Example
    /// ```
    /// let users = User::filter(
    ///     kwargs!(age <= 18).and(kwargs!(weight == 80.0)),
    ///     &conn,
    /// ).await;
    /// println!("{:#?}", users);
    /// ```
    async fn filter(kw: Vec<Kwargs>, conn: &Connection) -> Result<Vec<Self>, Error>
    where
        Self: Sized + for<'de> serde::Deserialize<'de>,
    {
        let select_query = builder::to_select_query(kw);

        let query = format!(
            "SELECT * FROM {name} WHERE {placeholders};",
            name = Self::NAME,
            placeholders = select_query.placeholders,
        );
        let params = binds!(select_query.args.iter());
        let rows = conn.query(&query, params).await?;
        let results = utils::libsql_from_row(rows).await?;
        Ok(results)
    }

    #[cfg(not(feature = "turso"))]
    /// Retrieves the first instance of the model matching the filter criteria.
    ///
    /// # Arguments
    /// * `kw` - The key-value arguments for filtering.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// An optional instance matching the filter criteria.
    ///
    /// # Example
    /// ```
    /// let user = User::get(
    ///     kwargs!(email == "24nomeniavo@gmail.com").and(kwargs!(password == "strongpassword")),
    ///     &conn,
    /// ).await;
    /// println!("{:#?}", user);
    /// ```
    async fn get(kw: Vec<Kwargs>, conn: &Connection) -> Result<Option<Self>, Error>
    where
        Self: Sized + Unpin + for<'r> sqlx::FromRow<'r, sqlx::any::AnyRow> + Clone,
    {
        Ok(Self::filter(kw, conn).await?.first().cloned())
    }

    #[cfg(feature = "turso")]
    /// Retrieves the first instance of the model matching the filter criteria.
    ///
    /// # Arguments
    /// * `kw` - The key-value arguments for filtering.
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// An optional instance matching the filter criteria.
    ///
    /// # Example
    /// ```
    /// let user = User::get(
    ///     kwargs!(email == "24nomeniavo@gmail.com").and(kwargs!(password == "strongpassword")),
    ///     &conn,
    /// ).await;
    /// println!("{:#?}", user);
    /// ```
    async fn get(kw: Vec<Kwargs>, conn: &Connection) -> Result<Option<Self>, Error>
    where
        Self: Sized + Clone + for<'de> serde::Deserialize<'de>,
    {
        Ok(Self::filter(kw, conn).await?.first().cloned())
    }

    /// Counts the number of instances of the model in the database.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// The count of instances.
    ///
    /// # Example
    /// ```
    /// let count = User::count(&conn).await;
    /// println!("User count: {}", count);
    /// ```
    async fn count(conn: &Connection) -> Result<i64, Error>
    where
        Self: Sized,
    {
        let query = format!("select count(*) from {name}", name = Self::NAME);
        #[cfg(not(feature = "turso"))]
        {
            let slf = sqlx::query(&query).fetch_one(conn).await?;
            Ok(sqlx::Row::try_get(&slf, 0)?)
        }

        #[cfg(feature = "turso")]
        {
            let row = conn
                .query(&query, ())
                .await?
                .next()
                .await?
                .ok_or("no rows returned")?;
            Ok(row.get(0)?)
        }
    }
}

/// Trait for deleting database records.
#[async_trait::async_trait]
pub trait Delete {
    async fn delete(&self, conn: &Connection) -> Result<(), Error>;
}

#[async_trait::async_trait]
impl<T> Delete for Vec<T>
where
    T: Model + Sync,
{
    /// Deletes all instances of the model from the database.
    ///
    /// This method will delete all records from the table corresponding to the model `T`.
    /// Be cautious when using this method, as it will remove all entries without conditions.
    ///
    /// # Arguments
    /// * `conn` - The database connection.
    ///
    /// # Returns
    /// `true` if deletion is successful, `false` otherwise.
    ///
    /// # Example
    /// ```
    /// # use rusql_alchemy::prelude::*;
    /// # use sqlx::FromRow;
    /// #
    /// # #[derive(FromRow, Debug, Default, Model, Clone)]
    /// # struct Product {
    /// #     #[field(primary_key = true, auto = true)]
    /// #     id: Integer,
    /// #     #[field(size = 50)]
    /// #     name: String,
    /// #     price: Float,
    /// #     description: Text,
    /// #     #[field(default = true)]
    /// #     is_sel: Boolean,
    /// #     #[field(foreign_key = "User.id")]
    /// #     owner: Integer,
    /// #     #[field(default = "now")]
    /// #     at: DateTime,
    /// # }
    /// #
    /// #[tokio::main]
    /// async fn main() -> Result<(), rusql_alchemy::Error> {
    ///     let conn = Database::new().await?.conn;
    ///
    ///     let products = Product::all(&conn).await?;
    ///     let success = products.delete(&conn).await;
    ///     println!("Products delete success: {}", success);
    ///
    ///     let products = Product::all(&conn).await;
    ///     println!("Remaining products: {:#?}", products);
    /// }
    /// ```
    ///
    /// In the above example, all records from the `Product` table will be deleted.
    async fn delete(&self, conn: &Connection) -> Result<(), Error> {
        let query = format!("delete from {name}", name = T::NAME);
        #[cfg(not(feature = "turso"))]
        sqlx::query(&query).execute(conn).await?;

        #[cfg(feature = "turso")]
        conn.execute(&query, ()).await?;
        Ok(())
    }
}