wabot-feature-sqlite 0.2.0

SQLite foundation for Wabot — the document store, migrations and connection handling, for a single-node deployment with no database server.
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
//! `SqliteJsonbStore` — document storage for entities, in the same
//! shape `PgJsonbStore` uses.
//!
//! ```text
//! CREATE TABLE "<table>" (
//!   "id"         TEXT PRIMARY KEY,
//!   "created_at" INTEGER,          -- epoch milliseconds
//!   "data"       TEXT,             -- JSON
//!   <promoted columns…>
//! )
//! ```
//!
//! Everything lives in `data`; a *promoted column* is a value copied
//! out of the document on write so an index can serve a hot lookup.
//!
//! ## Two deliberate differences from the Postgres store
//!
//! **`created_at` is an INTEGER of epoch milliseconds**, not a
//! timestamp. SQLite has no date type — the alternatives are an ISO
//! string, which sorts correctly but costs more per row and per
//! comparison, or a number, which is what [`Entity`] already carries
//! internally. Keyset pagination compares it constantly, so the
//! cheaper one wins.
//!
//! **The table is created without an advisory lock.** The Postgres
//! store takes one because two booting nodes can race on the DDL;
//! here, one writer connection *is* the mutual exclusion, and a second
//! process on the same file is not a supported configuration.

use std::marker::PhantomData;
use std::sync::atomic::{AtomicBool, Ordering};

use rusqlite::types::Value as SqlValue;
use serde::de::DeserializeOwned;
use serde::Serialize;

use wabot_core::entity::{Entity, EntityFields};

use crate::database::SqliteDatabase;
use crate::error::{SqliteError, SqliteResult};

/// A value lifted out of the JSON document into its own column.
pub struct PromotedColumn<D> {
    /// Column name, e.g. `"chat_id"`.
    pub name: &'static str,
    /// SQLite type + constraints, e.g. `"TEXT"`.
    pub ddl_type: &'static str,
    /// Extractor run on every write.
    pub value: fn(&D) -> Option<String>,
}

// `#[derive(Clone)]` would demand `D: Clone`; the struct is all
// `Copy` fields, so implement it by hand and keep `D` unconstrained.
impl<D> Clone for PromotedColumn<D> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<D> Copy for PromotedColumn<D> {}

/// Extra DDL to run once the table exists — indexes, mostly.
/// Statements must be idempotent (`IF NOT EXISTS`), since they run on
/// every process start.
pub type IndexDdl = &'static str;

/// Document store for one entity type in one table.
pub struct SqliteJsonbStore<D>
where
    D: EntityFields + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    database: SqliteDatabase,
    table_name: String,
    /// Pre-quoted.
    qualified: String,
    promoted: Vec<PromotedColumn<D>>,
    indexes: Vec<IndexDdl>,
    ready: AtomicBool,
    _marker: PhantomData<fn() -> D>,
}

