keelson-gen 0.1.0

keelson's code generator: introspect a live schema, emit readable model .rs files against keelson-models.
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! SQLite inference, over `sqlite3-parser` (`lemon-rs` — SQLite's own
//! `parse.y` and lexer, ported C→Rust), the same parser keelson-sqlcheck's
//! grammar tier judges with.
//!
//! The rules are [`super`](crate::queries)'s decision table, unchanged: the
//! nullability half is a property of the SQL, not of the engine, so N1–N16
//! mean here exactly what they mean for PostgreSQL. What differs is the type
//! half, and only because SQLite's schema carries less: a declared type is a
//! hint about affinity, so `SUM(x)` over an `INTEGER` column is `i64` rather
//! than PostgreSQL's widened `numeric`, and an expression the type table
//! cannot place needs a `-- column:` annotation more often. That is the
//! schema's limit, recorded, not a weaker analyser.

use std::collections::BTreeMap;

use sqlite3_parser::ast;
use sqlite3_parser::{Bump, FallibleIterator, lexer::sql::Parser};

use crate::config::{Config, Dialect};
use crate::error::{GenError, Result};
use crate::queries::ir::{Analysis, OutputColumn};
use crate::queries::lex;
use crate::queries::nest;
use crate::queries::spec::QuerySpec;
use crate::schema::{Schema, TableDef};

/// Placeholder number → (suggested name, Rust type, which rule found it).
type ParamMap = BTreeMap<usize, (String, String, &'static str)>;

/// One `FROM` item and whether a join can make its columns NULL.
#[derive(Debug, Clone)]
struct Source {
    key: String,
    table: Option<TableDef>,
    outer: bool,
}

struct Scope<'a> {
    schema: &'a Schema,
    config: &'a Config,
    spec: &'a QuerySpec,
    sources: Vec<Source>,
}

/// What one expression yielded. The SQLite twin of the psql analyser's.
#[derive(Debug, Clone)]
struct Inferred {
    rust_type: Option<String>,
    nullable: bool,
    outer_join: bool,
    inner_nullable: bool,
    rule: &'static str,
    name: Option<String>,
}

impl Inferred {
    fn new(rust_type: Option<String>, nullable: bool, rule: &'static str) -> Inferred {
        Inferred {
            rust_type,
            nullable,
            outer_join: false,
            inner_nullable: nullable,
            rule,
            name: None,
        }
    }

    fn known(t: &str, nullable: bool, rule: &'static str) -> Inferred {
        Inferred::new(Some(t.to_owned()), nullable, rule)
    }

    fn unknown(rule: &'static str) -> Inferred {
        Inferred::new(None, true, rule)
    }

    fn named(mut self, name: &str) -> Inferred {
        self.name = Some(name.to_owned());
        self
    }
}

/// Analyse one SQLite query.
pub fn analyse(
    schema: &Schema,
    config: &Config,
    spec: &QuerySpec,
    source: &str,
) -> Result<Analysis> {
    let sql = spec.sql(source);
    let tokens = lex::scan_sqlite(sql, spec.sql_start)
        .map_err(|e| GenError::Config(format!("query `{}`: {e}", spec.name)))?;
    let placeholders = lex::placeholders(&tokens);
    let clauses = lex::clauses(&tokens, spec.sql_start, spec.sql_end);

    let arena = Bump::new();
    let mut parser = Parser::new(&arena, sql.as_bytes());
    let cmd = parser
        .next()
        .map_err(|e| GenError::Config(format!("query `{}`: SQLite rejected it: {e}", spec.name)))?
        .ok_or_else(|| GenError::Config(format!("query `{}`: no statement", spec.name)))?;

    let ast::Cmd::Stmt(stmt) = cmd else {
        return Err(GenError::Unsupported(format!(
            "query `{}`: only a statement can be generated from",
            spec.name
        )));
    };

    // A mutation is typed from its `RETURNING` list (empty for `:exec`) and
    // its `WHERE`; it has no mod face, which `lex::clauses` has already said.
    let mutation = match &stmt {
        ast::Stmt::Update {
            tbl_name,
            from,
            where_clause,
            returning,
            ..
        } => Some((tbl_name, from.as_ref(), where_clause.as_ref(), *returning)),
        ast::Stmt::Delete {
            tbl_name,
            where_clause,
            returning,
            ..
        } => Some((tbl_name, None, where_clause.as_ref(), *returning)),
        _ => None,
    };
    if let Some((tbl_name, from, where_clause, returning)) = mutation {
        let mut scope = Scope {
            schema,
            config,
            spec,
            sources: Vec::new(),
        };
        scope.add_named_table(&name(&tbl_name.name), None, &spec.name)?;
        if let Some(from) = from {
            scope.collect_from(from, &spec.name)?;
        }
        let outputs = scope.outputs(returning.unwrap_or(&[]))?;
        let mut found = ParamMap::new();
        if let Some(w) = where_clause {
            scope.walk_params(w, &mut found);
        }
        let params = crate::queries::assemble_params(spec, &placeholders, &found, '?')?;
        return Ok(Analysis {
            spec: spec.clone(),
            outputs,
            params,
            placeholders,
            clauses,
        });
    }

    let ast::Stmt::Select(select) = &stmt else {
        return Err(GenError::Unsupported(format!(
            "query `{}`: {} is not a statement this generator can type",
            spec.name,
            stmt_kind(&stmt)
        )));
    };

    // Rule N14: every arm of a compound select contributes to one row type, so
    // a column nullable in any arm is nullable in the result.
    let (mut outputs, mut found) = one_select(schema, config, spec, &select.body.select)?;
    for compound in select.body.compounds.iter().flat_map(|c| c.iter()) {
        let (right, right_found) = one_select(schema, config, spec, &compound.select)?;
        if outputs.len() != right.len() {
            return Err(GenError::Config(format!(
                "query `{}`: the arms of the compound select return {} and {} columns",
                spec.name,
                outputs.len(),
                right.len()
            )));
        }
        for (l, r) in outputs.iter_mut().zip(&right) {
            if l.rust_type != r.rust_type {
                return Err(GenError::Config(format!(
                    "query `{}`: column `{}` is `{}` in one arm of the compound select and \
                     `{}` in another; cast them to the same type or add `-- column:`",
                    spec.name, l.name, l.rust_type, r.rust_type
                )));
            }
            if r.nullable {
                l.nullable = true;
                l.inner_nullable = true;
                l.outer_join = false;
                l.rule = "N14";
            }
        }
        for (k, v) in right_found {
            found.entry(k).or_insert(v);
        }
    }

    if let Some(limit) = select.limit {
        note_limit(&limit.expr, "limit", &mut found);
        if let Some(offset) = &limit.offset {
            note_limit(offset, "offset", &mut found);
        }
    }
    let params = crate::queries::assemble_params(spec, &placeholders, &found, '?')?;

    Ok(Analysis {
        spec: spec.clone(),
        outputs,
        params,
        placeholders,
        clauses,
    })
}

/// One arm of a (possibly compound) `SELECT`, with its own `FROM` scope.
fn one_select(
    schema: &Schema,
    config: &Config,
    spec: &QuerySpec,
    one: &ast::OneSelect<'_>,
) -> Result<(Vec<OutputColumn>, ParamMap)> {
    let ast::OneSelect::Select {
        columns,
        from,
        where_clause,
        having,
        ..
    } = one
    else {
        return Err(GenError::Unsupported(format!(
            "query `{}`: a bare VALUES has no schema to type against",
            spec.name
        )));
    };
    let mut scope = Scope {
        schema,
        config,
        spec,
        sources: Vec::new(),
    };
    if let Some(from) = from {
        scope.collect_from(from, &spec.name)?;
    }
    let outputs = scope.outputs(columns)?;
    let mut found = ParamMap::new();
    // A placeholder can sit anywhere an expression can, so every expression
    // slot of the arm is walked — not only the `WHERE`.
    for c in *columns {
        if let ast::ResultColumn::Expr(e, _) = c {
            scope.walk_params(e, &mut found);
        }
    }
    if let Some(from) = from {
        for join in from.joins.iter().flat_map(|j| j.iter()) {
            if let Some(ast::JoinConstraint::On(on)) = &join.constraint {
                scope.walk_params(on, &mut found);
            }
        }
    }
    if let Some(w) = where_clause {
        scope.walk_params(w, &mut found);
    }
    if let Some(h) = having {
        scope.walk_params(h, &mut found);
    }
    Ok((outputs, found))
}

fn stmt_kind(stmt: &ast::Stmt<'_>) -> &'static str {
    match stmt {
        ast::Stmt::Insert { .. } => "INSERT",
        ast::Stmt::Update { .. } => "UPDATE",
        ast::Stmt::Delete { .. } => "DELETE",
        _ => "this statement",
    }
}

fn note_limit(expr: &ast::Expr<'_>, what: &'static str, out: &mut ParamMap) {
    if let ast::Expr::Variable(v) = expr
        && let Some(n) = crate::queries::spec::placeholder_number(v)
    {
        out.entry(n)
            .or_insert((what.to_owned(), "i64".to_owned(), "P3"));
    }
}

impl Scope<'_> {
    fn table(&self, name: &str) -> Option<&TableDef> {
        self.schema.tables.iter().find(|t| t.name == name)
    }

    fn collect_from(&mut self, from: &ast::FromClause<'_>, query: &str) -> Result<()> {
        if let Some(first) = from.select {
            self.add_table(first, false, query)?;
        }
        for join in from.joins.iter().flat_map(|j| j.iter()) {
            // A join whose operator carries LEFT (or FULL) makes the right
            // side's columns nullable — rule N2. SQLite has no RIGHT JOIN
            // before 3.39 and spells the rest the same way.
            let outer = matches!(
                join.operator,
                ast::JoinOperator::TypedJoin(Some(t))
                    if t.contains(ast::JoinType::LEFT) || t.contains(ast::JoinType::RIGHT)
            );
            if matches!(
                join.operator,
                ast::JoinOperator::TypedJoin(Some(t)) if t.contains(ast::JoinType::RIGHT)
            ) {
                for s in &mut self.sources {
                    s.outer = true;
                }
            }
            self.add_table(&join.table, outer, query)?;
        }
        Ok(())
    }

    /// Put one introspected table into scope under `alias` (or its own name).
    fn add_named_table(&mut self, relname: &str, alias: Option<String>, query: &str) -> Result<()> {
        let table = self.table(relname).cloned().ok_or_else(|| {
            GenError::Config(format!(
                "query `{query}`: `{relname}` is not a table or view in the introspected schema"
            ))
        })?;
        self.sources.push(Source {
            key: alias.unwrap_or_else(|| relname.to_owned()),
            table: Some(table),
            outer: false,
        });
        Ok(())
    }

    fn add_table(&mut self, t: &ast::SelectTable<'_>, outer: bool, query: &str) -> Result<()> {
        match t {
            ast::SelectTable::Table(qname, alias, _) => {
                let relname = name(&qname.name);
                let table = self.table(&relname).cloned().ok_or_else(|| {
                    GenError::Config(format!(
                        "query `{query}`: `{relname}` is not a table or view in the introspected \
                         schema"
                    ))
                })?;
                let key = alias
                    .as_ref()
                    .map(alias_name)
                    .unwrap_or_else(|| relname.clone());
                self.sources.push(Source {
                    key,
                    table: Some(table),
                    outer,
                });
                Ok(())
            }
            ast::SelectTable::Select(_, alias) | ast::SelectTable::Sub(_, alias) => {
                self.sources.push(Source {
                    key: alias.as_ref().map(alias_name).unwrap_or_default(),
                    table: None,
                    outer,
                });
                Ok(())
            }
            ast::SelectTable::TableCall(..) => Err(GenError::Unsupported(format!(
                "query `{query}`: a table-valued function in FROM cannot be typed"
            ))),
        }
    }

    fn column(&self, qualifier: Option<&str>, name: &str, query: &str) -> Result<Inferred> {
        let candidates: Vec<&Source> = match qualifier {
            Some(q) => self.sources.iter().filter(|s| s.key == q).collect(),
            None => self.sources.iter().collect(),
        };
        if candidates.is_empty() {
            return Err(GenError::Config(format!(
                "query `{query}`: `{}` refers to nothing in FROM",
                qualifier.unwrap_or(name)
            )));
        }
        let mut hits = Vec::new();
        for s in candidates {
            let Some(table) = &s.table else {
                return Err(GenError::Unsupported(format!(
                    "query `{query}`: `{name}` comes from a sub-select the generator does not \
                     look inside; give the column an `-- column:` annotation"
                )));
            };
            if let Some(c) = table.column(name) {
                hits.push((s, table, c));
            }
        }
        match hits.as_slice() {
            [] => Err(GenError::Config(format!(
                "query `{query}`: no column `{name}` in {}",
                self.sources
                    .iter()
                    .map(|s| s.key.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ))),
            [(s, table, c)] => {
                let resolved =
                    crate::typemap::resolve(Dialect::Sqlite, &self.config.types, table, c)?;
                let (nullable, rule) = if s.outer {
                    (true, "N2")
                } else {
                    (c.nullable, "N1")
                };
                Ok(Inferred {
                    rust_type: Some(resolved.rust_type),
                    nullable,
                    outer_join: s.outer,
                    inner_nullable: c.nullable,
                    rule,
                    name: Some(name.to_owned()),
                })
            }
            _ => Err(GenError::Config(format!(
                "query `{query}`: `{name}` is ambiguous — qualify it"
            ))),
        }
    }

    fn outputs(&self, columns: &[ast::ResultColumn<'_>]) -> Result<Vec<OutputColumn>> {
        let query = &self.spec.name;
        let mut out = Vec::new();
        for c in columns {
            match c {
                ast::ResultColumn::Star => {
                    for s in &self.sources {
                        self.expand(s, &mut out)?;
                    }
                }
                ast::ResultColumn::TableStar(id) => {
                    let key = name(id);
                    let s = self.sources.iter().find(|s| s.key == key).ok_or_else(|| {
                        GenError::Config(format!(
                            "query `{query}`: `{key}.*` refers to nothing in FROM"
                        ))
                    })?;
                    self.expand(s, &mut out)?;
                }
                ast::ResultColumn::Expr(e, alias) => {
                    let inferred = self.infer(e)?;
                    let name = match alias {
                        Some(a) => alias_name(a),
                        None => inferred.name.clone().ok_or_else(|| {
                            GenError::Config(format!(
                                "query `{query}`: an output column has no name of its own; add \
                                 an `AS` alias"
                            ))
                        })?,
                    };
                    out.push(self.finish(&name, inferred)?);
                }
            }
        }
        if out.is_empty() && self.spec.cardinality.returns_rows() {
            return Err(GenError::Config(format!(
                "query `{query}`: rows were asked for but the statement returns no columns"
            )));
        }
        Ok(out)
    }

    fn expand(&self, s: &Source, out: &mut Vec<OutputColumn>) -> Result<()> {
        let query = &self.spec.name;
        let Some(table) = &s.table else {
            return Err(GenError::Unsupported(format!(
                "query `{query}`: `*` over a sub-select cannot be expanded; list the columns"
            )));
        };
        for c in &table.columns {
            if !self.config.includes_column(&table.name, &c.name) {
                continue;
            }
            let inferred = self.column(Some(&s.key), &c.name, query)?;
            out.push(self.finish(&c.name, inferred)?);
        }
        Ok(())
    }

    fn finish(&self, name: &str, inferred: Inferred) -> Result<OutputColumn> {
        let query = &self.spec.name;
        let (rust_type, mut rule) = match self.spec.column_types.get(name) {
            Some(t) => (t.clone(), "A1"),
            None => (
                inferred.rust_type.ok_or_else(|| {
                    GenError::Config(format!(
                        "query `{query}`: the type of output column `{name}` cannot be inferred \
                         ({}); add `-- column: {name} <RustType>`",
                        inferred.rule
                    ))
                })?,
                inferred.rule,
            ),
        };
        let mut nullable = inferred.nullable;
        let mut outer_join = inferred.outer_join;
        let mut inner_nullable = inferred.inner_nullable;
        if let Some(n) = self.spec.column_nullable.get(name) {
            nullable = *n;
            inner_nullable = *n;
            outer_join = false;
            rule = "N16";
        }
        let (nesting, field) = nest::split(name, self.spec.prefix.as_deref());
        Ok(OutputColumn {
            name: name.to_owned(),
            field,
            nesting,
            rust_type,
            nullable,
            outer_join,
            inner_nullable,
            rule,
        })
    }

    // --- expressions -------------------------------------------------------

    fn infer(&self, e: &ast::Expr<'_>) -> Result<Inferred> {
        let query = &self.spec.name;
        Ok(match e {
            ast::Expr::Id(id) => self.column(None, &id_name(id), query)?,
            ast::Expr::Name(id) => self.column(None, &name(id), query)?,
            ast::Expr::Qualified(q, id) => self.column(Some(&name(q)), &name(id), query)?,
            ast::Expr::DoublyQualified(_, q, id) => {
                self.column(Some(&name(q)), &name(id), query)?
            }
            ast::Expr::Literal(lit) => literal(lit),
            ast::Expr::Cast { expr, type_name } => {
                let inner = self.infer(expr)?;
                let target = type_name.as_ref().map(|t| t.name.to_string());
                match target.as_deref().and_then(sqlite_type_to_rust) {
                    Some(t) => Inferred::known(t, inner.nullable, "N13"),
                    None => Inferred::unknown("N13"),
                }
            }
            ast::Expr::Binary(l, op, r) => {
                let (li, ri) = (self.infer(l)?, self.infer(r)?);
                let nullable = li.nullable || ri.nullable;
                match op {
                    ast::Operator::Equals
                    | ast::Operator::NotEquals
                    | ast::Operator::Less
                    | ast::Operator::LessEquals
                    | ast::Operator::Greater
                    | ast::Operator::GreaterEquals => {
                        Inferred::known("i64", nullable, "N10").named("bool")
                    }
                    // Rule N11: `IS` / `IS NOT` is the one comparison that
                    // answers rather than propagating — SQLite spells
                    // `x IS NOT NULL` this way instead of as a null test.
                    ast::Operator::Is | ast::Operator::IsNot => {
                        Inferred::known("i64", false, "N11").named("bool")
                    }
                    ast::Operator::And | ast::Operator::Or => {
                        Inferred::known("i64", nullable, "N10").named("bool")
                    }
                    ast::Operator::Concat => {
                        Inferred::known("String", nullable, "N10").named("concat")
                    }
                    _ => {
                        let ty = li.rust_type.clone().or_else(|| ri.rust_type.clone());
                        Inferred::new(ty, nullable, "N10").named("expr")
                    }
                }
            }
            ast::Expr::Unary(_, inner) => {
                let i = self.infer(inner)?;
                Inferred::new(i.rust_type, i.nullable, "N10").named("expr")
            }
            ast::Expr::Parenthesized(inner) => match inner.first() {
                Some(first) => self.infer(first)?,
                None => Inferred::unknown("U0"),
            },
            ast::Expr::IsNull(_) | ast::Expr::NotNull(_) => {
                Inferred::known("i64", false, "N11").named("bool")
            }
            ast::Expr::Exists(_) => Inferred::known("i64", false, "N11").named("exists"),
            ast::Expr::InList { .. } | ast::Expr::InSelect { .. } | ast::Expr::InTable { .. } => {
                Inferred::known("i64", false, "N11").named("bool")
            }
            ast::Expr::Between { lhs, .. } => {
                let i = self.infer(lhs)?;
                Inferred::known("i64", i.nullable, "N10").named("bool")
            }
            ast::Expr::Like { lhs, .. } => {
                let i = self.infer(lhs)?;
                Inferred::known("i64", i.nullable, "N10").named("bool")
            }
            ast::Expr::Case {
                when_then_pairs,
                else_expr,
                ..
            } => {
                // Rule N9.
                let mut ty: Option<String> = None;
                let mut nullable = else_expr.is_none();
                for (_, then) in when_then_pairs.iter() {
                    let i = self.infer(then)?;
                    if ty.is_none() {
                        ty.clone_from(&i.rust_type);
                    }
                    nullable |= i.nullable;
                }
                if let Some(e) = else_expr {
                    let i = self.infer(e)?;
                    if ty.is_none() {
                        ty = i.rust_type;
                    }
                    nullable |= i.nullable;
                }
                Inferred::new(ty, nullable, "N9").named("case")
            }
            ast::Expr::Subquery(_) => Inferred::unknown("N12"),
            // As in the psql analyser: a bound parameter is a value, not a
            // source of NULL, so rule N10 does not propagate from it.
            ast::Expr::Variable(_) => Inferred::new(None, false, "P0"),
            ast::Expr::FunctionCall {
                name: fname, args, ..
            } => self.infer_call(&unquote(fname.0), args.unwrap_or(&[]))?,
            ast::Expr::FunctionCallStar { name: fname, .. } => {
                self.infer_call(&unquote(fname.0), &[])?
            }
            _ => Inferred::unknown("U0"),
        })
    }

    fn infer_call(&self, name: &str, args: &[ast::Expr<'_>]) -> Result<Inferred> {
        let lower = name.to_ascii_lowercase();
        let first = match args.first() {
            Some(a) => Some(self.infer(a)?),
            None => None,
        };
        let arg_type = first.as_ref().and_then(|i| i.rust_type.clone());
        let arg_nullable = first.as_ref().is_some_and(|i| i.nullable);

        Ok(match lower.as_str() {
            // Rule N4.
            "count" => Inferred::known("i64", false, "N4").named("count"),
            // Rule N7: SQLite's coalesce/ifnull.
            "coalesce" | "ifnull" => {
                let mut ty = None;
                let mut nullable = true;
                for a in args {
                    let i = self.infer(a)?;
                    if ty.is_none() {
                        ty.clone_from(&i.rust_type);
                    }
                    nullable &= i.nullable;
                }
                Inferred::new(ty, nullable, "N7").named("coalesce")
            }
            // Rule N5. SQLite does not widen: sum over INTEGER stays integer
            // unless a REAL turns up, and total() is REAL always.
            "sum" => Inferred::new(arg_type.or(Some("i64".to_owned())), true, "N5").named(&lower),
            "total" => Inferred::known("f64", false, "N5").named(&lower),
            "avg" => Inferred::known("f64", true, "N5").named(&lower),
            "min" | "max" => Inferred::new(arg_type, true, "N5").named(&lower),
            "group_concat" => Inferred::known("String", true, "N5").named(&lower),
            // Scalar functions.
            "lower" | "upper" | "trim" | "ltrim" | "rtrim" | "replace" | "substr" | "hex" => {
                Inferred::new(Some("String".to_owned()), arg_nullable, "N10").named(&lower)
            }
            "length" => Inferred::new(Some("i64".to_owned()), arg_nullable, "N10").named(&lower),
            "abs" | "round" => Inferred::new(arg_type, arg_nullable, "N10").named(&lower),
            "datetime" | "current_timestamp" => {
                Inferred::known("chrono::NaiveDateTime", false, "N8").named(&lower)
            }
            "date" | "current_date" => {
                Inferred::known("chrono::NaiveDate", false, "N8").named(&lower)
            }
            "row_number" | "rank" | "dense_rank" | "ntile" => {
                Inferred::known("i64", false, "N15").named(&lower)
            }
            _ => Inferred::new(None, true, "U1").named(&lower),
        })
    }

    // --- parameters --------------------------------------------------------

    fn walk_params(&self, e: &ast::Expr<'_>, out: &mut ParamMap) {
        match e {
            ast::Expr::Binary(l, _, r) => {
                self.pair(l, r, out);
                self.pair(r, l, out);
                self.walk_params(l, out);
                self.walk_params(r, out);
            }
            ast::Expr::Unary(_, inner)
            | ast::Expr::IsNull(inner)
            | ast::Expr::NotNull(inner)
            | ast::Expr::Cast { expr: inner, .. } => self.walk_params(inner, out),
            ast::Expr::Parenthesized(items) => {
                for i in items.iter() {
                    self.walk_params(i, out);
                }
            }
            ast::Expr::InList { lhs, rhs, .. } => {
                for r in rhs.iter().flat_map(|r| r.iter()) {
                    self.pair(lhs, r, out);
                }
                self.walk_params(lhs, out);
            }
            ast::Expr::Between {
                lhs, start, end, ..
            } => {
                self.pair(lhs, start, out);
                self.pair(lhs, end, out);
                self.walk_params(lhs, out);
            }
            ast::Expr::Like { lhs, rhs, .. } => {
                self.pair(lhs, rhs, out);
                self.walk_params(lhs, out);
            }
            ast::Expr::Case {
                when_then_pairs,
                else_expr,
                ..
            } => {
                for (w, t) in when_then_pairs.iter() {
                    self.walk_params(w, out);
                    self.walk_params(t, out);
                }
                if let Some(e) = else_expr {
                    self.walk_params(e, out);
                }
            }
            ast::Expr::FunctionCall { args, .. } => {
                for a in args.iter().flat_map(|a| a.iter()) {
                    self.walk_params(a, out);
                }
            }
            _ => {}
        }
    }

    /// `known <op> ?n` types `?n`.
    fn pair(&self, known: &ast::Expr<'_>, param: &ast::Expr<'_>, out: &mut ParamMap) {
        let ast::Expr::Variable(v) = param else {
            return;
        };
        let Some(n) = crate::queries::spec::placeholder_number(v) else {
            return;
        };
        let Ok(i) = self.infer(known) else { return };
        let Some(ty) = i.rust_type else { return };
        let name = i.name.unwrap_or_else(|| "arg".to_owned());
        out.entry(n).or_insert((name, ty, "P1"));
    }
}

fn alias_name(a: &ast::As<'_>) -> String {
    match a {
        ast::As::As(n) | ast::As::Elided(n) => name(n),
    }
}

/// A `Name` as SQLite spells it, with its delimiters taken back off.
///
/// `lemon-rs` keeps an identifier's quoting in the token, so `AS "tags.name"`
/// arrives as `"tags.name"` — quotes and all. The name the *engine* reports
/// for that column is `tags.name`, which is what a row is keyed on and what
/// the nested-row naming splits, so the delimiters come off here, once.
fn name(n: &ast::Name<'_>) -> String {
    unquote(n.0)
}

/// The same, for the `Id` spelling `lemon-rs` uses in expressions.
fn id_name(n: &ast::Id<'_>) -> String {
    unquote(n.0)
}

/// Strip one layer of SQLite identifier quoting, undoubling an embedded
/// delimiter. SQLite accepts four spellings; all four mean the same name.
fn unquote(raw: &str) -> String {
    for (open, close) in [('"', '"'), ('`', '`'), ('\'', '\''), ('[', ']')] {
        if raw.len() >= 2 && raw.starts_with(open) && raw.ends_with(close) {
            let inner = &raw[open.len_utf8()..raw.len() - close.len_utf8()];
            return if open == close {
                inner.replace(&format!("{open}{open}"), &open.to_string())
            } else {
                inner.to_owned()
            };
        }
    }
    raw.to_owned()
}

/// Rule N8 for SQLite's literal forms.
fn literal(lit: &ast::Literal<'_>) -> Inferred {
    match lit {
        ast::Literal::Numeric(n) => {
            if n.contains('.') || n.contains('e') || n.contains('E') {
                Inferred::known("f64", false, "N8").named("real")
            } else {
                Inferred::known("i64", false, "N8").named("int")
            }
        }
        ast::Literal::String(_) => Inferred::known("String", false, "N8").named("text"),
        ast::Literal::Blob(_) => Inferred::known("Vec<u8>", false, "N8").named("blob"),
        ast::Literal::Keyword(k) => match k.to_ascii_lowercase().as_str() {
            "true" | "false" => Inferred::known("bool", false, "N8").named("bool"),
            "null" => Inferred::new(None, true, "N8").named("null"),
            _ => Inferred::unknown("N8"),
        },
        ast::Literal::Null => Inferred::new(None, true, "N8").named("null"),
        ast::Literal::CurrentDate => {
            Inferred::known("chrono::NaiveDate", false, "N8").named("current_date")
        }
        ast::Literal::CurrentTime => {
            Inferred::known("chrono::NaiveTime", false, "N8").named("current_time")
        }
        ast::Literal::CurrentTimestamp => {
            Inferred::known("chrono::NaiveDateTime", false, "N8").named("current_timestamp")
        }
    }
}

/// A cast's target type name → the Rust type, by SQLite's own affinity rules
/// (the same ones `crate::typemap` applies to a declared column type).
fn sqlite_type_to_rust(name: &str) -> Option<&'static str> {
    let n = name.to_ascii_lowercase();
    Some(match n.as_str() {
        "boolean" | "bool" => "bool",
        "datetime" | "timestamp" => "chrono::NaiveDateTime",
        "date" => "chrono::NaiveDate",
        "time" => "chrono::NaiveTime",
        _ => {
            if n.contains("int") {
                "i64"
            } else if n.contains("char") || n.contains("clob") || n.contains("text") {
                "String"
            } else if n.contains("blob") {
                "Vec<u8>"
            } else if n.contains("real") || n.contains("floa") || n.contains("doub") {
                "f64"
            } else {
                return None;
            }
        }
    })
}