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