microrm 0.6.3

Lightweight ORM using sqlite as a backend
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
use crate::{DBResult, Error};
use libsqlite3_sys as sq;
use std::{
    cell::Cell,
    ffi::{c_void, CStr, CString},
    pin::Pin,
};

mod conn;

#[cfg(feature = "regex")]
mod regex;

pub use conn::*;

fn check_rcode<'a>(sql_gen: impl FnOnce() -> Option<&'a str>, rcode: i32) -> Result<(), Error> {
    let code = rcode & 0xff;
    if code == sq::SQLITE_OK {
        Ok(())
    } else {
        Err(Error::Sqlite {
            code,
            extended_code: rcode & !0xff,
            msg: unsafe { CStr::from_ptr(sq::sqlite3_errstr(rcode)) }
                .to_str()?
                .to_string(),
            sql: sql_gen().map(String::from),
        })
    }
}

pub(crate) trait PreparedKey {
    fn into_u64(self) -> u64;
}

impl PreparedKey for u64 {
    fn into_u64(self) -> u64 {
        self
    }
}

impl PreparedKey for std::any::TypeId {
    fn into_u64(self) -> u64 {
        use std::hash::Hash;
        use std::hash::Hasher;
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.hash(&mut hasher);
        hasher.finish()
    }
}

/// A database transaction. Note that the transaction must be *explicitly* committed for any
/// effects to reach the database; transactions may also abort during commit, so be prepared for
/// retry logic.
pub struct Transaction {
    db: ConnectionLease,
    committed: bool,
}

impl Transaction {
    fn begin_transaction(&mut self) -> DBResult<()> {
        struct BeginTransaction;
        self.db.with_prepared(
            std::any::TypeId::of::<BeginTransaction>(),
            || Ok(String::from("BEGIN TRANSACTION")),
            |ctx| {
                ctx.run()?;
                Ok(())
            },
        )
    }

    fn commit_transaction(&mut self) -> DBResult<()> {
        struct CommitTransaction;
        self.db.with_prepared(
            std::any::TypeId::of::<CommitTransaction>(),
            || Ok(String::from("COMMIT TRANSACTION")),
            |ctx| {
                ctx.run()?;
                Ok(())
            },
        )
    }

    fn rollback_transaction(&mut self) -> DBResult<()> {
        struct RollbackTransaction;
        self.db.with_prepared(
            std::any::TypeId::of::<RollbackTransaction>(),
            || Ok(String::from("ROLLBACK TRANSACTION")),
            |ctx| {
                ctx.run()?;
                Ok(())
            },
        )
    }

    pub(crate) fn new(db: ConnectionLease) -> DBResult<Self> {
        let mut r = Self {
            db,
            committed: false,
        };

        r.begin_transaction()?;

        Ok(r)
    }

    pub(crate) fn lease(&mut self) -> &mut ConnectionLease {
        &mut self.db
    }

    /// Actually commit the transaction. Note that this can fail, and if it does, _all_ changes
    /// made to the database via this transaction will be rolled back!
    pub fn commit(mut self) -> DBResult<()> {
        self.committed = true;

        match self.commit_transaction() {
            Err(Error::Sqlite {
                code: sq::SQLITE_BUSY,
                ..
            }) => Err(Error::TransactionAbort),
            v => v,
        }
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        if !self.committed {
            let _ = self.rollback_transaction();
        }
    }
}

#[derive(Debug)]
pub(crate) struct RawSchemaRow {
    pub type_: String,
    pub name: String,
    pub tbl_name: String,
    pub _rootpage: String,
    pub sql: String,
}

