toasty-core 0.3.0

Core types, schema representations, and driver interface for Toasty
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
use crate::{
    Schema,
    schema::{
        app::{Field, Model, ModelId, ModelRoot},
        db::{self, Column, ColumnId, Table, TableId},
    },
    stmt::{
        Delete, Expr, ExprArg, ExprColumn, ExprFunc, ExprReference, ExprSet, Insert, InsertTarget,
        Query, Returning, Select, Source, SourceTable, Statement, TableDerived, TableFactor,
        TableRef, Type, TypeUnion, Update, UpdateTarget,
    },
};

/// Provides schema-aware context for expression type inference and reference
/// resolution.
///
/// An `ExprContext` binds a schema reference, an optional parent scope (for
/// nested queries), and a target indicating what the expressions reference
/// (a model, table, or source). It is used by the query engine to infer
/// expression types and resolve column/field references.
///
/// # Examples
///
/// ```ignore
/// use toasty_core::stmt::{ExprContext, ExprTarget};
///
/// let cx = ExprContext::new(&schema);
/// let ty = cx.infer_expr_ty(&expr, &[]);
/// ```
#[derive(Debug)]
pub struct ExprContext<'a, T = Schema> {
    schema: &'a T,
    parent: Option<&'a ExprContext<'a, T>>,
    target: ExprTarget<'a>,
}

