floz-orm 0.1.7

A lightweight, typesafe Rust ORM — unifying DAO and DSL from a single schema
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
//! `Executor` trait and `bind_params!` macro.
//!
//! The `Executor` trait is the core abstraction for database operations.
//! Both `Db` (connection pool) and `Tx` (transaction) implement it,
//! so DAO methods accept `&impl Executor` generically.

use crate::error::FlozError;
use crate::value::Value;
use super::row_bound::FlozRowBound;
use super::pool::{Db, DbInner};
use super::tx::{Tx, TxInner};

// ═══════════════════════════════════════════════════════════════
// Executor Trait
// ═══════════════════════════════════════════════════════════════

/// The core database execution trait.
///
/// All floz DAO and DSL methods accept `&impl Executor`, allowing
/// seamless switching between connection pools, transactions, and mocks.
///
/// ```ignore
/// // Both work:
/// let users = User::all(&db).await?;
/// let users = User::all(&tx).await?;
/// ```
pub trait Executor {
    /// Execute a raw SQL statement, returning the number of affected rows.
    fn execute_raw(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> impl std::future::Future<Output = Result<u64, FlozError>> + Send;

    /// Fetch all matching rows.
    fn fetch_all<T>(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> impl std::future::Future<Output = Result<Vec<T>, FlozError>> + Send
    where
        T: Send + Unpin + FlozRowBound;

    /// Fetch exactly one row. Returns `FlozError::NotFound` if no rows match.
    fn fetch_one<T>(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> impl std::future::Future<Output = Result<T, FlozError>> + Send
    where
        T: Send + Unpin + FlozRowBound;

    /// Fetch zero or one row.
    fn fetch_optional<T>(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> impl std::future::Future<Output = Result<Option<T>, FlozError>> + Send
    where
        T: Send + Unpin + FlozRowBound;
}

// ═══════════════════════════════════════════════════════════════
// bind_params! macro
// ═══════════════════════════════════════════════════════════════

/// Bind a `Vec<Value>` to a `sqlx::query()` builder.
///
/// Each `Value` variant is pattern-matched to call `.bind()` with the
/// concrete type. Works for both Postgres and SQLite.
macro_rules! bind_params {
    ($query:expr, $params:expr) => {{
        let mut q = $query;
        for param in $params {
            q = match param {
                // Non-nullable
                Value::Short(v) => q.bind(v),
                Value::Int(v) => q.bind(v),
                Value::BigInt(v) => q.bind(v),
                Value::Real(v) => q.bind(v),
                Value::Double(v) => q.bind(v),
                Value::Bool(v) => q.bind(v),
                Value::String(v) => q.bind(v),
                Value::Bytes(v) => q.bind(v),
                Value::Uuid(v) => q.bind(v.to_string()),
                Value::DateTime(v) => q.bind(v),
                Value::NaiveDateTime(v) => q.bind(v),
                Value::NaiveDate(v) => q.bind(v),
                Value::NaiveTime(v) => q.bind(v),
                Value::Json(v) => q.bind(v.to_string()),
                Value::Jsonb(v) => q.bind(v.to_string()),
                // Nullable
                Value::OptionShort(v) => q.bind(v),
                Value::OptionInt(v) => q.bind(v),
                Value::OptionBigInt(v) => q.bind(v),
                Value::OptionReal(v) => q.bind(v),
                Value::OptionDouble(v) => q.bind(v),
                Value::OptionBool(v) => q.bind(v),
                Value::OptionString(v) => q.bind(v),
                Value::OptionBytes(v) => q.bind(v),
                Value::OptionUuid(v) => q.bind(v.map(|u| u.to_string())),
                Value::OptionDateTime(v) => q.bind(v),
                Value::OptionNaiveDateTime(v) => q.bind(v),
                Value::OptionNaiveDate(v) => q.bind(v),
                Value::OptionNaiveTime(v) => q.bind(v),
                Value::OptionJson(v) => q.bind(v.map(|j| j.to_string())),
                Value::OptionJsonb(v) => q.bind(v.map(|j| j.to_string())),
            };
        }
        q
    }};
}

// ═══════════════════════════════════════════════════════════════
// impl Executor for Db
// ═══════════════════════════════════════════════════════════════

impl Executor for Db {
    #[allow(unreachable_patterns)]
    async fn execute_raw(&self, sql: &str, params: Vec<Value>) -> Result<u64, FlozError> {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            DbInner::Postgres(pool) => {
                let query = bind_params!(sqlx::query(&sql), params);
                let result = query.execute(pool).await?;
                Ok(result.rows_affected())
            }
            #[cfg(feature = "sqlite")]
            DbInner::Sqlite(pool) => {
                let query = bind_params!(sqlx::query(&sql), params);
                let result = query.execute(pool).await?;
                Ok(result.rows_affected())
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_all<T>(&self, sql: &str, params: Vec<Value>) -> Result<Vec<T>, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            DbInner::Postgres(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_all(pool).await?)
            }
            #[cfg(feature = "sqlite")]
            DbInner::Sqlite(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_all(pool).await?)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_one<T>(&self, sql: &str, params: Vec<Value>) -> Result<T, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            DbInner::Postgres(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                query
                    .fetch_optional(pool)
                    .await?
                    .ok_or(FlozError::NotFound)
            }
            #[cfg(feature = "sqlite")]
            DbInner::Sqlite(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                query
                    .fetch_optional(pool)
                    .await?
                    .ok_or(FlozError::NotFound)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_optional<T>(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> Result<Option<T>, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            DbInner::Postgres(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_optional(pool).await?)
            }
            #[cfg(feature = "sqlite")]
            DbInner::Sqlite(pool) => {
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_optional(pool).await?)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }
}

// ═══════════════════════════════════════════════════════════════
// impl Executor for Tx
// ═══════════════════════════════════════════════════════════════

impl Executor for Tx {
    #[allow(unreachable_patterns)]
    async fn execute_raw(&self, sql: &str, params: Vec<Value>) -> Result<u64, FlozError> {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            TxInner::Postgres(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query(&sql), params);
                let result = query.execute(&mut **c).await?;
                Ok(result.rows_affected())
            }
            #[cfg(feature = "sqlite")]
            TxInner::Sqlite(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query(&sql), params);
                let result = query.execute(&mut **c).await?;
                Ok(result.rows_affected())
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_all<T>(&self, sql: &str, params: Vec<Value>) -> Result<Vec<T>, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            TxInner::Postgres(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_all(&mut **c).await?)
            }
            #[cfg(feature = "sqlite")]
            TxInner::Sqlite(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_all(&mut **c).await?)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_one<T>(&self, sql: &str, params: Vec<Value>) -> Result<T, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            TxInner::Postgres(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                query
                    .fetch_optional(&mut **c)
                    .await?
                    .ok_or(FlozError::NotFound)
            }
            #[cfg(feature = "sqlite")]
            TxInner::Sqlite(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                query
                    .fetch_optional(&mut **c)
                    .await?
                    .ok_or(FlozError::NotFound)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }

    #[allow(unreachable_patterns)]
    async fn fetch_optional<T>(
        &self,
        sql: &str,
        params: Vec<Value>,
    ) -> Result<Option<T>, FlozError>
    where
        T: Send + Unpin + FlozRowBound,
    {
        let sql = self.adjust_sql(sql);
        match &self.inner {
            #[cfg(feature = "postgres")]
            TxInner::Postgres(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_optional(&mut **c).await?)
            }
            #[cfg(feature = "sqlite")]
            TxInner::Sqlite(conn) => {
                let mut c = conn.lock().await;
                let query = bind_params!(sqlx::query_as::<_, T>(&sql), params);
                Ok(query.fetch_optional(&mut **c).await?)
            }
            _ => unreachable!("no database backend enabled"),
        }
    }
}

// ═══════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn db_is_send_sync() {
        fn _assert_send<T: Send>() {}
        fn _assert_sync<T: Sync>() {}
        _assert_send::<Db>();
        _assert_sync::<Db>();
    }

    #[test]
    fn tx_is_debug() {
        fn _assert_debug<T: std::fmt::Debug>() {}
        _assert_debug::<Tx>();
    }

    // ── SQLite integration tests ──

    #[cfg(feature = "sqlite")]
    mod sqlite_tests {
        use super::*;

        #[tokio::test]
        async fn connect_memory() {
            let db = Db::connect("sqlite::memory:").await.unwrap();
            let affected = db.execute_raw("SELECT 1", vec![]).await.unwrap();
            assert_eq!(affected, 0);
        }

        #[tokio::test]
        async fn create_insert_fetch() {
            let db = Db::connect("sqlite::memory:").await.unwrap();

            db.execute_raw(
                "CREATE TABLE test_users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
                vec![],
            )
            .await
            .unwrap();

            let affected = db
                .execute_raw(
                    "INSERT INTO test_users (id, name) VALUES ($1, $2)",
                    vec![Value::Int(1), Value::String("Alice".into())],
                )
                .await
                .unwrap();
            assert_eq!(affected, 1);

            #[derive(Debug, sqlx::FromRow)]
            struct User {
                id: i32,
                name: String,
            }

            let users: Vec<User> = db
                .fetch_all("SELECT id, name FROM test_users ORDER BY id", vec![])
                .await
                .unwrap();
            assert_eq!(users.len(), 1);
            assert_eq!(users[0].name, "Alice");
        }

        #[tokio::test]
        async fn fetch_one_not_found() {
            let db = Db::connect("sqlite::memory:").await.unwrap();
            db.execute_raw("CREATE TABLE test_nf (id INTEGER)", vec![])
                .await
                .unwrap();

            #[derive(Debug, sqlx::FromRow)]
            struct Row {
                id: i32,
            }

            let result: Result<Row, _> = db
                .fetch_one(
                    "SELECT id FROM test_nf WHERE id = $1",
                    vec![Value::Int(999)],
                )
                .await;
            assert!(matches!(result, Err(FlozError::NotFound)));
        }

        #[tokio::test]
        async fn transaction_commit() {
            let db = Db::connect("sqlite::memory:").await.unwrap();
            db.execute_raw("CREATE TABLE test_tx (id INTEGER)", vec![])
                .await
                .unwrap();

            let tx = db.begin().await.unwrap();
            tx.execute_raw(
                "INSERT INTO test_tx VALUES ($1)",
                vec![Value::Int(1)],
            )
            .await
            .unwrap();
            tx.commit().await.unwrap();

            #[derive(Debug, sqlx::FromRow)]
            struct Row {
                id: i32,
            }

            let rows: Vec<Row> = db
                .fetch_all("SELECT id FROM test_tx", vec![])
                .await
                .unwrap();
            assert_eq!(rows.len(), 1);
        }

        #[tokio::test]
        async fn transaction_rollback() {
            let db = Db::connect("sqlite::memory:").await.unwrap();
            db.execute_raw("CREATE TABLE test_rb (id INTEGER)", vec![])
                .await
                .unwrap();

            let tx = db.begin().await.unwrap();
            tx.execute_raw(
                "INSERT INTO test_rb VALUES ($1)",
                vec![Value::Int(1)],
            )
            .await
            .unwrap();
            tx.rollback().await.unwrap();

            #[derive(Debug, sqlx::FromRow)]
            struct Row {
                id: i32,
            }

            let rows: Vec<Row> = db
                .fetch_all("SELECT id FROM test_rb", vec![])
                .await
                .unwrap();
            assert_eq!(rows.len(), 0);
        }
    }

    // ── PostgreSQL integration tests ──

    #[cfg(feature = "postgres")]
    mod pg_tests {
        use super::*;

        fn test_url() -> Option<String> {
            std::env::var("DATABASE_URL").ok()
        }

        #[tokio::test]
        async fn connect_to_postgres() {
            let Some(url) = test_url() else { return };
            let db = Db::connect(&url).await.unwrap();
            let affected = db.execute_raw("SELECT 1", vec![]).await.unwrap();
            assert_eq!(affected, 0);
        }

        #[tokio::test]
        async fn execute_with_params() {
            let Some(url) = test_url() else { return };
            let db = Db::connect(&url).await.unwrap();

            db.execute_raw(
                "CREATE TEMP TABLE floz_test_params (id INT, name TEXT)",
                vec![],
            )
            .await
            .unwrap();

            let affected = db
                .execute_raw(
                    "INSERT INTO floz_test_params (id, name) VALUES ($1, $2)",
                    vec![Value::Int(1), Value::String("Alice".into())],
                )
                .await
                .unwrap();
            assert_eq!(affected, 1);
        }

        #[tokio::test]
        async fn fetch_all_rows() {
            let Some(url) = test_url() else { return };
            let db = Db::connect(&url).await.unwrap();

            db.execute_raw(
                "CREATE TEMP TABLE floz_test_fetch (id INT, name TEXT)",
                vec![],
            )
            .await
            .unwrap();
            db.execute_raw(
                "INSERT INTO floz_test_fetch VALUES (1, 'Alice'), (2, 'Bob')",
                vec![],
            )
            .await
            .unwrap();

            #[derive(Debug, sqlx::FromRow)]
            struct Row {
                id: i32,
                name: String,
            }

            let rows: Vec<Row> = db
                .fetch_all(
                    "SELECT id, name FROM floz_test_fetch ORDER BY id",
                    vec![],
                )
                .await
                .unwrap();
            assert_eq!(rows.len(), 2);
            assert_eq!(rows[0].name, "Alice");
            assert_eq!(rows[1].name, "Bob");
        }

        #[tokio::test]
        async fn transaction_commit() {
            let Some(url) = test_url() else { return };
            let db = Db::connect(&url).await.unwrap();

            db.execute_raw("CREATE TEMP TABLE floz_test_tx (id INT)", vec![])
                .await
                .unwrap();

            let tx = db.begin().await.unwrap();
            tx.execute_raw(
                "INSERT INTO floz_test_tx VALUES ($1)",
                vec![Value::Int(1)],
            )
            .await
            .unwrap();
            tx.commit().await.unwrap();

            #[derive(Debug, sqlx::FromRow)]
            struct Row {
                id: i32,
            }

            let rows: Vec<Row> = db
                .fetch_all("SELECT id FROM floz_test_tx", vec![])
                .await
                .unwrap();
            assert_eq!(rows.len(), 1);
        }
    }
}