Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
module Ast = Astmodule Json = Sqlite_jsonmodule Jsonb = Jsonbmodule Collation = Collationmodule Encoding = Encodingmodule Order = Ordermodule Decimal = Decimalmodule Value_ops = Value_opsmodule Row = Rowmodule Ir = Irmodule Sqlite3_semantics = Sqlite3_semanticsmodule Vdbe = Vdbemodule Closure = Closuremodule Join = Join
let parse sql = Lexer.parse_statements sql
module Spi = Catalog.Spi
type outcome = Rows of Catalog.Value.t list list | Donetype t = Connection.t
let pp = Connection.pplet catalog = Connection.cataloglet changes = Connection.changeslet total_changes = Connection.total_changeslet last_insert_rowid = Connection.last_insert_rowidlet close = Connection.close
(* Whether the catalog holds a table of that name, under SQL's own comparison for one. {!Spi.tables} is the question every backend answers; {!Spi.schema} is not, since a backend that tracks no schema answers [None] for a table it holds. *)let table_exists cat name = List.exists (Ast.ident_equal name) (Spi.tables cat)
(* The table holding the index [name], if any: an index name is one namespace across the catalog, and each table's schema lists its own. *)let index_owner cat name = List.find_opt (fun table -> match Spi.schema cat table with | Some s -> List.exists (fun (i : Spi.Schema.index) -> Ast.ident_equal i.name name) s.indexes | None -> false) (Spi.tables cat)
(* What already holds a name a table or a view would take: names are one namespace across tables, views and indexes (build.c, sqlite3CheckObjectName). *)let holder cat name : View.holder option = if table_exists cat name then Some `Table else if Option.is_some (View.find cat name) then Some `View else if Option.is_some (index_owner cat name) then Some `Index else None
let triggers_of cat table = List.filter_map (fun (_, (d : Spi.Definition.t)) -> if d.kind = `Trigger && Ast.ident_equal d.table table then Some d.name else None) (Spi.definitions cat)
let trigger_exists cat name = List.exists (fun (_, d) -> Spi.Definition.is d `Trigger name) (Spi.definitions cat)
(* What a statement is called, in the refusal of one this engine does not run. *)let statement_name : Ast.stmt -> string = function | Select _ -> "SELECT" | Explain { query_plan = true; _ } -> "EXPLAIN QUERY PLAN" | Explain { query_plan = false; _ } -> "EXPLAIN" | Insert _ -> "INSERT" | Delete _ -> "DELETE" | Update _ -> "UPDATE" | Create_table _ -> "CREATE TABLE" | Create_table_as _ -> "CREATE TABLE ... AS" | Create_index _ -> "CREATE INDEX" | Create_view _ -> "CREATE VIEW" | Create_trigger _ -> "CREATE TRIGGER" | Drop { object_ = Table; _ } -> "DROP TABLE" | Drop { object_ = Index; _ } -> "DROP INDEX" | Drop { object_ = View; _ } -> "DROP VIEW" | Drop { object_ = Trigger; _ } -> "DROP TRIGGER" | Alter_table _ -> "ALTER TABLE" | Pragma _ -> "PRAGMA" | Begin _ -> "BEGIN" | Commit -> "COMMIT" | Rollback -> "ROLLBACK" | Savepoint _ -> "SAVEPOINT" | Release _ -> "RELEASE" | Rollback_to _ -> "ROLLBACK TO" | Vacuum _ -> "VACUUM" | Analyze -> "ANALYZE"
(* An INSERT, UPDATE or DELETE is atomic, counts from zero and publishes what it changed when it ends (vdbeaux.c, sqlite3VdbeHalt and sqlite3VdbeSetChanges), and one with a RETURNING answers its rows. One that fails is undone as far back as the resolution of its violation says ({!Connection.resolved}): one that keeps its rows publishes them, one undone publishes none. Its AUTOINCREMENT counters are registered before it runs and written back when it completes, and none where it fails ({!Write.register_programs}). *)let counted conn st ~returning f = Connection.start conn; let run () = Write.register_programs conn st; let rows = f () in Write.flush_counters conn; rows in match Connection.atomic conn run with | rows -> Connection.publish conn; if returning = [] then Done else Rows rows | exception e -> let bt = Printexc.get_raw_backtrace () in Write.discard_counters conn; (match Connection.(undo_scope (resolved conn)) with | `Row -> Connection.publish conn | `Statement | `Transaction -> Connection.discard conn); Printexc.raise_with_backtrace e bt
(* The tables in the order sqlite3's schema hash iterates them, as a schema load inserts the schema table and then each table and view (pragma.c, PragTyp_FOREIGN_KEY_CHECK). *)let schema_order cat = let views = List.filter_map (fun (_, (d : Spi.Definition.t)) -> if d.kind = `View then Some d.name else None) (Spi.definitions cat) in List.filter (fun n -> not (String.equal n "sqlite_master")) (Tbl_hash.iteration (("sqlite_master" :: Spi.tables cat) @ views))
(* sqlite_sequence, which the first AUTOINCREMENT table makes after itself (build.c, sqlite3EndTable), declared as sqlite3 declares it. *)let sequence_table cat = match Lexer.parse Autoinc.table_sql with | Ok ct -> Spi.table cat ~sql:Autoinc.table_sql (Engine.table_schema ~source:Autoinc.table_sql ct) | Error e -> Fmt.invalid_arg "Sql: %s: %s" Autoinc.table_sql e
(* A dropped AUTOINCREMENT table's counter goes with it (build.c, sqlite3CodeDropTable: DELETE FROM sqlite_sequence WHERE name = the table). *)let drop_counter cat name = match Spi.schema cat name with | Some s when s.autoincrement && table_exists cat Autoinc.table -> List.iter (fun ((_, row) as r) -> match row with | Catalog.Value.Text n :: _ when Ast.ident_equal n name -> Spi.delete cat Autoinc.table ~row:r | _ -> ()) (Spi.rows_rowid cat Autoinc.table) | Some _ | None -> ()
(* A change of the schema is atomic too, and counts nothing. *)let ddl conn f = Connection.start conn; Connection.atomic conn f; Done
(* The pragmas over a store: what the engine answers from the definitions, the schemas and the rows the store keeps. A store has no file, so it adds no pragma of its own. *)module Pragmas = Pragma.Make (struct type t = Connection.t
let connection conn = conn
(* A table first, then a view, as sqlite3LocateTable finds them; a table read from the text it holds, where its store keeps one. *) let relation conn name = let cat = Connection.catalog conn in if table_exists cat name then let text = List.find_map (fun (_, (d : Spi.Definition.t)) -> if Spi.Definition.is d `Table name then d.sql else None) (Spi.definitions cat) in match Option.map (fun sql -> (sql, Lexer.parse sql)) text with | Some (sql, Ok ct) -> Some (Pragma.Table (ct, sql)) | Some (_, Error _) | None -> Option.map (fun s -> Pragma.Declared s) (Spi.schema cat name) else Option.map (fun cv -> Pragma.View (Query.resolve_env (Engine.catalog conn), cv)) (View.find cat name)
let tables conn = let cat = Connection.catalog conn in List.filter_map (fun name -> Option.map (fun (s : Spi.Schema.t) -> { Introspect.table = s.table; columns = Spi.Schema.column_names s; without_rowid = s.without_rowid; indexes = Introspect.indexes s; }) (Spi.schema cat name)) (Spi.tables cat)
let table conn name = Option.map Table.v (Spi.schema (Connection.catalog conn) name)
let schema_order conn = schema_order (Connection.catalog conn)
let is_view conn name = Option.is_some (View.find (Connection.catalog conn) name)
let table_name conn name = match Spi.schema (Connection.catalog conn) name with | Some s -> s.table | None -> Catalog.Error.fail_prepare "no such table: %s" name
let foreign_key_check conn names = Foreign_key.check_rows (Write.foreign_key_violations conn names)
(* The schema table holds rows no rule reads. *) let integrity conn ~quick:_ ~budget table = let cat = Connection.catalog conn in match table with | Some name when Schema_table.is_name name -> [ "ok" ] | Some name when not (table_exists cat name) -> Catalog.Error.fail_prepare "no such table: %s" name | table -> Integrity.check cat ~budget table
let pragmas = []end)
let v ?recursion_cap cat = Connection.v ?recursion_cap ~table_function:Pragmas.table_function cat
(* A pragma answers its rows, or none for one that sets what it names. *)let pragma conn p = match Pragmas.exec conn p with [] -> Done | rows -> Rows rows
(* A table checked as sqlite3StartTable and sqlite3EndTable check it, and the sqlite_sequence the first AUTOINCREMENT table makes after it. *)let new_table conn ~source (ct : Ast.create_table) = let cat = Connection.catalog conn in Create_table.check_columns ct; let schema = Engine.table_schema ~source ct in (* a generation cycle is the one rule sqlite3 leaves to the statement *) Self_ref.check_generated_loop (List.map (fun (n, (g : Ast.generated_column)) -> (n, g.expr)) ct.generated); ddl conn (fun () -> Spi.table cat ~sql:(Alter_text.stored source) schema; if schema.autoincrement && not (table_exists cat Autoinc.table) then sequence_table cat)
let stmt conn ~source (st : Ast.stmt) = let cat = Connection.catalog conn in (match st with Drop d -> Schema_table.check_drop d | _ -> ()); match st with | Create_table ct when ct.ct_if_not_exists && table_exists cat ct.tbl_name -> Done (* the name is located before a column is read (build.c, sqlite3StartTable) *) | Create_table ct when table_exists cat ct.tbl_name -> Catalog.Error.fail_prepare "table %s already exists" ct.tbl_name | Create_table ct when Option.is_some (View.find cat ct.tbl_name) -> if ct.ct_if_not_exists then Done else Catalog.Error.fail_prepare "view %s already exists" ct.tbl_name | Create_table ct -> new_table conn ~source ct | Create_index ci when ci.if_not_exists && index_owner cat ci.name <> None -> Done | Create_index ci -> ddl conn (fun () -> Spi.index cat ~sql:(Alter_text.stored source) ci.table (Engine.index_schema ci)) | Insert i -> counted conn st ~returning:i.returning (fun () -> Write.insert conn i) | Delete d -> counted conn st ~returning:d.returning (fun () -> Write.delete conn d) | Update u -> counted conn st ~returning:u.returning (fun () -> Write.update conn u) | Select s -> let cat = Engine.catalog conn in (* checked as it runs: a table-valued function's hidden columns are its arguments by then, which a name of a subquery reads *) Query.check_select cat (Query.table_arguments cat [||] s); Rows (Engine.run_select cat s [||]) | Drop { object_ = Table; name; _ } when Option.is_some (View.find cat name) -> Catalog.Error.fail_prepare "use DROP VIEW to delete view %s" name | Drop { schema = None; object_ = Table; name; if_exists } when if_exists && not (table_exists cat name) -> Done (* a table's triggers go with it (build.c, sqlite3DropTable), and under foreign keys its rows first, as a DELETE that counts them (fkey.c, sqlite3FkDropTable) *) | Drop { object_ = Table; name; _ } -> let drop () = Write.delete_for_drop conn name; List.iter (Spi.undefine cat `Trigger) (triggers_of cat name); drop_counter cat name; Spi.drop_table cat name in if Write.drop_deletes conn name then counted conn st ~returning:[] (fun () -> drop (); []) else ddl conn drop | Create_view cv -> ddl conn (fun () -> if View.check_create ~held:(holder cat cv.name) cv then Spi.define cat (Spi.Definition.v `View ~name:cv.name ~table:cv.name (Some (Alter_text.stored source)))) | Drop { schema = None; object_ = View; name; if_exists } -> if Option.is_some (View.find cat name) then ddl conn (fun () -> Spi.undefine cat `View name) else if table_exists cat name then Catalog.Error.fail_prepare "use DROP TABLE to delete table %s" name else if if_exists then Done else Catalog.Error.fail_prepare "no such view: %s" name (* a trigger's target is looked up among tables and views alone, and its name among triggers alone (trigger.c, sqlite3BeginTrigger) *) | Create_trigger tg -> let target = match holder cat tg.table with | Some `Table -> Some `Table | Some `View -> Some `View | Some `Index | None -> None in ddl conn (fun () -> if Trigger.check_create ~target ~taken:(trigger_exists cat tg.name) tg then Spi.define cat (Spi.Definition.v `Trigger ~name:tg.name ~table:tg.table (Some (Alter_text.stored source)))) | Alter_table a -> ddl conn (fun () -> Alter.exec conn ~held:(fun n -> Option.is_some (holder cat n)) ~source a) | Pragma p -> pragma conn p | Drop { schema = None; object_ = Trigger; name; if_exists } -> if trigger_exists cat name then ddl conn (fun () -> Spi.undefine cat `Trigger name) else if if_exists then Done else Catalog.Error.fail_prepare "no such trigger: %s" name | Drop { schema = None; object_ = Index; name; if_exists } -> ( match index_owner cat name with | Some table -> ddl conn (fun () -> Spi.drop_index cat table name) | None when if_exists -> Done | None -> Catalog.Error.fail_prepare "no such index: %s" name) | Begin kind -> Connection.begin_ conn kind; Done | Commit -> Connection.commit conn; Done | Rollback -> Connection.rollback conn; Done | Savepoint name -> Connection.savepoint conn name; Done | Release name -> Connection.release conn name; Done | Rollback_to name -> Connection.rollback_to conn name; Done | st -> Engine.unsupported (statement_name st)
(* A statement that read the database outside a transaction ends the one it read in, whether it ran or failed. *)let run_statement conn ~source st = match stmt conn ~source st with | outcome -> if Connection.reads_database ~sets_connection:Pragmas.sets_connection st then Connection.end_read conn; outcome | exception e -> let bt = Printexc.get_raw_backtrace () in if Connection.reads_database ~sets_connection:Pragmas.sets_connection st then Connection.end_read conn; Printexc.raise_with_backtrace e bt
(* Run [sql]'s statements in order on [conn], each prepared once the one before it ran, as sqlite3_exec prepares them; the result is the last one's -- rows for a trailing SELECT, [Done] otherwise. Each statement's text is its own source, the text a definition it makes keeps. *)let exec conn sql = Seq.fold_left (fun _ -> function | Ok (text, st) -> run_statement conn ~source:text st (* 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 e -> Catalog.Error.fail_prepare "%s" e) Done (Lexer.script ~known:(fun name -> (Engine.catalog conn).holds name) sql)
let select conn s ~params = Engine.run_select (Engine.catalog conn) (Param_number.number_select s) (Array.of_list params)
let query conn sql ~params = match parse sql with | Error e -> Catalog.Error.fail_prepare "%s" e | Ok [ Ast.Select s ] -> select conn s ~params | Ok _ -> Catalog.Error.fail_prepare "query: %S is not one SELECT" sql
let eval conn e = Engine.eval_const (Engine.catalog conn) [||] elet explain_select conn s = Query.explain (Engine.catalog conn) slet run = Typed.runlet iter = Typed.iterlet explain = Typed.explainlet text_of_query = Typed.text_of_querylet update = Typed.updatelet delete = Typed.deletelet ident = Render.identlet pp_ident = Render.pp_identlet pp_expr = Render.pp_exprlet pp_select = Render.pp_select
module Private = struct module Alter = Alter module Alter_text = Alter_text module Autoinc = Autoinc module Collate = Collate module Conflict = Conflict module Connection = Connection module Column_tokens = Column_tokens module Create_table = Create_table module Datetime = Datetime module Engine = Engine module Func = Func module Integrity = Integrity module Introspect = Introspect module Json1 = Json1 module Lexer = Lexer module Lower = Lower module Param_number = Param_number module Pragma = Pragma module Pragma_value = Pragma_value module Parser = Parser module Plan = Plan module Query = Query module Render = Render module Resolve = Resolve module Schema_table = Schema_table module Self_ref = Self_ref module Strict = Strict module Table = Table module Value_op = Value_op module View = View module Trigger = Trigger module Semantics = Semantics module Vdbe_core = Vdbe_core module Ir_core = Ir_core module Closure_core = Closure_core module Row_core = Row_core module Join_core = Join_core module Window = Window module Write = Write module Foreign_key = Foreign_key module Tbl_hash = Tbl_hashend