/// Result of resolving an `ExprReference` to its concrete schema location.
///
/// When an expression references a field or column (e.g., `user.name` in a
/// WHERE clause), the `ExprContext::resolve_expr_reference()` method returns
/// this enum to indicate whether the reference points to an application field,
/// physical table column, or CTE column.
///
/// This distinction is important for different processing stages: application
/// fields are used during high-level query building, physical columns during
/// SQL generation, and CTE columns require special handling with generated
/// identifiers based on position.
#[derive(Debug)]
pub enum ResolvedRef<'a> {
    /// A resolved reference to a physical database column.
    ///
    /// Contains a reference to the actual Column struct with column metadata including
    /// name, type, and constraints. Used when resolving ExprReference::Column expressions
    /// that point to concrete table columns in the database schema.
    ///
    /// Example: Resolving `user.name` in a query returns Column with name="name",
    /// ty=Type::String from the users table schema.
    Column(&'a Column),

    /// A resolved reference to an application-level field.
    ///
    /// Contains a reference to the Field struct from the application schema,
    /// which includes field metadata like name, type, and model relationships.
    /// Used when resolving ExprReference::Field expressions that point to
    /// model fields before they are lowered to database columns.
    ///
    /// Example: Resolving `User::name` in a query returns Field with name="name"
    /// from the User model's field definitions.
    Field(&'a Field),

    /// A resolved reference to a model
    Model(&'a ModelRoot),

    /// A resolved reference to a Common Table Expression (CTE) column.
    ///
    /// Contains the nesting level and column index for CTE references when resolving
    /// ExprReference::Column expressions that point to CTE outputs rather than physical
    /// table columns. The nesting indicates how many query levels to traverse upward,
    /// and index identifies which column within the CTE's output.
    ///
    /// Example: In a WITH clause, resolving a reference to the second column of a CTE
    /// defined 1 level up returns Cte { nesting: 1, index: 1 }.
    Cte {
        /// How many query scopes up from the current scope.
        nesting: usize,
        /// Column index within the CTE's output.
        index: usize,
    },

    /// A resolved reference to a derived table (subquery in FROM clause) column.
    ///
    /// Contains the nesting level, column index, and a reference to the derived
    /// table itself. This allows consumers to inspect the derived table's
    /// content (e.g., checking VALUES rows for constant values).
    Derived(DerivedRef<'a>),
}

/// A resolved reference into a derived table column.
#[derive(Debug)]
pub struct DerivedRef<'a> {
    /// How many query scopes up from the current scope.
    pub nesting: usize,

    /// The column index within the derived table's output.
    pub index: usize,

    /// Reference to the derived table definition.
    pub derived: &'a TableDerived,
}

impl DerivedRef<'_> {
    /// Returns `true` if the derived table is backed by a VALUES body and every
    /// row has `Null` at this column position.
    ///
    /// Returns `false` conservatively when the body is not VALUES, the VALUES
    /// is empty, or any row doesn't have a recognizable null at the column.
    pub fn is_column_always_null(&self) -> bool {
        let ExprSet::Values(values) = &self.derived.subquery.body else {
            return false;
        };

        if values.is_empty() {
            return false;
        }

        values.rows.iter().all(|row| self.row_column_is_null(row))
    }

    fn row_column_is_null(&self, row: &Expr) -> bool {
        match row {
            Expr::Value(super::Value::Record(record)) => {
                self.index < record.len() && record[self.index].is_null()
            }
            Expr::Record(record) => {
                self.index < record.len()
                    && matches!(&record.fields[self.index], Expr::Value(super::Value::Null))
            }
            Expr::Value(super::Value::Null) => true,
            _ => false,
        }
    }
}

/// What an expression in the current scope references.
///
/// Determines how column and field references are resolved within an
/// [`ExprContext`].
#[derive(Debug, Clone, Copy)]
pub enum ExprTarget<'a> {
    /// Expression does *not* reference any model or table.
    Free,

    /// Expression references a single model
    Model(&'a ModelRoot),

    /// Expression references a single table
    ///
    /// Used primarily by database drivers
    Table(&'a Table),

    /// Expression references a source table (a FROM clause with table references).
    Source(&'a SourceTable),
}

/// Schema resolution trait used by [`ExprContext`] to look up models,
/// tables, and the model-to-table mapping.
///
/// Implemented for [`Schema`], [`db::Schema`](crate::schema::db::Schema),
/// and `()` (which resolves nothing).
pub trait Resolve {
    /// Returns the database table that stores the given model, if any.
    fn table_for_model(&self, model: &ModelRoot) -> Option<&Table>;

    /// Returns a reference to the application Model with the specified ID.
    ///
    /// Used during high-level query building to access model metadata such as
    /// field definitions, relationships, and validation rules. Returns None if
    /// the model ID is not found in the application schema.
    fn model(&self, id: ModelId) -> Option<&Model>;

    /// Returns a reference to the database Table with the specified ID.
    ///
    /// Used during SQL generation and query execution to access table metadata
    /// including column definitions, constraints, and indexes. Returns None if
    /// the table ID is not found in the database schema.
    fn table(&self, id: TableId) -> Option<&Table>;
}

/// Conversion trait for producing an [`ExprTarget`] from a statement or
/// schema element.
pub trait IntoExprTarget<'a, T = Schema> {
    /// Converts `self` into an [`ExprTarget`] using the provided schema.
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a>;
}

#[derive(Debug)]
struct ArgTyStack<'a> {
    tys: &'a [Type],
    parent: Option<&'a ArgTyStack<'a>>,
}

impl<'a, T> ExprContext<'a, T> {
    /// Returns a reference to the schema.
    pub fn schema(&self) -> &'a T {
        self.schema
    }

    /// Returns the current expression target.
    pub fn target(&self) -> ExprTarget<'a> {
        self.target
    }

    /// Return the target at a specific nesting
    pub fn target_at(&self, nesting: usize) -> &ExprTarget<'a> {
        let mut curr = self;

        // Walk up the stack to the correct nesting level
        for _ in 0..nesting {
            let Some(parent) = curr.parent else {
                todo!("bug: invalid nesting level");
            };

            curr = parent;
        }

        &curr.target
    }
}

impl<'a> ExprContext<'a, ()> {
    /// Creates a free context with no schema and no target.
    pub fn new_free() -> ExprContext<'a, ()> {
        ExprContext {
            schema: &(),
            parent: None,
            target: ExprTarget::Free,
        }
    }
}

impl<'a, T: Resolve> ExprContext<'a, T> {
    /// Creates a context bound to the given schema with a free target.
    pub fn new(schema: &'a T) -> ExprContext<'a, T> {
        ExprContext::new_with_target(schema, ExprTarget::Free)
    }

    /// Creates a context bound to the given schema and target.
    pub fn new_with_target(
        schema: &'a T,
        target: impl IntoExprTarget<'a, T>,
    ) -> ExprContext<'a, T> {
        let target = target.into_expr_target(schema);
        ExprContext {
            schema,
            parent: None,
            target,
        }
    }

