Skip to main content

sqlx_json/
sqlite.rs

1//! [`RowExt`](crate::RowExt) implementation for `SQLite` rows.
2
3use sqlx::sqlite::SqliteRow;
4
5use crate::prelude::*;
6
7impl RowExt for SqliteRow {
8    fn to_json(&self) -> Value {
9        row_to_json(self)
10    }
11}
12
13impl DecodeCell for SqliteRow {
14    fn decode_cell(&self, idx: usize, type_name: &str) -> Cell {
15        match type_name {
16            "BOOLEAN" | "BOOL" => self.try_get(idx).map_or(Cell::Null, Cell::Bool),
17
18            "INTEGER" | "INT" | "BIGINT" | "SMALLINT" | "TINYINT" | "MEDIUMINT" => {
19                self.try_get(idx).map_or(Cell::Null, Cell::Int)
20            }
21
22            "REAL" | "FLOAT" | "DOUBLE" | "NUMERIC" => self.try_get(idx).map_or(Cell::Null, Cell::Float64),
23
24            "BLOB" => self.try_get(idx).map_or(Cell::Null, Cell::Bytes),
25
26            "TEXT" | "VARCHAR" | "CHAR" | "CLOB" | "DATE" | "DATETIME" | "TIMESTAMP" | "TIME" => {
27                self.try_get(idx).map_or(Cell::Null, Cell::Text)
28            }
29
30            // SQLite reports "NULL" type for expressions like COUNT(*), SUM().
31            // The value is not null (checked by the caller), so probe: i64 → f64 → String.
32            _ => dynamic_probe(self, idx),
33        }
34    }
35}
36
37/// Probes a `SQLite` value by trying types in order: i64 → f64 → String → Null.
38fn dynamic_probe(row: &SqliteRow, idx: usize) -> Cell {
39    if let Ok(n) = row.try_get::<i64, _>(idx) {
40        return Cell::Int(n);
41    }
42    if let Ok(f) = row.try_get::<f64, _>(idx) {
43        return Cell::Float64(f);
44    }
45    row.try_get::<String, _>(idx).map_or(Cell::Null, Cell::Text)
46}
47
48#[cfg(test)]
49mod tests {
50    use serde_json::json;
51    use sqlx::{Connection as _, SqliteConnection};
52
53    use super::*;
54
55    async fn fetch(setup: &'static str, query: &'static str) -> Value {
56        let mut conn = SqliteConnection::connect("sqlite::memory:")
57            .await
58            .expect("in-memory database opens");
59        sqlx::raw_sql(setup).execute(&mut conn).await.expect("setup runs");
60        sqlx::query(query)
61            .fetch_one(&mut conn)
62            .await
63            .expect("query returns a row")
64            .to_json()
65    }
66
67    #[tokio::test]
68    async fn declared_types_map_to_json_shapes() {
69        let row = fetch(
70            "CREATE TABLE t (b BOOLEAN, i INTEGER, r REAL, n NUMERIC, bl BLOB, tx TEXT, d DATE, ts TIMESTAMP);
71             INSERT INTO t VALUES (1, -5, 1.5, 2.25, X'68690A', 'abc', '2026-01-02', '2026-01-02 03:04:05');",
72            "SELECT * FROM t",
73        )
74        .await;
75
76        assert_eq!(
77            row,
78            json!({
79                "b": true,
80                "i": -5,
81                "r": 1.5,
82                "n": 2.25,
83                "bl": "aGkK",
84                "tx": "abc",
85                "d": "2026-01-02",
86                "ts": "2026-01-02 03:04:05",
87            })
88        );
89    }
90
91    #[tokio::test]
92    async fn null_values_are_json_null() {
93        let row = fetch(
94            "CREATE TABLE t (i INTEGER, tx TEXT, bl BLOB);
95             INSERT INTO t VALUES (NULL, NULL, NULL);",
96            "SELECT * FROM t",
97        )
98        .await;
99
100        assert_eq!(row, json!({ "i": null, "tx": null, "bl": null }));
101    }
102
103    #[tokio::test]
104    async fn untyped_expressions_are_probed() {
105        let row = fetch(
106            "CREATE TABLE t (i INTEGER, r REAL);
107             INSERT INTO t VALUES (1, 0.5), (2, 0.25);",
108            "SELECT COUNT(*) AS c, SUM(i) AS si, SUM(r) AS sr, 'x' || 'y' AS s FROM t",
109        )
110        .await;
111
112        assert_eq!(row, json!({ "c": 2, "si": 3, "sr": 0.75, "s": "xy" }));
113    }
114}