pub(crate) fn get_raw_schema(lease: &mut ConnectionLease) -> DBResult<Vec<RawSchemaRow>> {
    let mut schema_entries: Vec<RawSchemaRow> = vec![];

    unsafe extern "C" fn rowcb(
        entries: *mut c_void,
        ncols: i32,
        rowdata: *mut *mut i8,
        _cols: *mut *mut i8,
    ) -> i32 {
        assert_eq!(ncols, 5);
        let rows = std::slice::from_raw_parts(rowdata, ncols as usize);
        let entries = (entries as *mut Vec<RawSchemaRow>).as_mut().unwrap();

        let extract_value = |idx: usize| {
            if !rows[idx].is_null() {
                CStr::from_ptr(rows[idx]).to_str().map(ToString::to_string)
            } else {
                Ok(String::new())
            }
        };

        let row = (|| {
            DBResult::Ok(RawSchemaRow {
                type_: extract_value(0)?,
                name: extract_value(1)?,
                tbl_name: extract_value(2)?,
                _rootpage: extract_value(3)?,
                sql: extract_value(4)?,
            })
        })();

        match row {
            Ok(row) => {
                // log::trace!("should save extracted row {row:?}");
                entries.push(row);
                // log::trace!("saved");
                0
            },
            Err(err) => {
                log::error!("error while getting raw schema: {err:?}");
                1
            },
        }
    }

    unsafe {
        let sql = "SELECT * FROM sqlite_schema";
        let c_sql = CString::new(sql)?;
        let entries_ptr = (&mut schema_entries) as *mut Vec<RawSchemaRow>;
        check_rcode(
            || Some(sql),
            sq::sqlite3_exec(
                lease.conn.sqlite,
                c_sql.as_ptr(),
                Some(rowcb),
                entries_ptr as *mut c_void,
                std::ptr::null_mut(),
            ),
        )?;
    }

    Ok(schema_entries)
}

struct Statement {
    #[allow(unused)]
    sqlite: *mut sq::sqlite3,
    stmt: *mut sq::sqlite3_stmt,
}

impl Statement {
    fn make_context(&mut self) -> DBResult<StatementContext<'_>> {
        // begin by resetting the statement
        unsafe {
            check_rcode(|| None, sq::sqlite3_reset(self.stmt))?;
        }

        Ok(StatementContext {
            stmt: self,
            owned_strings: Default::default(),
            done: false.into(),
        })
    }
}

impl Drop for Statement {
    fn drop(&mut self) {
        unsafe {
            sq::sqlite3_finalize(self.stmt);
        }
    }
}

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

    #[test]
    fn simple_sql() {
        let c = ConnectionPool::new(":memory:").expect("couldn't open test db");
        let mut t = c.start().unwrap();
        t.lease()
            .execute_raw_sql("CREATE TABLE test_table (id integer primary key, value string)")
            .expect("couldn't execute sql");
    }

    #[test]
    fn prepare_stmt() {
        let c = ConnectionPool::new(":memory:").expect("couldn't open test db");
        let mut t = c.start().unwrap();
        t.lease()
            .execute_raw_sql("CREATE TABLE test_table (id integer primary key, value string)")
            .expect("couldn't execute sql");

        t.lease()
            .with_prepared(
                1,
                || Ok(format!("INSERT INTO test_table VALUES (?, ?)")),
                |ctx| {
                    ctx.bind(1, 1usize)?;
                    ctx.bind(2, "value")?;

                    ctx.iter().last();

                    Ok(())
                },
            )
            .expect("couldn't run prepared INSERT statement");

        t.lease()
            .with_prepared(
                2,
                || Ok(format!("SELECT * FROM test_table")),
                |ctx| {
                    let count = ctx
                        .iter()
                        .map(|row| {
                            let row = row.unwrap();
                            assert_eq!(row.read::<i64>(0).expect("couldn't read row ID"), 1);
                            assert_eq!(
                                row.read::<String>(1).expect("couldn't read row value"),
                                "value"
                            );
                        })
                        .count();
                    assert!(count > 0);

                    Ok(())
                },
            )
            .expect("couldn't run prepared SELECT statement");
    }
}

/// A table row that an `Entity` can be read out of.
pub struct StatementRow<'a> {
    stmt: &'a Statement,
    _ctx: Option<StatementContext<'a>>,
}

impl StatementRow<'_> {
    /// Read a single [`Readable`] out of the database row.
    pub fn read<T: Readable>(&self, index: i32) -> DBResult<T> {
        T::read_from(self, index)
    }

    /// Borrow a single [`Borrowable`] out of the database row.
    pub fn borrow<T: Borrowable>(&self, index: i32) -> DBResult<T> {
        T::borrow(self, index)
    }
}

/// A query context.
pub struct StatementContext<'a> {
    stmt: &'a Statement,
    owned_strings: Vec<Pin<String>>,
    done: Cell<bool>,
}

impl<'a> StatementContext<'a> {
    /// Bind data to the context at a given index.
    ///
    /// Remember that bind indices start at 1!
    pub fn bind<B: Bindable>(&self, index: i32, bindable: B) -> DBResult<()> {
        bindable.bind(self, index)
    }

    /// Transfer ownership of a string to the statement context. For transient strings, this is required in order to have
    /// the string outlive the query.
    pub fn transfer(&mut self, s: Pin<String>) {
        self.owned_strings.push(s);
    }

