(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Model open Handle open Decl module Engine = Sql.Private.Engine module Resolve = Sql.Private.Resolve module Lexer = Sql.Private.Lexer module Ident = Catalog.Ident let ident_equal = Ident.equal (* What a [Raw.query] statement parses to: a SELECT, an EXPLAIN, or a PRAGMA that returns rows. Every other statement kind is refused here rather than further down, since a caller holding only a query entry point cannot run one. *) let parse_query ?known sql = match Lexer.parse_statements ?known sql with (* the frontend's message already says what is wrong, in sqlite3's words; a stage name in front of it only gets between the user and the answer *) | Error msg -> Catalog.Error.fail_prepare "%s" msg | Ok [ Sql.Ast.Select s ] -> ( match Sql.Private.Param_number.number_params (Sql.Ast.Select s) with | Sql.Ast.Select s -> Select_query (s, Handle.memo ()) | _ -> assert false) | Ok [ Sql.Ast.Explain e ] -> Explain_query e | Ok [ Sql.Ast.Pragma p ] -> Pragma_query p | Ok [ _ ] -> Catalog.Error.fail_prepare "query: statement is not a SELECT" | Ok _ -> Catalog.Error.fail_prepare "query: expected a single SELECT statement" (* Whether [t] holds an object of the name, which a statement reading a table of another schema needs to name the table sqlite3 fails to locate first. *) let holds t name = Handle.name_holder t name <> None (* Parse a [Raw.query] statement, reusing a cached AST for a repeated string. The cache is bounded; once full it stops admitting new entries (a fixed working set of queries -- the common case -- stays cached, while ad-hoc SQL still parses, just uncached). *) let parse_query_cached t sql = match Hashtbl.find_opt t.query_cache sql with | Some s -> s | None -> let s = parse_query ~known:(holds t) sql in if Hashtbl.length t.query_cache < 512 then Hashtbl.replace t.query_cache sql s; s (* Whether [stmt] writes from its start, as sqlite3 opens its btree transaction for writing (OP_Transaction, p2 non-zero): its session is then the write session at once rather than a read session it leaves for one. A PRAGMA that only reads, or that sets the connection, opens a read transaction. *) let writes : Sql.Ast.stmt -> bool = function | Pragma p -> not (Pragma.reads_only p || Pragma.sets_connection p) | Insert _ | Delete _ | Update _ | Create_table _ | Create_table_as _ | Create_index _ | Create_view _ | Create_trigger _ | Drop _ | Alter_table _ | Vacuum None | Analyze | Begin (Immediate | Exclusive) -> true | Select _ | Explain _ | Begin Deferred | Commit | Rollback | Savepoint _ | Release _ | Rollback_to _ | Vacuum (Some _) -> false (* Run [f] over the statements of [stmts] as one script door ({!Session.script_op}), which takes the write session first where the first statement, [stmt] of the first element, writes. *) let script t ~stmt stmts f = match Seq.uncons stmts with | None -> Session.script_op t (fun () -> f Seq.empty) | Some (head, rest) -> Session.script_op ~write:(writes (stmt head)) t (fun () -> f (Seq.cons head rest)) (* The statements of a [;]-separated script, each paired with the text it came from: a statement that stores its own source stores that piece, so what is stored parses on its own. Placeholders are numbered once per statement. A statement is parsed only as the one before it is reached ({!Lexer.script}). *) let parse_script ?known sql = Seq.map (function | Error msg -> Catalog.Error.fail_prepare "%s" msg | Ok (piece, s) -> (piece, Sql.Private.Param_number.number_params s)) (Lexer.script ?known sql) module type S = sig type t = Handle.t val vm_select_rows : ?memo:Handle.memo -> t -> Sql.Private.Query.catalog -> Sql.Ast.value array -> Sql.Ast.select -> Sql.Ast.value list list val vm_select_iter : ?memo:Handle.memo -> t -> Sql.Private.Query.catalog -> Sql.Ast.value array -> Sql.Ast.select -> f:(Sql.Row.t -> unit) -> unit val explain_rows : t -> Sql.Ast.explain -> Sql.Ast.value list list val dml_rows : t -> Sql.Ast.select -> Sql.Ast.value array -> Sql.Ast.value list list option val dml_iter : ?refused:(string -> bool) -> t -> Sql.Ast.select -> Sql.Ast.value array -> f:(Sql.Ast.value list -> unit) -> bool end module Make (R : S) = struct (* The three reads a run makes that this layer cannot name: running a SELECT is the executor's, and the executor is built above the driver. Everything else -- the catalog, the storage door, the DML -- is called qualified. *) let catalog = Cat.v let table_column_names = Cat.column_names let insert_values = Write.Rows.insert let vm_select_rows = R.vm_select_rows let vm_select_iter = R.vm_select_iter let explain_rows = R.explain_rows (* The same rows, each handed to [f] as the scan reaches it, or [false], with none handed over, where the VM does not run the select. *) let dml_scan ?refused t params s ~f = R.dml_iter ?refused t s params ~f (* The index door onto the one namespace tables, views and indexes share. sqlite3 looks for a table of the name first and that lookup answers for a view too, so the refusal says "table" of a view. IF NOT EXISTS reaches the index half alone; a trigger is outside this namespace. *) let index_name_free t ~if_not_exists name = match Handle.name_holder t name with | None -> true | Some (Table_name | View_name) -> Catalog.Error.fail_prepare "there is already a table named %s" name | Some Index_name when if_not_exists -> false | Some Index_name -> Catalog.Error.fail_prepare "index %s already exists" name (* CREATE [UNIQUE] INDEX: validate, materialise a B-tree from the current rows and record it in sqlite_master. A unique index also enforces distinct keys from here on. *) let add_index t gt ~sql (ci : Sql.Ast.create_index) = let idx = Ddl.index t.pager gt ~rowid:(Handle.next_master_rowid t) ~sql ci in Ddl.populate ~admits:(fun ~addr values -> let rowid = Index_row.rowid_of addr in if idx.unique && Index_row.holds gt.schema ?rowid idx values then Sql.Private.Connection.fail (Handle.connection t) Abort (Index.violation gt.schema idx)) ~entry:(fun ~addr ~held values -> (* An entry built over a row already stored holds what its record holds (sqlite3GenerateIndexKey reads the column without OP_RealAffinity). *) Index_row.entry gt.schema ~reals:false ~held idx ~addr values) gt idx; let gt' = Ddl.with_index gt idx in t.all_tables <- List.map (fun g -> if g == gt then gt' else g) t.all_tables; Session.rebuild_page1 t let exec_create_index t ~sql (ci : Sql.Ast.create_index) = let gt = match Handle.table t ci.table with | Some gt -> gt | None -> ( (* The target is looked for in the namespace tables and views share, so a view of the name is found and refused for what it is rather than reported missing. A name nothing holds is reported with the database it was looked for in, [main] here. *) match Handle.name_holder t ci.table with | Some View_name -> Catalog.Error.fail_prepare "views may not be indexed" | Some (Table_name | Index_name) | None -> Catalog.Error.fail_prepare "no such table: main.%s" ci.table) in let cols = table_column_names t ci.table in (* An index's WHERE and its expression keys are stored and re-evaluated against one row at a time, so each must answer from that row alone. Refusing here keeps the file portable: sqlite3 re-resolves both on open and answers a bad one with "malformed database schema". The keys are checked first, in key order, each as {!Decl.index_key_read} reads it: a column key's column, then the sequence it names (sqlite3CreateIndex). *) let rowid = rowid_stored gt in List.iter (fun k -> match Decl.index_key_read k with | Sql.Ast.Column (c : Sql.Ast.indexed_column) -> if not (List.exists (ident_equal c.column) cols) then Catalog.Error.fail_prepare "no such column: %s" c.column; Option.iter (fun n -> ignore (Sql.Private.Collate.resolve n : Sql.Collation.t)) c.collation | Sql.Ast.Expression e -> Sql.Private.Self_ref.check Index_expression ~rowid ~table:ci.table ~cols e.expr) ci.keys; Option.iter (Sql.Private.Self_ref.check Partial_index ~rowid ~table:ci.table ~cols) ci.where; (* sqlite3 codes the keys and the WHERE as it builds the index, whether the table holds a row or none, so what the coding refuses is refused here rather than at the first row. *) (match List.filter_map (fun k -> match Decl.index_key_read k with | Sql.Ast.Expression e -> Some e.expr | Sql.Ast.Column _ -> None) ci.keys @ Option.to_list ci.where with | [] -> () | exprs -> let coded = Engine.row_values ~stored:Index_expression (Sql.Private.Table.catalog (Row.table gt.schema)) [||] ci.table cols ~rowid exprs in ignore (coded : ?rowid:int64 -> _ -> _)); if index_name_free t ~if_not_exists:ci.if_not_exists ci.name then add_index t gt ~sql ci let exec_create_table t ~sql (ct : Sql.Ast.create_table) = (* sqlite3 locates the name before it reads a column (sqlite3StartTable), and reads none of a table IF NOT EXISTS finds; each column's name, DEFAULT and COLLATE are refused as it is read, before any later column and any table constraint. *) if Handle.table_name_free t ~if_not_exists:ct.ct_if_not_exists ct.tbl_name then begin Sql.Private.Create_table.check_columns ct; (* Everything sqlite3 refuses to hold in a schema, asked of the statement here and of the text read back in {!Reconnect.open_table}. A generation cycle is the one rule sqlite3 leaves to statement time, so it is asked only here: this is where a file gets one. *) Sql.Private.Create_table.check ct; Sql.Private.Self_ref.check_generated_loop (List.map (fun (n, (g : Sql.Ast.generated_column)) -> (n, g.expr)) ct.generated); (* The name is {!Autoinc.create_table}'s to accept or refuse too: it is the door every created table goes through, this one and the one a caller writes out itself. *) Autoinc.create_table t ~sql end (* CREATE TABLE name AS query: the query's output column names become the new table's columns (all default affinity), and its rows populate the table. The rows are computed before the table is created (the query cannot see it). *) (* The column names the materialised table declares. Two result columns naming one identifier would declare one column twice, which is a table sqlite3 cannot open, so the later one takes its own name suffixed with its position -- [SELECT 1 AS a, 2 AS A] declares [a] and ["A:1"], as sqlite3 does (sqlite/src/select.c, sqlite3GenerateColumnNames). *) let disambiguated_columns cols = List.mapi (fun i c -> let earlier = List.filteri (fun j _ -> j < i) cols in if List.exists (ident_equal c) earlier then Fmt.str "%s:%d" c i else c) cols let exec_create_table_as t cat params (cta : Sql.Ast.create_table_as) = let name = cta.name in (* Asked here as well as in {!Autoinc.create_table} below, because the query runs in between: a statement refused for its name is one that never ran it, and one skipped over by IF NOT EXISTS never ran it either. *) if Handle.table_name_free t ~if_not_exists:cta.if_not_exists name then begin let cols = disambiguated_columns (Resolve.select_columns (Sql.Private.Query.resolve_env cat) cta.query) in let rows = vm_select_rows t cat params cta.query in (* sqlite3 stores the materialised column list, e.g. [CREATE TABLE u(a,b)], each name written as an identifier (build.c, createTableStmt). *) let sql = Fmt.str "CREATE TABLE %a(%a)" Sql.pp_ident name Fmt.(list ~sep:(any ",") Sql.pp_ident) cols in Autoinc.create_table t ~sql; List.iter (fun row -> ignore (insert_values t ~table:name row)) rows end (* A view is recorded as a [sqlite_master] entry of type "view" holding the original CREATE VIEW text (the source of truth, re-parsed when the view is used or the database is reopened). It owns no B-tree pages. *) let exec_create_view t ~sql (cv : Sql.Ast.create_view) = let held = match Handle.name_holder t cv.name with | Some Table_name -> Some `Table | Some View_name -> Some `View | Some Index_name -> Some `Index | None -> None in if Sql.Private.View.check_create ~held cv then Session.define t (Catalog.Spi.Definition.v `View ~name:cv.name ~table:cv.name (Some sql)) (* A trigger is a definition of the store, checked as sqlite3BeginTrigger checks it ({!Sql.Private.Trigger.check_create}). Its target is looked up among tables and views alone, and its name among triggers alone: sqlite3 keeps one hash per kind of schema object (trigger.c). *) let exec_create_trigger t ~sql (tg : Sql.Ast.create_trigger) = let target = match Handle.name_holder t tg.table with | Some Table_name -> Some `Table | Some View_name -> Some `View | Some Index_name | None -> None in let taken = List.exists (fun (_, d) -> Catalog.Spi.Definition.is d `Trigger tg.name) (Session.definitions t) in if Sql.Private.Trigger.check_create ~target ~taken tg then Session.define t (Catalog.Spi.Definition.v `Trigger ~name:tg.name ~table:tg.table (Some sql)) (* Rewrite every row of [gt]'s table B-tree through [f] (on the decoded record values), in place at the same rowid. Indexes are untouched, so callers must ensure index entries stay valid. *) let rewrite_rows gt ~f = (* A WITHOUT ROWID table's record is its b-tree key, so rewriting one moves the row: the whole tree has to be rebuilt under the new layout, which is not written here. Refused by name rather than left to corrupt the key. *) let btree = match gt.store with | Rowid_rows b -> b | Pk_index_rows _ -> unsupported_storage gt "cannot rewrite the rows of" in let rows = ref [] and e = Btree.Table.encoding btree in Btree.Table.iter btree (fun rowid payload -> rows := (rowid, Btree.Record.decode e payload) :: !rows); List.iter (fun (rowid, vals) -> Btree.Table.insert btree ~rowid (Btree.Record.encode e (f vals))) !rows (* Swap [gt] for [new_gt]. A table whose rows are its own b-tree keys derives its record description from the schema, so a statement that changed the column list has to derive it again -- at the same root, the rows not having moved. *) let replace_table t gt new_gt = let new_gt = match new_gt.store with | Rowid_rows _ -> new_gt | Pk_index_rows p -> let schema = new_gt.schema in { new_gt with store = Pk_index_rows (Reconnect.pk_rows_at t.pager ~schema ~constraints:(unique_constraints ~without_rowid:true schema) ~root:(Some (Btree.Index.root_page p.index))); } in t.all_tables <- List.map (fun g -> if g == gt then new_gt else g) t.all_tables (* Whether the table holds a row at all: a count stopped at the first one, which is one descent rather than a walk whichever kind of b-tree the rows are in. What it decides is which DEFAULT an ADD COLUMN may declare, so it is asked once per statement. *) let table_has_rows (gt : generic_table) = Model.row_count gt.store ~upto:1 > 0 (* ADD COLUMN splices the declaration, as written, into the stored CREATE TABLE, which then declares the column as it would have had the table been created with it; the rules are sqlite3's ({!Sql.Private.Alter.add_column}). The existing rows are left short of the schema and read the column's declared default, which is what makes this O(1) rather than a pass over every row. *) let alter_add_column t (gt : generic_table) ~sql ~start ~stop (c : Sql.Ast.column_decl) = let tbl_name = gt.schema.tbl_name in let new_sql, ct = Sql.Private.Alter.add_column ~table:tbl_name ~columns:(column_names gt.schema.columns) ~has_rowid:(rowid_stored gt) ~foreign_keys: (Sql.Private.Connection.foreign_keys (Handle.connection t)) ~has_rows:(fun () -> table_has_rows gt) ~sql:gt.schema.sql (String.sub sql start (stop - start)) c in replace_table t gt { gt with schema = schema_of_ast ~encoding:(rows_encoding gt.store) ~tbl_name ~sql:new_sql ct; } (* Once the table is read back, the rows the new column left as they were are checked as sqlite3 checks them, through [PRAGMA quick_check] ({!Sql.Private.Alter.check_added_rows}). *) let check_rows_after_add_column t ~table (c : Sql.Ast.column_decl) = match (Cat.gtable t table).schema.parsed with | None -> () | Some ct -> Sql.Private.Alter.check_added_rows ct c (fun () -> Integrity.rows (Pragma.integrity_report_table t ~quick:true table)) (* RENAME TO: every stored statement that reads the table is rewritten, as sqlite3 runs sqlite_rename_table over every row of sqlite_master but the indexes of other tables (sqlite/src/alter.c, sqlite3AlterRenameTable): the table's own text and its indexes', every view and trigger, and every other table whose foreign keys name it as their parent. Every index follows the table, and autoindex names embed the table name. *) (* Every index of a renamed table, under the new name. An autoindex is named after its table, so it follows; an explicit one keeps its own name and carries the table's inside its stored text, which [renamed] rewrites. *) (* An autoindex keeps its number and has its table respelled, as sqlite3 rewrites its name: 'sqlite_autoindex_' || new || substr(name, len(old) + 18) (alter.c, sqlite3AlterRenameTable). A WITHOUT ROWID table's first autoindex is its primary key, which is the table, so the number is not the place in [indexes]. *) let renamed_indexes ~renamed ~from_ ~new_name indexes = let prefix = String.length "sqlite_autoindex_" + String.length from_ in List.map (fun (idx : index) -> let name = match idx.sql with | None when String.length idx.name >= prefix -> "sqlite_autoindex_" ^ new_name ^ String.sub idx.name prefix (String.length idx.name - prefix) | None | Some _ -> idx.name in { idx with tbl_name = new_name; name; sql = Option.map renamed idx.sql }) indexes let alter_rename_table t gt new_name = let renamed sql = Sql.Private.Alter_text.rename_table sql ~from_:gt.schema.tbl_name ~to_:new_name in let renamed_value = function | Sql.Ast.Text sql -> Sql.Ast.Text (renamed sql) | v -> v in let new_gt = { gt with schema = schema_of_columns ~encoding:(rows_encoding gt.store) ~tbl_name:new_name ~columns:gt.schema.columns ~sql:(renamed gt.schema.sql); indexes = renamed_indexes ~renamed ~from_:gt.schema.tbl_name ~new_name gt.indexes; (* An index this handle cannot rebuild still carries the text sqlite3 will resolve, so it needs the rename as much as one it maintains. *) unusable = List.map (fun (u : unusable_index) -> { u with sql = renamed_value u.sql }) gt.unusable; } in replace_table t gt new_gt; (* Another table names this one only as the parent of a foreign key. *) List.iter (fun (other : generic_table) -> if other != new_gt then let sql = renamed other.schema.sql in if not (String.equal sql other.schema.sql) then replace_table t other { other with schema = schema_of_columns ~encoding:(rows_encoding other.store) ~tbl_name:other.schema.tbl_name ~columns:other.schema.columns ~sql; }) t.all_tables; Autoinc.rename_counter t ~from_:gt.schema.tbl_name ~to_:new_name; (* Every view and trigger reads the new name, and a trigger recorded against the old table is recorded against the new one. *) t.extra_master <- List.map (fun rm -> let rm = { rm with sql = renamed_value rm.sql } in if ident_equal rm.tbl_name gt.schema.tbl_name then { rm with tbl_name = new_name } else rm) t.extra_master (* The CREATE TABLE an ALTER reads, which a table whose text does not parse lacks: its schema is malformed. *) let parsed (gt : generic_table) = match gt.schema.parsed with Some ct -> ct | None -> Integrity.malformed () (* Every view and trigger with a renamed column respelled wherever it reads it, computed whole before anything is written ({!Sql.Private.Alter.renamed_views_and_triggers}). *) let extra_master_renamed t gt ~from_ ~to_ = let definition (rm : raw_master_entry) = match (Session.definition_kind rm.type_, rm.sql) with | Some kind, Sql.Ast.Text sql -> Some (Catalog.Spi.Definition.v kind ~name:rm.name ~table:rm.tbl_name (Some sql)) | _ -> None in let renamed = Sql.Private.Alter.renamed_views_and_triggers ~table:gt.schema.tbl_name ~from_ ~to_ (List.filter_map definition t.extra_master) in List.map (fun (rm : raw_master_entry) -> match List.find_opt (fun (d : Catalog.Spi.Definition.t) -> Session.definition_kind rm.type_ = Some d.kind && ident_equal d.name rm.name) renamed with | Some { sql = Some sql; _ } -> { rm with sql = Sql.Ast.Text sql } | Some _ | None -> rm) t.extra_master let alter_rename_column t gt ~from_ ~to_ = let sql = Sql.Private.Alter.rename_column ~table:gt.schema.tbl_name ~has_rowid:(rowid_stored gt) ~sql:gt.schema.sql (parsed gt) ~from_ ~to_ in let columns = List.map (fun (c : column) -> if ident_equal c.name from_ then { c with name = to_ } else c) gt.schema.columns in (* An index names the columns it keys on and the ones its predicate reads, in its own stored text, so the rename reaches that text too -- sqlite3 resolves it on every open and answers a stale one with "malformed database schema (i) - no such column: b" rather than a row. *) let renamed sql = Sql.Private.Alter_text.rename_column_in_index sql ~from_ ~to_ in let new_gt = { gt with schema = schema_of_columns ~encoding:(rows_encoding gt.store) ~tbl_name:gt.schema.tbl_name ~columns ~sql; indexes = List.map (fun (idx : index) -> { idx with sql = Option.map renamed idx.sql }) gt.indexes; unusable = List.map (fun (u : unusable_index) -> match u.sql with | Sql.Ast.Text sql -> { u with sql = Sql.Ast.Text (renamed sql) } | _ -> u) gt.unusable; } in (* Before the table changes, so a statement this rename cannot resolve refuses the ALTER with nothing written. *) let extra_master = extra_master_renamed t gt ~from_ ~to_ in replace_table t gt new_gt; t.extra_master <- extra_master (* [idx] with the column positions it records shifted down past the hole a dropped column leaves. An expression key names its columns rather than numbering them, so nothing in it moves. *) let index_past_dropped_column ~pos idx = { idx with keys = List.map (function | Column p -> Column (if p > pos then p - 1 else p) | Expression _ as k -> k) idx.keys; } (* The rules and the new text are sqlite3's ({!Sql.Private.Alter.drop_column}), over the indexes a statement created, each read from its text: the others are the constraints', which the table's own text answers for. *) let alter_drop_column t gt col = let cols = gt.schema.columns in let indexes = List.filter_map (fun (idx : index) -> match Option.map Lexer.parse_statements idx.sql with | Some (Ok [ Sql.Ast.Create_index ci ]) -> Some (idx.name, ci) | Some _ | None -> None) gt.indexes in let pos, dropped_sql = Sql.Private.Alter.drop_column ~table:gt.schema.tbl_name ~has_rowid:(rowid_stored gt) ~sql:gt.schema.sql ~indexes (parsed gt) col in (* The dropped column was in no index, so existing index entries (keyed by value) stay valid; only the column positions recorded in each index, which are read by the planner, shift down past the hole. An expression key names its columns rather than numbering them, so nothing in it moves. *) let indexes = List.map (index_past_dropped_column ~pos) gt.indexes in let new_gt = { gt with schema = schema_of_columns ~encoding:(rows_encoding gt.store) ~tbl_name:gt.schema.tbl_name ~columns:(List.filteri (fun i _ -> i <> pos) cols) ~sql:dropped_sql; indexes; } in (* The rewrite is by position in the record, which is not the declared numbering when the table has a VIRTUAL generated column: that column is in no record, so dropping it rewrites nothing. *) (match Row.record_index gt.schema pos with | None -> () | Some rpos -> rewrite_rows gt ~f:(List.filteri (fun i _ -> i <> rpos))); replace_table t gt new_gt (* The relation an ALTER names is located among the tables, the schema tables and the views, and refused as sqlite3 refuses it before reading a column ({!Sql.Private.Alter.check}). *) let exec_alter_table t ~sql (a : Sql.Ast.alter_table) = let found = Handle.table t a.table in let kind, declared = match found with | Some gt -> (`Table, gt.schema.tbl_name) | None when Sql.Private.Schema_table.is_name a.table -> (`Table, Sql.Private.Schema_table.name a.table) | None -> ( match List.find_opt (fun (rm : raw_master_entry) -> String.equal rm.type_ "view" && ident_equal rm.name a.table) t.extra_master with | Some rm -> (`View, rm.name) | None -> Catalog.Error.fail_prepare "no such table: %s" a.table) in Sql.Private.Alter.check ~held:(fun name -> Option.is_some (Handle.name_holder t name)) a.op kind declared; let gt = match found with | Some gt -> gt | None -> Catalog.Error.fail_prepare "no such table: %s" a.table in (* Every shape of ALTER rewrites the table's rows or its column positions, so each leaves an index this handle cannot rebuild describing something the table no longer is. *) let gt = maintainable gt in (match a.op with | Add_column { column; start; stop } -> alter_add_column t gt ~sql ~start ~stop column | Rename_table new_name -> alter_rename_table t gt new_name | Rename_column (from_, to_) -> alter_rename_column t gt ~from_ ~to_ | Drop_column col -> alter_drop_column t gt col); (* Persist the catalog change to sqlite_master so it survives a reopen. *) Session.rebuild_page1 t; (* Then read the schema back, so this handle answers from the text it just wrote. A rename changes what the stored index names mean, and only re-reading the rewritten CREATE INDEX resolves them again. *) Session.load_schema t; match a.op with | Add_column { column; _ } -> check_rows_after_add_column t ~table:a.table column | Rename_table _ | Rename_column _ | Drop_column _ -> () (* VACUUM writes the compact image over the database and is committed as its own transaction, which cuts the file ({!Session.vacuum}). It writes every page, and outside a transaction a statement opens no journal, which would copy each page it overwrites. *) let exec_vacuum t = Session.check_vacuum t; Handle.check_not_scanning t "wrote"; Session.writing t; let conn = Handle.connection t in Sql.Private.Connection.start conn; (* the compact image takes the cookie one past this file's (Vacuum.copy, as sqlite3RunVacuum), and the handle reads the schema back from it *) Sql.Private.Connection.atomic conn (fun () -> Session.vacuum t) (* DROP TABLE / DROP INDEX. Returns the object's pages to the freelist, removes it from the schema, then rewrites page 1. Freeing first lets the rewrite reuse the pages and leaves none unreachable. DROP TABLE also forgets the table's auto-indexes and rowid counter. *) (* Drop a view or a trigger, a definition of the store ({!Session.undefine}). [what] names the object in the "no such " error sqlite raises when it is absent. *) let drop_definition t (d : Sql.Ast.drop) kind ~what = if List.exists (fun (_, def) -> Catalog.Spi.Definition.is def kind d.name) (Session.definitions t) then Session.undefine t kind d.name else if not d.if_exists then Catalog.Error.fail_prepare "no such %s: %s" what d.name (* DROP INDEX: an explicit index lives inside its table's [generic_table], so drop it by rewriting that table's index list. An autoindex (sql = None) backs a UNIQUE/PRIMARY KEY constraint and cannot be dropped on its own. An index this handle could not rebuild is droppable in the same way, and dropping it is how a database carrying one becomes writable again. *) let drop_unusable_index t (d : Sql.Ast.drop) = let target (gt : generic_table) = List.find_opt (fun (u : unusable_index) -> ident_equal u.name d.name) gt.unusable in match List.find_map (fun gt -> Option.map (fun u -> (gt, u)) (target gt)) t.all_tables with | None -> false | Some (_, (u : unusable_index)) when u.sql = Sql.Ast.Null -> Catalog.Error.fail_prepare "index associated with UNIQUE or PRIMARY KEY constraint cannot be \ dropped" | Some (gt, u) -> let gt' = Ddl.without_unusable gt u in t.all_tables <- List.map (fun g -> if g == gt then gt' else g) t.all_tables; Ddl.destroy_unusable t.pager u ~moved:(Session.root_moved t); Session.rebuild_page1 t; true let drop_index t (d : Sql.Ast.drop) = let target (gt : generic_table) = List.find_opt (fun (i : index) -> ident_equal i.name d.name) gt.indexes in match List.find_map (fun gt -> Option.map (fun i -> (gt, i)) (target gt)) t.all_tables with | None -> if (not (drop_unusable_index t d)) && not d.if_exists then Catalog.Error.fail_prepare "no such index: %s" d.name | Some (_, idx) when idx.sql = None -> Catalog.Error.fail_prepare "index associated with UNIQUE or PRIMARY KEY constraint cannot be \ dropped" | Some (gt, idx) -> let gt' = Ddl.without_index gt idx in t.all_tables <- List.map (fun g -> if g == gt then gt' else g) t.all_tables; let root = Btree.Index.root_page idx.btree in Option.iter (fun from -> Session.root_moved t ~from ~to_:root) (Btree.Index.destroy idx.btree); Session.rebuild_page1 t (* A schema other than main holds nothing, so what a DROP names there is missing (build.c, sqlite3DropTable and its siblings). *) let exec_drop_foreign (d : Sql.Ast.drop) schema = if not d.if_exists then let kind = match d.object_ with | Table -> "table" | Index -> "index" | View -> "view" | Trigger -> "trigger" in Catalog.Error.fail_prepare "no such %s: %s.%s" kind schema d.name (* Whether a DROP TABLE codes the DELETE FROM sqlite3FkDropTable runs before the drop ({!Sql.Private.Foreign_key.Make.drop_deletes}). Coded, it counts into changes() whether it runs or not. *) let drop_deletes t (gt : generic_table) = Write.drop_deletes t gt.schema.tbl_name (* The DELETE itself, where it runs ({!Sql.Private.Foreign_key.Make.drop_delete_runs}). An immediate violation it leaves fails the statement where every statement's does ({!with_undo}), and the undo takes the drop back with the rows, as sqlite3 halts before the schema changes (sqlite3HaltConstraint after OP_FkIfZero with P1 clear). *) let drop_delete t ~run_trigger_body (gt : generic_table) = let table = gt.schema.tbl_name in if Write.drop_delete_runs t table then Write.delete_for_drop t ~run_trigger_body table let exec_drop_main t ~run_trigger_body (d : Sql.Ast.drop) = match d.object_ with | Table -> ( match Handle.table t d.name with | None -> if not d.if_exists then Catalog.Error.fail_prepare "no such table: %s" d.name | Some gt -> (* IF EXISTS does not soften this one: it excuses a name that is not there, and this name is. The table was located first, which is why a "sqlite_" name nothing declares still reads as absent (build.c, sqlite3DropTable, after sqlite3LocateTableItem). *) if not (Ddl.droppable_name gt.schema.tbl_name) then Catalog.Error.fail_prepare "table %s may not be dropped" gt.schema.tbl_name; drop_delete t ~run_trigger_body gt; t.all_tables <- List.filter (fun gt -> not (ident_equal gt.schema.tbl_name d.name)) t.all_tables; Ddl.destroy_table t.pager gt ~moved:(Session.root_moved t); (* The key cache names a b-tree this drop has just destroyed, so it goes with the table -- the store's own ["kv"] as much as a namespaced one, both being entries of the one map. *) t.named_tables <- List.filter (fun (n, _) -> not (ident_equal n d.name)) t.named_tables; t.extra_master <- List.filter (fun rm -> not (ident_equal rm.tbl_name d.name)) t.extra_master; Ident.Tbl.remove t.insert_rowids d.name; (* The counter went with the table. Left behind it would be handed to whatever table is created under that name next, which is a counter about rows that no longer exist (build.c, sqlite3DropTable runs "DELETE FROM sqlite_sequence WHERE name=%Q"). *) Autoinc.drop_counter t d.name; Session.rebuild_page1 t) | Index -> drop_index t d | View -> drop_definition t d `View ~what:"view" | Trigger -> drop_definition t d `Trigger ~what:"trigger" (* The schema table is answered from the catalog and is in no table list, so a DROP naming it locates nothing in either schema. *) let exec_drop t ~run_trigger_body (d : Sql.Ast.drop) = Sql.Private.Schema_table.check_drop d; match d.schema with | Some schema -> exec_drop_foreign d schema | None -> exec_drop_main t ~run_trigger_body d (* The table a DROP TABLE of the main schema names, where it codes the DELETE of {!drop_deletes}: the name sqlite3 would drop, past the checks that refuse it while it is prepared. *) let drop_counts t (d : Sql.Ast.drop) = match (d.schema, d.object_) with | None, Table -> ( match Handle.table t d.name with | Some gt -> Ddl.droppable_name gt.schema.tbl_name && drop_deletes t gt | None -> false) | Some _, _ | None, (Index | View | Trigger) -> false (* The planner otherwise prices every equality on a non-unique index at sqlite3's default of ten rows; ANALYZE walks each index and leaves the counts in [sqlite_stat1], and the samples a sqlite3 built with SQLITE_ENABLE_STAT4 keeps in [sqlite_stat4], the tables sqlite3 declares, so a database analysed here plans the same way there. Both are written whole each time, each created where it is missing, stat1 first (openStatTable). The tables go in the order sqlite3's analyzeDatabase walks its schema hash, which holds the statistics tables only once they exist. The target ANALYZE may name is ignored and the whole database analysed. *) let exec_analyze t = (* Taken before the statistics tables are written to, so what goes in describes the database the statement was given. Which tables ANALYZE reads and what each contributes are the table's own answers ({!Ddl.analyzable}, {!Ddl.analyze}). *) let stat1, stat4 = Sql.Private.Tbl_hash.iteration ("sqlite_master" :: Session.master_names t) |> List.filter_map (Handle.table t) |> List.filter Ddl.analyzable |> List.map Ddl.analyze |> List.split in let reset name ~sql = match Handle.table t name with | Some gt -> ignore (Btree.Table.clear (rowid_btree gt) : int); (* the rows are gone, so the rowids they held are free again *) Ident.Tbl.remove t.insert_rowids name | None -> Autoinc.create_table t ~sql in reset Session.stat_table ~sql:Session.stat_table_sql; reset Session.stat4_table ~sql:Session.stat4_table_sql; let insert table = List.iter (fun row -> ignore (insert_values t ~table row)) in List.iter (insert Session.stat_table) stat1; List.iter (insert Session.stat4_table) stat4; Session.rebuild_page1 t (* Wrap PRAGMA result rows as a [VALUES] select so they flow through the same row channel as a SELECT. *) let pragma_rows_select rows : Sql.Ast.select = { ctes = []; distinct = false; cols = [ { expr = Star; alias = None } ]; from = Values (List.map (List.map (fun v -> Sql.Ast.Lit v)) rows); joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } (* Project a RETURNING clause over the rows a DML statement affected and emit them through [on_select], like a SELECT. [[]] returning is a no-op. *) let emit_returning t cat params ~table returning rows on_select = match returning with | [] -> () | ret -> let cols = table_column_names t table in let projected = Engine.returning_rows cat params ~table ~cols ret rows in on_select cat params (pragma_rows_select projected) (* The direct mutation APIs -- the typed writes, [Kv], [Kv.Table] and [Raw] -- run a mutation outside the SQL statement runner, so they reproduce its autocommit boundary by hand: refresh, then the mutation inside {!Session.autocommit}. Inside an explicit transaction both are no-ops. *) let autocommit_op t f = (* A write is the other thing a scan's callback may not do: the pages it moves are the ones the scan's cursors are standing on. Refused here and in {!mutating}, which are the two ways a write reaches the pages, and before the refresh so nothing has been touched when it raises. *) Handle.check_not_scanning t "wrote"; (* The whole door and not the commit alone: the refresh below reads the log beside the file, which suspends the fiber running it, and a second fiber arriving between that read and the commit would write from a page count this one has already read. *) Session.write_op t @@ fun () -> Session.maybe_refresh t; Handle.statement_boundary t; Session.autocommit t (fun () -> Session.new_database t; f ()) (* How far back a failing statement is undone, by the resolution the failing constraint recorded as it unwound. *) let undo_scope t = Sql.Private.Connection.(undo_scope (resolved (Handle.connection t))) let with_undo t f = let conn = Handle.connection t in Sql.Private.Connection.start conn; Autoinc.discard t; (* the end of the statement's program writes the AUTOINCREMENT counters before OP_Halt judges the foreign keys (insert.c, sqlite3AutoincrementEnd; {!Sql.Private.Connection.atomic}) *) let f () = let r = f () in Autoinc.flush t; r in match Sql.Private.Connection.atomic conn f with | r -> r | exception exn -> (* a halted program never reaches its end *) Autoinc.discard t; raise exn (* Run a mutating statement as the statement it is, atomic through the connection: outside a transaction its own, made durable when it ends; a trigger body's statement belongs to the statement that fired it. It takes the write session first, and a read-only handle is turned away before the statement has touched a page. A statement that [begins_write] lays page 1 of a database of no pages out first, inside its undo, as sqlite3BtreeBeginTrans calls newDatabase (btree.c); a PRAGMA does not, and writes page 1 only where it sets a header field ({!Session.rebuild_page1}). *) let undone ~begins_write t f = (* The SQL half of the same refusal: an INSERT, an UPDATE, a DELETE or a DDL reaches the pages through here, whether it was written out as a statement or spelled by one of the direct doors. Before the undo opens, so the refusal leaves no journal behind and no row written. *) Handle.check_not_scanning t "wrote"; Session.writing t; Session.check_writable t; with_undo t (fun () -> if begins_write then Session.new_database t; f ()) let mutating t f = undone ~begins_write:true t f (* An INSERT, UPDATE or DELETE publishes the rows it changed when it ends, and one a failure undid publishes none: what a FAIL kept is published, what an ABORT or a ROLLBACK undid is not (vdbeaux.c, sqlite3VdbeHalt and sqlite3VdbeSetChanges). *) let counted t f = match f () with | r -> Sql.Private.Connection.publish (Handle.connection t); r | exception e -> let bt = Printexc.get_raw_backtrace () in (match undo_scope t with | `Row -> Sql.Private.Connection.publish (Handle.connection t) | `Statement | `Transaction -> Sql.Private.Connection.discard (Handle.connection t)); Printexc.raise_with_backtrace e bt (* A trigger step's INSERT, UPDATE or DELETE publishes its count when it ends, inside the program's frame (trigger.c, codeTriggerProgram, the OP_ResetCount after each step). *) let step t f = ignore (f () : (int64 option * Sql.Ast.value list) list); Sql.Private.Connection.publish (Handle.connection t) (* A statement that may change the schema: one that did moves the schema cookie (sqlite3ChangeCookie), inside its undo, so a failed statement or a rolled-back transaction takes the move back with the rows. A statement that left sqlite_master as it was -- CREATE ... IF NOT EXISTS of a table already there -- moves nothing, as in sqlite3. *) let schema_changing t f = mutating t (fun () -> let before = Session.master_entries t in let r = f () in if Session.master_entries t <> before then Handle.bump_schema_cookie t; r) (* [exec_stmt] and [run_trigger_body] are one knot: a write fires its triggers, a trigger body is a statement, and a statement may be that write again. The executor is handed down rather than left in a cell, so no firing is without one. *) let rec exec_stmt t cat params ~sql ~on_select stmt = (* Each statement reads the wall clock for itself, so the last reading is dropped here rather than at the script door. A trigger body is not a statement of its own for this purpose. *) Handle.statement_boundary t; match stmt with (* A script enters through {!Session.script_op}, which asks nothing about a scan standing on a row: a script that writes is not a read, and the write it makes is refused by {!mutating} with the verb that fits. What is left is the script's own reads, refused here. *) | Sql.Ast.Select s -> Handle.check_not_scanning t "read"; Session.pin_read t; on_select cat params s | Explain e -> Handle.check_not_scanning t "read"; Session.pin_read t; on_select cat params (pragma_rows_select (explain_rows t e)) | Insert i -> let rows = counted t (fun () -> mutating t (fun () -> Write.register_programs t stmt; Write.exec_insert t cat params ~run_trigger_body i)) in emit_returning t cat params ~table:i.table i.returning rows on_select | Delete d -> let rows = counted t (fun () -> mutating t (fun () -> Write.register_programs t stmt; Write.exec_delete ~select:(R.dml_rows t) ~scan:(dml_scan t params) t cat params ~run_trigger_body d)) in emit_returning t cat params ~table:d.table d.returning rows on_select | Update u -> let rows = counted t (fun () -> mutating t (fun () -> Write.register_programs t stmt; Write.exec_update ~select:(R.dml_rows t) ~scan:(fun ~refused -> dml_scan ~refused t params) t cat params ~run_trigger_body u)) in emit_returning t cat params ~table:u.table u.returning rows on_select | Create_table ct -> schema_changing t (fun () -> exec_create_table t ~sql ct) | Create_table_as cta -> schema_changing t (fun () -> exec_create_table_as t cat params cta) | Create_index ci -> schema_changing t (fun () -> exec_create_index t ~sql ci) | Create_view cv -> schema_changing t (fun () -> exec_create_view t ~sql cv) | Create_trigger tg -> schema_changing t (fun () -> exec_create_trigger t ~sql tg) | Drop d -> let drop () = schema_changing t (fun () -> exec_drop t ~run_trigger_body d) in if drop_counts t d then counted t drop else drop () | Alter_table a -> schema_changing t (fun () -> exec_alter_table t ~sql a) (* A setting of the handle changes no page, so it needs no undo and no handle that may write: sqlite3 takes it on a read-only connection. *) | Pragma p when Pragma.sets_connection p -> ( match Pragma.exec t p with | [] -> () | rows -> on_select cat params (pragma_rows_select rows)) | Pragma p -> ( (* A PRAGMA that only reads is a read, as a SELECT is: no statement journal, which a read-only handle refuses, and no write session. *) let rows = if Pragma.reads_only p then begin Handle.check_not_scanning t "read"; Session.pin_read t; Pragma.exec t p end else undone ~begins_write:false t (fun () -> Pragma.exec t p) in match rows with | [] -> () | rows -> on_select cat params (pragma_rows_select rows)) (* The transaction verbs are the connection's, which drives the file store's transaction door ({!Session.begin_transaction}); they are the undo machinery, not subjects of it. *) | Begin kind -> Sql.Private.Connection.begin_ (Handle.connection t) kind | Commit -> Sql.Private.Connection.commit (Handle.connection t) | Rollback -> Sql.Private.Connection.rollback (Handle.connection t) | Savepoint name -> Sql.Private.Connection.savepoint (Handle.connection t) name | Release name -> Sql.Private.Connection.release (Handle.connection t) name | Rollback_to name -> Sql.Private.Connection.rollback_to (Handle.connection t) name | Vacuum None -> exec_vacuum t | Vacuum (Some file) -> ( Session.check_vacuum t; Session.pin_read t; match (Engine.eval_const cat params file, t.db_path) with | Text name, Some (dir, _) -> Session.vacuum_into_read t (dir, name) | Text _, None -> Catalog.Error.fail_runtime "cannot VACUUM INTO from a database with no directory" | _ -> Catalog.Error.fail_runtime "non-text filename") | Analyze -> schema_changing t (fun () -> exec_analyze t) (* Run one step of a trigger program, in the frame already on the connection ({!Sql.Private.Connection.current}). A step is part of the statement that fired it, not a statement of its own: it opens no undo and crosses no statement boundary, and the firing statement's undo covers what it writes. Its conflict policy is the frame's where the firing statement named one, else its own OR clause (trigger.c, codeTriggerProgram). A body SELECT runs and its rows are discarded, since a [RAISE()] in it is what stops the firing statement and the function it names must exist. *) and run_trigger_body t stmt = let frame = Sql.Private.Connection.current (Handle.connection t) in let cat = catalog t and params = [||] in match stmt with | Sql.Ast.Insert i -> step t (fun () -> Write.exec_insert t cat params ~run_trigger_body { i with conflict = Sql.Private.Trigger.step_policy frame i.conflict; }) | Update u -> step t (fun () -> Write.exec_update ~select:(R.dml_rows t) ~scan:(fun ~refused -> dml_scan ~refused t params) t cat params ~run_trigger_body { u with conflict = Sql.Private.Trigger.step_policy frame u.conflict; }) | Delete d -> step t (fun () -> Write.exec_delete ~select:(R.dml_rows t) ~scan:(dml_scan t params) t cat params ~run_trigger_body d) (* A body SELECT reads the OLD/NEW row like the body's writes do, so the scope is bound in first as parameters ({!Resolve.bind_scope}), turning it into a select the VM can scan on its own. *) | Select s -> let u, params = Resolve.bind_scope (Sql.Private.Query.resolve_env cat) frame.scope s ~params in ignore (vm_select_rows t cat params u) | _ -> Fmt.invalid_arg "a trigger body holds only INSERT, UPDATE, DELETE and SELECT" (* A statement that reads the database outside a transaction ends one, as it ends ({!Sql.Private.Connection.end_read}). *) let run_stmt t cat params ~sql ~on_select stmt = let ended () = if Sql.Private.Connection.reads_database ~sets_connection:Pragma.sets_connection stmt then Sql.Private.Connection.end_read (Handle.connection t) in match exec_stmt t cat params ~sql ~on_select stmt with | () -> ended () | exception exn -> let bt = Printexc.get_raw_backtrace () in ended (); Printexc.raise_with_backtrace exn bt (* Run every statement of a [;]-separated script in order. SELECTs go to [on_select]; a fresh catalog per statement so each sees the rows left by the ones before it. *) let run_statements t sql ~params ~on_select = (* Run every statement of a [;]-separated script in order, a fresh catalog per statement. It goes in through the same boundary as every other door, so a read-only handle is counted in the reader registry while it runs. {!Session.script_op} and not {!Session.read_op}, since a script runs once and its statements say what they read. *) script t ~stmt:snd (parse_script ~known:(holds t) sql) @@ fun stmts -> let params = Array.of_list params in Seq.iter (fun (sql, stmt) -> run_stmt t (catalog t) params ~sql ~on_select stmt) stmts let exec t sql ~params = run_statements t sql ~params ~on_select:(fun _ _ _ -> invalid_arg "exec: SELECT returns rows; use Sqlite.query or Raw.run") (* A SELECT of a script runs as {!iter} runs one: through the access paths a seek or a bounded scan takes, then the VM, then the engine. *) let run_script t sql ~params ~on_row = run_statements t sql ~params ~on_select:(fun cat params s -> vm_select_iter t cat params s ~f:(fun r -> on_row (Sql.Row.to_list r))) let user_version t = Session.read_op t (fun () -> t.user_version) let set_user_version t v = autocommit_op t (fun () -> t.user_version <- v; Session.rebuild_page1 t) let query t sql ~params = Session.read_op t @@ fun () -> Handle.statement_boundary t; match parse_query_cached t sql with | Select_query (s, memo) -> let params = Array.of_list params in vm_select_rows ~memo t (catalog t) params s | Explain_query e -> explain_rows t e | Pragma_query p -> Pragma.query t p (* {!query} answering a row at a time. The same one statement -- [parse_query] refuses a script, which has an answer per statement where this has one -- and the same read around it, so [f] is called while the handle is holding the state its rows were read from. *) let emit_values f rows = List.iter (fun vs -> Sql.Row.with_values vs f) rows let iter t sql ~params ~f = Session.read_op t @@ fun () -> Handle.statement_boundary t; match parse_query_cached t sql with | Select_query (s, memo) -> let params = Array.of_list params in vm_select_iter ~memo t (catalog t) params s ~f | Explain_query e -> emit_values f (explain_rows t e) | Pragma_query p -> emit_values f (Pragma.query t p) end