impl<D> SqliteJsonbStore<D>
where
    D: EntityFields + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    pub fn new(database: SqliteDatabase, table: impl Into<String>) -> Self {
        let table_name = table.into();
        let qualified = format!("\"{}\"", table_name.replace('"', "\"\""));
        Self {
            database,
            table_name,
            qualified,
            promoted: Vec::new(),
            indexes: Vec::new(),
            ready: AtomicBool::new(false),
            _marker: PhantomData,
        }
    }

    /// Add a column copied out of the document on every write.
    pub fn with_promoted_column(mut self, column: PromotedColumn<D>) -> Self {
        self.promoted.push(column);
        self
    }

    /// Add an idempotent `CREATE INDEX IF NOT EXISTS …` run after the
    /// table is created.
    ///
    /// A document field is queried as `"data"->>'$."field"'`, so an
    /// index on anything else is one the planner will never use —
    /// build the expression with
    /// [`field_expression`](crate::query_sql::field_expression) rather
    /// than by hand, and the two cannot drift.
    pub fn with_index(mut self, ddl: IndexDdl) -> Self {
        self.indexes.push(ddl);
        self
    }

    /// The placement the query builder uses: promoted fields are
    /// columns, everything else lives in the document.
    pub fn placement(&self) -> crate::query_sql::FieldPlacement {
        crate::query_sql::FieldPlacement::promoted(
            self.promoted.iter().map(|column| column.name.to_string()),
        )
    }

    pub fn database(&self) -> &SqliteDatabase {
        &self.database
    }

    /// Quoted table name, for hand-written SQL.
    pub fn table(&self) -> &str {
        &self.qualified
    }

    // ---------- schema management ----------------------------------

    /// Create the table, promoted columns and indexes if they don't
    /// exist. Idempotent, and cheap after the first call.
    pub async fn ensure_ready(&self) -> SqliteResult<()> {
        if self.ready.load(Ordering::Relaxed) {
            return Ok(());
        }
        let ddl = self.ddl_statements();
        let indexes = self.indexes.clone();
        self.database
            .write(move |connection| {
                for statement in ddl {
                    connection.execute(&statement, [])?;
                }
                for index in indexes {
                    // An index failure shouldn't stop a boot — queries
                    // still work, just slower.
                    if let Err(error) = connection.execute(index, []) {
                        tracing::warn!(ddl = %index, %error, "index creation failed");
                    }
                }
                Ok(())
            })
            .await?;
        self.ready.store(true, Ordering::Relaxed);
        Ok(())
    }

    fn ddl_statements(&self) -> Vec<String> {
        let mut columns = vec![
            "\"id\" TEXT PRIMARY KEY".to_string(),
            "\"created_at\" INTEGER".to_string(),
            "\"data\" TEXT".to_string(),
        ];
        for column in &self.promoted {
            columns.push(format!("\"{}\" {}", column.name, column.ddl_type));
        }

        let mut statements = vec![format!(
            "CREATE TABLE IF NOT EXISTS {} ({})",
            self.qualified,
            columns.join(", ")
        )];

        // Every listing and every page is ordered by this pair, so it
        // is the one index the store builds for itself.
        statements.push(format!(
            "CREATE INDEX IF NOT EXISTS \"{}_created_at_id\" ON {} (\"created_at\" DESC, \"id\" DESC)",
            self.table_name.replace('"', ""),
            self.qualified
        ));
        statements
    }

    /// Add promoted columns a previous build didn't have.
    ///
    /// Separate from [`ensure_ready`](Self::ensure_ready) because
    /// SQLite has no `ADD COLUMN IF NOT EXISTS`: the only way to ask
    /// is to read the table back.
    pub async fn migrate_promoted_columns(&self) -> SqliteResult<()> {
        self.ensure_ready().await?;
        let table = self.qualified.clone();
        let wanted: Vec<(String, String)> = self
            .promoted
            .iter()
            .map(|column| (column.name.to_string(), column.ddl_type.to_string()))
            .collect();

        self.database
            .write(move |connection| {
                let existing: std::collections::HashSet<String> = connection
                    .prepare(&format!(
                        "SELECT name FROM pragma_table_info('{}')",
                        table.trim_matches('"')
                    ))?
                    .query_map([], |row| row.get::<_, String>(0))?
                    .collect::<rusqlite::Result<_>>()?;

                for (name, ddl_type) in wanted {
                    if !existing.contains(&name) {
                        connection.execute(
                            &format!("ALTER TABLE {table} ADD COLUMN \"{name}\" {ddl_type}"),
                            [],
                        )?;
                    }
                }
                Ok(())
            })
            .await
    }

    // ---------- CRUD -----------------------------------------------

    /// `INSERT` a new entity. Fails if the id already exists — use
    /// [`save`](Self::save) for upsert semantics.
    pub async fn create(&self, entity: &Entity<D>) -> SqliteResult<()> {
        self.ensure_ready().await?;
        let sql = self.insert_sql(false);
        let values = self.write_values(entity)?;
        self.database
            .write(move |connection| connection.execute(&sql, rusqlite::params_from_iter(values)))
            .await?;
        Ok(())
    }

    /// `INSERT … ON CONFLICT DO UPDATE` — the write the async
    /// repositories use, since a job is created then updated many
    /// times and neither caller wants to care which it is.
    pub async fn save(&self, entity: &Entity<D>) -> SqliteResult<()> {
        self.ensure_ready().await?;
        let sql = self.insert_sql(true);
        let values = self.write_values(entity)?;
        self.database
            .write(move |connection| connection.execute(&sql, rusqlite::params_from_iter(values)))
            .await?;
        Ok(())
    }

    /// `UPDATE` by id. Returns `false` when no row matched.
    pub async fn update(&self, entity: &Entity<D>) -> SqliteResult<bool> {
        self.ensure_ready().await?;
        let mut sets = vec![
            "\"created_at\" = ?2".to_string(),
            "\"data\" = ?3".to_string(),
        ];
        for (index, column) in self.promoted.iter().enumerate() {
            sets.push(format!("\"{}\" = ?{}", column.name, index + 4));
        }
        let sql = format!(
            "UPDATE {} SET {} WHERE \"id\" = ?1",
            self.qualified,
            sets.join(", ")
        );
        let values = self.write_values(entity)?;
        let affected = self
            .database
            .write(move |connection| connection.execute(&sql, rusqlite::params_from_iter(values)))
            .await?;
        Ok(affected > 0)
    }

    pub async fn delete(&self, id: &str) -> SqliteResult<()> {
        self.ensure_ready().await?;
        let sql = format!("DELETE FROM {} WHERE \"id\" = ?1", self.qualified);
        let id = id.to_string();
        self.database
            .write(move |connection| connection.execute(&sql, [id]))
            .await?;
        Ok(())
    }

    pub async fn find_by_id(&self, id: &str) -> SqliteResult<Option<Entity<D>>> {
        let sql = format!(
            "SELECT \"data\" FROM {} WHERE \"id\" = ?1 LIMIT 1",
            self.qualified
        );
        self.query_opt(&sql, vec![SqlValue::Text(id.to_string())])
            .await
    }

    // ---------- query escape hatches --------------------------------

    /// Run SQL that selects the `data` column and decode every row.
    ///
    /// ```ignore
    /// store.query(
    ///     &format!("SELECT data FROM {} WHERE data->>'$.\"commandName\"' = ?1", store.table()),
    ///     vec![SqlValue::Text(command_name)],
    /// ).await?
    /// ```
    pub async fn query(&self, sql: &str, values: Vec<SqlValue>) -> SqliteResult<Vec<Entity<D>>> {
        self.ensure_ready().await?;
        let sql = sql.to_string();
        let documents: Vec<String> = self
            .database
            .read(move |connection| {
                connection
                    .prepare(&sql)?
                    .query_map(rusqlite::params_from_iter(values), |row| {
                        row.get::<_, String>(0)
                    })?
                    .collect()
            })
            .await?;
        documents.iter().map(|json| decode::<D>(json)).collect()
    }

    /// [`query`](Self::query) for a single optional row.
    pub async fn query_opt(
        &self,
        sql: &str,
        values: Vec<SqlValue>,
    ) -> SqliteResult<Option<Entity<D>>> {
        Ok(self.query(sql, values).await?.into_iter().next())
    }

    /// Scalar count query.
    pub async fn count(&self, sql: &str, values: Vec<SqlValue>) -> SqliteResult<i64> {
        self.ensure_ready().await?;
        let sql = sql.to_string();
        self.database
            .read(move |connection| {
                connection.query_row(&sql, rusqlite::params_from_iter(values), |row| row.get(0))
            })
            .await
    }

    /// Run a storage-agnostic [`Query`](wabot_core::repository::Query)
    /// against this table.
    pub async fn find_by_query(
        &self,
        query: &wabot_core::repository::Query,
    ) -> SqliteResult<Vec<Entity<D>>> {
        let built = crate::query_sql::build_query_sql(query, &self.placement(), None)
            .map_err(|error| SqliteError::Other(error.to_string()))?;
        let values = crate::query_sql::bind_values(query)
            .map_err(|error| SqliteError::Other(error.to_string()))?;
        let sql = format!("SELECT \"data\" FROM {}{}", self.qualified, built.sql);
        self.query(&sql, values.iter().map(to_sql_value).collect())
            .await
    }

    // ---------- internals -------------------------------------------

    fn insert_sql(&self, upsert: bool) -> String {
        let mut columns = vec![
            "id".to_string(),
            "created_at".to_string(),
            "data".to_string(),
        ];
        for column in &self.promoted {
            columns.push(column.name.to_string());
        }
        let quoted: Vec<String> = columns.iter().map(|c| format!("\"{c}\"")).collect();
        let placeholders: Vec<String> = (1..=columns.len()).map(|i| format!("?{i}")).collect();

        let mut sql = format!(
            "INSERT INTO {} ({}) VALUES ({})",
            self.qualified,
            quoted.join(", "),
            placeholders.join(", ")
        );
        if upsert {
            let updates: Vec<String> = quoted
                .iter()
                .skip(1)
                .map(|column| format!("{column} = excluded.{column}"))
                .collect();
            sql.push_str(&format!(
                " ON CONFLICT (\"id\") DO UPDATE SET {}",
                updates.join(", ")
            ));
        }
        sql
    }

    /// id / created_at / data / promoted columns, in that order.
    /// `UPDATE` reuses it because its `SET` list is written in the
    /// same order with `id` first.
    fn write_values(&self, entity: &Entity<D>) -> SqliteResult<Vec<SqlValue>> {
        let data = entity.data();
        let base = data.entity();
        let id = base
            .id
            .clone()
            .ok_or_else(|| SqliteError::Other("entity has no id".into()))?;
        let created_at = base
            .created_at
            .unwrap_or_else(|| chrono::Utc::now().timestamp_millis());
        let json = serde_json::to_string(data)?;

        let mut values = vec![
            SqlValue::Text(id),
            SqlValue::Integer(created_at),
            SqlValue::Text(json),
        ];
        for column in &self.promoted {
            values.push(match (column.value)(data) {
                Some(value) => SqlValue::Text(value),
                None => SqlValue::Null,
            });
        }
        Ok(values)
    }
}