    fn step(&self) -> DBResult<bool> {
        if self.done.get() {
            return Ok(false);
        }
        let step_result = unsafe { sq::sqlite3_step(self.stmt.stmt) };
        // primary result code is in the 8LSB
        match step_result & 0xff {
            sq::SQLITE_ROW => Ok(true),
            sq::SQLITE_DONE => {
                self.done.set(true);
                Ok(false)
            },
            sq::SQLITE_BUSY => {
                log::trace!("Concurrent database access!");
                Err(Error::TransactionAbort)
            },
            sq::SQLITE_CONSTRAINT => {
                let msg = unsafe { CStr::from_ptr(sq::sqlite3_errmsg(self.stmt.sqlite)) }
                    .to_str()
                    .unwrap()
                    .to_string();
                log::trace!("SQLite constraint violation: {msg}");
                Err(Error::ConstraintViolation(msg))
            },
            err => {
                log::trace!("unexpected error during sqlite3_step: {:?}", err);
                check_rcode(|| None, err)?;
                unreachable!()
            },
        }
    }

    // this needs to be replaced with a "single" version that keeps the StatementContext alive, or
    // StatementRow needs an optional StatementContext to keep alive
    #[doc(hidden)]
    pub fn run(self) -> DBResult<Option<StatementRow<'a>>> {
        if self.step()? {
            Ok(Some(StatementRow {
                stmt: self.stmt,
                _ctx: Some(self),
            }))
        } else {
            Ok(None)
        }
    }

    #[doc(hidden)]
    pub fn iter(self) -> impl Iterator<Item = DBResult<StatementRow<'a>>> {
        struct I<'a>(StatementContext<'a>);

        impl<'a> Iterator for I<'a> {
            type Item = DBResult<StatementRow<'a>>;

            fn next(&mut self) -> Option<Self::Item> {
                // XXX: unwrap
                match self.0.step() {
                    Ok(true) => Some(Ok(StatementRow {
                        _ctx: None,
                        stmt: self.0.stmt,
                    })),
                    Ok(false) => None,
                    Err(e) => Some(Err(e)),
                }
                /*map(|_| )*/
            }
        }

        I(self)
    }
}

impl Drop for StatementContext<'_> {
    fn drop(&mut self) {
        // attempt to bind NULLs into each parameter
        unsafe {
            // clear out the rest of the rows
            while self.step().is_ok_and(|v| v) {}
            sq::sqlite3_clear_bindings(self.stmt.stmt);
        }
    }
}

/// Data that can be bound into a [`StatementContext`].
pub trait Bindable {
    /// Bind data into the [`StatementContext`].
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()>;
}

impl Bindable for () {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        unsafe { check_rcode(|| None, sq::sqlite3_bind_null(ctx.stmt.stmt, index)) }
    }
}

impl Bindable for i64 {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        unsafe { check_rcode(|| None, sq::sqlite3_bind_int64(ctx.stmt.stmt, index, *self)) }
    }
}

impl Bindable for usize {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        (*self as i64).bind(ctx, index)
    }
}

impl Bindable for f32 {
    fn bind<'ctx, 'data: 'ctx>(&self, ctx: &StatementContext<'ctx>, index: i32) -> DBResult<()> {
        (*self as f64).bind(ctx, index)
    }
}

impl Bindable for f64 {
    fn bind<'ctx, 'data: 'ctx>(&self, ctx: &StatementContext<'ctx>, index: i32) -> DBResult<()> {
        unsafe {
            check_rcode(
                || None,
                sq::sqlite3_bind_double(ctx.stmt.stmt, index, *self),
            )
        }
    }
}

impl Bindable for &str {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        unsafe {
            check_rcode(
                || None,
                sq::sqlite3_bind_text(
                    ctx.stmt.stmt,
                    index,
                    self.as_ptr().cast(),
                    self.len() as i32,
                    sq::SQLITE_STATIC(),
                ),
            )
        }
    }
}

impl Bindable for str {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        <&'_ str>::bind(&self, ctx, index)
    }
}

impl Bindable for String {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        self.as_str().bind(ctx, index)
    }
}

impl Bindable for &[u8] {
    fn bind<'ctx, 'data: 'ctx>(
        &'data self,
        ctx: &StatementContext<'ctx>,
        index: i32,
    ) -> DBResult<()> {
        unsafe {
            check_rcode(
                || None,
                sq::sqlite3_bind_blob64(
                    ctx.stmt.stmt,
                    index,
                    self.as_ptr().cast(),
                    self.len() as u64,
                    sq::SQLITE_STATIC(),
                ),
            )
        }
    }
}