    /// Creates a child context with a new target, linked to this context
    /// as parent for nested scope resolution.
    pub fn scope<'child>(
        &'child self,
        target: impl IntoExprTarget<'child, T>,
        // target: impl Into<ExprTarget<'child>>,
    ) -> ExprContext<'child, T> {
        let target = target.into_expr_target(self.schema);
        ExprContext {
            schema: self.schema,
            parent: Some(self),
            target,
        }
    }

    /// Resolves an ExprReference::Column reference to the actual database Column it
    /// represents.
    ///
    /// Given an ExprReference::Column (which contains table/column indices and nesting
    /// info), returns the Column struct containing the column's name, type,
    /// constraints, and other metadata.
    ///
    /// Handles:
    /// - Nested query scopes (walking up parent contexts based on nesting
    ///   level)
    /// - Different statement targets (INSERT, UPDATE, SELECT with joins, etc.)
    /// - Table references in multi-table operations (using the table index)
    ///
    /// Used by SQL serialization to get column names, query planning to
    /// match index columns, and key extraction to identify column IDs.
    pub fn resolve_expr_reference(&self, expr_reference: &ExprReference) -> ResolvedRef<'a> {
        let nesting = match expr_reference {
            ExprReference::Column(expr_column) => expr_column.nesting,
            ExprReference::Field { nesting, .. } => *nesting,
            ExprReference::Model { nesting } => *nesting,
        };

        let target = self.target_at(nesting);

        match target {
            ExprTarget::Free => todo!("cannot resolve column in free context"),
            ExprTarget::Model(model) => match expr_reference {
                ExprReference::Model { .. } => ResolvedRef::Model(model),
                ExprReference::Field { index, .. } => ResolvedRef::Field(&model.fields[*index]),
                ExprReference::Column(expr_column) => {
                    assert_eq!(expr_column.table, 0, "TODO: is this true?");

                    let Some(table) = self.schema.table_for_model(model) else {
                        panic!(
                            "Failed to find database table for model '{:?}' - model may not be mapped to a table",
                            model.name
                        )
                    };
                    ResolvedRef::Column(&table.columns[expr_column.column])
                }
            },
            ExprTarget::Table(table) => match expr_reference {
                ExprReference::Model { .. } => {
                    panic!("Cannot resolve ExprReference::Model in Table target context")
                }
                ExprReference::Field { .. } => panic!(
                    "Cannot resolve ExprReference::Field in Table target context - use ExprReference::Column instead"
                ),
                ExprReference::Column(expr_column) => {
                    ResolvedRef::Column(&table.columns[expr_column.column])
                }
            },
            ExprTarget::Source(source_table) => {
                match expr_reference {
                    ExprReference::Column(expr_column) => {
                        // Get the table reference at the specified index
                        let table_ref = &source_table.tables[expr_column.table];
                        match table_ref {
                            TableRef::Table(table_id) => {
                                let Some(table) = self.schema.table(*table_id) else {
                                    panic!(
                                        "Failed to resolve table with ID {:?} - table not found in schema.",
                                        table_id,
                                    );
                                };
                                ResolvedRef::Column(&table.columns[expr_column.column])
                            }
                            TableRef::Derived(derived) => ResolvedRef::Derived(DerivedRef {
                                nesting: expr_column.nesting,
                                index: expr_column.column,
                                derived,
                            }),
                            TableRef::Cte {
                                nesting: cte_nesting,
                                index,
                            } => {
                                // TODO: return more info
                                ResolvedRef::Cte {
                                    nesting: expr_column.nesting + cte_nesting,
                                    index: *index,
                                }
                            }
                            TableRef::Arg(_) => todo!(),
                        }
                    }
                    ExprReference::Model { .. } => {
                        panic!("Cannot resolve ExprReference::Model in Source::Table context")
                    }
                    ExprReference::Field { .. } => panic!(
                        "Cannot resolve ExprReference::Field in Source::Table context - use ExprReference::Column instead"
                    ),
                }
            }
        }
    }

    /// Infers the return type of a statement given argument types.
    pub fn infer_stmt_ty(&self, stmt: &Statement, args: &[Type]) -> Type {
        let cx = self.scope(stmt);

        match stmt {
            Statement::Delete(stmt) => stmt
                .returning
                .as_ref()
                .map(|returning| cx.infer_returning_ty(returning, args, false))
                .unwrap_or(Type::Unit),
            Statement::Insert(stmt) => stmt
                .returning
                .as_ref()
                .map(|returning| cx.infer_returning_ty(returning, args, stmt.source.single))
                .unwrap_or(Type::Unit),
            Statement::Query(stmt) => match &stmt.body {
                ExprSet::Select(body) => cx.infer_returning_ty(&body.returning, args, stmt.single),
                ExprSet::SetOp(_body) => todo!(),
                ExprSet::Update(_body) => todo!(),
                ExprSet::Values(_body) => todo!(),
                ExprSet::Insert(body) => body
                    .returning
                    .as_ref()
                    .map(|returning| cx.infer_returning_ty(returning, args, stmt.single))
                    .unwrap_or(Type::Unit),
            },
            Statement::Update(stmt) => stmt
                .returning
                .as_ref()
                .map(|returning| cx.infer_returning_ty(returning, args, false))
                .unwrap_or(Type::Unit),
        }
    }

    fn infer_returning_ty(&self, returning: &Returning, args: &[Type], single: bool) -> Type {
        let arg_ty_stack = ArgTyStack::new(args);

        match returning {
            Returning::Model { .. } => {
                let ty = Type::Model(
                    self.target
                        .model_id()
                        .expect("returning `Model` when not in model context"),
                );

                if single { ty } else { Type::list(ty) }
            }
            Returning::Changed => todo!(),
            Returning::Expr(expr) => {
                let ty = self.infer_expr_ty2(&arg_ty_stack, expr, false);

                if single { ty } else { Type::list(ty) }
            }
            Returning::Value(expr) => self.infer_expr_ty2(&arg_ty_stack, expr, true),
        }
    }

    /// Infers the type of an expression given argument types.
    pub fn infer_expr_ty(&self, expr: &Expr, args: &[Type]) -> Type {
        let arg_ty_stack = ArgTyStack::new(args);
        self.infer_expr_ty2(&arg_ty_stack, expr, false)
    }

    fn infer_expr_ty2(&self, args: &ArgTyStack<'_>, expr: &Expr, returning_expr: bool) -> Type {
        match expr {
            Expr::Arg(e) => args.resolve_arg_ty(e).clone(),
            Expr::And(_) => Type::Bool,
            Expr::BinaryOp(_) => Type::Bool,
            Expr::Cast(e) => e.ty.clone(),
            Expr::Reference(expr_ref) => {
                assert!(
                    !returning_expr,
                    "should have been handled in Expr::Project. Invalid expr?"
                );
                self.infer_expr_reference_ty(expr_ref)
            }
            Expr::IsNull(_) => Type::Bool,
            Expr::IsVariant(_) => Type::Bool,
            Expr::List(e) => {
                debug_assert!(!e.items.is_empty());
                Type::list(self.infer_expr_ty2(args, &e.items[0], returning_expr))
            }
            Expr::Map(e) => {
                // Compute the map base type
                let base = self.infer_expr_ty2(args, &e.base, returning_expr);

                // The base type should be a list (as it is being mapped)
                let Type::List(item) = base else {
                    todo!("error handling; base={base:#?}")
                };

                let scope_tys = &[*item];

                // Create a new type scope
                let args = args.scope(scope_tys);

                // Infer the type of each map call
                let ty = self.infer_expr_ty2(&args, &e.map, returning_expr);

                // The mapped type is a list
                Type::list(ty)
            }
            Expr::Or(_) => Type::Bool,
            Expr::Project(e) => {
                if returning_expr {
                    match &*e.base {
                        Expr::Arg(expr_arg) => {
                            // When `returning_expr` is `true`, the expression is being
                            // evaluated from a RETURNING EXPR clause. In this case, the
                            // returning expression is *not* a projection. Referencing a
                            // column implies a *list* of
                            assert!(e.projection.as_slice().len() == 1);
                            return args.resolve_arg_ty(expr_arg).clone();
                        }
                        Expr::Reference(expr_reference) => {
                            // When `returning_expr` is `true`, the expression is being
                            // evaluated from a RETURNING EXPR clause. In this case, the
                            // returning expression is *not* a projection. Referencing a
                            // column implies a *list* of
                            assert!(e.projection.as_slice().len() == 1);
                            return self.infer_expr_reference_ty(expr_reference);
                        }
                        _ => {}
                    }
                }

                let mut base = self.infer_expr_ty2(args, &e.base, returning_expr);

                for step in e.projection.iter() {
                    base = match base {
                        Type::Record(mut fields) => {
                            std::mem::replace(&mut fields[*step], Type::Null)
                        }
                        Type::List(items) => *items,
                        expr => todo!(
                            "returning_expr={returning_expr:#?}; expr={expr:#?}; project={e:#?}"
                        ),
                    }
                }

                base
            }
            Expr::Record(e) => Type::Record(
                e.fields
                    .iter()
                    .map(|field| self.infer_expr_ty2(args, field, returning_expr))
                    .collect(),
            ),
            Expr::Value(value) => value.infer_ty(),
            Expr::Let(expr_let) => {
                let scope_tys: Vec<_> = expr_let
                    .bindings
                    .iter()
                    .map(|b| self.infer_expr_ty2(args, b, returning_expr))
                    .collect();
                let args = args.scope(&scope_tys);
                self.infer_expr_ty2(&args, &expr_let.body, returning_expr)
            }
            Expr::Match(expr_match) => {
                // Collect the distinct non-null types from all arms and the else
                // branch. If all agree on one type, return it directly. If they
                // differ, return a Union so callers know exactly which shapes are
                // possible at runtime.
                let mut union = TypeUnion::new();
                for arm in &expr_match.arms {
                    let ty = self.infer_expr_ty2(args, &arm.expr, returning_expr);
                    union.insert(ty);
                }
                let else_ty = self.infer_expr_ty2(args, &expr_match.else_expr, returning_expr);
                union.insert(else_ty);
                union.simplify()
            }
            // Error is a bottom type — it can never be evaluated, so it
            // could be any type. Return Unknown so it unifies with whatever
            // the other branches produce.
            Expr::Error(_) => Type::Unknown,
            Expr::Exists(_) => Type::Bool,
            Expr::Func(ExprFunc::Count(_)) => Type::U64,
            Expr::Func(ExprFunc::LastInsertId(_)) => Type::I64,
            _ => todo!("{expr:#?}"),
        }
    }

    /// Infers the type of an expression reference (field or column).
    pub fn infer_expr_reference_ty(&self, expr_reference: &ExprReference) -> Type {
        match self.resolve_expr_reference(expr_reference) {
            ResolvedRef::Model(model) => Type::Model(model.id),
            ResolvedRef::Column(column) => column.ty.clone(),
            ResolvedRef::Field(field) => field.expr_ty().clone(),
            ResolvedRef::Cte { .. } => todo!("type inference for CTE columns not implemented"),
            ResolvedRef::Derived(_) => {
                todo!("type inference for derived table columns not implemented")
            }
        }
    }
}