/// A JSON value as SQLite would store it.
///
/// Numbers stay numbers: this is what makes a range filter on a
/// document field compare numerically, since SQLite's `->>` also
/// yields a number. Bind an integer as text and `9 > 10` comes back
/// true, silently.
pub fn to_sql_value(value: &serde_json::Value) -> SqlValue {
    match value {
        serde_json::Value::Null => SqlValue::Null,
        serde_json::Value::Bool(flag) => SqlValue::Integer(i64::from(*flag)),
        serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
            (Some(int), _) => SqlValue::Integer(int),
            (None, Some(float)) => SqlValue::Real(float),
            _ => SqlValue::Text(number.to_string()),
        },
        serde_json::Value::String(text) => SqlValue::Text(text.clone()),
        // An array or object compared against a scalar extraction has
        // no useful SQL spelling; its JSON text at least matches what
        // `->` would return.
        other => SqlValue::Text(other.to_string()),
    }
}

fn decode<D>(json: &str) -> SqliteResult<Entity<D>>
where
    D: EntityFields + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    Ok(Entity::new(serde_json::from_str::<D>(json)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use wabot_core::entity::EntityData;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct ThingData {
        #[serde(flatten)]
        base: EntityData,
        name: String,
        total: i64,
    }

    impl EntityFields for ThingData {
        fn entity(&self) -> &EntityData {
            &self.base
        }
        fn entity_mut(&mut self) -> &mut EntityData {
            &mut self.base
        }
    }

    /// `create`, not `new`: `new` leaves `id` and `created_at` unset,
    /// and a store writing those columns needs them stamped.
    fn thing(name: &str, total: i64) -> Entity<ThingData> {
        Entity::create(ThingData {
            base: EntityData::default(),
            name: name.to_string(),
            total,
        })
    }

    async fn store() -> SqliteJsonbStore<ThingData> {
        SqliteJsonbStore::new(SqliteDatabase::in_memory().expect("open"), "things")
            .with_promoted_column(PromotedColumn {
                name: "owner_id",
                ddl_type: "TEXT",
                value: |d| Some(d.name.clone()),
            })
    }

    #[tokio::test]
    async fn insert_sql_covers_promoted_columns() {
        let sql = store().await.insert_sql(false);
        assert_eq!(
            sql,
            "INSERT INTO \"things\" (\"id\", \"created_at\", \"data\", \"owner_id\") \
             VALUES (?1, ?2, ?3, ?4)"
        );
    }

    #[tokio::test]
    async fn upsert_sql_updates_every_column_but_the_key() {
        let sql = store().await.insert_sql(true);
        assert!(sql.contains("ON CONFLICT (\"id\") DO UPDATE SET"));
        assert!(sql.contains("\"data\" = excluded.\"data\""));
        assert!(
            !sql.contains("\"id\" = excluded.\"id\""),
            "the conflict key must not be in the SET list"
        );
    }

    #[tokio::test]
    async fn an_entity_round_trips() {
        let store = store().await;
        let entity = thing("Ada", 10);
        store.create(&entity).await.expect("create");

        let found = store
            .find_by_id(entity.id())
            .await
            .expect("find")
            .expect("present");
        assert_eq!(found.data().name, "Ada");
        assert_eq!(found.data().total, 10);
        assert_eq!(found.id(), entity.id());
    }

    #[tokio::test]
    async fn create_refuses_a_duplicate_but_save_upserts() {
        let store = store().await;
        let entity = thing("Ada", 1);
        store.create(&entity).await.expect("create");
        assert!(store.create(&entity).await.is_err(), "the id is taken");

        let mut updated = entity.clone();
        updated.update(|data| data.total = 2);
        store.save(&updated).await.expect("save");

        let found = store.find_by_id(entity.id()).await.expect("find").unwrap();
        assert_eq!(found.data().total, 2);
    }

    #[tokio::test]
    async fn update_reports_whether_a_row_matched() {
        let store = store().await;
        let entity = thing("Ada", 1);
        assert!(
            !store.update(&entity).await.expect("update"),
            "nothing to update yet"
        );
        store.create(&entity).await.expect("create");
        assert!(store.update(&entity).await.expect("update"));
    }

    #[tokio::test]
    async fn a_promoted_column_is_written_and_indexable() {
        let store = store().await;
        store.create(&thing("Ada", 1)).await.expect("create");

        let count = store
            .count(
                "SELECT COUNT(*) FROM \"things\" WHERE \"owner_id\" = ?1",
                vec![SqlValue::Text("Ada".into())],
            )
            .await
            .expect("count");
        assert_eq!(count, 1);
    }

    /// The end-to-end version of the "no cast needed" claim in
    /// `query_sql`: a range filter on a document field has to compare
    /// numerically against a real database, not just render nicely.
    #[tokio::test]
    async fn a_document_field_compares_numerically() {
        let store = store().await;
        for total in [9, 10, 100] {
            store.create(&thing("x", total)).await.expect("create");
        }

        let found = store
            .find_by_query(&wabot_core::repository::Query::new().gt("total", 9))
            .await
            .expect("query");
        let mut totals: Vec<i64> = found.iter().map(|e| e.data().total).collect();
        totals.sort();
        assert_eq!(
            totals,
            vec![10, 100],
            "lexicographic comparison would have dropped 100 and kept nothing above 9"
        );
    }

    #[tokio::test]
    async fn membership_and_ordering_survive_a_real_query() {
        let store = store().await;
        for (name, total) in [("a", 1), ("b", 2), ("c", 3)] {
            store.create(&thing(name, total)).await.expect("create");
        }

        let found = store
            .find_by_query(
                &wabot_core::repository::Query::new()
                    .is_in("name", serde_json::json!(["a", "c"]))
                    .order_desc("total"),
            )
            .await
            .expect("query");

        assert_eq!(
            found
                .iter()
                .map(|e| e.data().name.as_str())
                .collect::<Vec<_>>(),
            vec!["c", "a"]
        );
    }

    /// A column added by a later build has to appear without dropping
    /// the table — and SQLite has no `ADD COLUMN IF NOT EXISTS`, so
    /// this is the path that reads the table back.
    #[tokio::test]
    async fn a_new_promoted_column_is_added_to_an_existing_table() {
        let database = SqliteDatabase::in_memory().expect("open");
        let first: SqliteJsonbStore<ThingData> = SqliteJsonbStore::new(database.clone(), "things");
        first.ensure_ready().await.expect("ready");

        let second = SqliteJsonbStore::<ThingData>::new(database.clone(), "things")
            .with_promoted_column(PromotedColumn {
                name: "total_col",
                ddl_type: "INTEGER",
                value: |d| Some(d.total.to_string()),
            });
        second.migrate_promoted_columns().await.expect("migrate");
        // Twice, because it runs on every boot.
        second
            .migrate_promoted_columns()
            .await
            .expect("migrating again is a no-op");

        second.create(&thing("Ada", 42)).await.expect("create");
        let count = second
            .count(
                "SELECT COUNT(*) FROM \"things\" WHERE \"total_col\" = ?1",
                vec![SqlValue::Text("42".into())],
            )
            .await
            .expect("count");
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn json_numbers_bind_as_numbers() {
        assert_eq!(
            to_sql_value(&serde_json::json!(7)),
            SqlValue::Integer(7),
            "an integer must not become text, or ordering comparisons go lexicographic"
        );
        assert_eq!(to_sql_value(&serde_json::json!(1.5)), SqlValue::Real(1.5));
        assert_eq!(to_sql_value(&serde_json::json!(true)), SqlValue::Integer(1));
        assert_eq!(to_sql_value(&serde_json::json!(null)), SqlValue::Null);
    }
}