/// Data that can be read from a [`StatementRow`].
pub trait Readable: Sized {
    /// Read an instance of `Self` from a [`StatementRow`].
    ///
    /// Remember that read indices start at 0!
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self>;
}

/// Data that can be borrowed from a [`StatementRow`].
pub trait Borrowable: Sized {
    /// Construct an instance of `Self` from a [`StatementRow`].
    ///
    /// Remember that read indices start at 0!
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self>;
}

/// Readable that can be used to pre-determine if a value is NULL, i.e. for `Option::None`
/// checking.
pub struct IsNull(pub bool);

// NULL-checker
impl Readable for IsNull {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        let column_type = unsafe { sq::sqlite3_column_type(sr.stmt.stmt, index) };
        if column_type == sq::SQLITE_NULL {
            Ok(IsNull(true))
        } else {
            Ok(IsNull(false))
        }
    }
}

impl Borrowable for IsNull {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        let column_type = unsafe { sq::sqlite3_column_type(sr.stmt.stmt, index) };
        if column_type == sq::SQLITE_NULL {
            Ok(IsNull(true))
        } else {
            Ok(IsNull(false))
        }
    }
}

impl Readable for i64 {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe { Ok(sq::sqlite3_column_int64(sr.stmt.stmt, index)) }
    }
}

impl Borrowable for i64 {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        i64::read_from(sr, index)
    }
}

impl Readable for usize {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        i64::read_from(sr, index).map(|i| i as usize)
    }
}

impl Borrowable for usize {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        usize::read_from(sr, index)
    }
}

impl Readable for f32 {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        f64::read_from(sr, index).map(|i| i as f32)
    }
}

impl Borrowable for f32 {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        f32::read_from(sr, index)
    }
}

impl Readable for f64 {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe { Ok(sq::sqlite3_column_double(sr.stmt.stmt, index)) }
    }
}

impl Borrowable for f64 {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        f64::read_from(sr, index)
    }
}

impl Readable for String {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe {
            let text = sq::sqlite3_column_text(sr.stmt.stmt, index);
            if text.is_null() {
                Err(Error::InternalError(
                    "NULL pointer result from sqlite3_column_text",
                ))
            } else {
                Ok(CStr::from_ptr(text.cast()).to_str()?.to_string())
            }
        }
    }
}

impl Borrowable for &str {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe {
            let text = sq::sqlite3_column_text(sr.stmt.stmt, index);
            if text.is_null() {
                Err(Error::InternalError(
                    "NULL pointer result from sqlite3_column_text",
                ))
            } else {
                Ok(CStr::from_ptr(text.cast()).to_str()?)
            }
        }
    }
}

impl Readable for Vec<u8> {
    fn read_from(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe {
            let ptr = sq::sqlite3_column_blob(sr.stmt.stmt, index);
            let len = sq::sqlite3_column_bytes(sr.stmt.stmt, index);

            match len.cmp(&0) {
                std::cmp::Ordering::Equal => Ok(vec![]),
                std::cmp::Ordering::Less => Err(Error::InternalError(
                    "negative length returned from sqlite3_column_bytes",
                )),
                std::cmp::Ordering::Greater => {
                    Ok(std::slice::from_raw_parts(ptr.cast(), len as usize).to_vec())
                },
            }
        }
    }
}

impl Borrowable for &[u8] {
    fn borrow(sr: &StatementRow<'_>, index: i32) -> DBResult<Self> {
        unsafe {
            let ptr = sq::sqlite3_column_blob(sr.stmt.stmt, index);
            let len = sq::sqlite3_column_bytes(sr.stmt.stmt, index);

            match len.cmp(&0) {
                std::cmp::Ordering::Equal => Ok(&[]),
                std::cmp::Ordering::Less => Err(Error::InternalError(
                    "negative length returned from sqlite3_column_bytes",
                )),
                std::cmp::Ordering::Greater => {
                    Ok(std::slice::from_raw_parts(ptr.cast(), len as usize))
                },
            }
        }
    }
}

#[cfg(test)]
mod sendsync_check {
    struct CheckSend<T: Send>(std::marker::PhantomData<T>);
    struct CheckSync<T: Sync>(std::marker::PhantomData<T>);

    #[test]
    fn check_send() {
        let _ = CheckSend::<super::ConnectionPool>(Default::default());
    }

    #[test]
    fn check_sync() {
        let _ = CheckSync::<super::ConnectionPool>(Default::default());
    }
}