impl<'a> ExprContext<'a, Schema> {
    /// Returns the context target as a `ModelRoot` reference, or `None` if the target is not a
    /// model.
    pub fn target_as_model(&self) -> Option<&'a ModelRoot> {
        self.target.as_model()
    }

    /// Creates an `ExprReference::Column` for the given column ID.
    ///
    /// # Panics
    ///
    /// Panics if the context has no table target (`ExprTarget::Free`), if the column does not
    /// belong to the table associated with the current target, or if the target's model has no
    /// mapped database table.
    pub fn expr_ref_column(&self, column_id: impl Into<ColumnId>) -> ExprReference {
        let column_id = column_id.into();

        match self.target {
            ExprTarget::Free => {
                panic!("Cannot create ExprColumn in free context - no table target available")
            }
            ExprTarget::Model(model) => {
                let Some(table) = self.schema.table_for_model(model) else {
                    panic!(
                        "Failed to find database table for model '{:?}' - model may not be mapped to a table",
                        model.name
                    )
                };

                assert_eq!(table.id, column_id.table);
            }
            ExprTarget::Table(table) => assert_eq!(table.id, column_id.table),
            ExprTarget::Source(source_table) => {
                let [TableRef::Table(table_id)] = source_table.tables[..] else {
                    panic!(
                        "Expected exactly one table reference, found {} tables",
                        source_table.tables.len()
                    );
                };
                assert_eq!(table_id, column_id.table);
            }
        }

        ExprReference::Column(ExprColumn {
            nesting: 0,
            table: 0,
            column: column_id.index,
        })
    }
}

