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
//! Turning a [`Query`] into SQLite SQL.
//!
//! Pure and database-free, so the interesting cases are unit tests
//! rather than integration tests. Deliberately a sibling of
//! `wabot-feature-pg`'s `query_sql`, not a shared abstraction — see
//! the note at the bottom of this file for why, and when that should
//! change.
//!
//! ## Four things SQLite does differently
//!
//! Each one is a silently-wrong result if you assume the Postgres
//! spelling works:
//!
//! 1. **Placeholders are `?n`.** `$n` parses in SQLite but means a
//!    *named* parameter, which rusqlite's positional binding will not
//!    fill.
//! 2. **`= ANY(?)` does not exist.** A membership test expands to one
//!    placeholder per element, so `In` consumes N of them and the
//!    caller has to flatten the array to match.
//! 3. **`->>` preserves types.** Postgres's `->>` always yields text,
//!    so a numeric comparison there needs `::numeric` or `"9" > "10"`
//!    comes out true. SQLite returns an INTEGER for an integer, so the
//!    cast is not merely unnecessary — `::numeric` is not SQLite
//!    syntax at all.
//! 4. **A JSON path is explicit.** `data->>'$."field"'`, with the
//!    label quoted, so a field name containing a `.` looks up that key
//!    instead of traversing into a nested object.
//!
//! ## Values never enter the string
//!
//! Every value becomes a `?n` placeholder. A field *name* does become
//! part of the statement, so it is validated against the columns the
//! store declared — an unknown one is an error, not an escaped
//! identifier.

use std::collections::HashSet;

use wabot_core::repository::query::{Direction, Query, QueryOperator};

/// Which fields are real columns.
#[derive(Debug, Clone)]
pub enum FieldPlacement {
    /// Document storage: these fields are promoted columns, the rest
    /// live in the JSON blob.
    Promoted(HashSet<String>),
    /// Columnar storage: every field is a column, and there is no blob
    /// to fall back to.
    All,
}

impl FieldPlacement {
    pub fn promoted<S: Into<String>>(fields: impl IntoIterator<Item = S>) -> Self {
        Self::Promoted(fields.into_iter().map(Into::into).collect())
    }

    pub fn none() -> Self {
        Self::Promoted(HashSet::new())
    }

    fn is_column(&self, field: &str) -> bool {
        matches!(field, "id" | "created_at" | "createdAt")
            || match self {
                FieldPlacement::All => true,
                FieldPlacement::Promoted(fields) => fields.contains(field),
            }
    }
}

#[derive(Debug, thiserror::Error, PartialEq)]
pub enum QuerySqlError {
    /// A field name reaches the statement as an identifier, so an
    /// unrecognised one is refused rather than quoted and hoped for.
    #[error("unknown field {field:?}: the columnar store has no such column")]
    UnknownField { field: String },
    #[error("{operator:?} on {field:?} needs a value")]
    MissingValue { field: String, operator: String },
    /// `In` / `NotIn` need a list to expand into placeholders.
    #[error("{operator:?} on {field:?} needs an array of values")]
    NotAList { field: String, operator: String },
}

/// A rendered `WHERE`/`ORDER BY`/`LIMIT` and how many placeholders it
/// used.
#[derive(Debug, Clone, PartialEq)]
pub struct BuiltQuery {
    /// Everything after the table: `WHERE … ORDER BY … LIMIT …`.
    /// Empty when the query selects everything.
    pub sql: String,
    /// Total `?n` slots. Equal to the number of *values* to bind,
    /// which is not the number of conditions once `In` is involved.
    pub placeholders: usize,
}

/// `id` / `createdAt` are what a caller writes; `created_at` is the
/// column.
fn column_for(field: &str) -> &str {
    match field {
        "createdAt" => "created_at",
        other => other,
    }
}

fn quote_ident(name: &str) -> String {
    format!("\"{}\"", name.replace('"', "\"\""))
}

/// A JSON path with the label quoted, so `a.b` is one key rather than
/// a traversal into `b`.
///
/// Two layers of escaping, which is why this is its own function: the
/// backslash-escape belongs to the JSON path grammar, and the doubled
/// single quote belongs to the surrounding SQL string literal.
fn json_path(field: &str) -> String {
    let label = field.replace('\\', "\\\\").replace('"', "\\\"");
    format!("'$.\"{}\"'", label.replace('\'', "''"))
}

/// The SQL for one field.
///
/// Public to the crate so an *index* can be built on the very same
/// expression a query filters on — an index on anything else is one
/// the planner will not use.
pub fn field_expression(field: &str, placement: &FieldPlacement) -> String {
    if placement.is_column(field) {
        quote_ident(column_for(field))
    } else {
        // No cast: unlike Postgres, SQLite's `->>` gives back an
        // INTEGER for an integer and a REAL for a float, so ordering
        // comparisons are already numeric.
        format!("\"data\"->>{}", json_path(field))
    }
}

