(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* sqlite3's transfer optimisation (insert.c, xferOptimization), condition for condition: where it copies records whole, so does this; where it does not, the statement takes the ordinary path. The two differ in more than speed, since a transfer into a table with an index keeps the source's rowids. *) open Model type t = { src : generic_table; keep_rowids : bool; check_rowids : bool; needs_empty : bool; conflict : Sql.Ast.insert_conflict; indexes : (index * index) list; } let source (i : Sql.Ast.insert) = match i with | { columns = []; upsert = None; returning = []; source = Select { ctes = []; distinct = false; cols = [ { expr = Star; alias = None } ]; from = Table { name; subquery = None; _ }; joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; }; _; } -> Some name | _ -> None let same_name a b = match (a, b) with | None, None -> true | Some a, Some b -> Catalog.Ident.equal a b | Some _, None | None, Some _ -> false let same_expr a b = match (a, b) with | None, None -> true | Some a, Some b -> Sql.Ast.equal_expr a b | Some _, None | None, Some _ -> false (* A STRICT [dst] column takes what a STRICT [src] column holds when it is ANY, the same type, or INT for INTEGER and back. *) let strict_fits ~dst ~src = match (dst, src) with | Sql.Private.Strict.Any, _ -> true | (Sql.Private.Strict.Int | Integer), (Sql.Private.Strict.Int | Integer) -> true | d, s -> d = s (* The conflict resolution an index carries (pIdx->onError): none for a plain index, ABORT for a CREATE UNIQUE INDEX, and for a constraint's autoindex the clause it names, which is a value of its own when it names none. *) let index_on_error (idx : index) = if not idx.unique then `None else match (idx.origin, idx.on_conflict) with | Created, _ -> `Resolve Sql.Ast.Abort | (Unique_constraint | Primary_key), Sql.Ast.Unspecified -> `Default | (Unique_constraint | Primary_key), c -> `Resolve c let same_key a b = match (a, b) with | Column i, Column j -> i = j | Expression a, Expression b -> Sql.Ast.equal_expr a b | Column _, Expression _ | Expression _, Column _ -> false let same_index_column (a : index_column) (b : index_column) = a.cid = b.cid && Sql.Order.equal a.order b.order let same_columns a b = List.compare_lengths a b = 0 && List.for_all2 same_index_column a b let same_trailing a b = match (a, b) with | Rowid_ref, Rowid_ref -> true | Pk_ref a, Pk_ref b -> same_columns a b | Rowid_ref, Pk_ref _ | Pk_ref _, Rowid_ref -> false (* xferCompatibleIndex: the same keys in the same orders, the same resolution and the same WHERE. *) let compatible_index (d : index) (s : index) = index_on_error d = index_on_error s && List.compare_lengths d.keys s.keys = 0 && List.for_all2 same_key d.keys s.keys && List.compare_lengths d.orders s.orders = 0 && List.for_all2 Sql.Order.equal d.orders s.orders && same_trailing d.trailing s.trailing && same_expr d.where s.where let generated_expr (ct : Sql.Ast.create_table) name = Option.map (fun (g : Sql.Ast.generated_column) -> g.expr) (Catalog.Ident.assoc_opt name ct.generated) let default_text (schema : schema) (ct : Sql.Ast.create_table) name = Option.map (Sql.Ast.default_text schema.sql) (Catalog.Ident.assoc_opt name ct.defaults) (* A table and its parsed CREATE text, which the conditions read. *) type side = { gt : generic_table; ct : Sql.Ast.create_table } let strict_column_fits ~strict dst_storage src_storage = match (strict, dst_storage, src_storage) with | true, Sql.Private.Table.Strict d, Sql.Private.Table.Strict s -> strict_fits ~dst:d ~src:s | true, _, _ -> false | false, _, _ -> true (* Both generated alike, with the same expression, or neither generated: a generated column is copied as it is stored. *) let generated_fits dst src (dc : column) (sc : column) = dc.generated = sc.generated && (dc.generated = None || same_expr (generated_expr dst.ct dc.name) (generated_expr src.ct sc.name)) (* Past the first column the DEFAULTs read the same, since a record shorter than its table reads its missing columns from them. *) let default_fits dst src i (dc : column) (sc : column) = dc.generated <> None || i = 0 || Option.equal String.equal (default_text dst.gt.schema dst.ct dc.name) (default_text src.gt.schema src.ct sc.name) (* The per-column conditions, the [i]th column of each table. *) let column_fits ~strict dst src i ((dc : column), dst_storage) ((sc : column), src_storage) = strict_column_fits ~strict dst_storage src_storage && generated_fits dst src dc sc && Sql.Private.Table.affinity dst_storage = Sql.Private.Table.affinity src_storage && same_name dc.collation sc.collation && (dc.not_null = None || sc.not_null <> None) && default_fits dst src i dc sc let rec columns_fit ~strict dst src i ds ss = match (ds, ss) with | d :: ds, s :: ss -> column_fits ~strict dst src i d s && columns_fit ~strict dst src (i + 1) ds ss | [], [] -> true | _ :: _, [] | [], _ :: _ -> false (* Whether [e] reads the rowid of [dst]: [rowid], [oid] or [_rowid_] where no declared column takes the name (insert.c, xferCheckRowid: a TK_COLUMN with iColumn < 0). *) let reads_rowid (dst : generic_table) e = let found = ref false in Sql.Private.Resolve.walk_expr ~table:(fun () _ -> ()) ~col:(fun () _ name -> if Decl.written_rowid dst.schema.columns ~has_rowid:true name then found := true) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> None) () e; !found (* The CHECKs of [dst] are those of [src], so a copied row passes them; and, where [dst] has no INTEGER PRIMARY KEY ([ipk] false), none reads the rowid, whether the copy would keep the rowids or not. That is sqlite3 3.54's rule (insert.c:3014-3027, xferCompatibleCheck, after forum post 2026-05-11T13:15:57Z): the rows then go in one by one, each under the rowid it is given and checked there. *) let checks_fit ~dst ~(dct : Sql.Ast.create_table) ~(sct : Sql.Ast.create_table) ~ipk = dct.checks = [] || List.compare_lengths dct.checks sct.checks = 0 && List.for_all2 (fun (d : Sql.Ast.check_constraint) (s : Sql.Ast.check_constraint) -> Sql.Ast.equal_expr d.expr s.expr) dct.checks sct.checks && (ipk || not (List.exists (fun (c : Sql.Ast.check_constraint) -> reads_rowid dst c.expr) dct.checks)) (* The PRIMARY KEY a WITHOUT ROWID table is ordered by: its key columns and their conflict resolutions. *) let same_pk (d : generic_table) (s : generic_table) = match (d.store, s.store) with | Rowid_rows _, Rowid_rows _ -> true | Pk_index_rows dp, Pk_index_rows sp -> ( match (dp.key, sp.key) with | Some (dk, dn), Some (sk, sn) -> dn = sn && same_columns dk sk && List.for_all2 (fun (a : column) (b : column) -> a.primary_key = b.primary_key) d.schema.columns s.schema.columns | _ -> false) | Rowid_rows _, Pk_index_rows _ | Pk_index_rows _, Rowid_rows _ -> false (* The statement's resolution, or the INTEGER PRIMARY KEY's ON CONFLICT where it names none, or ABORT. *) let on_conflict ~conflict (dst : generic_table) ipk = match conflict with | Sql.Ast.Unspecified -> ( match Option.bind ipk (fun i -> (List.nth dst.schema.columns i).primary_key) with | None | Some Sql.Ast.Unspecified -> Sql.Ast.Abort | Some c -> c) | Abort | Fail | Ignore | Replace | Rollback -> conflict (* Each index of [dst] with the index of [src] it copies, or [None] where one has none. *) let paired_indexes (dst : generic_table) (src : generic_table) = let pairs = List.filter_map (fun d -> Option.map (fun s -> (d, s)) (List.find_opt (compatible_index d) src.indexes)) dst.indexes in if List.compare_lengths pairs dst.indexes = 0 then Some pairs else None (* The table-wide conditions that need no parse of either table. *) let tables_fit ~fk_enforce ~triggers (dst : generic_table) (dct : Sql.Ast.create_table) (src : generic_table) = (not triggers) && (not (fk_enforce && dct.foreign_keys <> [])) && (not (Catalog.Ident.equal dst.schema.tbl_name src.schema.tbl_name)) && rowid_stored dst = rowid_stored src && List.compare_lengths dst.schema.columns src.schema.columns = 0 && Decl.rowid_alias_index dst.schema.columns = Decl.rowid_alias_index src.schema.columns let v ~conflict ~indexes (dst : generic_table) src ipk = let conflict = on_conflict ~conflict dst ipk in let unique = (not (rowid_stored dst)) || List.exists (fun (i : index) -> i.unique) dst.indexes in { src; keep_rowids = ipk <> None || dst.indexes <> []; check_rowids = ipk <> None; needs_empty = (ipk = None && dst.indexes <> []) || unique || not (match conflict with | Sql.Ast.Abort | Rollback -> true | Unspecified | Fail | Ignore | Replace -> false); conflict; indexes; } let plan ~fk_enforce ~triggers ~conflict ~(dst : generic_table) (src : generic_table) = match (dst.schema.parsed, src.schema.parsed) with | Some dct, Some sct when tables_fit ~fk_enforce ~triggers dst dct src -> ( let ipk = Decl.rowid_alias_index dst.schema.columns in let strict = dct.ct_strict in let d = { gt = dst; ct = dct } and s = { gt = src; ct = sct } in match paired_indexes dst src with | Some indexes when ((not strict) || sct.ct_strict) && columns_fit ~strict d s 0 (List.combine dst.schema.columns (Sql.Private.Table.storage (Row.table dst.schema))) (List.combine src.schema.columns (Sql.Private.Table.storage (Row.table src.schema))) && same_pk dst src && checks_fit ~dst ~dct ~sct ~ipk:(ipk <> None) -> Some (v ~conflict ~indexes dst src ipk) | Some _ | None -> None) | _ -> None let conflict_name : Sql.Ast.insert_conflict -> string = function | Unspecified -> "unspecified" | Abort -> "ABORT" | Fail -> "FAIL" | Ignore -> "IGNORE" | Replace -> "REPLACE" | Rollback -> "ROLLBACK" let pp ppf t = Fmt.pf ppf "@[transfer from %s, rowids %s%s%s, %s, %d index%s@]" t.src.schema.tbl_name (if t.keep_rowids then "kept" else "renumbered") (if t.check_rowids then " and checked" else "") (if t.needs_empty then ", into an empty table" else "") (conflict_name t.conflict) (List.length t.indexes) (if List.length t.indexes = 1 then "" else "es")