impl<'a, T> Clone for ExprContext<'a, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> Copy for ExprContext<'a, T> {}

impl<'a> ResolvedRef<'a> {
    /// Returns the inner `Column` reference.
    ///
    /// # Panics
    ///
    /// Panics if this is not `ResolvedRef::Column`.
    #[track_caller]
    pub fn as_column_unwrap(self) -> &'a Column {
        match self {
            ResolvedRef::Column(column) => column,
            _ => panic!("Expected ResolvedRef::Column, found {:?}", self),
        }
    }

    /// Returns the inner `Field` reference.
    ///
    /// # Panics
    ///
    /// Panics if this is not `ResolvedRef::Field`.
    #[track_caller]
    pub fn as_field_unwrap(self) -> &'a Field {
        match self {
            ResolvedRef::Field(field) => field,
            _ => panic!("Expected ResolvedRef::Field, found {:?}", self),
        }
    }

    /// Returns the inner `ModelRoot` reference.
    ///
    /// # Panics
    ///
    /// Panics if this is not `ResolvedRef::Model`.
    #[track_caller]
    pub fn as_model_unwrap(self) -> &'a ModelRoot {
        match self {
            ResolvedRef::Model(model) => model,
            _ => panic!("Expected ResolvedRef::Model, found {:?}", self),
        }
    }
}