/// Flatten a query's values in the order the rendered placeholders
/// expect them.
///
/// Not the same as [`Query::bind_values`]: an `In` condition holds one
/// array but renders N placeholders, so the array has to be unpacked
/// here or every value after it binds to the wrong slot.
pub fn bind_values(query: &Query) -> Result<Vec<serde_json::Value>, QuerySqlError> {
    let mut values = Vec::with_capacity(query.conditions.len());
    for condition in &query.conditions {
        if !condition.operator.takes_value() {
            continue;
        }
        let Some(value) = &condition.value else {
            return Err(QuerySqlError::MissingValue {
                field: condition.field.clone(),
                operator: format!("{:?}", condition.operator),
            });
        };
        match condition.operator {
            QueryOperator::In | QueryOperator::NotIn => match value {
                serde_json::Value::Array(items) => values.extend(items.iter().cloned()),
                _ => {
                    return Err(QuerySqlError::NotAList {
                        field: condition.field.clone(),
                        operator: format!("{:?}", condition.operator),
                    })
                }
            },
            _ => values.push(value.clone()),
        }
    }
    Ok(values)
}

/// Render the tail of a SELECT/DELETE for `query`.
///
/// `placement` decides which fields are columns. In
/// [`FieldPlacement::All`] an unknown field is an error, because there
/// is no blob it could have lived in; with promoted columns it falls
/// back to the document.
pub fn build_query_sql(
    query: &Query,
    placement: &FieldPlacement,
    columns: Option<&HashSet<String>>,
) -> Result<BuiltQuery, QuerySqlError> {
    let mut sql = String::new();
    let mut placeholders = 0usize;

    let known = |field: &str| -> Result<(), QuerySqlError> {
        match columns {
            Some(columns)
                if !columns.contains(field)
                    && !matches!(field, "id" | "created_at" | "createdAt") =>
            {
                Err(QuerySqlError::UnknownField {
                    field: field.to_string(),
                })
            }
            _ => Ok(()),
        }
    };

    if !query.conditions.is_empty() {
        let mut rendered = Vec::with_capacity(query.conditions.len());
        for condition in &query.conditions {
            known(&condition.field)?;
            let lhs = field_expression(&condition.field, placement);

            if condition.operator.takes_value() && condition.value.is_none() {
                return Err(QuerySqlError::MissingValue {
                    field: condition.field.clone(),
                    operator: format!("{:?}", condition.operator),
                });
            }

            let mut slot = || {
                placeholders += 1;
                format!("?{placeholders}")
            };

            rendered.push(match condition.operator {
                QueryOperator::IsNull => format!("{lhs} IS NULL"),
                QueryOperator::IsNotNull => format!("{lhs} IS NOT NULL"),
                QueryOperator::Equals => format!("{lhs} = {}", slot()),
                QueryOperator::Not => format!("{lhs} <> {}", slot()),
                QueryOperator::Gt => format!("{lhs} > {}", slot()),
                QueryOperator::Gte => format!("{lhs} >= {}", slot()),
                QueryOperator::Lt => format!("{lhs} < {}", slot()),
                QueryOperator::Lte => format!("{lhs} <= {}", slot()),
                QueryOperator::Like => format!("{lhs} LIKE {}", slot()),
                QueryOperator::NotLike => format!("{lhs} NOT LIKE {}", slot()),
                QueryOperator::In | QueryOperator::NotIn => {
                    let list = expand_in(condition, &mut placeholders)?;
                    let negate = matches!(condition.operator, QueryOperator::NotIn);
                    match (negate, list.is_empty()) {
                        // `x IN ()` is a syntax error in SQLite, and an
                        // empty set has an unambiguous answer anyway.
                        (false, true) => "0 = 1".to_string(),
                        (true, true) => "1 = 1".to_string(),
                        (false, false) => format!("{lhs} IN ({})", list.join(", ")),
                        (true, false) => format!("{lhs} NOT IN ({})", list.join(", ")),
                    }
                }
            });
        }
        sql.push_str(" WHERE ");
        sql.push_str(&rendered.join(" AND "));
    }

    if !query.order.is_empty() {
        let mut parts = Vec::with_capacity(query.order.len());
        for (field, direction) in &query.order {
            known(field)?;
            parts.push(format!(
                "{} {}",
                field_expression(field, placement),
                match direction {
                    Direction::Asc => "ASC",
                    Direction::Desc => "DESC",
                }
            ));
        }
        sql.push_str(" ORDER BY ");
        sql.push_str(&parts.join(", "));
    }

    // Rendered rather than bound: they are numbers this code produced,
    // never a caller's string, and inlining keeps the placeholder
    // numbering aligned with `bind_values`.
    if let Some(limit) = query.limit {
        sql.push_str(&format!(" LIMIT {limit}"));
    }
    if let Some(offset) = query.offset {
        // SQLite refuses OFFSET without LIMIT; -1 is its documented
        // spelling for "no limit".
        if query.limit.is_none() {
            sql.push_str(" LIMIT -1");
        }
        sql.push_str(&format!(" OFFSET {offset}"));
    }

    Ok(BuiltQuery { sql, placeholders })
}

