Skip to main content

inillucent_sql/
catalog_view.rs

1//! What the binder is allowed to know about a schema.
2//!
3//! Invariant: this is a read-only view over an immutable snapshot. Nothing here
4//! can open a page, and nothing here changes while a statement is being bound,
5//! so a bound statement is a pure function of its SQL and one generation of one
6//! catalog. That is what makes prepared-statement invalidation a comparison of
7//! two numbers rather than a re-derivation.
8//!
9//! The types are defined here, below the catalog that fills them in, so the
10//! binder can be compiled and tested against a hand-built schema with no file
11//! anywhere near it.
12
13use crate::ast::{ConflictAction, ReferentialAction};
14use inillucent_value::Affinity;
15
16/// Where an index came from, which decides whether it can be dropped and how
17/// it is named in `sqlite_schema`.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum IndexOrigin {
20    /// `CREATE INDEX`.
21    Created,
22    /// A `UNIQUE` constraint.
23    Unique,
24    /// A `PRIMARY KEY` constraint on a rowid table.
25    PrimaryKey,
26    /// An index a module owns, named by `CREATE INDEX ... USING <module>`.
27    ///
28    /// **Not a b-tree, and the planner has to know that.** Its rows live in a
29    /// virtual table, its `root` is that table's own root, and none of the
30    /// b-tree paths apply to it - there is nothing to seek and nothing to
31    /// range-scan. What it can do is answer "the k nearest to this vector",
32    /// which is a whole access path of its own.
33    Module,
34}
35
36/// The distance a `Module`-origin vector index was declared to minimise.
37///
38/// **Only a vector index has one of these, and only a real one.** An ordinary
39/// b-tree orders by a collation, not a distance, so every `IndexInfo` that is
40/// not `IndexOrigin::Module` carries `None`. A `Module` index carries `None`
41/// too unless its own module is one the planner has verified actually honours
42/// the setting: `inillucent-engine/src/vectors.rs` only ever reports `Some`
43/// for `inillucent_search` (which backs `USING inillucent_hnsw`), because that
44/// is the one module whose store was changed to read the graph under this
45/// metric. An `ivfflat` index that was declared `WITH (metric = 'l2')` still
46/// reads back as `None` here, deliberately: `ivfflat`'s own argument parser
47/// silently accepts and ignores a key it does not recognise, so trusting the
48/// text would let the planner believe an index orders by Euclidean distance
49/// when the structure behind it still computes cosine - the exact "wrong
50/// answer that looks like a working index" this field exists to prevent.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum IndexMetric {
53    /// One minus the cosine similarity of two unit vectors.
54    Cosine,
55    /// Euclidean distance.
56    L2,
57}
58
59/// One column of a table or view.
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct ColumnInfo {
62    /// The name as declared.
63    pub name: Vec<u8>,
64    /// The ASCII-folded lookup key.
65    pub folded: Vec<u8>,
66    /// The declared type, exactly as written, empty when none was given.
67    pub declared_type: Vec<u8>,
68    /// The affinity derived from the declared type.
69    pub affinity: Affinity,
70    /// The folded name of the column's declared collation.
71    pub collation: Vec<u8>,
72    /// Whether the column is `NOT NULL`.
73    pub not_null: bool,
74    /// The `ON CONFLICT` clause written on the `NOT NULL`, when there was one.
75    ///
76    /// A constraint carries its own algorithm and the statement may override
77    /// it: `INSERT OR IGNORE` beats `NOT NULL ON CONFLICT ABORT`. Recording it
78    /// per constraint rather than per table is what makes that override a
79    /// choice between two known values instead of a guess.
80    pub not_null_conflict: Option<ConflictAction>,
81    /// The `ON CONFLICT` clause written on the column's `PRIMARY KEY`.
82    ///
83    /// **A different constraint from the `NOT NULL`, and a different clause.**
84    /// For a rowid alias this is the only place a rowid collision's algorithm
85    /// is written down - SQLite records `id INTEGER PRIMARY KEY ON CONFLICT
86    /// REPLACE` against the column, because the alias *is* the column and there
87    /// is no index to hang it on. Every other primary key gets an `IndexInfo`
88    /// and carries it there.
89    ///
90    /// Reading `not_null_conflict` for it, which is what the write path used to
91    /// do, answers a question about a constraint the table may not
92    /// even declare.
93    pub primary_key_conflict: Option<ConflictAction>,
94    /// The `DEFAULT` expression, as written.
95    pub default_sql: Option<Vec<u8>>,
96    /// The one-based position in the primary key, when it is in one.
97    pub primary_key_position: Option<u16>,
98    /// Whether the column is hidden from `SELECT *`.
99    pub hidden: bool,
100    /// Whether the column is generated.
101    pub generated: bool,
102    /// Whether a generated column's value is stored in the record.
103    ///
104    /// A `VIRTUAL` column occupies no slot and is computed on every read; a
105    /// `STORED` one occupies a slot like any other column. The distinction is
106    /// not cosmetic: it changes which *record position* every column after it
107    /// lives at, so a reader that ignored it would read the wrong column.
108    pub stored: bool,
109    /// The generating expression, as the source text it was written as.
110    pub generated_sql: Option<Vec<u8>>,
111}
112
113/// One key column of an index.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct IndexColumnInfo {
116    /// The table column this key indexes, when it indexes a bare column.
117    pub column: Option<u16>,
118    /// The key expression, as written, when the key is an expression.
119    pub expr_sql: Option<Vec<u8>>,
120    /// The folded collation name the key is ordered by.
121    pub collation: Vec<u8>,
122    /// Whether the key is stored descending.
123    pub descending: bool,
124    /// Whether the *declaration* said descending, whatever the storage does.
125    ///
126    /// **A different question from `descending`, and the two used to be one.**
127    /// This engine's trees are always built ascending, so the catalog flattens
128    /// `descending` to false for the planner's sake - a planner told about a
129    /// descending tree that does not exist draws three inverted conclusions
130    /// (see `inillucent-catalog`'s `stored_ascending`). But
131    /// `PRAGMA index_xinfo` reports what was *declared*, and an application
132    /// reading it to reconstruct a `CREATE INDEX` needs the `DESC` back.
133    pub declared_descending: bool,
134}
135
136/// An index over a table.
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct IndexInfo {
139    /// The index name.
140    pub name: Vec<u8>,
141    /// The ASCII-folded lookup key.
142    pub folded: Vec<u8>,
143    /// The root page of the index B-tree.
144    pub root: u32,
145    /// Whether the index enforces uniqueness.
146    pub unique: bool,
147    /// The key columns, in order.
148    pub columns: Vec<IndexColumnInfo>,
149    /// The partial-index predicate, as written.
150    pub partial_sql: Option<Vec<u8>>,
151    /// Where the index came from.
152    pub origin: IndexOrigin,
153    /// The `ON CONFLICT` clause the constraint that created it carried.
154    pub conflict: Option<ConflictAction>,
155    /// For each leading prefix of the key, the average number of rows sharing
156    /// it, as `ANALYZE` measured.
157    ///
158    /// Empty until the schema has been analysed, which is the *usual* state and
159    /// not an error: the planner falls back to SQLite's own guesses, and those
160    /// guesses are what make an unanalysed plan match the reference's.
161    pub prefix_rows: Vec<i64>,
162    /// How many entries the index itself holds, as `ANALYZE` measured.
163    ///
164    /// **The same number as the table's row count for an ordinary index, and a
165    /// different one for a partial index**, which holds only
166    /// the rows its predicate accepted. It is what lets the planner price
167    /// reading the whole of such an index against scanning the table it is on -
168    /// 120 entries against 6,000 rows, in the case this was found on.
169    ///
170    /// `None` until the schema has been analysed.
171    pub analysed_rows: Option<i64>,
172    /// The distance a vector index minimises, when it is one the planner may
173    /// trust to answer for it. See [`IndexMetric`].
174    pub metric: Option<IndexMetric>,
175}
176
177/// What kind of schema object a name resolves to.
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum TableKind {
180    /// An ordinary table.
181    Table,
182    /// A view.
183    View,
184    /// A virtual table.
185    Virtual,
186    /// A nested query standing in for a table: a FROM subquery, a CTE
187    /// reference, or an expanded view.
188    ///
189    /// It is a kind rather than a flag because every question the binder asks
190    /// of a table - has it a rowid, can it be written to, may an index be used
191    /// on it - has the same answer for all three, and a kind makes the answer
192    /// one match arm instead of three conditions that can drift apart.
193    Subquery,
194}
195
196/// A view's parsed definition.
197///
198/// The arena lives here, in the catalog snapshot, rather than being re-parsed
199/// on every reference. That is not only a saving: the binder holds the snapshot
200/// for the whole statement, so a body kept here outlives the bind and can be
201/// bound in place, while one parsed inside the binder would be a local whose
202/// borrow ends before the bound tree does.
203#[derive(Clone, Debug, PartialEq, Eq)]
204pub struct ViewBody {
205    /// The arena the view's `SELECT` was parsed into.
206    pub ast: crate::ast::Ast,
207    /// The `SELECT` inside the arena.
208    pub select: crate::ast::SelectId,
209    /// The explicit column list, when the `CREATE VIEW` wrote one.
210    pub columns: Vec<Vec<u8>>,
211}
212
213/// What a trigger fires on, with `UPDATE OF` already folded.
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub enum TriggerEventInfo {
216    /// `INSERT`.
217    Insert,
218    /// `DELETE`.
219    Delete,
220    /// `UPDATE`, optionally narrowed to a set of folded column names.
221    Update(Vec<Vec<u8>>),
222}
223
224/// A trigger's parsed definition.
225///
226/// Kept parsed here for the same reason a view body is: the arena belongs to
227/// the catalog snapshot, which the binder holds for the whole statement, so a
228/// body can be bound in place. A body re-parsed inside the binder would be a
229/// local whose borrow ends before the bound tree does.
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct TriggerInfo {
232    /// The trigger name as declared.
233    pub name: Vec<u8>,
234    /// The ASCII-folded lookup key.
235    pub folded: Vec<u8>,
236    /// When it fires. `CREATE TRIGGER` with no time written means `BEFORE`.
237    pub time: crate::ast::TriggerTime,
238    /// What it fires on.
239    pub event: TriggerEventInfo,
240    /// The arena the `WHEN` guard and the body were parsed into.
241    pub ast: crate::ast::Ast,
242    /// The `WHEN` guard, when one was written.
243    pub when: Option<crate::ast::ExprId>,
244    /// The body statements, in written order.
245    pub body: Vec<crate::ast::Statement>,
246}
247
248impl ColumnInfo {
249    /// Reports whether the column was declared a vector at all.
250    ///
251    /// `VECTOR(768)` and a bare `VECTOR` both answer true, where
252    /// [`ColumnInfo::vector_dimensions`] answers a width only for the first.
253    /// The difference matters to the operators: a bare `VECTOR` cannot be
254    /// indexed, but adding two of them is just as meaningless.
255    pub fn is_vector(&self) -> bool {
256        let declared = self.declared_type.to_ascii_lowercase();
257        let Some(rest) = declared.strip_prefix(b"vector".as_slice()) else {
258            return false;
259        };
260        rest.is_empty()
261            || rest
262                .first()
263                .is_some_and(|byte| !byte.is_ascii_alphanumeric())
264    }
265
266    /// Returns how many dimensions a `VECTOR(N)` column declares.
267    ///
268    /// **Read out of the declared type rather than stored beside it**, because
269    /// every path that builds a `ColumnInfo` - the catalog loader, a module's
270    /// declaration, the binder's synthetic ones - would otherwise have to know
271    /// about vectors, and a column's declared type is the one place SQLite
272    /// itself keeps what a column was called.
273    ///
274    /// `VECTOR(768)` and `vector( 768 )` both answer 768. A bare `VECTOR`
275    /// answers `None`, which means "a vector of whatever arrives" and is what a
276    /// table holding two models' embeddings needs; anything that is not a
277    /// vector answers `None` too, and its caller then checks nothing.
278    ///
279    /// **The affinity is deliberately left alone.** SQLite gives `VECTOR(768)`
280    /// NUMERIC affinity, and NUMERIC leaves a blob exactly as it arrived - so
281    /// the bytes round-trip without this engine having to disagree with the
282    /// reference about what an affinity is. What the declaration buys is the
283    /// width check on write, and a column an index can be built over.
284    pub fn vector_dimensions(&self) -> Option<usize> {
285        let declared = self.declared_type.to_ascii_lowercase();
286        let rest = declared.strip_prefix(b"vector".as_slice())?;
287        let inside: Vec<u8> = rest
288            .iter()
289            .copied()
290            .skip_while(|byte| byte.is_ascii_whitespace())
291            .collect();
292        let inside = inside.strip_prefix(b"(".as_slice())?;
293        let inside = inside.strip_suffix(b")".as_slice())?;
294        let text = std::str::from_utf8(inside).ok()?.trim();
295        let width: usize = text.parse().ok()?;
296        (width > 0).then_some(width)
297    }
298}
299
300impl TriggerInfo {
301    /// Returns whether this trigger fires for one event on one column set.
302    ///
303    /// `changed` is the folded names an UPDATE assigns, and is empty for the
304    /// other two events. `UPDATE OF a, b` fires only when the statement writes
305    /// `a` or `b` - which SQLite decides from the *statement*, not from whether
306    /// the value actually differs.
307    pub fn fires_for(&self, event: &TriggerEventInfo, changed: &[Vec<u8>]) -> bool {
308        match (&self.event, event) {
309            (TriggerEventInfo::Insert, TriggerEventInfo::Insert) => true,
310            (TriggerEventInfo::Delete, TriggerEventInfo::Delete) => true,
311            (TriggerEventInfo::Update(of), TriggerEventInfo::Update(_)) => {
312                of.is_empty() || of.iter().any(|name| changed.contains(name))
313            }
314            _ => false,
315        }
316    }
317}
318
319/// A table, view or virtual table.
320#[derive(Clone, Debug, PartialEq, Eq)]
321pub struct TableInfo {
322    /// The name as declared.
323    pub name: Vec<u8>,
324    /// The ASCII-folded lookup key.
325    pub folded: Vec<u8>,
326    /// Which attached database it belongs to.
327    pub database: usize,
328    /// The root page of the table B-tree, or zero for a view.
329    pub root: u32,
330    /// The columns, in declaration order.
331    pub columns: Vec<ColumnInfo>,
332    /// The column that is an alias for the rowid, when there is one.
333    pub rowid_alias: Option<u16>,
334    /// Whether the table is `WITHOUT ROWID`.
335    pub without_rowid: bool,
336    /// Whether the table is `STRICT`.
337    pub strict: bool,
338    /// Whether the rowid alias was declared `AUTOINCREMENT`.
339    ///
340    /// It changes where a new rowid comes from: an ordinary table reuses the
341    /// numbers its deleted rows had, and an `AUTOINCREMENT` one never does,
342    /// because it remembers the largest it has ever handed out in
343    /// `sqlite_sequence`.
344    pub autoincrement: bool,
345    /// What kind of object this is.
346    pub kind: TableKind,
347    /// The `CREATE` text as stored in `sqlite_schema`.
348    pub create_sql: Vec<u8>,
349    /// The indexes over this table.
350    pub indexes: Vec<IndexInfo>,
351    /// The parsed body, when this is a view.
352    pub view: Option<Box<ViewBody>>,
353    /// The triggers attached to this table or view, in schema order.
354    pub triggers: Vec<TriggerInfo>,
355    /// How many rows `ANALYZE` counted, when it has run.
356    pub analysed_rows: Option<i64>,
357    /// The triggers this table's writes fire because of a foreign key.
358    ///
359    /// Both directions are here, because both are things that happen when
360    /// *this* table is written: the checks its own keys need when a row
361    /// arrives, and the actions the keys pointing at it need when a row
362    /// leaves. They are built once when the schema is read rather than once
363    /// per statement, because generating and parsing them is the same work
364    /// every time and the schema is what decides them.
365    pub foreign_key_triggers: Vec<ForeignKeyTrigger>,
366    /// Every foreign key declared on this table, in declaration order.
367    ///
368    /// The child's side of the relationship, which is the side the table
369    /// carries. Finding the keys that point *at* a table means walking the
370    /// database's tables and asking each one, which is what
371    /// `CatalogView::foreign_keys_referencing` does - and is what SQLite does
372    /// too, because nothing in the file records the reverse direction.
373    pub foreign_keys: Vec<ForeignKeyInfo>,
374    /// Every `CHECK` constraint, as the source text it was written as.
375    ///
376    /// The text rather than a bound expression, for the same reason
377    /// `default_sql` is text: the catalog is below the binder, so it cannot
378    /// bind anything, and a constraint that had been half-interpreted on the
379    /// way through would be a second source of truth beside the `CREATE`
380    /// statement the file actually stores.
381    pub checks: Vec<CheckInfo>,
382    /// The module a virtual table is implemented by, and its arguments.
383    ///
384    /// The catalog records the question and the session fills in the answer:
385    /// what columns the table has is the module's to say, not the file's, so a
386    /// virtual table arrives here with a module and no columns and leaves the
387    /// connection's schema load with both.
388    pub module: Option<crate::vtab::ModuleRef>,
389}
390
391/// One trigger a foreign key implies, or the reason there is not one.
392#[derive(Clone, Debug, PartialEq, Eq)]
393pub struct ForeignKeyTrigger {
394    /// Whether it refuses a write rather than repairing one.
395    ///
396    /// Only a check can be deferred. An action is what the constraint *does*,
397    /// and doing it at commit time instead would leave the rows in between
398    /// visible to the statements that come after.
399    pub is_check: bool,
400    /// Whether the key it enforces was declared `INITIALLY DEFERRED`.
401    pub deferred: bool,
402    /// The trigger, or `None` when the key cannot be enforced at all.
403    pub trigger: Option<TriggerInfo>,
404    /// Why it cannot be, when it cannot.
405    ///
406    /// A key whose parent table is missing, or whose parent columns are not a
407    /// key of the parent, is legal to declare: SQLite reports it when
408    /// something writes, not when the schema is read, so that a schema can be
409    /// loaded in any order. The message is kept here and reported then.
410    pub fault: Vec<u8>,
411    /// Whether the key's child table and its parent table are the same table.
412    ///
413    /// **Read by `DROP TABLE`'s implicit delete (task-1979, F6).** That delete
414    /// removes every row of one table, so a key whose child is that same table
415    /// cannot be violated once the statement has finished - the rows that would
416    /// be left pointing at nothing are themselves gone. SQLite reaches the same
417    /// answer a different way: its immediate foreign keys are a counter checked
418    /// at the end of the statement, so the violation deleting the first row
419    /// creates is cancelled by deleting the row that made it.
420    pub self_referencing: bool,
421}
422
423/// One foreign key, from the child table that declares it.
424#[derive(Clone, Debug, PartialEq, Eq)]
425pub struct ForeignKeyInfo {
426    /// The constraint's position in its table, counting from zero.
427    ///
428    /// `PRAGMA foreign_key_list` reports it, and it is how a diagnostic names
429    /// a constraint that was written without a name - which is most of them.
430    pub id: u32,
431    /// The child columns, in the order they were written.
432    pub columns: Vec<u16>,
433    /// The parent table's name as written.
434    pub parent: Vec<u8>,
435    /// The parent table's folded name.
436    pub parent_folded: Vec<u8>,
437    /// The parent columns as written, or empty when the clause named none.
438    ///
439    /// Empty means the parent's primary key, and it stays empty rather than
440    /// being resolved here: the catalog builds one table at a time and the
441    /// parent may not have been read yet - or may not exist, which is legal
442    /// until something writes a row.
443    pub parent_columns: Vec<Vec<u8>>,
444    /// What happens to the child rows when a parent row is deleted.
445    pub on_delete: ReferentialAction,
446    /// What happens to the child rows when a parent key changes.
447    pub on_update: ReferentialAction,
448    /// The `MATCH` clause as written, which SQLite parses and ignores.
449    pub match_clause: Vec<u8>,
450    /// Whether `DEFERRABLE` was written.
451    pub deferrable: bool,
452    /// Whether `INITIALLY DEFERRED` was written.
453    pub initially_deferred: bool,
454    /// Whether following this key can lead back to the table that declares it.
455    ///
456    /// A tree with `ON DELETE CASCADE` on its parent column is the everyday
457    /// case, and it is the one case an action cannot simply be inlined into
458    /// the statement that fires it: the body would have to appear once per
459    /// level the data happens to be deep, which is not known when the
460    /// statement is compiled. A cyclic key's action is applied by repeating it
461    /// until nothing changes instead, and this is what says which keys need
462    /// that.
463    pub cyclic: bool,
464}
465
466impl ForeignKeyInfo {
467    /// Reports whether the constraint's checks wait until the transaction
468    /// commits.
469    pub fn is_deferred(&self) -> bool {
470        self.deferrable && self.initially_deferred
471    }
472}
473
474/// One `CHECK` constraint.
475#[derive(Clone, Debug, PartialEq, Eq)]
476pub struct CheckInfo {
477    /// The constraint's name, when one was written.
478    pub name: Option<Vec<u8>>,
479    /// The predicate, as the source text between its parentheses.
480    pub expr_sql: Vec<u8>,
481    /// The `ON CONFLICT` clause a table-level `CHECK` was written with.
482    ///
483    /// **Recorded and not acted on**, because that is what the reference does:
484    /// SQLite's grammar accepts `CHECK (expr) onconf` on a table constraint and
485    /// its builder never reads the clause, so such a constraint aborts like any
486    /// other. It is kept here so the derivation is a full account of the text
487    /// rather than a lossy one, and so the next reader finds the measurement
488    /// instead of the question.
489    pub conflict: Option<ConflictAction>,
490}
491
492impl TableInfo {
493    /// Returns the position of a column by its folded name.
494    pub fn column_position(&self, folded: &[u8]) -> Option<u16> {
495        self.columns
496            .iter()
497            .position(|column| column.folded == folded)
498            .map(|index| index as u16)
499    }
500
501    /// Returns a column by position.
502    pub fn column(&self, position: u16) -> Option<&ColumnInfo> {
503        self.columns.get(position as usize)
504    }
505
506    /// Returns whether the table has a rowid a query may refer to.
507    pub fn has_rowid(&self) -> bool {
508        // A virtual table has one unless its module declared otherwise: FTS5
509        // and the R-Tree both key their rows by it, and `SELECT rowid FROM t`
510        // is how an application joins to them.
511        matches!(self.kind, TableKind::Table | TableKind::Virtual) && !self.without_rowid
512    }
513
514    /// Returns a table that stands for an eponymous module.
515    ///
516    /// A module reached as a name rather than through `CREATE VIRTUAL TABLE` -
517    /// `generate_series`, `json_each`, `pragma_table_info` - belongs to no
518    /// database and has no `sqlite_schema` row, so everything a stored table
519    /// carries is absent and only the module's declaration remains.
520    ///
521    /// @param name - the module's name, which is also the table's
522    /// @param columns - the columns the module declared
523    /// @param module - the module reference the executor resolves it by
524    /// @param without_rowid - whether the module declared no rowid
525    pub fn eponymous(
526        name: Vec<u8>,
527        columns: Vec<ColumnInfo>,
528        module: crate::vtab::ModuleRef,
529        without_rowid: bool,
530    ) -> TableInfo {
531        let folded = name.to_ascii_lowercase();
532        TableInfo {
533            name,
534            folded,
535            database: 0,
536            root: 0,
537            columns,
538            rowid_alias: None,
539            without_rowid,
540            strict: false,
541            autoincrement: false,
542            kind: TableKind::Virtual,
543            create_sql: Vec::new(),
544            foreign_keys: Vec::new(),
545            foreign_key_triggers: Vec::new(),
546            module: Some(module),
547            view: None,
548            triggers: Vec::new(),
549            analysed_rows: None,
550            indexes: Vec::new(),
551            checks: Vec::new(),
552        }
553    }
554
555    /// Returns a table that stands for a nested query's result.
556    ///
557    /// The column list is the block's result columns: their names are what a
558    /// reference to the subquery resolves against, and their affinity and
559    /// collation are the ones the expressions behind them carry, so a
560    /// comparison against a subquery column applies the same rules it would
561    /// have applied one level down.
562    pub fn subquery(name: Vec<u8>, database: usize, columns: Vec<ColumnInfo>) -> TableInfo {
563        let folded = name.to_ascii_lowercase();
564        TableInfo {
565            name,
566            folded,
567            database,
568            root: 0,
569            columns,
570            rowid_alias: None,
571            without_rowid: true,
572            strict: false,
573            autoincrement: false,
574            kind: TableKind::Subquery,
575            create_sql: Vec::new(),
576            foreign_keys: Vec::new(),
577            foreign_key_triggers: Vec::new(),
578            module: None,
579            view: None,
580            triggers: Vec::new(),
581            analysed_rows: None,
582            indexes: Vec::new(),
583            checks: Vec::new(),
584        }
585    }
586
587    /// Returns the record slot a column's value lives in, when it has one.
588    ///
589    /// `VIRTUAL` generated columns take no slot, so the slots of the columns
590    /// after them shift down. Every read of a stored column has to go through
591    /// this rather than through the column's declared position, and a `VIRTUAL`
592    /// column has no slot at all - it is computed.
593    pub fn record_slot(&self, column: u16) -> Option<usize> {
594        if self.without_rowid {
595            return self
596                .record_order()
597                .iter()
598                .position(|stored| *stored == column);
599        }
600        let mut slot = 0usize;
601        for (position, info) in self.columns.iter().enumerate() {
602            if info.generated && !info.stored {
603                if position == usize::from(column) {
604                    return None;
605                }
606                continue;
607            }
608            if position == usize::from(column) {
609                return Some(slot);
610            }
611            slot = slot.saturating_add(1);
612        }
613        None
614    }
615
616    /// Returns the primary key's columns, in key order.
617    ///
618    /// Key order, not declaration order: `PRIMARY KEY(b, a)` is ordered by `b`
619    /// and then `a` however the columns were declared, and for a `WITHOUT
620    /// ROWID` table that order also decides where in the record they sit.
621    pub fn primary_key(&self) -> Vec<u16> {
622        let mut keys: Vec<(u16, u16)> = self
623            .columns
624            .iter()
625            .enumerate()
626            .filter_map(|(position, column)| {
627                column
628                    .primary_key_position
629                    .map(|key| (key, position as u16))
630            })
631            .collect();
632        keys.sort_by_key(|(key, _)| *key);
633        keys.into_iter().map(|(_, position)| position).collect()
634    }
635
636    /// Returns the columns a record holds, in the order it holds them.
637    ///
638    /// A rowid table stores its columns as declared. A `WITHOUT ROWID` table's
639    /// B-tree is an index whose key is the primary key, so its record is the
640    /// key columns first, in key order, and then everything else as declared -
641    /// verified against a file the pinned build wrote: `PRIMARY KEY(b, a)` over
642    /// `(a, b, c)` stores `(b, a, c)`.
643    pub fn record_order(&self) -> Vec<u16> {
644        let stored = |position: usize| {
645            self.columns
646                .get(position)
647                .is_some_and(|column| !column.generated || column.stored)
648        };
649        if !self.without_rowid {
650            return (0..self.columns.len())
651                .filter(|position| stored(*position))
652                .map(|position| position as u16)
653                .collect();
654        }
655        let keys = self.primary_key();
656        let mut order = keys.clone();
657        for position in 0..self.columns.len() {
658            if keys.contains(&(position as u16)) || !stored(position) {
659                continue;
660            }
661            order.push(position as u16);
662        }
663        order
664    }
665
666    /// Returns whether a name is one of the rowid's three spellings and is not
667    /// shadowed by a real column.
668    ///
669    /// SQLite's rule is exactly this: `rowid`, `_rowid_` and `oid` name the
670    /// rowid *unless* the table declares a column with that name, in which case
671    /// the column wins. A table without a rowid has none of the three.
672    pub fn is_rowid_name(&self, folded: &[u8]) -> bool {
673        if !self.has_rowid() {
674            return false;
675        }
676        let spelled = folded == b"rowid" || folded == b"_rowid_" || folded == b"oid";
677        spelled && self.column_position(folded).is_none()
678    }
679}
680
681/// The read-only schema the binder resolves names against.
682pub trait CatalogView {
683    /// Returns the number of attached databases.
684    fn database_count(&self) -> usize;
685
686    /// Returns the name of an attached database by index.
687    fn database_name(&self, index: usize) -> &[u8];
688
689    /// Returns the index of an attached database by folded name.
690    fn database_index(&self, folded: &[u8]) -> Option<usize>;
691
692    /// Returns a table, view or virtual table by name.
693    ///
694    /// With no qualifier the search follows SQLite's order: `temp`, then
695    /// `main`, then every other attached database in attachment order.
696    fn find_table(&self, database: Option<&[u8]>, folded: &[u8]) -> Option<&TableInfo>;
697
698    /// Returns a table as a shared pointer, for a caller that has to keep it.
699    ///
700    /// A binder keeps what it finds for the life of the bound statement.
701    /// [`CatalogView::find_table`] hands back a borrow, so keeping it meant
702    /// cloning a `TableInfo` - two name vectors, a `ColumnInfo` per column with
703    /// its own heap fields, the `CREATE` text and an `IndexInfo` per index -
704    /// for every table reference in every statement. Measured at 2,938 ns of
705    /// `prepare.point`'s 6,093 ns compile.
706    ///
707    /// The default is that clone, so an implementor that has nothing to share
708    /// keeps working and is merely no faster. `StaticCatalog` shares.
709    ///
710    /// @param database - the schema qualifier, if the statement wrote one
711    /// @param folded - the table's folded name
712    fn shared_table(
713        &self,
714        database: Option<&[u8]>,
715        folded: &[u8],
716    ) -> Option<std::rc::Rc<TableInfo>> {
717        self.find_table(database, folded)
718            .map(|table| std::rc::Rc::new(table.clone()))
719    }
720
721    /// Returns the table an index belongs to, together with the index.
722    ///
723    /// Index names live in the same namespace as table names in SQLite, but
724    /// the catalog stores an index inside the table it indexes - which is
725    /// where every reader of one wants it. `DROP INDEX` is the caller that
726    /// has only the name, so the search lives here rather than being written
727    /// out again wherever a name has to be resolved.
728    fn find_index(
729        &self,
730        database: Option<&[u8]>,
731        folded: &[u8],
732    ) -> Option<(&TableInfo, &IndexInfo)>;
733
734    /// Returns the table a trigger is attached to, together with the trigger.
735    ///
736    /// Triggers share the name namespace with tables and indexes and are stored
737    /// on the object they fire for, so this is `find_index` again for the other
738    /// kind of attached object: `DROP TRIGGER` and `CREATE TRIGGER` both have
739    /// only the name.
740    fn find_trigger(
741        &self,
742        database: Option<&[u8]>,
743        folded: &[u8],
744    ) -> Option<(&TableInfo, &TriggerInfo)> {
745        let wanted = database.and_then(|name| self.database_index(name));
746        for table in self.every_table() {
747            if wanted.is_some_and(|index| index != table.database) {
748                continue;
749            }
750            if let Some(trigger) = table.triggers.iter().find(|one| one.folded == folded) {
751                return Some((table, trigger));
752            }
753        }
754        None
755    }
756
757    /// Returns every table of every attached database.
758    ///
759    /// It exists so [`CatalogView::find_trigger`] can have one implementation
760    /// rather than one per catalog: a trigger search is the same walk whatever
761    /// the tables are stored in.
762    fn every_table(&self) -> Vec<&TableInfo>;
763
764    /// Returns every table of one attached database, in no particular order.
765    fn tables_of(&self, database: usize) -> Vec<&TableInfo>;
766
767    /// Returns the schema cookie of an attached database, which a prepared
768    /// statement records so it can tell whether the schema moved under it.
769    fn schema_cookie(&self, database: usize) -> u32;
770
771    /// Returns the generation of the whole snapshot.
772    fn generation(&self) -> u64;
773}
774
775/// A catalog held in memory, which is what a test binds against and what the
776/// loader produces once it has read `sqlite_schema`.
777#[derive(Clone, Debug, Default, PartialEq, Eq)]
778pub struct StaticCatalog {
779    /// The attached databases, in attachment order, with their cookies.
780    pub databases: Vec<(Vec<u8>, u32)>,
781    /// Every table, in no particular order.
782    ///
783    /// **Shared rather than owned, because binding a statement used to clone
784    /// one.** `BoundSource.table` was a `TableInfo` by value, so every table
785    /// reference in every statement deep-copied the catalog's entry: two name
786    /// vectors, a `ColumnInfo` per column each with its own heap fields, the
787    /// full `CREATE` text, and an `IndexInfo` per index with its own column
788    /// vector. Forty-odd allocations to bind one `WHERE id = ?1`, measured at
789    /// 2,938 ns of `prepare.point`'s 6,093 - 48% of the statement's whole
790    /// compile. An `Rc` makes it a refcount bump.
791    pub tables: Vec<std::rc::Rc<TableInfo>>,
792    /// The eponymous virtual tables the connection's modules provide.
793    ///
794    /// `generate_series`, `json_each`, `json_tree`, `pragma_table_info`: the
795    /// name *is* the table, so they belong to no database and have no
796    /// `sqlite_schema` row. They are searched **last**, so a real table called
797    /// `generate_series` shadows the module rather than the other way round -
798    /// which is SQLite's order and the only safe one, because the file was
799    /// there first.
800    ///
801    /// Filled by the engine from its module registry on every catalog refresh.
802    /// Nothing used to fill it, and the eponymous form did not exist:
803    /// `FROM generate_series(1,10)` was `no such table`, which also left
804    /// `json_each` unreachable from SQL by any route, because `JsonWalkModule`
805    /// refuses `CREATE VIRTUAL TABLE` outright.
806    pub eponymous: Vec<std::rc::Rc<TableInfo>>,
807    /// The generation of this snapshot.
808    pub generation: u64,
809}
810
811impl StaticCatalog {
812    /// Returns a catalog with one `main` database and no objects.
813    pub fn empty() -> StaticCatalog {
814        StaticCatalog {
815            databases: vec![(b"main".to_vec(), 0)],
816            tables: Vec::new(),
817            eponymous: Vec::new(),
818            generation: 0,
819        }
820    }
821
822    /// Adds an eponymous virtual table, returning the catalog.
823    ///
824    /// @param table - the module's table, as its declaration describes it
825    pub fn with_eponymous(mut self, table: TableInfo) -> StaticCatalog {
826        self.eponymous.push(std::rc::Rc::new(table));
827        self
828    }
829
830    /// Adds a table, returning the catalog, for building fixtures.
831    /// Returns one table by folded name, searching every database.
832    ///
833    /// Attachment order, `main` first, which is the order an unqualified name
834    /// resolves in. A module asking about a name it was given as an argument
835    /// wants the same table the statement that named it would have found.
836    ///
837    /// @param folded - the table's ASCII-folded name
838    pub fn table_named(&self, folded: &[u8]) -> Option<&TableInfo> {
839        self.tables
840            .iter()
841            .map(std::rc::Rc::as_ref)
842            .find(|table| table.folded == folded)
843    }
844
845    /// Returns this catalog with one more table in it.
846    ///
847    /// @param table - the table to add
848    pub fn with_table(mut self, table: TableInfo) -> StaticCatalog {
849        self.tables.push(std::rc::Rc::new(table));
850        self
851    }
852}
853
854/// Returns the name a schema qualified table name is looked up under.
855///
856/// **`temp.sqlite_schema` and `temp.sqlite_master` are the temporary
857/// catalog**, as SQLite answers them. The temporary catalog is registered only
858/// as `sqlite_temp_schema` and `sqlite_temp_master`, because an unqualified
859/// `sqlite_schema` searches `temp` first and has to mean `main`'s. A qualified
860/// name has no search, so it is mapped here, and after `CREATE TEMP TABLE
861/// scratch (x)` all four names answer `scratch`.
862///
863/// @param database - the qualifier the statement wrote
864/// @param folded - the table's folded name
865fn qualified_catalog_name<'a>(database: &[u8], folded: &'a [u8]) -> &'a [u8] {
866    if !database.eq_ignore_ascii_case(b"temp") {
867        return folded;
868    }
869    match folded {
870        b"sqlite_schema" => b"sqlite_temp_schema",
871        b"sqlite_master" => b"sqlite_temp_master",
872        other => other,
873    }
874}
875
876impl CatalogView for StaticCatalog {
877    /// Returns a table as a shared pointer; the trait method's override.
878    ///
879    /// @param database - the schema qualifier, if the statement wrote one
880    /// @param folded - the table's folded name
881    fn shared_table(
882        &self,
883        database: Option<&[u8]>,
884        folded: &[u8],
885    ) -> Option<std::rc::Rc<TableInfo>> {
886        if let Some(database) = database {
887            let index = self.database_index(database)?;
888            let folded = qualified_catalog_name(database, folded);
889            return self
890                .tables
891                .iter()
892                .find(|table| table.database == index && table.folded == folded)
893                .map(std::rc::Rc::clone);
894        }
895        for index in self.search_order() {
896            if let Some(found) = self
897                .tables
898                .iter()
899                .find(|table| table.database == index && table.folded == folded)
900            {
901                return Some(std::rc::Rc::clone(found));
902            }
903        }
904        self.eponymous
905            .iter()
906            .find(|table| table.folded == folded)
907            .map(std::rc::Rc::clone)
908    }
909
910    /// Returns the number of attached databases.
911    fn database_count(&self) -> usize {
912        self.databases.len()
913    }
914
915    /// Returns the name of an attached database by index.
916    fn database_name(&self, index: usize) -> &[u8] {
917        self.databases.get(index).map_or(&[], |(name, _)| name)
918    }
919
920    /// Returns the index of an attached database by folded name.
921    fn database_index(&self, folded: &[u8]) -> Option<usize> {
922        self.databases
923            .iter()
924            .position(|(name, _)| name.eq_ignore_ascii_case(folded))
925    }
926
927    /// Returns a table by name, searching in SQLite's own order.
928    fn find_table(&self, database: Option<&[u8]>, folded: &[u8]) -> Option<&TableInfo> {
929        if let Some(database) = database {
930            let index = self.database_index(database)?;
931            let folded = qualified_catalog_name(database, folded);
932            return self
933                .tables
934                .iter()
935                .find(|table| table.database == index && table.folded == folded)
936                .map(std::rc::Rc::as_ref);
937        }
938        for index in self.search_order() {
939            if let Some(found) = self
940                .tables
941                .iter()
942                .find(|table| table.database == index && table.folded == folded)
943            {
944                return Some(found.as_ref());
945            }
946        }
947        // Last, so a real table of the same name shadows the module.
948        self.eponymous
949            .iter()
950            .find(|table| table.folded == folded)
951            .map(std::rc::Rc::as_ref)
952    }
953
954    /// Returns the table an index belongs to, and the index.
955    fn every_table(&self) -> Vec<&TableInfo> {
956        self.tables.iter().map(std::rc::Rc::as_ref).collect()
957    }
958
959    fn find_index(
960        &self,
961        database: Option<&[u8]>,
962        folded: &[u8],
963    ) -> Option<(&TableInfo, &IndexInfo)> {
964        let wanted = database.and_then(|name| self.database_index(name));
965        for table in &self.tables {
966            if wanted.is_some_and(|index| index != table.database) {
967                continue;
968            }
969            if let Some(index) = table.indexes.iter().find(|index| index.folded == folded) {
970                return Some((table, index));
971            }
972        }
973        None
974    }
975
976    /// Returns every table of one attached database.
977    fn tables_of(&self, database: usize) -> Vec<&TableInfo> {
978        self.tables
979            .iter()
980            .filter(|table| table.database == database)
981            .map(std::rc::Rc::as_ref)
982            .collect()
983    }
984
985    /// Returns the schema cookie of an attached database.
986    fn schema_cookie(&self, database: usize) -> u32 {
987        self.databases
988            .get(database)
989            .map_or(0, |(_, cookie)| *cookie)
990    }
991
992    /// Returns the generation of the snapshot.
993    fn generation(&self) -> u64 {
994        self.generation
995    }
996}
997
998impl StaticCatalog {
999    /// Returns the database indexes in the order an unqualified name searches.
1000    fn search_order(&self) -> Vec<usize> {
1001        let mut order: Vec<usize> = Vec::with_capacity(self.databases.len());
1002        if let Some(temp) = self
1003            .databases
1004            .iter()
1005            .position(|(name, _)| name.eq_ignore_ascii_case(b"temp"))
1006        {
1007            order.push(temp);
1008        }
1009        for (index, _) in self.databases.iter().enumerate() {
1010            if !order.contains(&index) {
1011                order.push(index);
1012            }
1013        }
1014        order
1015    }
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::*;
1021
1022    /// Builds a one-column table for the tests below.
1023    fn table(name: &[u8], database: usize) -> TableInfo {
1024        TableInfo {
1025            name: name.to_vec(),
1026            folded: name.to_ascii_lowercase(),
1027            database,
1028            root: 2,
1029            columns: vec![ColumnInfo {
1030                name: b"a".to_vec(),
1031                folded: b"a".to_vec(),
1032                declared_type: Vec::new(),
1033                affinity: Affinity::Blob,
1034                collation: b"binary".to_vec(),
1035                not_null: false,
1036                not_null_conflict: None,
1037                primary_key_conflict: None,
1038                default_sql: None,
1039                primary_key_position: None,
1040                hidden: false,
1041                generated: false,
1042                stored: false,
1043                generated_sql: None,
1044            }],
1045            rowid_alias: None,
1046            without_rowid: false,
1047            strict: false,
1048            autoincrement: false,
1049            kind: TableKind::Table,
1050            create_sql: Vec::new(),
1051            indexes: Vec::new(),
1052            view: None,
1053            triggers: Vec::new(),
1054            analysed_rows: None,
1055            checks: Vec::new(),
1056            foreign_keys: Vec::new(),
1057            foreign_key_triggers: Vec::new(),
1058            module: None,
1059        }
1060    }
1061
1062    /// An unqualified name finds `temp` before `main`, which is the rule that
1063    /// lets a temp table shadow a real one.
1064    #[test]
1065    fn temp_is_searched_before_main() {
1066        let catalog = StaticCatalog {
1067            databases: vec![(b"main".to_vec(), 1), (b"temp".to_vec(), 2)],
1068            tables: vec![
1069                std::rc::Rc::new(table(b"t", 0)),
1070                std::rc::Rc::new(table(b"t", 1)),
1071            ],
1072            eponymous: Vec::new(),
1073            generation: 7,
1074        };
1075        let found = catalog.find_table(None, b"t").expect("it resolves");
1076        assert_eq!(found.database, 1);
1077        let qualified = catalog
1078            .find_table(Some(b"main"), b"t")
1079            .expect("it resolves");
1080        assert_eq!(qualified.database, 0);
1081    }
1082
1083    /// The three rowid spellings resolve, and a real column of that name wins.
1084    #[test]
1085    fn the_rowid_spellings_resolve_unless_shadowed() {
1086        let mut plain = table(b"t", 0);
1087        assert!(plain.is_rowid_name(b"rowid"));
1088        assert!(plain.is_rowid_name(b"_rowid_"));
1089        assert!(plain.is_rowid_name(b"oid"));
1090        assert!(!plain.is_rowid_name(b"id"));
1091
1092        if let Some(column) = plain.columns.first_mut() {
1093            column.name = b"oid".to_vec();
1094            column.folded = b"oid".to_vec();
1095        }
1096        assert!(!plain.is_rowid_name(b"oid"));
1097        assert!(plain.is_rowid_name(b"rowid"));
1098
1099        let mut without = table(b"t", 0);
1100        without.without_rowid = true;
1101        assert!(!without.is_rowid_name(b"rowid"));
1102    }
1103
1104    /// A missing database or table is `None`, never a panic.
1105    #[test]
1106    fn a_missing_name_is_none() {
1107        let catalog = StaticCatalog::empty();
1108        assert!(catalog.find_table(None, b"nope").is_none());
1109        assert!(catalog.find_table(Some(b"nodb"), b"t").is_none());
1110        assert_eq!(catalog.database_name(99), b"");
1111        assert_eq!(catalog.schema_cookie(99), 0);
1112    }
1113}