impl Resolve for Schema {
    fn model(&self, id: ModelId) -> Option<&Model> {
        Some(self.app.model(id))
    }

    fn table(&self, id: TableId) -> Option<&Table> {
        Some(self.db.table(id))
    }

    fn table_for_model(&self, model: &ModelRoot) -> Option<&Table> {
        Some(self.table_for(model.id))
    }
}

impl Resolve for db::Schema {
    fn model(&self, _id: ModelId) -> Option<&Model> {
        None
    }

    fn table(&self, id: TableId) -> Option<&Table> {
        Some(db::Schema::table(self, id))
    }

    fn table_for_model(&self, _model: &ModelRoot) -> Option<&Table> {
        None
    }
}

impl Resolve for () {
    fn model(&self, _id: ModelId) -> Option<&Model> {
        None
    }

    fn table(&self, _id: TableId) -> Option<&Table> {
        None
    }

    fn table_for_model(&self, _model: &ModelRoot) -> Option<&Table> {
        None
    }
}

impl<'a> ExprTarget<'a> {
    /// Returns the model if this target is [`ExprTarget::Model`], or `None`.
    pub fn as_model(self) -> Option<&'a ModelRoot> {
        match self {
            ExprTarget::Model(model) => Some(model),
            _ => None,
        }
    }

    /// Returns the model, panicking if not [`ExprTarget::Model`].
    ///
    /// # Panics
    ///
    /// Panics if the target is not `Model`.
    #[track_caller]
    pub fn as_model_unwrap(self) -> &'a ModelRoot {
        match self.as_model() {
            Some(model) => model,
            _ => panic!("expected ExprTarget::Model; was {self:#?}"),
        }
    }

    /// Returns the model ID if this target is [`ExprTarget::Model`], or `None`.
    pub fn model_id(self) -> Option<ModelId> {
        Some(match self {
            ExprTarget::Model(model) => model.id,
            _ => return None,
        })
    }

    /// Returns the table if this target is [`ExprTarget::Table`], or `None`.
    pub fn as_table(self) -> Option<&'a Table> {
        match self {
            ExprTarget::Table(table) => Some(table),
            _ => None,
        }
    }

    /// Returns the table, panicking if not [`ExprTarget::Table`].
    ///
    /// # Panics
    ///
    /// Panics if the target is not `Table`.
    #[track_caller]
    pub fn as_table_unwrap(self) -> &'a Table {
        self.as_table()
            .unwrap_or_else(|| panic!("expected ExprTarget::Table; was {self:#?}"))
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for ExprTarget<'a> {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            ExprTarget::Source(source_table) => {
                if source_table.from.len() == 1 && source_table.from[0].joins.is_empty() {
                    match &source_table.from[0].relation {
                        TableFactor::Table(source_table_id) => {
                            debug_assert_eq!(0, source_table_id.0);
                            debug_assert_eq!(1, source_table.tables.len());

                            match &source_table.tables[0] {
                                TableRef::Table(table_id) => {
                                    let table = schema.table(*table_id).unwrap();
                                    ExprTarget::Table(table)
                                }
                                _ => self,
                            }
                        }
                    }
                } else {
                    self
                }
            }
            _ => self,
        }
    }
}