fn expand_in(
    condition: &wabot_core::repository::query::Condition,
    placeholders: &mut usize,
) -> Result<Vec<String>, QuerySqlError> {
    let Some(serde_json::Value::Array(items)) = &condition.value else {
        return Err(QuerySqlError::NotAList {
            field: condition.field.clone(),
            operator: format!("{:?}", condition.operator),
        });
    };
    Ok(items
        .iter()
        .map(|_| {
            *placeholders += 1;
            format!("?{placeholders}")
        })
        .collect())
}

// A note for whoever adds the third backend, or gets tired of reading
// this file next to the Postgres one:
//
// The obvious move is a `SqlDialect` in `wabot-core` that both crates
// render through. It is probably right — but it was deliberately not
// done when this file was written, because a dialect abstraction
// designed against one implementation is a guess. Now that there are
// two, the differences are visible and small (placeholder syntax, `IN`
// expansion, the JSON extraction and its cast), and the extraction can
// be driven by what actually differs rather than by what might.
//
// Do it before a third backend, not after: two files drifting is
// annoying, three is a bug farm.

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

    fn columnar() -> FieldPlacement {
        FieldPlacement::All
    }

    fn built(query: &Query, placement: &FieldPlacement) -> String {
        build_query_sql(query, placement, None).unwrap().sql
    }

    #[test]
    fn an_empty_query_adds_nothing() {
        assert_eq!(built(&Query::new(), &columnar()), "");
    }

    #[test]
    fn conditions_become_and_ed_placeholders() {
        let sql = built(
            &Query::new().eq("owner_id", "u-1").gt("total", 100),
            &columnar(),
        );
        assert_eq!(sql, " WHERE \"owner_id\" = ?1 AND \"total\" > ?2");
    }

    #[test]
    fn every_operator_renders() {
        let query = Query::new()
            .eq("a", 1)
            .not("b", 1)
            .gt("c", 1)
            .gte("d", 1)
            .lt("e", 1)
            .lte("f", 1)
            .like("g", "x%")
            .not_like("h", "x%")
            .is_in("i", json!([1]))
            .not_in("j", json!([1]))
            .is_null("k")
            .is_not_null("l");

        let built = build_query_sql(&query, &columnar(), None).unwrap();
        assert!(built.sql.contains("\"a\" = ?1"));
        assert!(built.sql.contains("\"b\" <> ?2"));
        assert!(built.sql.contains("\"g\" LIKE ?7"));
        assert!(built.sql.contains("\"i\" IN (?9)"));
        assert!(built.sql.contains("\"j\" NOT IN (?10)"));
        assert!(built.sql.contains("\"k\" IS NULL"));
        assert!(built.sql.contains("\"l\" IS NOT NULL"));
        assert_eq!(built.placeholders, 10);
        assert_eq!(
            built.placeholders,
            bind_values(&query).unwrap().len(),
            "placeholders and bind values must agree, or every value lands on the wrong condition"
        );
    }

    /// The divergence most likely to be got wrong by porting the
    /// Postgres spelling: one array becomes N placeholders, so the
    /// values after it shift.
    #[test]
    fn membership_expands_to_one_placeholder_per_element() {
        let query = Query::new()
            .eq("before", "x")
            .is_in("status", json!(["open", "paid", "void"]))
            .eq("after", "y");

        let built = build_query_sql(&query, &columnar(), None).unwrap();
        assert_eq!(
            built.sql,
            " WHERE \"before\" = ?1 AND \"status\" IN (?2, ?3, ?4) AND \"after\" = ?5"
        );
        assert_eq!(built.placeholders, 5);

        let values = bind_values(&query).unwrap();
        assert_eq!(values.len(), 5, "the array was flattened");
        assert_eq!(
            values[4],
            json!("y"),
            "the value after the list still lines up"
        );
    }

    /// `x IN ()` is a syntax error in SQLite, but an empty set has an
    /// obvious answer — so it becomes a constant rather than a crash.
    #[test]
    fn an_empty_membership_list_is_a_constant() {
        let sql = built(&Query::new().is_in("s", json!([])), &columnar());
        assert_eq!(sql, " WHERE 0 = 1");

        let sql = built(&Query::new().not_in("s", json!([])), &columnar());
        assert_eq!(sql, " WHERE 1 = 1");
    }

    /// Where SQLite is *better* than Postgres, and the reason there is
    /// no `::numeric` anywhere in this file: `->>` keeps the type.
    #[test]
    fn a_json_field_needs_no_cast() {
        let placement = FieldPlacement::promoted(["owner_id"]);

        assert_eq!(
            built(&Query::new().gt("total", 100), &placement),
            " WHERE \"data\"->>'$.\"total\"' > ?1"
        );
        assert_eq!(
            built(&Query::new().gt("owner_id", "a"), &placement),
            " WHERE \"owner_id\" > ?1",
            "a promoted column is already typed"
        );
    }

    #[test]
    fn the_reserved_columns_are_always_native() {
        let placement = FieldPlacement::none();
        assert_eq!(
            built(&Query::new().gt("createdAt", 1).eq("id", "x"), &placement),
            " WHERE \"created_at\" > ?1 AND \"id\" = ?2",
            "`createdAt` is the field name; `created_at` is the column"
        );
    }

    #[test]
    fn ordering_limit_and_offset_are_rendered() {
        let sql = built(
            &Query::new()
                .order_desc("created_at")
                .order_asc("id")
                .limit(20)
                .offset(40),
            &columnar(),
        );
        assert_eq!(
            sql,
            " ORDER BY \"created_at\" DESC, \"id\" ASC LIMIT 20 OFFSET 40"
        );
    }

    /// SQLite refuses `OFFSET` without `LIMIT`, where Postgres accepts
    /// it — so the builder supplies the documented "no limit" value.
    #[test]
    fn an_offset_without_a_limit_still_parses() {
        let sql = built(&Query::new().offset(10), &columnar());
        assert_eq!(sql, " LIMIT -1 OFFSET 10");
    }

    /// A field name becomes part of the statement, so an unknown one
    /// is refused rather than quoted and hoped for.
    #[test]
    fn an_unknown_field_is_refused_when_the_columns_are_known() {
        let columns: HashSet<String> = ["owner_id".to_string()].into_iter().collect();

        assert!(build_query_sql(
            &Query::new().eq("owner_id", "u-1"),
            &columnar(),
            Some(&columns)
        )
        .is_ok());

        let error = build_query_sql(
            &Query::new().eq("total; DROP TABLE orders", 1),
            &columnar(),
            Some(&columns),
        )
        .unwrap_err();
        assert!(
            matches!(error, QuerySqlError::UnknownField { .. }),
            "{error}"
        );

        let error = build_query_sql(&Query::new().order_asc("nope"), &columnar(), Some(&columns))
            .unwrap_err();
        assert!(
            matches!(error, QuerySqlError::UnknownField { .. }),
            "ordering too"
        );
    }

    /// Even without a column list a hostile field name cannot break
    /// out: an identifier's quotes are doubled, and a JSON label is
    /// escaped for both the path grammar and the SQL literal around
    /// it.
    #[test]
    fn identifiers_and_json_labels_are_escaped() {
        assert_eq!(
            built(&Query::new().eq("we\"ird", 1), &columnar()),
            " WHERE \"we\"\"ird\" = ?1"
        );
        assert_eq!(
            built(&Query::new().eq("we'ird", 1), &FieldPlacement::none()),
            " WHERE \"data\"->>'$.\"we''ird\"' = ?1"
        );
        assert_eq!(
            built(&Query::new().eq("we\"ird", 1), &FieldPlacement::none()),
            " WHERE \"data\"->>'$.\"we\\\"ird\"' = ?1"
        );
    }

    #[test]
    fn a_value_less_comparison_is_an_error_not_a_broken_statement() {
        let query = Query::new().condition(wabot_core::repository::query::Condition {
            field: "total".into(),
            operator: QueryOperator::Gt,
            value: None,
        });
        assert!(matches!(
            build_query_sql(&query, &columnar(), None),
            Err(QuerySqlError::MissingValue { .. })
        ));
    }

    #[test]
    fn membership_against_a_non_list_is_an_error() {
        let query = Query::new().is_in("s", json!("not-a-list"));
        assert!(matches!(
            build_query_sql(&query, &columnar(), None),
            Err(QuerySqlError::NotAList { .. })
        ));
        assert!(matches!(
            bind_values(&query),
            Err(QuerySqlError::NotAList { .. })
        ));
    }
}