impl<'a, T> IntoExprTarget<'a, T> for &'a ModelRoot {
    fn into_expr_target(self, _schema: &'a T) -> ExprTarget<'a> {
        ExprTarget::Model(self)
    }
}

impl<'a, T> IntoExprTarget<'a, T> for &'a Table {
    fn into_expr_target(self, _schema: &'a T) -> ExprTarget<'a> {
        ExprTarget::Table(self)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Query {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        self.body.into_expr_target(schema)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a ExprSet {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            ExprSet::Select(select) => select.into_expr_target(schema),
            ExprSet::SetOp(_) => todo!(),
            ExprSet::Update(update) => update.into_expr_target(schema),
            ExprSet::Values(_) => ExprTarget::Free,
            ExprSet::Insert(insert) => insert.into_expr_target(schema),
        }
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Select {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        self.source.into_expr_target(schema)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Insert {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        self.target.into_expr_target(schema)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Update {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        self.target.into_expr_target(schema)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Delete {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        self.from.into_expr_target(schema)
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a InsertTarget {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            InsertTarget::Scope(query) => query.into_expr_target(schema),
            InsertTarget::Model(model) => {
                let Some(model) = schema.model(*model) else {
                    todo!()
                };
                ExprTarget::Model(model.as_root_unwrap())
            }
            InsertTarget::Table(insert_table) => {
                let table = schema.table(insert_table.table).unwrap();
                ExprTarget::Table(table)
            }
        }
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a UpdateTarget {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            UpdateTarget::Query(query) => query.into_expr_target(schema),
            UpdateTarget::Model(model) => {
                let Some(model) = schema.model(*model) else {
                    todo!()
                };
                ExprTarget::Model(model.as_root_unwrap())
            }
            UpdateTarget::Table(table_id) => {
                let Some(table) = schema.table(*table_id) else {
                    todo!()
                };
                ExprTarget::Table(table)
            }
        }
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Source {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            Source::Model(source_model) => {
                let Some(model) = schema.model(source_model.id) else {
                    todo!()
                };
                ExprTarget::Model(model.as_root_unwrap())
            }
            Source::Table(source_table) => {
                ExprTarget::Source(source_table).into_expr_target(schema)
            }
        }
    }
}

impl<'a, T: Resolve> IntoExprTarget<'a, T> for &'a Statement {
    fn into_expr_target(self, schema: &'a T) -> ExprTarget<'a> {
        match self {
            Statement::Delete(stmt) => stmt.into_expr_target(schema),
            Statement::Insert(stmt) => stmt.into_expr_target(schema),
            Statement::Query(stmt) => stmt.into_expr_target(schema),
            Statement::Update(stmt) => stmt.into_expr_target(schema),
        }
    }
}

impl<'a> ArgTyStack<'a> {
    fn new(tys: &'a [Type]) -> ArgTyStack<'a> {
        ArgTyStack { tys, parent: None }
    }

    fn resolve_arg_ty(&self, expr_arg: &ExprArg) -> &'a Type {
        let mut nesting = expr_arg.nesting;
        let mut args = self;

        while nesting > 0 {
            args = args.parent.unwrap();
            nesting -= 1;
        }

        &args.tys[expr_arg.position]
    }

    fn scope<'child>(&'child self, tys: &'child [Type]) -> ArgTyStack<'child> {
        ArgTyStack {
            tys,
            parent: Some(self),
        }
    }
}