tempest-db-js 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conditions.ts","../src/aliased.ts","../src/query.ts","../src/window.ts","../src/serialize.ts","../src/mutations.ts","../src/url.ts","../src/expressions.ts","../src/search.ts","../src/dialect.ts","../src/join.ts","../src/mixins.ts","../src/integrity.ts","../src/signals.ts","../src/setops.ts","../src/repository.ts","../src/outbox.ts","../src/explain.ts","../src/tenant.ts","../src/audit.ts","../src/unit-of-work.ts","../src/engine.ts","../src/backup.ts","../src/cte.ts","../src/active-record.ts","../src/relations.ts","../src/index.ts"],"names":["fn","column","expression","col","decode","union","update","sql","select","call","index","count","now","snapshot","b","run"],"mappings":";;;;;;AAkHA,IAAM,SAAA,mBAAY,MAAA,CAAO,GAAA,CAAI,yBAAyB,CAAA;AAS/C,SAAS,YAAY,KAAA,EAAoC;AAC9D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,UAAU,IAAA,IACT,KAAA,CAAuC,SAAS,CAAA,KAAM,IAAA;AAE3D;AAGO,SAAS,WAAW,KAAA,EAAsD;AAC/E,EAAA,OAAO,WAAA,CAAY,KAAK,CAAA,GAAI,KAAA,CAAM,OAAO,EAAE,IAAA,EAAM,QAAA,EAAU,MAAA,EAAQ,KAAA,EAAM;AAC3E;AAEA,SAAS,KAAK,IAAA,EAA2B;AACvC,EAAA,OAAO,EAAE,CAAC,SAAS,GAAG,MAAM,IAAA,EAAK;AACnC;AAYA,SAAS,WAAW,OAAA,EAA4B;AAC9C,EAAA,OAAO,YAAA,CAAa,OAAO,CAAA,GAAI,OAAA,CAAQ,OAAO,EAAE,IAAA,EAAM,OAAA,EAAS,KAAA,EAAO,OAAA,EAAQ;AAChF;AAaA,SAAS,mBAAA,CAAoB,IAAY,QAAA,EAAoC;AAC3E,EAAA,IAAI,QAAA,CAAS,IAAA,CAAK,Y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AG,CAAA;AAAA,EAC5B;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-HXK6WIBP.js","sourcesContent":["/**\n * tempest-db-js — logical combinators for `where` (and/or/not).\n *\n * A `where` value is either the object form (an implicit AND of its fields) or a\n * `Condition` built with `and`/`or`/`not`. Both normalize to a `CondNode` tree\n * that every builder stores and the dialect compiles recursively — so select,\n * update, delete and join all share one condition language.\n */\n\nimport type { Operator, WhereInput } from \"./query.js\";\n\n/** Field-map condition (implicit AND of its entries). */\nexport interface CondFields {\n readonly kind: \"fields\";\n readonly fields: Record<string, unknown>;\n}\n\n/**\n * One side of a comparison: a column reference, a bound value, or a SQL function\n * applied to other expressions.\n *\n * A column reference carries the **property** name, not the database column —\n * the dialect resolves it through the node's name map, so `col()` cannot become a\n * back door around an explicit `.name()` mapping.\n */\nexport type ExprNode =\n | { readonly kind: \"column\"; readonly name: string }\n | { readonly kind: \"value\"; readonly value: unknown }\n | { readonly kind: \"fn\"; readonly name: string; readonly args: readonly ExprNode[] }\n | {\n readonly kind: \"case\";\n readonly branches: readonly {\n readonly when: CondNode;\n readonly result: ExprNode;\n }[];\n readonly fallback: ExprNode | null;\n }\n | { readonly kind: \"cast\"; readonly operand: ExprNode; readonly to: CastType }\n | { readonly kind: \"scalar\"; readonly select: unknown }\n | { readonly kind: \"star\" }\n | {\n readonly kind: \"window\";\n /** The function being windowed (`row_number()`, `sum(total)`, …). */\n readonly fn: ExprNode;\n /** `PARTITION BY` columns, by property name. */\n readonly partitionBy: readonly string[];\n /** `ORDER BY` inside the window. */\n readonly orderBy: readonly {\n readonly column: string;\n readonly direction: \"asc\" | \"desc\";\n }[];\n /** An explicit frame clause (`ROWS BETWEEN …`), or `null` for the default. */\n readonly frame: string | null;\n }\n | {\n readonly kind: \"rank\";\n readonly columns: readonly string[];\n readonly term: string;\n readonly language: string;\n };\n\n/**\n * A target type for {@link cast}.\n *\n * Kept as a portable vocabulary rather than raw SQL: each dialect maps it to the\n * name it actually accepts (`integer` is `INTEGER` on PostgreSQL and `SIGNED` on\n * MySQL), so the same model does not need a different cast per database.\n */\nexport type CastType =\n | \"integer\"\n | \"bigint\"\n | \"real\"\n | \"numeric\"\n | \"text\"\n | \"boolean\"\n | \"date\"\n | \"datetime\"\n | \"timestamp\"\n | \"uuid\"\n | \"json\"\n | \"jsonb\"\n | \"blob\";\n\n/** Logical condition nodes. */\nexport type CondNode =\n | CondFields\n | { readonly kind: \"and\"; readonly parts: readonly CondNode[] }\n | { readonly kind: \"or\"; readonly parts: readonly CondNode[] }\n | { readonly kind: \"not\"; readonly part: CondNode }\n | {\n readonly kind: \"compare\";\n readonly left: ExprNode;\n readonly op: Operator;\n readonly right: ExprNode;\n }\n | {\n readonly kind: \"exists\";\n /** The subquery's SELECT node. */\n readonly select: unknown;\n /** True for `NOT EXISTS`. */\n readonly negate: boolean;\n }\n | {\n readonly kind: \"fullText\";\n readonly columns: readonly string[];\n readonly term: string;\n readonly language: string;\n /**\n * The substring condition to compile where there is no text-search engine.\n * Built once, here, so the dialects do not each reimplement the fallback.\n */\n readonly fallback: CondNode;\n };\n\nconst CONDITION = Symbol.for(\"tempest-db-js.condition\");\n\n/** A composed condition produced by `and`/`or`/`not`. */\nexport interface Condition {\n readonly [CONDITION]: true;\n readonly node: CondNode;\n}\n\n/** Runtime guard: is this value a composed `Condition`? */\nexport function isCondition(value: unknown): value is Condition {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[CONDITION] === true\n );\n}\n\n/** Normalize a where argument (object form or `Condition`) to a `CondNode`. */\nexport function toCondNode(input: Condition | Record<string, unknown>): CondNode {\n return isCondition(input) ? input.node : { kind: \"fields\", fields: input };\n}\n\nfunction wrap(node: CondNode): Condition {\n return { [CONDITION]: true, node };\n}\n\n/**\n * A `where` argument: the object form (keys typed against `Row`) or a `Condition`.\n *\n * @typeParam Row - the row type whose columns the field keys are checked against.\n * Defaults to a permissive shape; pass it explicitly (e.g. `or<UserRow>(...)`)\n * for full key + operator checking inside combinators.\n */\nexport type WhereArg<Row = Record<string, unknown>> = WhereInput<Row> | Condition;\n\n/** Normalize a comparison operand: an {@link Expression}, or a bound value. */\nfunction toExprNode(operand: unknown): ExprNode {\n return isExpression(operand) ? operand.node : { kind: \"value\", value: operand };\n}\n\n/**\n * Reject an {@link Expression} among operands that are bound as values.\n *\n * `IN` and `BETWEEN` bind their operands, so an expression slipped into the list\n * would be serialized by the driver instead of rendered as SQL — the same silent\n * corruption that `set()` guards against.\n *\n * @param op The operator name, for the message.\n * @param operands The operands to check.\n * @throws Error When any operand is an expression.\n */\nfunction assertValueOperands(op: string, operands: readonly unknown[]): void {\n if (operands.some(isExpression)) {\n throw new Error(\n `The \"${op}\" operator binds its operands, so it takes values, not expressions.`,\n );\n }\n}\n\n/** Runtime guard: is this operand a built {@link Expression}? */\nexport function isExpression(value: unknown): value is Expression {\n return value instanceof Expression;\n}\n\n/**\n * One side of a comparison, built with {@link col}, {@link val} or {@link fn}.\n *\n * The comparison methods mirror the `where` operators, but both sides are\n * expressions — which is what makes `col(\"total\").gt(col(\"paid\"))` and a\n * functional-index lookup like `fn.lower(\"email\").eq(fn.lower(val(probe)))`\n * expressible at all. An operand that is not an `Expression` is bound as a\n * parameter, so `.eq(probe)` stays safe by default.\n */\nexport class Expression<T = unknown> {\n /** Phantom: the value type this expression produces, read only by the types. */\n declare readonly __t?: T;\n\n constructor(\n /** The expression AST the dialect renders. */\n readonly node: ExprNode,\n ) {}\n\n /** Compare this expression against another expression or a bound value. */\n private compare(op: Operator, operand: unknown): Condition {\n return wrap({ kind: \"compare\", left: this.node, op, right: toExprNode(operand) });\n }\n\n /** `=` (or `IS NULL` for a null value). */\n eq(operand: unknown): Condition {\n return this.compare(\"eq\", operand);\n }\n /** `<>` (or `IS NOT NULL` for a null value). */\n ne(operand: unknown): Condition {\n return this.compare(\"ne\", operand);\n }\n /** `>`. */\n gt(operand: unknown): Condition {\n return this.compare(\"gt\", operand);\n }\n /** `>=`. */\n gte(operand: unknown): Condition {\n return this.compare(\"gte\", operand);\n }\n /** `<`. */\n lt(operand: unknown): Condition {\n return this.compare(\"lt\", operand);\n }\n /** `<=`. */\n lte(operand: unknown): Condition {\n return this.compare(\"lte\", operand);\n }\n /** `LIKE` — `%` and `_` in the operand are wildcards. */\n like(pattern: string | Expression): Condition {\n return this.compare(\"like\", pattern);\n }\n /** `ILIKE` — case-insensitive **pattern** matching, wildcards included. */\n ilike(pattern: string | Expression): Condition {\n return this.compare(\"ilike\", pattern);\n }\n /** Case-insensitive equality (`lower(a) = lower(b)`), with no wildcards. */\n ieq(operand: unknown): Condition {\n return this.compare(\"ieq\", operand);\n }\n /**\n * `IN (...)` over a list of values.\n *\n * @param values The values to test against.\n * @returns The condition.\n * @throws Error When an entry is an {@link Expression} — a list operand is\n * bound, so an expression there would be serialized as a parameter instead of\n * rendered as SQL.\n */\n in(values: readonly unknown[]): Condition {\n assertValueOperands(\"in\", values);\n return this.compare(\"in\", values);\n }\n /**\n * `NOT IN (...)` over a list of values.\n *\n * @param values The values to exclude.\n * @returns The condition.\n * @throws Error When an entry is an {@link Expression} (see {@link Expression.in}).\n */\n notIn(values: readonly unknown[]): Condition {\n assertValueOperands(\"notIn\", values);\n return this.compare(\"notIn\", values);\n }\n /**\n * `BETWEEN lo AND hi` (inclusive).\n *\n * @param lo The lower bound.\n * @param hi The upper bound.\n * @returns The condition.\n * @throws Error When a bound is an {@link Expression} (see {@link Expression.in}).\n */\n between(lo: unknown, hi: unknown): Condition {\n assertValueOperands(\"between\", [lo, hi]);\n return this.compare(\"between\", [lo, hi]);\n }\n /** `IS NULL` (true) / `IS NOT NULL` (false). */\n isNull(value = true): Condition {\n return this.compare(\"isNull\", value);\n }\n}\n\n/**\n * Wrap a raw condition node as a {@link Condition}.\n *\n * The escape hatch for the helpers that build a node kind of their own (full-text\n * search), so they do not have to re-export the brand.\n *\n * @param node The node to wrap.\n * @returns The branded condition.\n */\nexport function conditionFromNode(node: CondNode): Condition {\n return wrap(node);\n}\n\n/**\n * Wrap a raw expression node as an {@link Expression}.\n *\n * @param node The node to wrap.\n * @returns The expression.\n */\nexport function expressionFromNode<T = unknown>(node: ExprNode): Expression<T> {\n return new Expression<T>(node);\n}\n\n/**\n * A column reference, by **property** name.\n *\n * Pass the row type for key-safety: `col<UserRow>(\"total\")` rejects a name that\n * is not a column. The name is resolved through the model's column-name map at\n * compile time, exactly like the object form of `where`.\n *\n * @param name The model property name.\n * @returns An expression referencing that column.\n *\n * @example\n * ```ts\n * select(Order).where(col<OrderRow>(\"total\").gt(col<OrderRow>(\"paid\")));\n * // SELECT * FROM \"orders\" WHERE \"total\" > \"paid\"\n * ```\n */\nexport function col<Row = Record<string, unknown>>(name: keyof Row & string): Expression {\n return new Expression({ kind: \"column\", name });\n}\n\n/**\n * A bound value, for the places that take an expression and would otherwise read\n * a bare string as a column name (the arguments of {@link fn}).\n *\n * @param value The value to bind as a parameter.\n * @returns An expression that renders as a placeholder.\n */\nexport function val(value: unknown): Expression {\n return new Expression({ kind: \"value\", value });\n}\n\n/**\n * A `CASE WHEN ... THEN ... ELSE ... END` expression.\n *\n * The branch conditions are the same `where` language used everywhere else — the\n * object form or a `Condition` — so no second grammar shows up just for `CASE`.\n * The branch results are expressions, and a bare value there is **bound**, not\n * interpolated.\n *\n * The classic use is a conditional aggregate: summing only the rows that match,\n * in one pass over the table instead of one query per bucket.\n *\n * @param branches `[condition, result]` pairs, evaluated in order.\n * @param fallback The `ELSE` result. Omitted, a row matching no branch is `NULL`.\n * @returns An expression usable anywhere an expression is.\n * @throws Error When no branch is given — `CASE END` is not valid SQL.\n *\n * @example\n * ```ts\n * select(Order).aggregate([\"customer\"], {\n * paid: sum(caseWhen([[{ status: \"paid\" }, col(\"total\")]], val(0))),\n * });\n * // SUM(CASE WHEN \"status\" = $1 THEN \"total\" ELSE $2 END) AS \"paid\"\n * ```\n */\nexport function caseWhen<Row = Record<string, unknown>>(\n branches: readonly (readonly [WhereArg<Row>, unknown])[],\n fallback?: unknown,\n): Expression {\n if (branches.length === 0) {\n throw new Error(\"caseWhen() needs at least one [condition, result] branch.\");\n }\n return new Expression({\n kind: \"case\",\n branches: branches.map(([when, result]) => ({\n when: toCondNode(when as Condition | Record<string, unknown>),\n result: toExprNode(result),\n })),\n fallback: fallback === undefined ? null : toExprNode(fallback),\n });\n}\n\n/**\n * A `CAST(x AS type)` expression.\n *\n * @param operand The expression to convert; a bare string is a column name.\n * @param to The target type, from the portable {@link CastType} vocabulary.\n * @returns An expression for the cast.\n *\n * @example\n * ```ts\n * select(Event).where(cast(\"externalId\", \"integer\").eq(42));\n * // WHERE CAST(\"externalId\" AS INTEGER) = $1\n * ```\n */\nexport function cast(operand: Expression | string, to: CastType): Expression {\n return new Expression({ kind: \"cast\", operand: toArg(operand), to });\n}\n\n/** Function names are interpolated verbatim, so they must be plain identifiers. */\nconst FUNCTION_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Coerce a function argument: a bare string is a column, everything else a value. */\nfunction toArg(arg: Expression | string): ExprNode {\n return typeof arg === \"string\" ? { kind: \"column\", name: arg } : arg.node;\n}\n\n/**\n * Build a call to a SQL function.\n *\n * A bare string argument is a **column name** — that is the useful default here\n * (`fn.lower(\"username\")`), and it is why a literal has to be wrapped in\n * {@link val}. The function name is interpolated into the statement, so it is\n * validated as a plain identifier and must never come from user input; the\n * arguments are always rendered through the expression compiler.\n *\n * @param name The SQL function name.\n * @param args Column names or expressions.\n * @returns An expression for the call.\n * @throws Error When `name` is not a plain SQL identifier.\n */\nfunction call(name: string, ...args: (Expression | string)[]): Expression {\n if (!FUNCTION_NAME.test(name)) {\n throw new Error(\n `fn.call() takes a plain SQL function name; got ${JSON.stringify(name)}.`,\n );\n }\n return new Expression({ kind: \"fn\", name, args: args.map(toArg) });\n}\n\n/**\n * SQL functions usable on either side of a comparison.\n *\n * The named entries are the ones every supported dialect implements. Anything\n * else — `date_trunc`, `strftime`, a custom function — goes through\n * {@link fn.call}, which does not pretend to be portable.\n *\n * @example\n * ```ts\n * select(AdminUser).where(fn.lower(\"username\").eq(fn.lower(val(probe))));\n * // WHERE lower(\"username\") = lower($1)\n * ```\n */\nexport const fn = {\n /** `lower(x)`. */\n lower: (arg: Expression | string): Expression => call(\"lower\", arg),\n /** `upper(x)`. */\n upper: (arg: Expression | string): Expression => call(\"upper\", arg),\n /** `trim(x)`. */\n trim: (arg: Expression | string): Expression => call(\"trim\", arg),\n /** `length(x)`. */\n length: (arg: Expression | string): Expression => call(\"length\", arg),\n /** `abs(x)`. */\n abs: (arg: Expression | string): Expression => call(\"abs\", arg),\n /** `coalesce(a, b, ...)`. */\n coalesce: (...args: (Expression | string)[]): Expression => call(\"coalesce\", ...args),\n /**\n * Any other SQL function, by name. Portability is the caller's problem —\n * `date_trunc` is PostgreSQL, `strftime` is SQLite.\n */\n call,\n} as const;\n\n/** Combine conditions with `AND`. */\nexport function and<Row = Record<string, unknown>>(\n ...inputs: WhereArg<NoInfer<Row>>[]\n): Condition {\n return wrap({\n kind: \"and\",\n parts: inputs.map((i) => toCondNode(i as Record<string, unknown>)),\n });\n}\n\n/** Combine conditions with `OR`. */\nexport function or<Row = Record<string, unknown>>(\n ...inputs: WhereArg<NoInfer<Row>>[]\n): Condition {\n return wrap({\n kind: \"or\",\n parts: inputs.map((i) => toCondNode(i as Record<string, unknown>)),\n });\n}\n\n/** Negate a condition with `NOT`. */\nexport function not<Row = Record<string, unknown>>(\n input: WhereArg<NoInfer<Row>>,\n): Condition {\n return wrap({ kind: \"not\", part: toCondNode(input as Record<string, unknown>) });\n}\n","/**\n * tempest-db-js — table aliases outside the join builder.\n *\n * `join(Model, \"a\")` has always taken an alias, so a self-join works there. A\n * plain `select()` had no way to name its table, which is what a correlated\n * subquery over the **same** table needs: without an alias, the inner and outer\n * `users` are the same name, and the correlation cannot be written at all.\n */\n\nimport type { ModelClass, NamingStrategy, TableConstraint } from \"./index.js\";\n\n/**\n * The same model, reading from an alias.\n *\n * The result is a real model class — same columns, same naming strategy, same\n * codecs — whose `tablename` is the alias. Everything that already takes a model\n * takes this: `select`, `join`, `col(\"alias.column\")`, row coercion.\n *\n * Table constraints are **not** carried over: an alias is a way to read a table,\n * not a second declaration of it, and reflecting it into a migration would try to\n * create a table named after the alias.\n *\n * @param model The model to alias.\n * @param alias The name to read it under.\n * @returns A model class bound to the alias.\n *\n * @example\n * ```ts\n * const sub = aliased(User, \"sub\");\n * select(User).where(\n * exists(select(sub).where({ managerId: col(\"users.id\") })),\n * );\n * // WHERE EXISTS (SELECT * FROM \"users\" AS \"sub\" WHERE \"managerId\" = \"users\".\"id\")\n * ```\n */\nexport function aliased<C extends ModelClass>(model: C, alias: string): C {\n const aliasedModel = class extends (model as unknown as new () => object) {};\n Object.defineProperty(aliasedModel, \"tablename\", { value: alias, writable: true });\n Object.defineProperty(aliasedModel, \"naming\", {\n value: (model as { naming?: NamingStrategy }).naming,\n writable: true,\n });\n Object.defineProperty(aliasedModel, \"tableArgs\", {\n value: undefined as (() => readonly TableConstraint[]) | undefined,\n writable: true,\n });\n Object.defineProperty(aliasedModel, \"aliasOf\", { value: model, writable: true });\n return aliasedModel as unknown as C;\n}\n\n/**\n * The model an alias was made from, or `null` when it is not an alias.\n *\n * @param model Any model class.\n * @returns The underlying model, or `null`.\n */\nexport function aliasOf(model: ModelClass): ModelClass | null {\n return (model as { aliasOf?: ModelClass }).aliasOf ?? null;\n}\n","/**\n * tempest-db-js — Phase 2 feasibility spike: the typed query builder.\n *\n * The builder is PURE AST + phantom types. It does not touch a database — that is\n * Phase 4 (`session.execute`). This file proves that:\n * - `select(User)` infers the full row type,\n * - `select(User, [\"id\", \"name\"])` infers a `Pick` projection,\n * - `.where(...)` / `.orderBy(...)` reject keys that are not columns,\n * all at compile time.\n *\n * This is a SPIKE, not the final API.\n */\n\nimport { aliasOf } from \"./aliased.js\";\nimport {\n type CondNode,\n type Condition,\n type ExprNode,\n type Expression,\n conditionFromNode,\n expressionFromNode,\n toCondNode,\n} from \"./conditions.js\";\nimport {\n type InferModel,\n type ModelClass,\n type NameMap,\n codecsOf,\n columnNamesOf,\n} from \"./index.js\";\n\n// --------------------------------------------------------------------------\n// AST\n// --------------------------------------------------------------------------\n\n/** The value type an expression produces, for `compute`'s row type. */\nexport type ExpressionValue<E> = E extends Expression<infer T> ? T : unknown;\n\n/** Flatten an intersection into one object literal, for readable inference. */\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** Sort direction for ORDER BY. */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/** One ORDER BY term. */\nexport interface OrderTerm {\n /** The column to sort by, or an expression (a full-text rank, for instance). */\n readonly column: string | ExprNode;\n readonly direction: SortDirection;\n}\n\n/** One aggregate expression in a grouped SELECT (`COUNT(*) AS \"n\"`). */\nexport interface AggregateTerm {\n readonly fn: \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n /**\n * What is aggregated: a column name, `\"*\"` (only valid for `count`), or an\n * expression — which is how a conditional aggregate\n * (`SUM(CASE WHEN ... END)`) is expressed.\n */\n readonly column: string | \"*\" | ExprNode;\n /** The result alias. */\n readonly alias: string;\n}\n\n/**\n * A row-level locking clause (`SELECT ... FOR UPDATE`).\n *\n * `wait` decides what happens when another transaction already holds the lock:\n * `\"block\"` waits, `\"skipLocked\"` skips those rows (the job-queue claim), and\n * `\"noWait\"` fails immediately.\n */\nexport interface LockClause {\n readonly strength: \"update\" | \"share\";\n readonly wait: \"block\" | \"skipLocked\" | \"noWait\";\n /** Tables to lock (`FOR UPDATE OF t`); empty locks every table in the query. */\n readonly of: readonly string[];\n}\n\n/** Options accepted by {@link SelectBuilder.forUpdate} / {@link SelectBuilder.forShare}. */\nexport interface LockOptions {\n /** Skip rows another transaction has locked instead of waiting for them. */\n readonly skipLocked?: boolean;\n /** Fail immediately instead of waiting for a locked row. */\n readonly noWait?: boolean;\n /** Restrict the lock to these tables (`FOR UPDATE OF ...`). */\n readonly of?: readonly string[];\n}\n\n/** Serializable AST for a SELECT. Dialects (Phase 4) compile this to SQL. */\nexport interface SelectNode {\n readonly kind: \"select\";\n readonly table: string;\n /** The name the table is read under (`FROM \"users\" AS \"sub\"`), when aliased. */\n readonly alias?: string | undefined;\n /** Projected columns, or \"*\" for the whole row. */\n readonly columns: readonly string[] | \"*\";\n /** Emit `SELECT DISTINCT` when true. */\n readonly distinct: boolean;\n /** Aggregate expressions; when non-empty, this is a grouped/aggregate query. */\n readonly aggregates: readonly AggregateTerm[];\n /** `GROUP BY` columns. */\n readonly groupBy: readonly string[];\n readonly where: CondNode | undefined;\n /** `HAVING` condition, keyed by aggregate alias or grouped column. */\n readonly having?: CondNode | undefined;\n readonly orderBy: readonly OrderTerm[];\n /** Per-column codecs for custom types, by property name, when the model has any. */\n readonly codecs?:\n | Readonly<Record<string, import(\"./index.js\").ColumnCodec>>\n | undefined;\n /** `WITH` entries this statement carries, in order. */\n readonly with?: readonly import(\"./cte.js\").CteNode[] | undefined;\n /** Extra projected expressions, by result alias (window functions, CASE, …). */\n readonly computed?: Readonly<Record<string, ExprNode>> | undefined;\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n /** Row-level locking clause, or `undefined` for none. */\n readonly lock?: LockClause | undefined;\n /** Property → column map, or `undefined` when every name is the identity. */\n readonly names?: NameMap | undefined;\n}\n\n// --------------------------------------------------------------------------\n// where input typing (Phase 3 — operators typed per column type)\n// --------------------------------------------------------------------------\n\n/**\n * A SELECT projecting exactly one column of type `T`, usable as the operand of\n * `in` / `notIn`.\n *\n * Build it with {@link SelectBuilder.asSubquery}, which both narrows the\n * projection to one column and gives the operand its element type.\n */\nexport interface Subquery<T> {\n /** Phantom: the element type the subquery yields, read only by the type system. */\n readonly __element?: T;\n /** The AST the outer statement embeds. */\n readonly node: SelectNode;\n}\n\n/**\n * `EXISTS (subquery)` — true when the subquery returns at least one row.\n *\n * The right shape for \"is there any…\" questions: the database can stop at the\n * first match, which an `IN` over a materialized list cannot. Correlate it by\n * referencing an outer column with a qualified `col(\"users.id\")`.\n *\n * @param subquery The inner SELECT, as a builder or a `.asSubquery()` result.\n * @returns A condition, composable with `and`/`or`/`not`.\n *\n * @example\n * ```ts\n * select(User).where(\n * exists(select(Order).where({ userId: col(\"users.id\"), status: \"open\" })),\n * );\n * // WHERE EXISTS (SELECT * FROM \"orders\" WHERE \"userId\" = \"users\".\"id\" AND ...)\n * ```\n */\nexport function exists(subquery: SubqueryLike): Condition {\n return conditionFromNode({ kind: \"exists\", select: nodeOf(subquery), negate: false });\n}\n\n/**\n * `NOT EXISTS (subquery)` — true when the subquery returns no row.\n *\n * @param subquery The inner SELECT.\n * @returns The condition.\n */\nexport function notExists(subquery: SubqueryLike): Condition {\n return conditionFromNode({ kind: \"exists\", select: nodeOf(subquery), negate: true });\n}\n\n/**\n * A scalar subquery — a `SELECT` of one column used where a value goes.\n *\n * Takes the result of `.asSubquery(column)` rather than a bare builder, because\n * that is what pins the projection to exactly **one** column: a scalar subquery\n * returning two columns is a runtime error in every database, and this makes it a\n * compile error instead.\n *\n * @param subquery A single-column subquery.\n * @returns An expression usable in `where`, `orderBy` or an aggregate.\n *\n * @example\n * ```ts\n * select(User).where(\n * scalar(select(Order, [\"total\"]).where({ userId: col(\"users.id\") })\n * .orderBy(\"createdAt\", \"desc\").limit(1).asSubquery(\"total\")).gt(100),\n * );\n * ```\n */\nexport function scalar<T>(subquery: Subquery<T>): Expression {\n return expressionFromNode({ kind: \"scalar\", select: subquery.node });\n}\n\n/** What the subquery helpers accept: a builder, or a narrowed subquery. */\n/* biome-ignore lint/suspicious/noExplicitAny: any select shape may be embedded. */\nexport type SubqueryLike = SelectBuilder<any, any, any> | Subquery<unknown>;\n\n/**\n * Read the SELECT node out of either accepted shape.\n *\n * @param subquery The builder or subquery.\n * @returns Its AST node.\n */\nfunction nodeOf(subquery: SubqueryLike): SelectNode {\n return (subquery as { node: SelectNode }).node;\n}\n\n/** Runtime guard: is this `in`/`notIn` operand a subquery rather than a list? */\nexport function isSubquery(value: unknown): value is Subquery<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { node?: { kind?: unknown } }).node?.kind === \"select\"\n );\n}\n\n/**\n * A comparison operand: a value of the column's type, or another expression.\n *\n * Accepting an {@link Expression} is what makes a correlated subquery readable —\n * `where({ userId: col(\"users.id\") })` compares two columns instead of binding\n * the string `\"users.id\"` as a parameter.\n */\nexport type Operand<T> = T | Expression;\n\n/** Operators valid on every column type. */\ninterface BaseOperators<T> {\n /** Equal to. */\n eq?: Operand<T>;\n /** Not equal to. */\n ne?: Operand<T>;\n /**\n * One of the given values (`IN`) — a list, or a single-column\n * {@link Subquery} built with `.asSubquery(column)`.\n */\n in?: readonly T[] | Subquery<T>;\n /** None of the given values (`NOT IN`), as a list or a {@link Subquery}. */\n notIn?: readonly T[] | Subquery<T>;\n /** `IS NULL` (true) / `IS NOT NULL` (false). */\n isNull?: boolean;\n}\n\n/** Extra operators for ordered types (numbers, bigint, dates). */\ninterface OrderedOperators<T> extends BaseOperators<T> {\n /** Greater than. */\n gt?: Operand<T>;\n /** Greater than or equal. */\n gte?: Operand<T>;\n /** Less than. */\n lt?: Operand<T>;\n /** Less than or equal. */\n lte?: Operand<T>;\n /** Inclusive range `BETWEEN lo AND hi`. */\n between?: readonly [T, T];\n}\n\n/** Extra operators for string-like types. */\ninterface StringOperators<T> extends BaseOperators<T> {\n /** `LIKE` pattern (case-sensitive). `%` and `_` are wildcards. */\n like?: string;\n /**\n * `ILIKE` **pattern** (case-insensitive). This is pattern matching, not\n * equality: `%` and `_` in the operand are wildcards, so `{ ilike: \"%\" }`\n * matches every row. Never feed it unescaped user input — for a\n * case-insensitive *equality* test use {@link StringOperators.ieq}, and to\n * match a literal that may contain wildcards, wrap it in `escapeLike`.\n */\n ilike?: string;\n /**\n * Case-insensitive equality — compiles to `lower(col) = lower($1)`, with no\n * wildcards. The safe operator for a case-insensitive lookup (login, email),\n * and the one that matches a `lower(col)` functional index.\n */\n ieq?: Operand<T>;\n /**\n * Case-insensitive **substring** match of a literal — the safe operator for a\n * search box.\n *\n * The operand is text the user typed, not a pattern: `%` and `_` in it are\n * escaped, so searching for `100%` matches `100%` instead of every row. It\n * compiles to `ILIKE '%…%' ESCAPE '\\\\'` (`LIKE` where there is no `ILIKE`).\n */\n iContains?: string;\n}\n\n/** Extra operators for array columns (PostgreSQL). */\ninterface ArrayOperators<T> extends BaseOperators<T> {\n /** `@>` — the column contains every element of the operand. */\n contains?: T;\n /** `<@` — every element of the column is in the operand. */\n containedBy?: T;\n /** `&&` — the column and the operand share at least one element. */\n overlaps?: T;\n}\n\n/**\n * The operator object allowed for a column of (non-null) type `T`:\n * - `T[]` → equality, `in`, `contains`/`containedBy`/`overlaps` (PostgreSQL)\n * - `string` → equality, `in`, `like`/`ilike`/`ieq`\n * - `number` / `bigint` / `Date` → equality, `in`, ordered comparisons, `between`\n * - `boolean` → equality, `isNull`\n * - anything else (json/blob) → equality and `in` only\n */\nexport type OperatorsFor<T> = [T] extends [readonly unknown[]]\n ? ArrayOperators<T>\n : [T] extends [string]\n ? StringOperators<T>\n : [T] extends [number]\n ? OrderedOperators<T>\n : [T] extends [bigint]\n ? OrderedOperators<T>\n : [T] extends [Date]\n ? OrderedOperators<T>\n : [T] extends [boolean]\n ? BaseOperators<T>\n : BaseOperators<T>;\n\n/**\n * `where` shape: each key must be a real column; each value accepts either a\n * bare value (shorthand for `eq`) or an operator object restricted to operators\n * valid for that column's type. A `like` on a `number` column, or `gt` on a\n * `string`, is a compile error.\n */\nexport type WhereInput<Row = Record<string, unknown>> = {\n [K in keyof Row]?: Row[K] | Expression | OperatorsFor<NonNullable<Row[K]>>;\n};\n\n/** The full set of operator keys, for the dialect compiler to recognize. */\nexport const OPERATORS = [\n \"eq\",\n \"ne\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"like\",\n \"ilike\",\n \"ieq\",\n \"iContains\",\n \"in\",\n \"notIn\",\n \"between\",\n \"isNull\",\n \"contains\",\n \"containedBy\",\n \"overlaps\",\n] as const;\n\n/** One supported operator name. */\nexport type Operator = (typeof OPERATORS)[number];\n\n// --------------------------------------------------------------------------\n// aggregate expressions\n// --------------------------------------------------------------------------\n\n/** An aggregate expression carrying its result type `T` as a phantom. */\nexport class Agg<T> {\n declare readonly __t: T;\n constructor(\n readonly fn: AggregateTerm[\"fn\"],\n readonly column: string | \"*\" | ExprNode,\n ) {}\n}\n\n/** `COUNT(*)` — the number of rows in the group (never null). */\nexport function count(): Agg<number> {\n return new Agg<number>(\"count\", \"*\");\n}\n/** `SUM(column)` — null when the group has no non-null values. */\nexport function sum(column: string | Expression): Agg<number | null> {\n return new Agg<number | null>(\"sum\", typeof column === \"string\" ? column : column.node);\n}\n/** `AVG(column)` — null when the group has no non-null values. */\nexport function avg(column: string | Expression): Agg<number | null> {\n return new Agg<number | null>(\"avg\", typeof column === \"string\" ? column : column.node);\n}\n/** `MIN(column)` — numeric columns; null on an empty group. */\nexport function min(column: string | Expression): Agg<number | null> {\n return new Agg<number | null>(\"min\", typeof column === \"string\" ? column : column.node);\n}\n/** `MAX(column)` — numeric columns; null on an empty group. */\nexport function max(column: string | Expression): Agg<number | null> {\n return new Agg<number | null>(\"max\", typeof column === \"string\" ? column : column.node);\n}\n\n/** Extract the phantom result type of an aggregate expression. */\ntype AggResult<A> = A extends Agg<infer T> ? T : never;\n\n/** Flatten an intersection into a single object literal. */\ntype SimplifyProj<T> = { [K in keyof T]: T[K] } & {};\n\n// --------------------------------------------------------------------------\n// builder\n// --------------------------------------------------------------------------\n\n/**\n * Immutable, chainable SELECT builder.\n *\n * @typeParam Full - the complete row type (constrains where/orderBy keys).\n * @typeParam Proj - the projected result type returned on execution.\n */\nexport class SelectBuilder<Full, Proj = Full, Grouped extends boolean = false> {\n /** Phantom: the result element type, read only by the type system. */\n declare readonly __row: Proj;\n /** Phantom: `true` once `aggregate()` has made `having()` meaningful. */\n declare readonly __grouped: Grouped;\n\n constructor(\n readonly node: SelectNode,\n /** The source model, used to coerce rows on execution. */\n readonly source: ModelClass,\n ) {}\n\n private with(patch: Partial<SelectNode>): SelectBuilder<Full, Proj, Grouped> {\n return new SelectBuilder<Full, Proj, Grouped>(\n { ...this.node, ...patch },\n this.source,\n );\n }\n\n /** Add a WHERE filter: the object form (keys typed) or an `and`/`or`/`not`. */\n where(input: WhereInput<Full> | Condition): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ where: toCondNode(input as Record<string, unknown>) });\n }\n\n /**\n * Filter by the result of the aggregation (`HAVING`).\n *\n * Only available on a grouped builder — `.having()` before `.aggregate()` is a\n * compile error, not invalid SQL at runtime. Keys are the aggregate aliases you\n * named plus the grouped columns; `WHERE` still filters rows *before* grouping,\n * which is a different question.\n *\n * @param input The condition, keyed by alias or grouped column.\n * @returns A builder carrying the `HAVING` clause.\n *\n * @example\n * ```ts\n * select(Outbound)\n * .where({ status: \"queued\" })\n * .aggregate([\"consumer\"], { n: count() })\n * .having({ n: { gt: 100 } });\n * // ... GROUP BY \"consumer\" HAVING COUNT(*) > $2\n * ```\n */\n having(\n this: SelectBuilder<Full, Proj, true>,\n input: WhereInput<Proj> | Condition,\n ): SelectBuilder<Full, Proj, true> {\n return new SelectBuilder<Full, Proj, true>(\n { ...this.node, having: toCondNode(input as Record<string, unknown>) },\n this.source,\n );\n }\n\n /** Emit `SELECT DISTINCT` — drop duplicate rows. */\n distinct(): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ distinct: true });\n }\n\n /**\n * Group by columns and compute aggregates. The result row is the grouped\n * columns (typed from the model) plus one field per aggregate alias.\n *\n * @param groupBy The columns to group by (checked against the model). Pass `[]`\n * for a whole-table aggregate.\n * @param spec A map of result alias → aggregate expression ({@link count},\n * {@link sum}, {@link avg}, {@link min}, {@link max}).\n * @returns A builder whose row is `Pick<Full, K> & { [alias]: aggResult }`.\n *\n * @example\n * ```ts\n * select(Order).aggregate([\"status\"], { n: count(), total: sum(\"amount\") });\n * // rows: { status: string; n: number; total: number | null }[]\n * ```\n */\n aggregate<K extends keyof Full & string, S extends Record<string, Agg<unknown>>>(\n groupBy: readonly K[],\n spec: S,\n ): SelectBuilder<\n Full,\n SimplifyProj<Pick<Full, K> & { [A in keyof S]: AggResult<S[A]> }>,\n true\n > {\n const aggregates: AggregateTerm[] = Object.entries(spec).map(([alias, agg]) => ({\n fn: agg.fn,\n column: agg.column,\n alias,\n }));\n return new SelectBuilder(\n { ...this.node, aggregates, groupBy },\n this.source,\n ) as unknown as SelectBuilder<\n Full,\n SimplifyProj<Pick<Full, K> & { [A in keyof S]: AggResult<S[A]> }>,\n true\n >;\n }\n\n /**\n * Order by a column of the model, or — on a grouped query — by an aggregate\n * alias. Unlike `HAVING`, every dialect accepts the output alias in `ORDER BY`,\n * so the alias is emitted as written.\n *\n * @param column A model column, or a projected alias.\n * @param direction `\"asc\"` (default) or `\"desc\"`.\n * @returns A builder carrying the ordering term.\n */\n /**\n * Project extra expressions alongside the columns, by alias.\n *\n * This is where a window function lands: unlike `aggregate()`, it does **not**\n * group — every row stays, with the computed value attached.\n *\n * @param map Alias → expression.\n * @returns A builder whose row type carries the aliases.\n *\n * @example\n * ```ts\n * select(Sale).compute({\n * rank: over(rowNumber(), { partitionBy: [\"region\"], orderBy: [[\"total\", \"desc\"]] }),\n * });\n * ```\n */\n compute<M extends Record<string, Expression<unknown>>>(\n map: M,\n ): SelectBuilder<\n Full,\n Simplify<Proj & { [K in keyof M]: ExpressionValue<M[K]> }>,\n Grouped\n > {\n const computed: Record<string, ExprNode> = { ...(this.node.computed ?? {}) };\n for (const [alias, expression] of Object.entries(map)) {\n computed[alias] = expression.node;\n }\n return this.with({ computed }) as unknown as SelectBuilder<\n Full,\n Simplify<Proj & { [K in keyof M]: ExpressionValue<M[K]> }>,\n Grouped\n >;\n }\n\n orderBy(\n column: (keyof Full & string) | (keyof Proj & string) | Expression,\n direction: SortDirection = \"asc\",\n ): SelectBuilder<Full, Proj, Grouped> {\n return this.with({\n orderBy: [\n ...this.node.orderBy,\n { column: typeof column === \"string\" ? column : column.node, direction },\n ],\n });\n }\n\n /** Limit the number of rows. */\n limit(n: number): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ limit: n });\n }\n\n /** Skip the first `n` rows. */\n offset(n: number): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ offset: n });\n }\n\n /**\n * Narrow this SELECT to a single column and mark it as a subquery, so it can be\n * the operand of `in` / `notIn`.\n *\n * The whole query — `where`, `orderBy`, `limit`, and a locking clause — is\n * embedded in the outer statement, which is what collapses the claim-a-batch\n * pattern into one round trip instead of selecting ids and sending them back.\n *\n * @param column The single column to project (checked against the model).\n * @returns A subquery carrying that column's type.\n *\n * @example\n * ```ts\n * update(Outbound)\n * .set({ status: \"sending\", attempts: sql.raw(\"attempts + 1\") })\n * .where({\n * id: {\n * in: select(Outbound)\n * .where({ status: \"queued\" })\n * .orderBy(\"nextAttemptAt\")\n * .limit(10)\n * .forUpdate({ skipLocked: true })\n * .asSubquery(\"id\"),\n * },\n * })\n * .returning();\n * ```\n */\n asSubquery<K extends keyof Full & string>(column: K): Subquery<Full[K]> {\n return { node: { ...this.node, columns: [column] } } as Subquery<Full[K]>;\n }\n\n /**\n * Lock the selected rows for update (`SELECT ... FOR UPDATE`), à la\n * SQLAlchemy's `with_for_update()`.\n *\n * `{ skipLocked: true }` is the job-queue claim: competing workers each take a\n * disjoint batch instead of blocking on — or worse, double-processing — the\n * same rows.\n *\n * PostgreSQL and MySQL 8.0+ only. SQLite has no row-level locking, and its\n * dialect throws rather than emitting a `SELECT` that silently locks nothing —\n * a lock that does not exist only fails under production concurrency.\n *\n * @param options `skipLocked` / `noWait` wait behavior, and `of` to restrict\n * the lock to specific tables.\n * @returns A builder carrying the locking clause.\n * @throws Error When both `skipLocked` and `noWait` are set.\n *\n * @example\n * ```ts\n * const batch = await session.execute(\n * select(Outbound)\n * .where({ status: \"queued\" })\n * .orderBy(\"nextAttemptAt\")\n * .limit(10)\n * .forUpdate({ skipLocked: true }),\n * ).all();\n * ```\n */\n forUpdate(options?: LockOptions): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ lock: buildLock(\"update\", options) });\n }\n\n /**\n * Take a shared read lock on the selected rows (`SELECT ... FOR SHARE`), the\n * weaker counterpart of {@link SelectBuilder.forUpdate}.\n *\n * @param options `skipLocked` / `noWait` wait behavior, and `of` tables.\n * @returns A builder carrying the locking clause.\n * @throws Error When both `skipLocked` and `noWait` are set.\n */\n forShare(options?: LockOptions): SelectBuilder<Full, Proj, Grouped> {\n return this.with({ lock: buildLock(\"share\", options) });\n }\n}\n\n/** Normalize {@link LockOptions} into the AST's {@link LockClause}. */\nfunction buildLock(\n strength: LockClause[\"strength\"],\n options: LockOptions | undefined,\n): LockClause {\n if (options?.skipLocked && options?.noWait) {\n throw new Error(\"forUpdate/forShare accept skipLocked or noWait, not both.\");\n }\n const wait: LockClause[\"wait\"] = options?.skipLocked\n ? \"skipLocked\"\n : options?.noWait\n ? \"noWait\"\n : \"block\";\n return { strength, wait, of: options?.of ?? [] };\n}\n\n// --------------------------------------------------------------------------\n// entrypoint\n// --------------------------------------------------------------------------\n\n/** Build a SELECT over every column of the model. */\nexport function select<C extends ModelClass>(\n model: C,\n): SelectBuilder<InferModel<C>, InferModel<C>>;\n\n/** Build a SELECT projecting only the given columns. */\nexport function select<C extends ModelClass, K extends keyof InferModel<C> & string>(\n model: C,\n columns: readonly K[],\n): SelectBuilder<InferModel<C>, Pick<InferModel<C>, K>>;\n\nexport function select(\n model: ModelClass,\n columns?: readonly string[],\n): SelectBuilder<unknown, unknown> {\n const base = aliasOf(model);\n return new SelectBuilder(\n {\n kind: \"select\",\n table: base ? base.tablename : model.tablename,\n alias: base ? model.tablename : undefined,\n columns: columns ?? \"*\",\n distinct: false,\n aggregates: [],\n groupBy: [],\n where: undefined,\n orderBy: [],\n limit: undefined,\n offset: undefined,\n names: columnNamesOf(model) ?? undefined,\n codecs: codecsOf(model) ?? undefined,\n },\n model,\n );\n}\n","/**\n * tempest-db-js — window functions.\n *\n * The questions a `GROUP BY` cannot answer without a second query: the position\n * of a row inside its group, a running total, the difference to the previous row.\n * Without them, \"top 3 per region\" becomes one query per region — the N+1 of\n * reporting.\n */\n\nimport { type ExprNode, type Expression, expressionFromNode } from \"./conditions.js\";\nimport { Agg } from \"./query.js\";\n\n/**\n * A function that is only legal **inside** a window.\n *\n * `row_number()` and `lag()` are errors without an `OVER` clause — SQLite says\n * \"misuse of window function\", PostgreSQL \"window function ... requires an OVER\n * clause\". Making them their own type means {@link over} is the only place they\n * can go, so the mistake does not compile instead of failing at runtime.\n */\nexport interface WindowFn<T = unknown> {\n /** The call node this wraps. */\n readonly call: ExprNode;\n /** Phantom: the value the function produces. */\n readonly __t?: T;\n}\n\n/** How a window is framed around the current row. */\nexport interface WindowSpec {\n /** Restart the window for each distinct value of these columns. */\n readonly partitionBy?: readonly string[];\n /** Order inside the window — what `rank` and a running total are computed over. */\n readonly orderBy?: readonly (string | readonly [string, \"asc\" | \"desc\"])[];\n /**\n * An explicit frame (`ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`).\n *\n * Omitted, the database's default applies — and the default is `RANGE`, which\n * for a running total lumps **every peer** of the current row together. When\n * rows share an `orderBy` value and that matters, say `ROWS` explicitly.\n */\n readonly frame?: string;\n}\n\n/** Turn a window function, aggregate or expression into the node a window wraps. */\nfunction functionNode(fn: Expression | Agg<unknown> | WindowFn<unknown>): ExprNode {\n if (\"call\" in fn) return fn.call;\n if (fn instanceof Agg) {\n const arg: ExprNode =\n fn.column === \"*\"\n ? { kind: \"star\" }\n : typeof fn.column === \"string\"\n ? { kind: \"column\", name: fn.column }\n : fn.column;\n return { kind: \"fn\", name: fn.fn, args: [arg] };\n }\n return fn.node;\n}\n\n/**\n * Apply a function `OVER` a window.\n *\n * @param fn The window function ({@link rowNumber}, {@link lag}, …) or an\n * aggregate (`sum(\"total\")`) used as one.\n * @param spec Partitioning, ordering and framing.\n * @returns An expression usable in `compute`, `where` and `orderBy`.\n *\n * @example\n * ```ts\n * select(Sale).compute({\n * rank: over(rowNumber(), { partitionBy: [\"region\"], orderBy: [[\"total\", \"desc\"]] }),\n * running: over(sum(\"total\"), { partitionBy: [\"region\"], orderBy: [\"date\"] }),\n * });\n * ```\n */\nexport function over<T = unknown>(\n fn: WindowFn<T> | Expression<T> | Agg<T>,\n spec: WindowSpec = {},\n): Expression<T> {\n return expressionFromNode<T>({\n kind: \"window\",\n fn: functionNode(fn as Expression | Agg<unknown> | WindowFn<unknown>),\n partitionBy: [...(spec.partitionBy ?? [])],\n orderBy: (spec.orderBy ?? []).map((term) =>\n typeof term === \"string\"\n ? { column: term, direction: \"asc\" as const }\n : { column: term[0], direction: term[1] },\n ),\n frame: spec.frame ?? null,\n });\n}\n\n/** Build a zero-argument window function. */\nfunction windowFn<T>(name: string, args: readonly ExprNode[] = []): WindowFn<T> {\n return { call: { kind: \"fn\", name, args } };\n}\n\n/** `row_number()` — 1, 2, 3 … within the window, with no ties. */\nexport function rowNumber(): WindowFn<number> {\n return windowFn<number>(\"row_number\");\n}\n\n/** `rank()` — ties share a position, and the next one skips (1, 1, 3). */\nexport function rank(): WindowFn<number> {\n return windowFn<number>(\"rank\");\n}\n\n/** `dense_rank()` — ties share a position, and the next one does not skip (1, 1, 2). */\nexport function denseRank(): WindowFn<number> {\n return windowFn<number>(\"dense_rank\");\n}\n\n/** `percent_rank()` — the rank as a fraction between 0 and 1. */\nexport function percentRank(): WindowFn<number> {\n return windowFn<number>(\"percent_rank\");\n}\n\n/**\n * `lag(column, offset)` — the value from a row **behind** the current one.\n *\n * @param column The column to read.\n * @param offset How many rows back (default 1).\n * @returns The expression.\n */\nexport function lag<T = unknown>(column: string, offset = 1): WindowFn<T | null> {\n return windowFn<T | null>(\"lag\", [\n { kind: \"column\", name: column },\n { kind: \"value\", value: offset },\n ]);\n}\n\n/**\n * `lead(column, offset)` — the value from a row **ahead** of the current one.\n *\n * @param column The column to read.\n * @param offset How many rows forward (default 1).\n * @returns The expression.\n */\nexport function lead<T = unknown>(column: string, offset = 1): WindowFn<T | null> {\n return windowFn<T | null>(\"lead\", [\n { kind: \"column\", name: column },\n { kind: \"value\", value: offset },\n ]);\n}\n\n/** `first_value(column)` — the first value in the window. */\nexport function firstValue<T = unknown>(column: string): WindowFn<T | null> {\n return windowFn<T | null>(\"first_value\", [{ kind: \"column\", name: column }]);\n}\n\n/** `last_value(column)` — the last value in the window (mind the default frame). */\nexport function lastValue<T = unknown>(column: string): WindowFn<T | null> {\n return windowFn<T | null>(\"last_value\", [{ kind: \"column\", name: column }]);\n}\n","/**\n * tempest-db-js — row (de)serialization, à la Python's `model_dump` / `model_validate`.\n *\n * Rows in tempest-db-js are plain inferred objects. This module converts between three\n * representations, coercing each field by its column type:\n *\n * - **Row** — native JS values (`Date`, `bigint`, `Uint8Array`, parsed JSON).\n * - **Dict** — a plain object of native values, restricted to known columns.\n * - **JSON** — a JSON-safe object (`Date` → ISO string, `bigint` → string,\n * `Uint8Array` → base64), ready for `JSON.stringify`.\n *\n * `fromDict` rebuilds a validated Row from arbitrary input (e.g. an API payload),\n * coercing strings back to `Date`/`bigint`/`Uint8Array` and validating that\n * required columns are present.\n */\n\nimport {\n Column,\n type ColumnType,\n type InferModel,\n type ModelClass,\n type NameMap,\n columnPropsOf,\n columnsOf,\n} from \"./index.js\";\n\n/** Raised when `fromDict` input fails validation against the model. */\nexport class ValidationError extends Error {\n constructor(\n readonly table: string,\n readonly issues: readonly string[],\n ) {\n super(`Validation failed for ${table}:\\n - ${issues.join(\"\\n - \")}`);\n this.name = \"ValidationError\";\n }\n}\n\n/** Base64-encode bytes (Node `Buffer`, falling back to a manual encoder). */\nfunction toBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== \"undefined\") return Buffer.from(bytes).toString(\"base64\");\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/** Base64-decode to bytes. */\nfunction fromBase64(value: string): Uint8Array {\n if (typeof Buffer !== \"undefined\") return new Uint8Array(Buffer.from(value, \"base64\"));\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * The same column without its codec, so the base conversion can run underneath.\n *\n * @param column A column carrying a codec.\n * @returns The column as its stored type sees it.\n */\nfunction baseOf(column: Column<unknown>): Column<unknown> {\n return new Column(\n column.type,\n column.flags,\n column.defaultValue,\n column.onUpdateValue,\n column.reference,\n column.dbName,\n null,\n );\n}\n\n/** Encode one native row value to its JSON-safe form, by column kind. */\nexport function encodeValue(column: Column<unknown>, value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (column.codec) return encodeValue(baseOf(column), column.codec.toDb(value));\n switch (column.type.kind) {\n case \"bigint\":\n return typeof value === \"bigint\" ? value.toString() : value;\n case \"date\":\n case \"datetime\":\n case \"timestamp\":\n return value instanceof Date ? value.toISOString() : value;\n case \"blob\":\n return value instanceof Uint8Array ? toBase64(value) : value;\n default:\n return value;\n }\n}\n\n/** Decode one dict value to its native row form, by column kind. */\nexport function decodeValue(column: Column<unknown>, value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (column.codec) return column.codec.fromDb(decodeValue(baseOf(column), value));\n switch (column.type.kind) {\n case \"bigint\":\n return typeof value === \"bigint\" ? value : BigInt(value as string | number);\n case \"date\":\n case \"datetime\":\n case \"timestamp\":\n return value instanceof Date ? value : new Date(value as string | number);\n case \"blob\":\n return value instanceof Uint8Array ? value : fromBase64(value as string);\n case \"json\":\n return typeof value === \"string\" ? JSON.parse(value) : value;\n case \"array\": {\n const element = column.type.meta.element;\n const items = typeof value === \"string\" ? JSON.parse(value) : value;\n if (!Array.isArray(items)) return items;\n if (!element) return items;\n return items.map((item) => decodeValue({ type: element } as Column<unknown>, item));\n }\n case \"numeric\":\n return typeof value === \"string\" ? value : String(value);\n case \"boolean\":\n return typeof value === \"boolean\" ? value : value === 1 || value === \"true\";\n case \"smallint\":\n case \"integer\":\n case \"real\":\n case \"double\":\n return typeof value === \"number\" ? value : Number(value);\n default:\n return value; // varchar/text/char/uuid/enum/time → string passthrough\n }\n}\n\n/**\n * Convert a row to a plain dict of native values, restricted to known columns.\n * Strips any non-column properties; keeps `Date`/`bigint`/`Uint8Array` as-is.\n *\n * @param model The model class.\n * @param row The row object.\n * @returns A plain object with one entry per column.\n */\nexport function toDict<C extends ModelClass>(\n model: C,\n row: InferModel<C>,\n): Record<string, unknown> {\n const columns = columnsOf(model);\n const out: Record<string, unknown> = {};\n for (const name of Object.keys(columns)) {\n out[name] = (row as Record<string, unknown>)[name] ?? null;\n }\n return out;\n}\n\n/**\n * Convert a row to a JSON-safe object: `Date` → ISO string, `bigint` → string,\n * `Uint8Array` → base64. Ready to hand to `JSON.stringify`.\n *\n * @param model The model class.\n * @param row The row object.\n * @returns A JSON-safe object with one entry per column.\n */\nexport function toJSON<C extends ModelClass>(\n model: C,\n row: InferModel<C>,\n): Record<string, unknown> {\n const columns = columnsOf(model);\n const out: Record<string, unknown> = {};\n for (const [name, col] of Object.entries(columns)) {\n out[name] = encodeValue(col, (row as Record<string, unknown>)[name] ?? null);\n }\n return out;\n}\n\n/** Convenience: `toJSON` then `JSON.stringify`. */\nexport function stringify<C extends ModelClass>(model: C, row: InferModel<C>): string {\n return JSON.stringify(toJSON(model, row));\n}\n\n/**\n * Build a validated row from an arbitrary dict/JSON object (e.g. an API body).\n *\n * Each known column is coerced from the input to its native type (strings back\n * to `Date`/`bigint`/`Uint8Array`, JSON strings parsed). A column that is\n * `notNull`, has no default, and is missing/null in the input is a validation\n * error. Unknown keys in the input are ignored.\n *\n * @param model The model class.\n * @param data The input object (parsed JSON or a plain dict).\n * @returns A typed row.\n * @throws ValidationError When a required column is absent.\n */\nexport function fromDict<C extends ModelClass>(\n model: C,\n data: Record<string, unknown>,\n): InferModel<C> {\n const columns = columnsOf(model);\n const out: Record<string, unknown> = {};\n const issues: string[] = [];\n\n for (const [name, col] of Object.entries(columns)) {\n const present = name in data && data[name] !== undefined && data[name] !== null;\n if (!present) {\n const required = col.flags.notNull && !col.flags.hasDefault;\n if (required) {\n issues.push(`missing required column \"${name}\"`);\n continue;\n }\n out[name] = null;\n continue;\n }\n try {\n out[name] = decodeValue(col, data[name]);\n } catch (error) {\n issues.push(`column \"${name}\": ${(error as Error).message}`);\n }\n }\n\n if (issues.length > 0) {\n throw new ValidationError(model.tablename, issues);\n }\n return out as InferModel<C>;\n}\n\n/** Parse a JSON string then build a validated row. */\nexport function parse<C extends ModelClass>(model: C, json: string): InferModel<C> {\n return fromDict(model, JSON.parse(json) as Record<string, unknown>);\n}\n\n/** A per-column value decoder for the hot read path. */\ntype Decoder = (value: unknown) => unknown;\n\n/**\n * Build the specialized decoder for a column type, or `null` when the type needs\n * no coercion (varchar/text/char/uuid/enum/time — plain string passthrough).\n * Dispatching on the kind once here (at build time) keeps the per-row path a\n * single indirect call instead of a switch.\n */\nfunction decoderFor(type: ColumnType): Decoder | null {\n switch (type.kind) {\n case \"bigint\":\n return (v) => (v == null ? null : typeof v === \"bigint\" ? v : BigInt(v as string));\n case \"date\":\n case \"datetime\":\n case \"timestamp\":\n return (v) => (v == null ? null : v instanceof Date ? v : new Date(v as string));\n case \"blob\":\n return (v) =>\n v == null ? null : v instanceof Uint8Array ? v : fromBase64(v as string);\n case \"json\":\n return (v) => (v == null ? null : typeof v === \"string\" ? JSON.parse(v) : v);\n case \"array\": {\n const element = type.meta.element;\n const inner = element ? decoderFor(element) : null;\n if (!inner) return null;\n return (v) => (v == null ? null : Array.isArray(v) ? v.map(inner) : v);\n }\n case \"numeric\":\n return (v) => (v == null ? null : typeof v === \"string\" ? v : String(v));\n case \"boolean\":\n return (v) =>\n v == null ? null : typeof v === \"boolean\" ? v : v === 1 || v === \"true\";\n case \"smallint\":\n case \"integer\":\n case \"real\":\n case \"double\":\n return (v) => (v == null ? null : typeof v === \"number\" ? v : Number(v));\n default:\n return null; // varchar/text/char/uuid/enum/time → passthrough\n }\n}\n\n/**\n * Everything needed to turn a raw driver row into a model row: how to rename the\n * keys back into property space, and how to coerce the values.\n */\ninterface RowMapper {\n /** Database column → property name, or `null` when every name is the identity. */\n readonly props: NameMap | null;\n /** Database column → decoder, for the columns that need coercion. */\n readonly decoders: Map<string, Decoder>;\n}\n\n/** Memoized per-model row mappers. */\nconst mapperCache = new WeakMap<ModelClass, RowMapper>();\n\n/**\n * The (memoized) row mapper for a model. Keyed by **database** column name,\n * because that is what the driver hands back — a model that renames its columns\n * still lands in property space after one lookup.\n */\nfunction mapperFor(model: ModelClass): RowMapper {\n const cached = mapperCache.get(model);\n if (cached) return cached;\n const props = columnPropsOf(model);\n const names = props\n ? Object.fromEntries(Object.entries(props).map(([db, prop]) => [prop, db]))\n : null;\n const decoders = new Map<string, Decoder>();\n for (const [prop, col] of Object.entries(columnsOf(model))) {\n const decoder = decoderFor(col.type);\n const codec = col.codec;\n if (codec) {\n // The codec runs **after** the base decoding, so a custom type over\n // `bigInteger` receives a bigint, not the driver's string.\n const decode: Decoder = decoder\n ? (value) =>\n value === null || value === undefined ? value : codec.fromDb(decoder(value))\n : (value) =>\n value === null || value === undefined ? value : codec.fromDb(value);\n decoders.set(names?.[prop] ?? prop, decode);\n continue;\n }\n if (decoder) decoders.set(names?.[prop] ?? prop, decoder);\n }\n const mapper: RowMapper = { props, decoders };\n mapperCache.set(model, mapper);\n return mapper;\n}\n\n/**\n * Coerce a raw driver row into native row values, by column type, renaming the\n * keys back to model property names when the model maps columns explicitly. Unlike\n * `fromDict`, it does NOT validate required columns — a row read from the\n * database (or a projection) is taken as-is, only its values are normalized\n * (e.g. `0/1` → boolean, ISO string → `Date`, JSON string → object). Keys that\n * are not columns of the model (or columns needing no coercion) pass through\n * untouched.\n *\n * Uses a memoized per-model decoder map so a large result set does not\n * re-reflect the model or re-dispatch the type switch on every row.\n *\n * @param model The model class.\n * @param raw The raw row returned by the driver.\n * @returns The row with native-typed values.\n */\nexport function coerceRow<C extends ModelClass>(\n model: C,\n raw: Record<string, unknown>,\n): InferModel<C> {\n const { props, decoders } = mapperFor(model);\n const out: Record<string, unknown> = {};\n for (const name of Object.keys(raw)) {\n const decode = decoders.get(name);\n out[props?.[name] ?? name] = decode ? decode(raw[name]) : raw[name];\n }\n return out as InferModel<C>;\n}\n","/**\n * tempest-db-js — Phase 2: typed INSERT / UPDATE / DELETE builders.\n *\n * Like `select`, these are PURE AST + phantom types — no database access. They\n * are executed in Phase 4 via `session.execute`.\n *\n * Safety rule: UPDATE and DELETE start in an *unguarded* type state. A builder\n * only becomes executable once it has a `.where(...)` clause or an explicit\n * `.unguarded()` opt-in. Phase 4's `session.execute` will accept only guarded\n * builders, making an accidental full-table write a compile error.\n */\n\nimport {\n type CondNode,\n type Condition,\n type Expression,\n isExpression,\n toCondNode,\n} from \"./conditions.js\";\nimport {\n type ColumnCodec,\n type InferInsert,\n type InferModel,\n type ModelClass,\n type NameMap,\n type SqlExpression,\n codecsOf,\n columnNamesOf,\n columnsOf,\n defaultAsWriteValue,\n isSqlExpression,\n} from \"./index.js\";\nimport type { WhereInput } from \"./query.js\";\nimport { ValidationError } from \"./serialize.js\";\n\n// --------------------------------------------------------------------------\n// shared\n// --------------------------------------------------------------------------\n\n/** Columns to return from a mutation, or \"*\" for the whole row. */\nexport type Returning = readonly string[] | \"*\" | null;\n\n/**\n * A write shape over `Row`: every column accepts its own value **or** a\n * {@link SqlExpression}, which the dialect renders inline instead of binding.\n * Optionality is preserved from `Row`, so an insert shape keeps its defaults\n * optional.\n */\nexport type WriteValues<Row> = {\n [K in keyof Row]: Row[K] | SqlExpression | Expression;\n};\n\n/** A partial write shape — the `SET` clause of an UPDATE or a `DO UPDATE`. */\nexport type WritePatch<Row> = {\n [K in keyof Row]?: Row[K] | SqlExpression | Expression;\n};\n\n/**\n * Column kinds whose stored value is legitimately an object or an array. Every\n * other kind takes a scalar, so an object reaching it is a mistake.\n */\nconst STRUCTURED_KINDS: ReadonlySet<string> = new Set([\"json\", \"array\", \"blob\"]);\n\n/** True when a value is a scalar SQL can bind as-is. */\nfunction isBindableScalar(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"bigint\" || type === \"boolean\") {\n return true;\n }\n return value instanceof Date || value instanceof Uint8Array;\n}\n\n/**\n * Reject write values that SQL cannot bind meaningfully, before they reach the\n * driver.\n *\n * Without this, a stray object is bound as a parameter and the driver stringifies\n * it (or stores null), so a typo like `{ attempts: { raw: \"attempts + 1\" } }`\n * silently corrupts the column instead of failing. TypeScript already rejects it,\n * but JavaScript callers, an `as` cast, or data crossing a network boundary do\n * not go through the type-checker. To write an expression, use the branded\n * `sql.raw()` / `sql.expr` values.\n *\n * @param model The model the statement writes to.\n * @param values The column → value map from `set()` / `values()`.\n * @param clause The clause name, for the error message.\n * @throws ValidationError When a value is not bindable, or a key is not a column.\n */\nfunction assertWritableValues(\n model: ModelClass,\n values: Record<string, unknown>,\n clause: \"set\" | \"values\",\n): void {\n const columns = columnsOf(model);\n const issues: string[] = [];\n for (const [key, value] of Object.entries(values)) {\n const col = columns[key];\n if (!col) {\n issues.push(`${clause}: \"${key}\" is not a column of ${model.tablename}`);\n continue;\n }\n // A column reference (`col(\"c.tier\")`) is a legitimate write value once\n // the statement has a second source — `UPDATE ... FROM other`.\n if (isExpression(value) || isSqlExpression(value) || isBindableScalar(value)) {\n continue;\n }\n if (typeof value === \"object\" && STRUCTURED_KINDS.has(col.type.kind)) continue;\n issues.push(\n `${clause}: \"${key}\" got ${describeValue(value)}, which cannot be bound to a ` +\n `${col.type.kind} column — use sql.raw()/sql.expr\\`...\\` for a SQL expression`,\n );\n }\n if (issues.length > 0) throw new ValidationError(model.tablename, issues);\n}\n\n/**\n * Convert a row's values into what the database stores, for the columns that\n * declare a custom type.\n *\n * Done here, in the builder, because this is the last place with the model in\n * hand: the dialect binds values without knowing which column they came from.\n *\n * @param model The model being written.\n * @param values The row as the caller wrote it.\n * @returns The row in stored representation.\n */\nfunction encodeWriteValues(\n model: ModelClass,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const codecs = codecsOf(model);\n if (!codecs) return values;\n const out: Record<string, unknown> = { ...values };\n for (const [key, codec] of Object.entries(codecs)) {\n if (!(key in out)) continue;\n const value = out[key];\n // A SQL expression is not a domain value — it is rendered, not converted.\n if (isSqlExpression(value) || isExpression(value)) continue;\n out[key] = codec.toDb(value);\n }\n return out;\n}\n\n/**\n * Reject a multi-row insert whose rows disagree about a **defaulted** column.\n *\n * Every row of one INSERT shares one column list, so a key present in some rows\n * and absent in others is bound as `NULL` for the rows that omit it. For a plain\n * nullable column that is exactly what omitting it meant anyway; for a column\n * with a `DEFAULT` (a primary key included) it is not — the row would be written\n * as NULL instead of taking its default. SQLite has no `DEFAULT` keyword inside\n * `VALUES`, so there is no portable per-row escape; failing loudly is the honest\n * option.\n *\n * @param model The model being inserted into.\n * @param rows The rows of this insert.\n * @throws ValidationError When rows disagree about a column that has a default.\n */\nfunction assertConsistentRows(\n model: ModelClass,\n rows: readonly Record<string, unknown>[],\n): void {\n if (rows.length < 2) return;\n const union = new Set<string>();\n for (const row of rows) for (const key of Object.keys(row)) union.add(key);\n const inconsistent = [...union].filter((key) => rows.some((row) => !(key in row)));\n if (inconsistent.length === 0) return;\n const columns = columnsOf(model);\n const defaulted = inconsistent.filter((key) => columns[key]?.flags.hasDefault);\n if (defaulted.length === 0) return;\n const named = defaulted.map((c) => `\"${c}\"`).join(\", \");\n const verb = defaulted.length === 1 ? \"has\" : \"have\";\n throw new ValidationError(model.tablename, [\n `values: ${named} ${verb} a default but is missing from some rows of this multi-row insert — every row shares one column list, so the omitting rows would be written as NULL instead of taking the default. Give the column in every row, or insert the rows separately.`,\n ]);\n}\n\n/** A short description of a rejected value, for the validation message. */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"function\") return \"a function\";\n if (Array.isArray(value)) return \"an array\";\n if (typeof value === \"symbol\") return \"a symbol\";\n return \"an object\";\n}\n\n// --------------------------------------------------------------------------\n// INSERT\n// --------------------------------------------------------------------------\n\n/**\n * Conflict-resolution clause for an INSERT (`ON CONFLICT`). `target` is the\n * conflicting column(s) (a unique/PK constraint); `update` is `\"nothing\"` for\n * `DO NOTHING`, or the columns to overwrite for `DO UPDATE SET`.\n */\nexport interface OnConflict {\n readonly target: readonly string[];\n readonly update: Record<string, unknown> | \"nothing\";\n /**\n * The predicate of a **partial** unique index. PostgreSQL only matches a\n * partial index as a conflict target when `ON CONFLICT` repeats its predicate,\n * so without this an insert against `... WHERE key IS NOT NULL` is rejected\n * with \"there is no unique or exclusion constraint matching the ON CONFLICT\n * specification\".\n */\n readonly targetWhere?: CondNode | undefined;\n /** Extra condition restricting which conflicting rows `DO UPDATE` rewrites. */\n readonly updateWhere?: CondNode | undefined;\n}\n\n/** Options for the `ON CONFLICT` clause of {@link InsertBuilder.onConflictDoNothing}. */\nexport interface OnConflictOptions<Full> {\n /** The predicate of the partial unique index used as the conflict target. */\n readonly where?: WhereInput<Full> | Condition;\n}\n\n/** Options for {@link InsertBuilder.onConflictDoUpdate}. */\nexport interface OnConflictUpdateOptions<Full> {\n /** The predicate of the partial unique index used as the conflict target. */\n readonly indexWhere?: WhereInput<Full> | Condition;\n /** Extra condition deciding which conflicting rows are actually rewritten. */\n readonly updateWhere?: WhereInput<Full> | Condition;\n}\n\n/** Serializable AST for an INSERT. */\nexport interface InsertNode {\n readonly kind: \"insert\";\n /** Per-column codecs for custom types, by property name. */\n readonly codecs?: Readonly<Record<string, ColumnCodec>> | undefined;\n readonly table: string;\n readonly values: readonly Record<string, unknown>[];\n /**\n * A `SELECT` feeding the insert, with the target columns it fills.\n *\n * Set by {@link InsertBuilder.fromSelect}; mutually exclusive with `values`.\n */\n readonly fromSelect?:\n | { readonly columns: readonly string[]; readonly select: unknown }\n | undefined;\n readonly returning: Returning;\n /** Conflict handling (`ON CONFLICT ...`), or `undefined` for none. */\n readonly onConflict?: OnConflict;\n /** Property → column map, or `undefined` when every name is the identity. */\n readonly names?: NameMap | undefined;\n}\n\n/**\n * INSERT builder.\n *\n * @typeParam Full - the complete row type (for `returning`).\n * @typeParam Ins - the insert shape (defaults/PK optional).\n * @typeParam Ret - execution result: `number` (rows affected) until `returning`.\n */\nexport class InsertBuilder<Full, Ins, Ret = number> {\n declare readonly __row: Ret;\n\n constructor(\n readonly node: InsertNode,\n /** The source model, used to coerce returned rows on execution. */\n readonly source: ModelClass,\n ) {}\n\n private with<R>(patch: Partial<InsertNode>): InsertBuilder<Full, Ins, R> {\n return new InsertBuilder<Full, Ins, R>({ ...this.node, ...patch }, this.source);\n }\n\n /**\n * Provide one row or many rows to insert, typed by the insert shape.\n *\n * @param rows One row, or an array of rows.\n * @returns A builder carrying the rows.\n * @throws ValidationError When a value is not a column value the dialect can\n * bind (see the `sql` helpers for writing an expression instead), or when the\n * rows of a multi-row insert disagree about a column that has a default.\n */\n values(\n rows: WriteValues<Ins> | readonly WriteValues<Ins>[],\n ): InsertBuilder<Full, Ins, Ret> {\n const list = (Array.isArray(rows) ? rows : [rows]) as readonly Record<\n string,\n unknown\n >[];\n // Encode before validating: a custom type's domain value (a Money object,\n // say) is not bindable until its codec has converted it, so validating first\n // would reject exactly the values the codec exists for.\n const encoded = list.map((row) => encodeWriteValues(this.source, row));\n for (const row of encoded) assertWritableValues(this.source, row, \"values\");\n assertConsistentRows(this.source, encoded);\n return this.with<Ret>({ values: encoded });\n }\n\n /**\n * On a unique/PK conflict on `target`, do nothing (skip the row).\n *\n * @param target The conflicting column(s) — a unique or primary key.\n * @param options Pass `where` to name the predicate of a **partial** unique\n * index, which PostgreSQL requires in order to match it as a conflict target.\n * @returns A builder carrying the conflict clause.\n *\n * @example\n * ```ts\n * insert(Outbound)\n * .values(data)\n * .onConflictDoNothing([\"consumer\", \"idempotencyKey\"], {\n * where: { idempotencyKey: { isNull: false } },\n * })\n * .returning();\n * ```\n */\n onConflictDoNothing(\n target: readonly (keyof Full & string)[],\n options?: OnConflictOptions<Full>,\n ): InsertBuilder<Full, Ins, Ret> {\n return this.with<Ret>({\n onConflict: {\n target,\n update: \"nothing\",\n targetWhere: options?.where ? toCondNode(options.where as never) : undefined,\n },\n });\n }\n\n /**\n * On a unique/PK conflict on `target`, overwrite the given columns (upsert).\n *\n * @param target The conflicting column(s) — a unique or primary key.\n * @param set The columns to update with new values.\n * @param options `indexWhere` names the predicate of a partial unique index\n * (the conflict target); `updateWhere` further restricts which conflicting\n * rows are rewritten.\n * @returns A builder carrying the conflict clause.\n * @throws ValidationError When a `set` value cannot be bound.\n */\n onConflictDoUpdate(\n target: readonly (keyof Full & string)[],\n set: WritePatch<Full>,\n options?: OnConflictUpdateOptions<Full>,\n ): InsertBuilder<Full, Ins, Ret> {\n assertWritableValues(this.source, set as Record<string, unknown>, \"set\");\n return this.with<Ret>({\n onConflict: {\n target,\n update: set as Record<string, unknown>,\n targetWhere: options?.indexWhere\n ? toCondNode(options.indexWhere as never)\n : undefined,\n updateWhere: options?.updateWhere\n ? toCondNode(options.updateWhere as never)\n : undefined,\n },\n });\n }\n\n /**\n * Fill the table from another query — `INSERT INTO t (a, b) SELECT …`.\n *\n * The rows never leave the database, which is the point: archiving or copying a\n * million rows should not become a million round trips through this process.\n *\n * @param columns The target columns, in the order the query projects them.\n * @param query The query producing the rows.\n * @returns A builder ready to execute.\n * @throws Error When no target column is given.\n *\n * @example\n * ```ts\n * insert(ArchivedOrder).fromSelect(\n * [\"id\", \"total\"],\n * select(Order, [\"id\", \"total\"]).where({ createdAt: { lt: cutoff } }),\n * );\n * ```\n */\n fromSelect<K extends keyof Ins & string>(\n columns: readonly K[],\n query: { readonly node: unknown; readonly __row: { [P in K]: unknown } },\n ): InsertBuilder<Full, Ins, Ret> {\n if (columns.length === 0) {\n throw new Error(\"fromSelect() needs at least one target column.\");\n }\n return this.with<Ret>({\n values: [],\n fromSelect: { columns: [...columns], select: query.node },\n });\n }\n\n /** Return the full inserted row(s). */\n returning(): InsertBuilder<Full, Ins, Full>;\n /** Return only the given columns of the inserted row(s). */\n returning<K extends keyof Full & string>(\n columns: readonly K[],\n ): InsertBuilder<Full, Ins, Pick<Full, K>>;\n returning(columns?: readonly string[]): InsertBuilder<Full, Ins, unknown> {\n return this.with<unknown>({ returning: columns ?? \"*\" });\n }\n}\n\n/** Build an INSERT into the model's table. */\nexport function insert<C extends ModelClass>(\n model: C,\n): InsertBuilder<InferModel<C>, InferInsert<C>> {\n return new InsertBuilder(\n {\n kind: \"insert\",\n table: model.tablename,\n values: [],\n returning: null,\n names: columnNamesOf(model) ?? undefined,\n codecs: codecsOf(model) ?? undefined,\n },\n model,\n );\n}\n\n// --------------------------------------------------------------------------\n// UPDATE\n// --------------------------------------------------------------------------\n\n/** Serializable AST for an UPDATE. */\nexport interface UpdateNode {\n readonly kind: \"update\";\n /** Per-column codecs for custom types, by property name. */\n readonly codecs?: Readonly<Record<string, ColumnCodec>> | undefined;\n readonly table: string;\n /** Extra source tables (`UPDATE ... FROM other`), by alias. */\n readonly from?: readonly { readonly table: string; readonly alias: string }[];\n readonly set: Record<string, unknown>;\n readonly where: CondNode | undefined;\n /** True once a where-clause or explicit opt-in makes the write safe. */\n readonly guarded: boolean;\n readonly returning: Returning;\n /** Property → column map, or `undefined` when every name is the identity. */\n readonly names?: NameMap | undefined;\n}\n\n/**\n * Add each column's `onUpdate` value to a patch that does not already set it.\n *\n * `.onUpdate(sql.now())` is applied here, on the write path, rather than in DDL:\n * only MySQL has a column-level `ON UPDATE`, so rendering it into the schema\n * would make the same model behave differently per database. An explicit value in\n * the patch always wins — the column's `onUpdate` is a default, not an override.\n *\n * @param model The model being updated.\n * @param values The caller's patch.\n * @returns The patch, plus every applicable `onUpdate` value.\n */\nfunction withOnUpdateValues(\n model: ModelClass,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...values };\n for (const [name, col] of Object.entries(columnsOf(model))) {\n if (col.onUpdateValue !== null && !(name in merged)) {\n merged[name] = defaultAsWriteValue(col.onUpdateValue);\n }\n }\n return merged;\n}\n\n/**\n * UPDATE builder.\n *\n * @typeParam Full - the complete row type.\n * @typeParam Guarded - `true` once safe to execute (has where or opted out).\n * @typeParam Ret - execution result type.\n */\nexport class UpdateBuilder<Full, Guarded extends boolean, Ret = number> {\n declare readonly __row: Ret;\n declare readonly __guarded: Guarded;\n\n constructor(\n readonly node: UpdateNode,\n /** The source model, used to coerce returned rows on execution. */\n readonly source: ModelClass,\n ) {}\n\n private with<G extends boolean, R>(\n patch: Partial<UpdateNode>,\n ): UpdateBuilder<Full, G, R> {\n return new UpdateBuilder<Full, G, R>({ ...this.node, ...patch }, this.source);\n }\n\n /**\n * The columns to write. Partial — only the given columns change.\n *\n * A value is bound as a parameter unless it is a {@link sql} expression, which\n * is rendered inline instead — that is how a counter is written without a\n * read-modify-write race.\n *\n * @param values The column → value map.\n * @returns A builder carrying the assignments.\n * @throws ValidationError When a value is not a column value the dialect can\n * bind (a bare object, an array on a scalar column, a function).\n *\n * @example\n * ```ts\n * update(Outbound)\n * .set({ attempts: sql.raw(\"attempts + 1\"), updatedAt: sql.now() })\n * .where({ id });\n * ```\n */\n set(values: WritePatch<Full>): UpdateBuilder<Full, Guarded, Ret> {\n const encoded = encodeWriteValues(this.source, values as Record<string, unknown>);\n assertWritableValues(this.source, encoded, \"set\");\n return this.with<Guarded, Ret>({\n set: withOnUpdateValues(this.source, encoded),\n });\n }\n\n /**\n * Read from another table while updating — `UPDATE t SET … FROM other WHERE …`.\n *\n * The join condition goes in `where`, where SQL wants it:\n * `.where({ customerId: col(\"c.id\") })`.\n *\n * PostgreSQL and SQLite (3.33+) only. MySQL spells this as a multi-table\n * `UPDATE a JOIN b`, which is out of this project's active scope, so it throws\n * there rather than emitting something the server rejects.\n *\n * @param model The extra source.\n * @param alias The name to reference it by.\n * @returns A builder carrying the extra source.\n */\n from<C extends ModelClass>(model: C, alias: string): UpdateBuilder<Full, Guarded, Ret> {\n return this.with<Guarded, Ret>({\n from: [...(this.node.from ?? []), { table: model.tablename, alias }],\n });\n }\n\n /** Restrict the rows to update. Marks the builder safe to execute. */\n where(input: WhereInput<Full> | Condition): UpdateBuilder<Full, true, Ret> {\n return this.with<true, Ret>({\n where: toCondNode(input as Record<string, unknown>),\n guarded: true,\n });\n }\n\n /** Explicit opt-in to update EVERY row. Use deliberately. */\n unguarded(): UpdateBuilder<Full, true, Ret> {\n return this.with<true, Ret>({ guarded: true });\n }\n\n /** Return the full updated row(s). */\n returning(): UpdateBuilder<Full, Guarded, Full>;\n /** Return only the given columns of the updated row(s). */\n returning<K extends keyof Full & string>(\n columns: readonly K[],\n ): UpdateBuilder<Full, Guarded, Pick<Full, K>>;\n returning(columns?: readonly string[]): UpdateBuilder<Full, Guarded, unknown> {\n return this.with<Guarded, unknown>({ returning: columns ?? \"*\" });\n }\n}\n\n/** Build an UPDATE on the model's table. Starts unguarded. */\nexport function update<C extends ModelClass>(\n model: C,\n): UpdateBuilder<InferModel<C>, false> {\n return new UpdateBuilder(\n {\n kind: \"update\",\n table: model.tablename,\n set: {},\n where: undefined,\n guarded: false,\n returning: null,\n names: columnNamesOf(model) ?? undefined,\n codecs: codecsOf(model) ?? undefined,\n },\n model,\n );\n}\n\n// --------------------------------------------------------------------------\n// DELETE\n// --------------------------------------------------------------------------\n\n/** Serializable AST for a DELETE. */\nexport interface DeleteNode {\n readonly kind: \"delete\";\n /** Per-column codecs for custom types, by property name. */\n readonly codecs?: Readonly<Record<string, ColumnCodec>> | undefined;\n readonly table: string;\n /** Extra source tables (`DELETE ... USING other`), by alias. */\n readonly using?: readonly { readonly table: string; readonly alias: string }[];\n readonly where: CondNode | undefined;\n readonly guarded: boolean;\n readonly returning: Returning;\n /** Property → column map, or `undefined` when every name is the identity. */\n readonly names?: NameMap | undefined;\n}\n\n/**\n * DELETE builder. Starts unguarded — same safety rule as UPDATE.\n *\n * @typeParam Full - the complete row type.\n * @typeParam Guarded - `true` once safe to execute.\n * @typeParam Ret - execution result type.\n */\nexport class DeleteBuilder<Full, Guarded extends boolean, Ret = number> {\n declare readonly __row: Ret;\n declare readonly __guarded: Guarded;\n\n constructor(\n readonly node: DeleteNode,\n /** The source model, used to coerce returned rows on execution. */\n readonly source: ModelClass,\n ) {}\n\n private with<G extends boolean, R>(\n patch: Partial<DeleteNode>,\n ): DeleteBuilder<Full, G, R> {\n return new DeleteBuilder<Full, G, R>({ ...this.node, ...patch }, this.source);\n }\n\n /**\n * Delete by matching another table — `DELETE FROM t USING other WHERE …`.\n *\n * PostgreSQL only. SQLite and MySQL have no `USING` here; there the portable\n * form is `where({ id: { in: select(Other, [\"id\"]).where(...).asSubquery(\"id\") } })`,\n * and this throws rather than pretending.\n *\n * @param model The extra source.\n * @param alias The name to reference it by.\n * @returns A builder carrying the extra source.\n */\n using<C extends ModelClass>(\n model: C,\n alias: string,\n ): DeleteBuilder<Full, Guarded, Ret> {\n return this.with<Guarded, Ret>({\n using: [...(this.node.using ?? []), { table: model.tablename, alias }],\n });\n }\n\n /** Restrict the rows to delete. Marks the builder safe to execute. */\n where(input: WhereInput<Full> | Condition): DeleteBuilder<Full, true, Ret> {\n return this.with<true, Ret>({\n where: toCondNode(input as Record<string, unknown>),\n guarded: true,\n });\n }\n\n /** Explicit opt-in to delete EVERY row. Use deliberately. */\n unguarded(): DeleteBuilder<Full, true, Ret> {\n return this.with<true, Ret>({ guarded: true });\n }\n\n /** Return the full deleted row(s). */\n returning(): DeleteBuilder<Full, Guarded, Full>;\n /** Return only the given columns of the deleted row(s). */\n returning<K extends keyof Full & string>(\n columns: readonly K[],\n ): DeleteBuilder<Full, Guarded, Pick<Full, K>>;\n returning(columns?: readonly string[]): DeleteBuilder<Full, Guarded, unknown> {\n return this.with<Guarded, unknown>({ returning: columns ?? \"*\" });\n }\n}\n\n/** Build a DELETE on the model's table. Starts unguarded. */\nexport function del<C extends ModelClass>(model: C): DeleteBuilder<InferModel<C>, false> {\n return new DeleteBuilder(\n {\n kind: \"delete\",\n table: model.tablename,\n where: undefined,\n guarded: false,\n returning: null,\n names: columnNamesOf(model) ?? undefined,\n codecs: codecsOf(model) ?? undefined,\n },\n model,\n );\n}\n","/**\n * tempest-db-js — database URL parsing & dialect detection.\n *\n * Mirrors SQLAlchemy's `make_url`: a single connection string identifies the\n * dialect (and optional driver), so switching databases is just swapping the\n * URL — `sqlite://./app.db` ↔ `postgresql://user:pass@host/db`.\n *\n * The driver suffix (`postgresql+pg`, `sqlite+better-sqlite3`, or SQLAlchemy's\n * async flavors like `postgresql+asyncpg`) is parsed out and ignored for dialect\n * detection, so URLs copied from a Python service still work here.\n */\n\n/** A database dialect tempest-db-js can target. */\nexport type Dialect = \"sqlite\" | \"postgresql\" | \"mysql\";\n\n/** A parsed database URL, dialect-neutral. */\nexport interface ParsedDatabaseUrl {\n /** The detected dialect. */\n readonly dialect: Dialect;\n /** Driver after the `+` in the scheme (e.g. `better-sqlite3`), or `null`. */\n readonly driver: string | null;\n /** Host (PostgreSQL/MySQL), or `null` for SQLite. */\n readonly host: string | null;\n /** Port, or `null`. */\n readonly port: number | null;\n /** Username, or `null`. */\n readonly user: string | null;\n /** Password, or `null`. */\n readonly password: string | null;\n /** Database name (PostgreSQL) or file path (SQLite). `:memory:` for in-memory. */\n readonly database: string | null;\n /** Extra query-string options (`?sslmode=require`). */\n readonly options: Readonly<Record<string, string>>;\n /** The original URL, untouched. */\n readonly raw: string;\n}\n\n/** Raised when a URL cannot be parsed or its dialect is unsupported. */\nexport class InvalidDatabaseUrl extends Error {\n constructor(url: string, reason: string) {\n super(`Invalid database URL ${JSON.stringify(url)}: ${reason}`);\n this.name = \"InvalidDatabaseUrl\";\n }\n}\n\n/** Map a scheme's base name to a tempest-db-js dialect. */\nconst DIALECT_ALIASES: Readonly<Record<string, Dialect>> = {\n sqlite: \"sqlite\",\n sqlite3: \"sqlite\",\n postgresql: \"postgresql\",\n postgres: \"postgresql\",\n pg: \"postgresql\",\n mysql: \"mysql\",\n mariadb: \"mysql\",\n};\n\n/** Split `\"postgresql+asyncpg\"` into `[\"postgresql\", \"asyncpg\"]`. */\nfunction splitScheme(scheme: string): { base: string; driver: string | null } {\n const plus = scheme.indexOf(\"+\");\n if (plus === -1) return { base: scheme.toLowerCase(), driver: null };\n return {\n base: scheme.slice(0, plus).toLowerCase(),\n driver: scheme.slice(plus + 1) || null,\n };\n}\n\n/** Decode a URL component, leaving it untouched if it is not encoded. */\nfunction decode(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * Parse a SQLite URL. Forms supported (SQLAlchemy-compatible):\n * - `sqlite://:memory:` / `sqlite::memory:` → in-memory\n * - `sqlite:///relative/path.db` → relative path\n * - `sqlite:////absolute/path.db` → absolute path\n * - `sqlite://./app.db` / `sqlite:app.db` → relative path (convenience)\n */\nfunction parseSqlite(\n raw: string,\n driver: string | null,\n rest: string,\n): ParsedDatabaseUrl {\n let database: string;\n if (rest.endsWith(\":memory:\")) {\n database = \":memory:\";\n } else if (rest.startsWith(\"///\")) {\n // sqlite:///rel → \"rel\" ; sqlite:////abs → \"/abs\"\n database = rest.slice(3) || \":memory:\";\n } else if (rest.startsWith(\"//\")) {\n database = rest.slice(2) || \":memory:\";\n } else {\n database = rest || \":memory:\";\n }\n return {\n dialect: \"sqlite\",\n driver,\n host: null,\n port: null,\n user: null,\n password: null,\n database: decode(database),\n options: {},\n raw,\n };\n}\n\n/**\n * Parse a network-style URL (PostgreSQL or MySQL) via the WHATWG URL parser.\n * Both share the `scheme://user:pass@host:port/db?opts` shape, so one parser\n * serves both — only the resulting `dialect` differs.\n */\nfunction parseNetworkUrl(\n raw: string,\n driver: string | null,\n rest: string,\n dialect: \"postgresql\" | \"mysql\",\n): ParsedDatabaseUrl {\n // Rebuild with a clean scheme so the WHATWG URL parser accepts it.\n let parsed: URL;\n try {\n parsed = new URL(`${dialect}:${rest}`);\n } catch {\n throw new InvalidDatabaseUrl(raw, \"could not parse host/credentials\");\n }\n const database = decode(parsed.pathname.replace(/^\\//, \"\")) || null;\n const options: Record<string, string> = {};\n for (const [key, value] of parsed.searchParams) options[key] = value;\n return {\n dialect,\n driver,\n host: parsed.hostname || null,\n port: parsed.port ? Number(parsed.port) : null,\n user: parsed.username ? decode(parsed.username) : null,\n password: parsed.password ? decode(parsed.password) : null,\n database,\n options,\n raw,\n };\n}\n\n/**\n * Parse a database URL into its dialect and connection parts.\n *\n * @param url A connection string, e.g. `\"postgresql://app:app@localhost/app\"`\n * or `\"sqlite:///app.db\"`. An async driver suffix (`+asyncpg`, `+aiosqlite`)\n * is accepted and ignored for dialect detection.\n * @returns The parsed, dialect-neutral connection descriptor.\n * @throws InvalidDatabaseUrl When the URL has no scheme or an unknown dialect.\n */\nexport function parseDatabaseUrl(url: string): ParsedDatabaseUrl {\n const schemeEnd = url.indexOf(\":\");\n if (schemeEnd === -1) {\n throw new InvalidDatabaseUrl(\n url,\n \"missing scheme (expected e.g. sqlite:// or postgresql://)\",\n );\n }\n const { base, driver } = splitScheme(url.slice(0, schemeEnd));\n const dialect = DIALECT_ALIASES[base];\n if (!dialect) {\n throw new InvalidDatabaseUrl(url, `unknown dialect ${JSON.stringify(base)}`);\n }\n const rest = url.slice(schemeEnd + 1);\n if (dialect === \"sqlite\") return parseSqlite(url, driver, rest);\n return parseNetworkUrl(url, driver, rest, dialect);\n}\n\n/** Detect just the dialect of a URL, ignoring the rest. */\nexport function detectDialect(url: string): Dialect {\n return parseDatabaseUrl(url).dialect;\n}\n","/**\n * tempest-db-js — portable SQL expression rendering.\n *\n * A `sql.now()` / `sql.uuidv4()` token is dialect-neutral in the AST and in the\n * migration IR; this is the single place it becomes concrete SQL. Kept in its own\n * module (types only, no runtime imports) so both the query dialect and the DDL\n * renderer share one mapping instead of drifting apart.\n */\n\nimport type { Dialect } from \"./url.js\";\n\n/** The dialect-neutral expression tokens (the non-fragment `PortableExpression`s). */\nexport type PortableToken = \"now\" | \"current_date\" | \"current_time\" | \"uuidv4\";\n\n/**\n * Render a reference to the incoming row of an upsert.\n *\n * PostgreSQL and SQLite expose it as the `excluded` pseudo-table; MySQL has no\n * such table and spells the same idea as `VALUES(col)` inside\n * `ON DUPLICATE KEY UPDATE`.\n *\n * @param column The already-quoted column identifier.\n * @param bare The column name without quoting, for MySQL's `VALUES()` form.\n * @param dialect The target dialect.\n * @returns The SQL text.\n */\nexport function renderExcluded(column: string, bare: string, dialect: Dialect): string {\n return dialect === \"mysql\" ? `VALUES(${bare})` : `excluded.${column}`;\n}\n\n/**\n * Render a portable expression token to SQL for the dialect.\n *\n * @param token The dialect-neutral token.\n * @param dialect The target dialect.\n * @returns The SQL text for that token.\n */\nexport function renderPortableToken(token: PortableToken, dialect: Dialect): string {\n switch (token) {\n case \"now\":\n if (dialect === \"postgresql\") return \"now()\";\n // SQLite's CURRENT_TIMESTAMP is \"YYYY-MM-DD HH:MM:SS\": no `T`, no\n // milliseconds, no zone. JS parses that as **local** time, so a row written\n // at 21:00Z read back as 00:00Z on a UTC-3 machine, and comparing the column\n // against a bound ISO string compared \" \" with \"T\" and silently matched\n // nothing. `strftime` writes exactly the format this package binds and reads.\n if (dialect === \"sqlite\") return \"strftime('%Y-%m-%dT%H:%M:%fZ', 'now')\";\n return \"CURRENT_TIMESTAMP\";\n case \"current_date\":\n return \"CURRENT_DATE\";\n case \"current_time\":\n return \"CURRENT_TIME\";\n case \"uuidv4\":\n if (dialect === \"postgresql\") return \"gen_random_uuid()\";\n if (dialect === \"mysql\") return \"(UUID())\";\n return \"(lower(hex(randomblob(16))))\";\n }\n}\n","/**\n * tempest-db-js — text search that survives what users actually type.\n *\n * Two layers, because they answer different questions:\n *\n * - {@link contains} — tokenized, **escaped** substring matching. Identical on\n * every dialect, needs no extension, no index and no migration. This is what\n * \"find the row whose name contains what the user typed\" should use.\n * - {@link fullText} / {@link fullTextRank} — PostgreSQL's `to_tsvector` /\n * `websearch_to_tsquery` / `ts_rank`: stemming, stop words and a relevance\n * score. On any other database they fall back to the first layer, which is the\n * honest degradation — the query still returns the right rows, just without\n * stemming.\n */\n\nimport { type Condition, type Expression, and, or } from \"./conditions.js\";\nimport { conditionFromNode, expressionFromNode } from \"./conditions.js\";\nimport type { WhereInput } from \"./query.js\";\n\n/**\n * A PostgreSQL text-search configuration (`regconfig`), such as `\"english\"` or\n * `\"portuguese\"`. `\"simple\"` disables stemming and stop-word removal.\n */\nexport type TextSearchLanguage = string;\n\n/** Options shared by the full-text helpers. */\nexport interface TextSearchOptions {\n /** The PostgreSQL text-search configuration. Defaults to `\"english\"`. */\n readonly language?: TextSearchLanguage;\n}\n\n/** Options for {@link contains}. */\nexport interface ContainsOptions {\n /**\n * Whether a row must match **every** token (default) or any one of them.\n *\n * `\"all\"` is what a search box wants: typing more words narrows the result.\n */\n readonly match?: \"all\" | \"any\";\n}\n\n/**\n * Escape the `LIKE` wildcards in a literal, for use with `like` / `ilike`.\n *\n * `%` and `_` are wildcards, and `\\` escapes them — so a user searching for\n * `100%` matches every row unless the literal is escaped first. The pattern this\n * produces is meant to be used with an `ESCAPE '\\'` clause, which is what the\n * {@link ContainsOptions} operator emits; PostgreSQL assumes that escape by\n * default, SQLite has none until it is given one.\n *\n * @param value The literal the user typed.\n * @returns The same text with `\\`, `%` and `_` escaped.\n */\nexport function escapeLike(value: string): string {\n return value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n}\n\n/**\n * Split a search term into the tokens a row has to match.\n *\n * @param term What the user typed.\n * @returns The non-empty whitespace-separated tokens.\n */\nexport function tokenize(term: string): string[] {\n return term.split(/\\s+/).filter((token) => token.length > 0);\n}\n\n/**\n * Case-insensitive substring search across one or more columns.\n *\n * The term is tokenized, and each token is matched — **escaped** — against every\n * listed column; a row matches when every token appears in at least one of them.\n * Behaves the same on every dialect, with no index or extension needed.\n *\n * @param columns The columns to search, by property name.\n * @param term What the user typed.\n * @param options `match: \"any\"` to require a single token instead of all of them.\n * @returns A condition for `where`, matching nothing when the term is blank.\n * @throws Error When no column is given.\n *\n * @example\n * ```ts\n * select(User).where(contains([\"name\", \"email\"], \"100% ana\"));\n * // (name ILIKE '%100\\%%' ESCAPE '\\' OR email ILIKE ...) AND (name ILIKE '%ana%' ...)\n * ```\n */\nexport function contains<Row = Record<string, unknown>>(\n columns: readonly string[],\n term: string,\n options?: ContainsOptions,\n): Condition {\n if (columns.length === 0) {\n throw new Error(\"contains() needs at least one column to search.\");\n }\n const tokens = tokenize(term);\n if (tokens.length === 0) return alwaysFalse();\n const perToken = tokens.map((token) =>\n or<Row>(\n ...columns.map((column) => ({ [column]: { iContains: token } }) as WhereInput<Row>),\n ),\n );\n if (options?.match === \"any\") return or<Row>(...perToken);\n return perToken.length === 1 ? (perToken[0] as Condition) : and<Row>(...perToken);\n}\n\n/** A condition matching no row, for a search whose term carried no tokens. */\nfunction alwaysFalse(): Condition {\n return conditionFromNode({\n kind: \"compare\",\n left: { kind: \"value\", value: 1 },\n op: \"eq\",\n right: { kind: \"value\", value: 0 },\n });\n}\n\n/**\n * PostgreSQL full-text search over one or more columns, with a portable fallback.\n *\n * On PostgreSQL this compiles to `to_tsvector(config, col || ' ' || col) @@\n * websearch_to_tsquery(config, term)`, so the search stems (`buying` matches\n * `buy`), drops stop words, and understands the quoting and `-exclusion` syntax\n * users already know from web search boxes.\n *\n * On any other database it compiles to {@link contains} instead — the same rows a\n * substring search would find, without stemming. That is a documented\n * degradation, not a silent one: a dev SQLite database keeps working, and the\n * difference is in ranking quality, not correctness.\n *\n * @param columns The columns to search, by property name.\n * @param term What the user typed.\n * @param options The text-search configuration.\n * @returns A condition for `where`.\n * @throws Error When no column is given.\n */\nexport function fullText<Row = Record<string, unknown>>(\n columns: readonly string[],\n term: string,\n options?: TextSearchOptions,\n): Condition {\n if (columns.length === 0) {\n throw new Error(\"fullText() needs at least one column to search.\");\n }\n return conditionFromNode({\n kind: \"fullText\",\n columns: [...columns],\n term,\n language: options?.language ?? \"english\",\n fallback: contains<Row>(columns, term).node,\n });\n}\n\n/**\n * The relevance score of a full-text match, for `orderBy`.\n *\n * On PostgreSQL this is `ts_rank(...)`, the number that makes \"best match first\"\n * mean something. Elsewhere it renders as a constant, so ordering by it is a\n * no-op and the query falls back to whatever other ordering is given — ranking is\n * the part that genuinely does not exist without a text-search engine.\n *\n * @param columns The same columns passed to {@link fullText}.\n * @param term The same term.\n * @param options The same configuration.\n * @returns An expression usable in `orderBy`.\n * @throws Error When no column is given.\n *\n * @example\n * ```ts\n * select(Post)\n * .where(fullText([\"title\", \"body\"], term, { language: \"portuguese\" }))\n * .orderBy(fullTextRank([\"title\", \"body\"], term, { language: \"portuguese\" }), \"desc\");\n * ```\n */\nexport function fullTextRank(\n columns: readonly string[],\n term: string,\n options?: TextSearchOptions,\n): Expression {\n if (columns.length === 0) {\n throw new Error(\"fullTextRank() needs at least one column to rank on.\");\n }\n return expressionFromNode({\n kind: \"rank\",\n columns: [...columns],\n term,\n language: options?.language ?? \"english\",\n });\n}\n","/**\n * tempest-db-js — Phase 4a: dialect SQL compilation.\n *\n * Turns the dialect-neutral AST (`SelectNode`, `InsertNode`, `UpdateNode`,\n * `DeleteNode` from Phases 1-2) into `{ sql, params }`. This is the ONLY place\n * SQL is produced — always parameterized (`?` for SQLite, `$1` for PostgreSQL),\n * never string interpolation, so it is injection-safe by construction.\n *\n * It does NOT touch a database — execution is Phase 4b (`session.execute`).\n */\n\nimport {\n type CastType,\n type CondNode,\n type ExprNode,\n isExpression,\n} from \"./conditions.js\";\nimport type { CteNode } from \"./cte.js\";\nimport type { TransactionOptions } from \"./engine.js\";\nimport { renderExcluded, renderPortableToken } from \"./expressions.js\";\nimport {\n type ColumnCodec,\n type NameMap,\n type SqlExpression,\n isSqlExpression,\n} from \"./index.js\";\nimport type { JoinNode } from \"./join.js\";\nimport type { DeleteNode, InsertNode, UpdateNode } from \"./mutations.js\";\nimport {\n type AggregateTerm,\n type LockClause,\n OPERATORS,\n type SelectNode,\n isSubquery,\n} from \"./query.js\";\nimport { escapeLike } from \"./search.js\";\nimport type { SetNode, SetOperator } from \"./setops.js\";\nimport type { Dialect } from \"./url.js\";\n\n/** A compiled, parameterized statement ready to hand to a driver. */\nexport interface CompiledQuery {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\n/** Any compilable AST node. */\nexport type QueryNode =\n | SelectNode\n | InsertNode\n | UpdateNode\n | DeleteNode\n | JoinNode\n | SetNode;\n\nconst OPERATOR_SET: ReadonlySet<string> = new Set(OPERATORS);\n\n/** Operators whose operand is a list or a tuple rather than a single value. */\nconst MULTI_VALUE_OPERATORS: ReadonlySet<string> = new Set([\"in\", \"notIn\", \"between\"]);\n\n/**\n * Convert an operator's operand into the stored representation.\n *\n * `isNull` takes a boolean that is not a column value, and `in`/`notIn`/`between`\n * take collections whose **elements** are the values — converting the collection\n * itself would corrupt them.\n *\n * @param op The operator.\n * @param operand The operand as written.\n * @param encode The column's conversion.\n * @returns The operand in stored representation.\n */\nfunction encodeOperand(\n op: string,\n operand: unknown,\n encode: (value: unknown) => unknown,\n): unknown {\n if (op === \"isNull\") return operand;\n if (MULTI_VALUE_OPERATORS.has(op)) {\n return Array.isArray(operand) ? operand.map(encode) : operand;\n }\n return encode(operand);\n}\n\n/**\n * Build the operand converter for a node's custom-typed columns.\n *\n * @param codecs The node's codecs, if any.\n * @returns A function converting a value for a column, identity when there are none.\n */\nfunction codecEncoder(\n codecs: Readonly<Record<string, ColumnCodec>> | undefined,\n): (key: string, value: unknown) => unknown {\n if (!codecs) return (_key, value) => value;\n return (key, value) => {\n const codec = codecs[key];\n return codec ? codec.toDb(value) : value;\n };\n}\n\n/** True when a where-value is an operator object rather than a bare value. */\nfunction isOperatorObject(value: unknown): value is Record<string, unknown> {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date ||\n value instanceof Uint8Array\n ) {\n return false;\n }\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((k) => OPERATOR_SET.has(k));\n}\n\n/**\n * Collects bound parameters and renders placeholders in dialect style. Exposed\n * because dialect subclasses receive it when overriding clause rendering.\n */\nexport class Params {\n readonly values: unknown[] = [];\n\n constructor(private readonly placeholder: (index: number) => string) {}\n\n bind(value: unknown): string {\n this.values.push(value);\n return this.placeholder(this.values.length);\n }\n}\n\n/**\n * A {@link Params} that inlines values instead of binding them.\n *\n * Schema SQL — a `CHECK` clause, a partial index's predicate — has nowhere to\n * bind a parameter, so the value has to be written into the statement. Quoting\n * follows the same rules a literal `DEFAULT` uses.\n */\nexport class LiteralParams extends Params {\n constructor() {\n super(() => \"\");\n }\n\n override bind(value: unknown): string {\n if (value === null || value === undefined) return \"NULL\";\n if (typeof value === \"boolean\") return value ? \"TRUE\" : \"FALSE\";\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (value instanceof Date) return `'${value.toISOString()}'`;\n return `'${String(value).replace(/'/g, \"''\")}'`;\n }\n}\n\n/**\n * The column list of an INSERT: the union of every row's keys, in first-seen\n * order.\n *\n * Taking only the first row's keys silently drops a value that a later row\n * supplies — the column is never named, so the value has nowhere to go. That was\n * unreachable while every row had to carry every key, and became reachable the\n * moment nullable columns turned optional on insert.\n *\n * @param rows The rows being inserted.\n * @returns Every column named by at least one row.\n */\nfunction insertColumns(rows: readonly Record<string, unknown>[]): string[] {\n const columns: string[] = [];\n const seen = new Set<string>();\n for (const row of rows) {\n for (const key of Object.keys(row)) {\n if (seen.has(key)) continue;\n seen.add(key);\n columns.push(key);\n }\n }\n return columns;\n}\n\n/** True when any value written by an INSERT is a SQL expression, not a literal. */\nfunction insertHasExpression(node: InsertNode): boolean {\n for (const row of node.values) {\n for (const value of Object.values(row)) {\n if (isSqlExpression(value)) return true;\n }\n }\n const update = node.onConflict?.update;\n if (update && update !== \"nothing\") {\n for (const value of Object.values(update)) {\n if (isSqlExpression(value)) return true;\n }\n }\n return false;\n}\n\n/**\n * Base SQL compiler shared by every dialect. Subclasses customize only what\n * actually differs between databases (placeholder syntax, `ILIKE` support).\n */\nexport abstract class BaseDialect {\n abstract readonly name: Dialect;\n\n /**\n * INSERT SQL templates keyed by structure (dialect|table|columns|rowCount|\n * returning). Shared across dialect instances — the key namespaces by dialect\n * name, and the placeholder text is dialect-specific but structure-determined.\n */\n private static readonly insertTemplates = new Map<string, string>();\n\n /** Quoted-identifier cache (see {@link quoteId}). Shared across dialects. */\n private static readonly quotedIds = new Map<string, string>();\n\n /** Render the n-th (1-based) placeholder. */\n protected abstract placeholder(index: number): string;\n\n /** Render a case-insensitive LIKE for the active dialect. */\n protected abstract ilike(column: string, param: string): string;\n\n /**\n * Render a case-insensitive LIKE whose pattern carries escaped wildcards.\n *\n * The `ESCAPE` clause is not decoration: PostgreSQL treats `\\` as the escape\n * character by default, **SQLite has none at all** until one is declared, so\n * without this the escaping done on our side would be meaningless there.\n *\n * @param column The rendered column.\n * @param param The bound pattern.\n * @returns The rendered comparison.\n */\n protected ilikeEscaped(column: string, param: string): string {\n return `${this.ilike(column, param)} ESCAPE '\\\\'`;\n }\n\n /**\n * Validate a subquery operand before it is rendered, for dialects that restrict\n * what an `IN (SELECT ...)` may contain. The default accepts everything.\n *\n * @param _node The subquery's AST.\n * @throws Error When the dialect cannot execute this subquery.\n */\n protected checkSubquery(_node: SelectNode): void {}\n\n /**\n * The SQL operator for an array containment/overlap test.\n *\n * Only PostgreSQL has native arrays; the other dialects throw rather than\n * emitting an operator that means something else there.\n *\n * @param op The array operator name.\n * @returns The SQL operator text.\n * @throws Error On a dialect without native array support.\n */\n protected arrayOperator(op: \"contains\" | \"containedBy\" | \"overlaps\"): string {\n throw new Error(\n `The \"${op}\" operator needs native array support, which ${this.name} does not have.`,\n );\n }\n\n /**\n * Quote an identifier (column/table) for the active dialect.\n *\n * Memoized: identifiers form a small, stable set (column/table names), but this\n * runs for every identifier on every compile. Caching the quoted form removes a\n * regex-replace + string allocation from the hot path. The standard double-quote\n * form is identical across both dialects, so one shared cache is correct.\n */\n protected quoteId(name: string): string {\n const cached = BaseDialect.quotedIds.get(name);\n if (cached !== undefined) return cached;\n const quoted = `\"${name.replace(/\"/g, '\"\"')}\"`;\n BaseDialect.quotedIds.set(name, quoted);\n return quoted;\n }\n\n /** Compile any node to `{ sql, params }`. */\n compile(node: QueryNode): CompiledQuery {\n const params = new Params((i) => this.placeholder(i));\n let sql: string;\n switch (node.kind) {\n case \"select\":\n sql = this.compileSelect(node, params);\n break;\n case \"insert\":\n sql = this.compileInsert(node, params);\n break;\n case \"update\":\n sql = this.compileUpdate(node, params);\n break;\n case \"delete\":\n sql = this.compileDelete(node, params);\n break;\n case \"join_select\":\n sql = this.compileJoin(node, params);\n break;\n case \"set_op\":\n sql = this.compileSetOp(node, params);\n break;\n }\n return { sql, params: params.values };\n }\n\n /**\n * Render a condition as schema SQL, with values inlined.\n *\n * Same compiler as a `WHERE`, different parameter strategy — so a `CHECK` and\n * the query language cannot drift apart in what they mean.\n *\n * @param node The condition.\n * @param params A {@link LiteralParams}.\n * @returns The rendered predicate.\n */\n renderConditionLiteral(node: CondNode, params: Params): string {\n return this.compileCondition(node, params, (key) => this.columnId(key, undefined));\n }\n\n /**\n * Render the `WITH` clause of a statement.\n *\n * `RECURSIVE` is a property of the **clause**, not of an entry: one recursive\n * entry makes the whole `WITH` recursive, which is what the SQL standard says\n * and what PostgreSQL and SQLite both implement.\n *\n * @param entries The `WITH` entries, if any.\n * @param params The parameter collector.\n * @returns The clause with a trailing space, or an empty string.\n */\n protected compileWith(entries: readonly CteNode[] | undefined, params: Params): string {\n if (!entries || entries.length === 0) return \"\";\n const recursive = entries.some((entry) => entry.recursive) ? \"RECURSIVE \" : \"\";\n const rendered = entries.map((entry) => {\n const body =\n entry.body.kind === \"set_op\"\n ? this.compileSetOp(entry.body, params)\n : this.compileSelect(entry.body, params);\n const hint =\n entry.materialized === null\n ? \"\"\n : entry.materialized\n ? \" MATERIALIZED\"\n : \" NOT MATERIALIZED\";\n return `${this.quoteId(entry.name)} AS${hint} (${body})`;\n });\n return `WITH ${recursive}${rendered.join(\", \")} `;\n }\n\n /**\n * The `EXPLAIN` prefix for this dialect.\n *\n * @param analyze Whether to measure by actually running the statement.\n * @returns The prefix to put in front of the statement.\n * @throws Error When the dialect cannot do what was asked.\n */\n explainPrefix(analyze: boolean): string {\n return analyze ? \"EXPLAIN (FORMAT JSON, ANALYZE)\" : \"EXPLAIN (FORMAT JSON)\";\n }\n\n /**\n * The SQL keyword for a set operation.\n *\n * @param op The operator.\n * @returns The keyword.\n * @throws Error On a dialect that does not implement it.\n */\n protected setOperator(op: SetOperator): string {\n switch (op) {\n case \"union\":\n return \"UNION\";\n case \"unionAll\":\n return \"UNION ALL\";\n case \"intersect\":\n return \"INTERSECT\";\n case \"except\":\n return \"EXCEPT\";\n }\n }\n\n /**\n * Compile a set operation.\n *\n * A branch carrying its own `ORDER BY`/`LIMIT` is parenthesized: without the\n * parentheses those clauses bind to the **combined** result, which is a\n * different query and a classic source of silently wrong output.\n *\n * @param node The set-operation node.\n * @param params The parameter collector.\n * @returns The rendered statement.\n */\n protected compileSetOp(node: SetNode, params: Params): string {\n const keyword = ` ${this.setOperator(node.op)} `;\n const branches = node.branches.map((branch) => {\n const sql =\n branch.kind === \"join_select\"\n ? this.compileJoin(branch, params)\n : this.compileSelect(branch, params);\n const scoped = branch.orderBy.length > 0 || branch.limit !== undefined;\n return scoped ? `(${sql})` : sql;\n });\n let sql = branches.join(keyword);\n if (node.orderBy.length > 0) {\n const terms = node.orderBy\n .map((t) => {\n const id =\n typeof t.column === \"string\"\n ? this.quoteId(t.column)\n : this.renderExpr(t.column, params, (k) => this.quoteId(k));\n return `${id} ${t.direction === \"desc\" ? \"DESC\" : \"ASC\"}`;\n })\n .join(\", \");\n sql += ` ORDER BY ${terms}`;\n }\n if (node.limit !== undefined) sql += ` LIMIT ${params.bind(node.limit)}`;\n if (node.offset !== undefined) sql += ` OFFSET ${params.bind(node.offset)}`;\n return sql;\n }\n\n /**\n * Render a qualified `alias.column` ref as `\"alias\".\"column\"`, translating the\n * property name to the real column name for that alias's model.\n *\n * @param ref The `alias.property` reference (a bare name is left unqualified).\n * @param names The node's per-alias name maps, if any source renames columns.\n * @returns The quoted, qualified identifier.\n */\n private qualify(\n ref: string,\n names?: Readonly<Record<string, NameMap>> | undefined,\n ): string {\n const dot = ref.indexOf(\".\");\n if (dot === -1) return this.quoteId(ref);\n const alias = ref.slice(0, dot);\n const prop = ref.slice(dot + 1);\n return `${this.quoteId(alias)}.${this.columnId(prop, names?.[alias])}`;\n }\n\n /**\n * Quote a column identifier, translating the model property name to the real\n * database column name first.\n *\n * `names` is `undefined` for a model that renames nothing — the overwhelmingly\n * common case — so this stays a single lookup plus the memoized quote.\n *\n * @param prop The model property name as written in the builder.\n * @param names The node's property → column map, if any.\n * @returns The quoted database identifier.\n */\n protected columnId(prop: string, names: NameMap | undefined): string {\n const mapped = names?.[prop];\n if (mapped !== undefined) return this.quoteId(mapped);\n const dot = prop.indexOf(\".\");\n // A dotted reference is a correlated one — `col(\"users.id\")` inside a\n // subquery points at the outer query's table, and quoting it whole would\n // produce the identifier \"users.id\" instead of \"users\".\"id\".\n if (dot > 0 && dot < prop.length - 1) {\n return `${this.quoteId(prop.slice(0, dot))}.${this.quoteId(prop.slice(dot + 1))}`;\n }\n return this.quoteId(prop);\n }\n\n /**\n * Render a {@link SqlExpression} inline, binding the parameters it carries.\n *\n * This is what keeps `set({ attempts: sql.raw(\"attempts + 1\") })` an expression\n * instead of a bound object: the fragment goes into the statement text, and\n * only a `sql.expr` template's interpolations become parameters.\n *\n * @param expr The branded expression.\n * @param params The parameter collector for the statement being compiled.\n * @returns The SQL text of the expression.\n */\n protected renderExpression(expr: SqlExpression, params: Params): string {\n const token = expr.expression;\n if (typeof token === \"string\") return renderPortableToken(token, this.name);\n if (\"raw\" in token) return token.raw;\n if (\"excluded\" in token) {\n return renderExcluded(this.quoteId(token.excluded), token.excluded, this.name);\n }\n const parts = token.parts;\n let sql = parts[0] ?? \"\";\n for (let i = 1; i < parts.length; i++) {\n sql += `${params.bind(expr.params[i - 1])}${parts[i]}`;\n }\n return sql;\n }\n\n /** Render one write value: a SQL expression inline, anything else as a parameter. */\n protected renderValue(value: unknown, params: Params): string {\n if (isSqlExpression(value)) return this.renderExpression(value, params);\n // A column reference written into a SET: `UPDATE ... SET tier = c.tier`.\n if (isExpression(value)) {\n return this.renderExpr(value.node, params, (k) => this.columnId(k, undefined));\n }\n return params.bind(value);\n }\n\n /**\n * The statements that open a transaction with the requested characteristics.\n *\n * Returned as a list because the dialects disagree on shape: PostgreSQL takes\n * everything on the `BEGIN` itself, MySQL needs a separate `SET TRANSACTION`\n * before it, and SQLite has no syntax at all.\n *\n * @param options The requested isolation level and read-only flag.\n * @returns The statements to run, in order.\n * @throws Error When the dialect cannot honor what was asked.\n */\n beginStatements(options?: TransactionOptions): string[] {\n const parts = [\"BEGIN\"];\n if (options?.isolation)\n parts.push(`ISOLATION LEVEL ${options.isolation.toUpperCase()}`);\n if (options?.readOnly) parts.push(\"READ ONLY\");\n return [parts.join(\" \")];\n }\n\n /**\n * Render a row-level locking clause (`FOR UPDATE ...`).\n *\n * Standard on PostgreSQL and MySQL 8.0+; SQLite overrides it to throw.\n *\n * @param lock The locking clause from the node.\n * @returns The SQL text, leading space included.\n */\n protected renderLock(lock: LockClause): string {\n const strength = lock.strength === \"update\" ? \"FOR UPDATE\" : \"FOR SHARE\";\n const of =\n lock.of.length > 0 ? ` OF ${lock.of.map((t) => this.quoteId(t)).join(\", \")}` : \"\";\n const wait =\n lock.wait === \"skipLocked\"\n ? \" SKIP LOCKED\"\n : lock.wait === \"noWait\"\n ? \" NOWAIT\"\n : \"\";\n return ` ${strength}${of}${wait}`;\n }\n\n // ---- statements -------------------------------------------------------\n\n /**\n * Compile a SELECT.\n *\n * Two alias rules differ between clauses and are handled here: PostgreSQL does\n * NOT accept a `SELECT` alias in `HAVING`, so an aggregate key is re-emitted as\n * its expression (`COUNT(*) > $1`), a form every dialect accepts; `ORDER BY`,\n * by contrast, accepts the output alias everywhere, so it is emitted as\n * written.\n *\n * @param node The select AST.\n * @param params The parameter collector.\n * @returns The SQL text.\n */\n private compileSelect(node: SelectNode, params: Params): string {\n const names = node.names;\n let cols: string;\n if (node.aggregates.length > 0) {\n // Grouped/aggregate query: SELECT group cols + `FN(col) AS \"alias\"`.\n const groupSel = node.groupBy.map((c) => this.columnId(c, names));\n const aggSel = node.aggregates.map((a) => {\n const inner = this.aggregateOperand(a, params, names);\n return `${a.fn.toUpperCase()}(${inner}) AS ${this.quoteId(a.alias)}`;\n });\n cols = [...groupSel, ...aggSel].join(\", \");\n } else {\n cols =\n node.columns === \"*\"\n ? \"*\"\n : node.columns.map((c) => this.columnId(c, names)).join(\", \");\n }\n const computed = Object.entries(node.computed ?? {}).map(\n ([alias, expr]) =>\n `${this.renderExpr(expr, params, (k) => this.columnId(k, names))} AS ${this.quoteId(alias)}`,\n );\n if (computed.length > 0) cols = [cols, ...computed].join(\", \");\n const from = node.alias\n ? `${this.quoteId(node.table)} AS ${this.quoteId(node.alias)}`\n : this.quoteId(node.table);\n let sql = `${this.compileWith(node.with, params)}SELECT ${node.distinct ? \"DISTINCT \" : \"\"}${cols} FROM ${from}`;\n\n const where = this.compileCondition(\n node.where,\n params,\n (k) => this.columnId(k, names),\n codecEncoder(node.codecs),\n );\n if (where) sql += ` WHERE ${where}`;\n\n if (node.groupBy.length > 0) {\n sql += ` GROUP BY ${node.groupBy.map((c) => this.columnId(c, names)).join(\", \")}`;\n }\n\n const aggByAlias = new Map(node.aggregates.map((a) => [a.alias, a]));\n\n if (node.having) {\n const having = this.compileCondition(node.having, params, (key) => {\n const agg = aggByAlias.get(key);\n if (!agg) return this.columnId(key, names);\n const inner = this.aggregateOperand(agg, params, names);\n return `${agg.fn.toUpperCase()}(${inner})`;\n });\n if (having) sql += ` HAVING ${having}`;\n }\n\n if (node.orderBy.length > 0) {\n const terms = node.orderBy\n .map((t) => {\n const id =\n typeof t.column !== \"string\"\n ? this.renderExpr(t.column, params, (k) => this.columnId(k, names))\n : aggByAlias.has(t.column)\n ? this.quoteId(t.column)\n : this.columnId(t.column, names);\n return `${id} ${t.direction === \"desc\" ? \"DESC\" : \"ASC\"}`;\n })\n .join(\", \");\n sql += ` ORDER BY ${terms}`;\n }\n if (node.limit !== undefined) sql += ` LIMIT ${params.bind(node.limit)}`;\n if (node.offset !== undefined) sql += ` OFFSET ${params.bind(node.offset)}`;\n if (node.lock) {\n if (node.distinct || node.groupBy.length > 0 || node.aggregates.length > 0) {\n throw new Error(\n \"FOR UPDATE / FOR SHARE cannot be combined with DISTINCT or an aggregate query — lock the underlying rows in a separate SELECT.\",\n );\n }\n sql += this.renderLock(node.lock);\n }\n return sql;\n }\n\n /**\n * Compile an INSERT.\n *\n * Takes the cached fast path only when the statement text is a pure function of\n * its structure. A SQL expression among the values, or a conflict predicate,\n * makes the text depend on the values themselves — those compile uncached, in\n * SQL order, so placeholder positions stay correct.\n */\n private compileInsert(node: InsertNode, params: Params): string {\n if (node.fromSelect) {\n const target = node.fromSelect.columns\n .map((c) => this.columnId(c, node.names))\n .join(\", \");\n const source = node.fromSelect.select as SelectNode | JoinNode | SetNode;\n const query =\n source.kind === \"join_select\"\n ? this.compileJoin(source, params)\n : source.kind === \"set_op\"\n ? this.compileSetOp(source, params)\n : this.compileSelect(source, params);\n const returning = this.compileReturning(node.returning, node.names);\n return `INSERT INTO ${this.quoteId(node.table)} (${target}) ${query}${returning}`;\n }\n const columns = insertColumns(node.values);\n const conflict = node.onConflict;\n const cacheable =\n conflict?.targetWhere === undefined &&\n conflict?.updateWhere === undefined &&\n !insertHasExpression(node);\n if (!cacheable) return this.compileInsertDirect(node, columns, params);\n\n // Bind every value in row-major, column order. The SQL text is independent of\n // the values (a null becomes a placeholder like any other), so it depends only\n // on the structure — which lets us cache the template below.\n for (const row of node.values) {\n for (const c of columns) params.bind((row as Record<string, unknown>)[c] ?? null);\n }\n // ON CONFLICT DO UPDATE binds its SET values after the row values, in key order.\n const conflictCols =\n conflict && conflict.update !== \"nothing\" ? Object.keys(conflict.update) : [];\n for (const c of conflictCols) {\n params.bind((conflict?.update as Record<string, unknown>)[c]);\n }\n return this.insertTemplate(node, columns, conflictCols, params);\n }\n\n /**\n * Compile an INSERT without the template cache, rendering clauses in statement\n * order so every parameter is bound at the position it appears.\n *\n * @param node The insert node.\n * @param columns The column keys shared by every row.\n * @param params The parameter collector.\n * @returns The SQL text.\n */\n private compileInsertDirect(\n node: InsertNode,\n columns: readonly string[],\n params: Params,\n ): string {\n const names = node.names;\n const colSql = columns.map((c) => this.columnId(c, names)).join(\", \");\n const rowsSql = node.values\n .map((row) => {\n const cells = columns.map((c) =>\n this.renderValue((row as Record<string, unknown>)[c] ?? null, params),\n );\n return `(${cells.join(\", \")})`;\n })\n .join(\", \");\n let sql = `INSERT INTO ${this.quoteId(node.table)} (${colSql}) VALUES ${rowsSql}`;\n if (node.onConflict) {\n const update = node.onConflict.update;\n const conflictCols = update === \"nothing\" ? [] : Object.keys(update);\n let cursor = 0;\n sql += this.renderConflict(\n node.onConflict,\n conflictCols,\n () => {\n const key = conflictCols[cursor++] as string;\n return this.renderValue((update as Record<string, unknown>)[key], params);\n },\n names,\n params,\n );\n }\n sql += this.compileReturning(node.returning, names);\n return sql;\n }\n\n /**\n * The INSERT SQL template for a given structure, cached across calls.\n *\n * The text depends only on (dialect, table, columns, row count, returning,\n * conflict shape) — never on the bound values — and placeholder positions are\n * deterministic from the counts (a fresh statement always starts binding at 1).\n * So a per-row insert loop compiles the string once and reuses it every row.\n */\n private insertTemplate(\n node: InsertNode,\n columns: readonly string[],\n conflictCols: readonly string[],\n params: Params,\n ): string {\n const returningKey =\n node.returning === null\n ? \"\"\n : node.returning === \"*\"\n ? \"*\"\n : node.returning.join(\",\");\n const conflictKey = node.onConflict\n ? `${node.onConflict.target.join(\",\")}>${node.onConflict.update === \"nothing\" ? \"nothing\" : conflictCols.join(\",\")}`\n : \"\";\n const key = `${this.name}|${node.table}|${columns.join(\",\")}|${node.values.length}|${returningKey}|${conflictKey}`;\n const cached = BaseDialect.insertTemplates.get(key);\n if (cached !== undefined) return cached;\n\n const names = node.names;\n const colSql = columns.map((c) => this.columnId(c, names)).join(\", \");\n let position = 0;\n const rowsSql = node.values\n .map(() => `(${columns.map(() => this.placeholder(++position)).join(\", \")})`)\n .join(\", \");\n let sql = `INSERT INTO ${this.quoteId(node.table)} (${colSql}) VALUES ${rowsSql}`;\n if (node.onConflict) {\n sql += this.renderConflict(\n node.onConflict,\n conflictCols,\n () => this.placeholder(++position),\n names,\n params,\n );\n }\n sql += this.compileReturning(node.returning, names);\n BaseDialect.insertTemplates.set(key, sql);\n return sql;\n }\n\n /**\n * Render the conflict-handling clause. Standard SQL (SQLite/PostgreSQL) uses\n * `ON CONFLICT (...) [WHERE predicate] DO NOTHING | DO UPDATE SET ... [WHERE ...]`;\n * MySQL overrides this.\n *\n * The index predicate is rendered before the `DO UPDATE` assignments because\n * that is where it sits in the statement, so its parameters bind first.\n *\n * @param onConflict The conflict clause from the node.\n * @param conflictCols The columns to overwrite on `DO UPDATE` (empty for nothing).\n * @param nextValue Yields the SQL for the next `DO UPDATE` assignment value.\n * @param names The node's property → column map, if any.\n * @param params The parameter collector, for the predicates.\n * @returns The SQL text, leading space included.\n */\n protected renderConflict(\n onConflict: NonNullable<InsertNode[\"onConflict\"]>,\n conflictCols: readonly string[],\n nextValue: () => string,\n names: NameMap | undefined,\n params: Params,\n ): string {\n const idFor = (key: string): string => this.columnId(key, names);\n const target = onConflict.target.map(idFor).join(\", \");\n const indexWhere = this.compileCondition(onConflict.targetWhere, params, idFor);\n const targetSql = indexWhere ? `(${target}) WHERE ${indexWhere}` : `(${target})`;\n if (onConflict.update === \"nothing\") return ` ON CONFLICT ${targetSql} DO NOTHING`;\n const assignments = conflictCols\n .map((c) => `${idFor(c)} = ${nextValue()}`)\n .join(\", \");\n let sql = ` ON CONFLICT ${targetSql} DO UPDATE SET ${assignments}`;\n const updateWhere = this.compileCondition(onConflict.updateWhere, params, idFor);\n if (updateWhere) sql += ` WHERE ${updateWhere}`;\n return sql;\n }\n\n private compileUpdate(node: UpdateNode, params: Params): string {\n const names = node.names;\n const sets = Object.entries(node.set)\n .map(\n ([col, value]) =>\n `${this.columnId(col, names)} = ${this.renderValue(value, params)}`,\n )\n .join(\", \");\n let sql = `UPDATE ${this.quoteId(node.table)} SET ${sets}`;\n sql += this.compileExtraSources(\"FROM\", node.from);\n const where = this.compileCondition(\n node.where,\n params,\n (k) => this.columnId(k, names),\n codecEncoder(node.codecs),\n );\n if (where) sql += ` WHERE ${where}`;\n sql += this.compileReturning(node.returning, names);\n return sql;\n }\n\n private compileDelete(node: DeleteNode, params: Params): string {\n const names = node.names;\n let sql = `DELETE FROM ${this.quoteId(node.table)}`;\n sql += this.compileExtraSources(\"USING\", node.using);\n const where = this.compileCondition(\n node.where,\n params,\n (k) => this.columnId(k, names),\n codecEncoder(node.codecs),\n );\n if (where) sql += ` WHERE ${where}`;\n sql += this.compileReturning(node.returning, names);\n return sql;\n }\n\n protected compileJoin(node: JoinNode, params: Params): string {\n const names = node.names;\n const cols = node.selections\n .map((s) => {\n const ref = `${s.alias}.${s.column}`;\n // `pick` projects one source flat, so the labels are the bare column\n // names a single-table shape needs, not the \"alias.column\" a composite\n // row is split by.\n const label = node.pick ? s.column : ref;\n return `${this.qualify(ref, names)} AS ${this.quoteId(label)}`;\n })\n .join(\", \");\n let sql = `${this.compileWith(node.with, params)}SELECT ${cols} FROM ${this.quoteId(node.base.table)} AS ${this.quoteId(node.base.alias)}`;\n for (const j of node.joins) {\n const kw = j.kind === \"left\" ? \"LEFT JOIN\" : \"INNER JOIN\";\n const on = j.on\n .map(([l, r]) => `${this.qualify(l, names)} = ${this.qualify(r, names)}`)\n .join(\" AND \");\n sql += ` ${kw} ${this.quoteId(j.table)} AS ${this.quoteId(j.alias)} ON ${on}`;\n }\n const where = this.compileCondition(node.where, params, (k) =>\n this.qualify(k, names),\n );\n if (where) sql += ` WHERE ${where}`;\n if (node.orderBy.length > 0) {\n const terms = node.orderBy\n .map(\n (t) =>\n `${this.qualify(t.ref, names)} ${t.direction === \"desc\" ? \"DESC\" : \"ASC\"}`,\n )\n .join(\", \");\n sql += ` ORDER BY ${terms}`;\n }\n if (node.limit !== undefined) sql += ` LIMIT ${params.bind(node.limit)}`;\n if (node.offset !== undefined) sql += ` OFFSET ${params.bind(node.offset)}`;\n return sql;\n }\n\n // ---- clauses ----------------------------------------------------------\n\n /**\n * Render the extra sources of an `UPDATE ... FROM` / `DELETE ... USING`.\n *\n * The dialects that do not have the clause override this and throw: emitting it\n * anyway would produce a statement the server rejects, and quietly dropping it\n * would change which rows are written.\n *\n * @param keyword `FROM` or `USING`.\n * @param sources The extra tables, if any.\n * @returns The clause with a leading space, or an empty string.\n */\n protected compileExtraSources(\n keyword: \"FROM\" | \"USING\",\n sources: readonly { readonly table: string; readonly alias: string }[] | undefined,\n ): string {\n if (!sources || sources.length === 0) return \"\";\n const list = sources\n .map((s) => `${this.quoteId(s.table)} AS ${this.quoteId(s.alias)}`)\n .join(\", \");\n return ` ${keyword} ${list}`;\n }\n\n protected compileReturning(\n returning: readonly string[] | \"*\" | null,\n names?: NameMap | undefined,\n ): string {\n if (returning === null) return \"\";\n if (returning === \"*\") return \" RETURNING *\";\n return ` RETURNING ${returning.map((c) => this.columnId(c, names)).join(\", \")}`;\n }\n\n /**\n * Compile a condition tree (fields / and / or / not) to SQL. `idFor` renders a\n * key to a quoted identifier — `quoteId` for single-table, `qualify` for joins —\n * so select/update/delete/join all share this one compiler.\n */\n protected compileCondition(\n node: CondNode | undefined,\n params: Params,\n idFor: (key: string) => string,\n encode: (key: string, value: unknown) => unknown = (_key, value) => value,\n ): string {\n if (!node) return \"\";\n switch (node.kind) {\n case \"fields\": {\n const conditions: string[] = [];\n for (const [key, value] of Object.entries(node.fields)) {\n const id = idFor(key);\n if (isExpression(value)) {\n // `where({ userId: col(\"users.id\") })` — the value is another column,\n // not a parameter. Binding it would compare the column against the\n // string \"users.id\".\n conditions.push(\n this.compileExprOperator(\n id,\n \"eq\",\n this.renderExpr(value.node, params, idFor),\n ),\n );\n } else if (isOperatorObject(value)) {\n for (const [op, operand] of Object.entries(value)) {\n conditions.push(\n isExpression(operand)\n ? this.compileExprOperator(\n id,\n op,\n this.renderExpr(operand.node, params, idFor),\n )\n : this.compileOperator(\n id,\n op,\n encodeOperand(op, operand, (v) => encode(key, v)),\n params,\n ),\n );\n }\n } else {\n // bare value → equality (null → IS NULL)\n const operand = encode(key, value);\n conditions.push(\n operand === null ? `${id} IS NULL` : `${id} = ${params.bind(operand)}`,\n );\n }\n }\n return conditions.join(\" AND \");\n }\n case \"and\":\n case \"or\": {\n const parts = node.parts\n .map((p) => this.compileCondition(p, params, idFor, encode))\n .filter((s) => s.length > 0);\n if (parts.length === 0) return \"\";\n const sep = node.kind === \"and\" ? \" AND \" : \" OR \";\n return parts.map((p) => `(${p})`).join(sep);\n }\n case \"not\": {\n const inner = this.compileCondition(node.part, params, idFor, encode);\n return inner ? `NOT (${inner})` : \"\";\n }\n case \"exists\": {\n const select = node.select as SelectNode;\n this.checkSubquery(select);\n const keyword = node.negate ? \"NOT EXISTS\" : \"EXISTS\";\n return `${keyword} (${this.compileSelect(select, params)})`;\n }\n case \"fullText\":\n return this.compileFullText(node, params, idFor);\n case \"compare\": {\n const left = this.renderExpr(node.left, params, idFor);\n if (node.right.kind === \"value\") {\n return this.compileOperator(left, node.op, node.right.value, params);\n }\n return this.compileExprOperator(\n left,\n node.op,\n this.renderExpr(node.right, params, idFor),\n );\n }\n }\n }\n\n /**\n * Compile a full-text condition.\n *\n * PostgreSQL gets the real thing (`@@ websearch_to_tsquery`); the dialects with\n * no text-search engine override this and compile the node's prebuilt substring\n * fallback instead, so the query still returns the right rows.\n *\n * @param node The full-text condition node.\n * @param params The parameter collector.\n * @param idFor Column-name resolver.\n * @returns The rendered condition.\n */\n protected compileFullText(\n node: Extract<CondNode, { kind: \"fullText\" }>,\n params: Params,\n idFor: (key: string) => string,\n ): string {\n const config = params.bind(node.language);\n return `${this.tsVector(node.columns, config, idFor)} @@ websearch_to_tsquery(${config}::regconfig, ${params.bind(node.term)})`;\n }\n\n /**\n * Render one side of a comparison.\n *\n * A column reference goes through `idFor`, so an explicit `.name()` mapping and\n * join qualification apply here exactly as they do in the object form of\n * `where` — `col()` is not a way around them. Only a `value` node binds.\n *\n * @param node The expression AST.\n * @param params The parameter collector.\n * @param idFor The identifier resolver for the enclosing statement.\n * @returns The SQL text of the expression.\n */\n /**\n * Render what an aggregate is applied to: `*`, a column, or an expression.\n *\n * An expression operand is what makes a conditional aggregate\n * (`SUM(CASE WHEN ... END)`) expressible — one pass over the table instead of a\n * query per bucket.\n *\n * @param agg The aggregate term.\n * @param params The parameter collector.\n * @param names The node's column-name map.\n * @returns The rendered operand.\n */\n private aggregateOperand(\n agg: AggregateTerm,\n params: Params,\n names: NameMap | undefined,\n ): string {\n if (agg.column === \"*\") return \"*\";\n if (typeof agg.column === \"string\") return this.columnId(agg.column, names);\n return this.renderExpr(agg.column, params, (k) => this.columnId(k, names));\n }\n\n private renderExpr(\n node: ExprNode,\n params: Params,\n idFor: (key: string) => string,\n ): string {\n switch (node.kind) {\n case \"column\":\n return idFor(node.name);\n case \"value\":\n return params.bind(node.value);\n case \"fn\": {\n const args = node.args.map((a) => this.renderExpr(a, params, idFor)).join(\", \");\n return `${node.name}(${args})`;\n }\n case \"case\": {\n const branches = node.branches\n .map(\n (b) =>\n `WHEN ${this.compileCondition(b.when, params, idFor)} THEN ${this.renderExpr(b.result, params, idFor)}`,\n )\n .join(\" \");\n const fallback =\n node.fallback === null\n ? \"\"\n : ` ELSE ${this.renderExpr(node.fallback, params, idFor)}`;\n return `CASE ${branches}${fallback} END`;\n }\n case \"cast\":\n return `CAST(${this.renderExpr(node.operand, params, idFor)} AS ${this.castTypeName(node.to)})`;\n case \"scalar\": {\n const select = node.select as SelectNode;\n this.checkSubquery(select);\n return `(${this.compileSelect(select, params)})`;\n }\n case \"rank\":\n return this.renderRank(node.columns, node.term, node.language, params, idFor);\n case \"star\":\n return \"*\";\n case \"window\": {\n const call = this.renderExpr(node.fn, params, idFor);\n const parts: string[] = [];\n if (node.partitionBy.length > 0) {\n parts.push(`PARTITION BY ${node.partitionBy.map(idFor).join(\", \")}`);\n }\n if (node.orderBy.length > 0) {\n const terms = node.orderBy\n .map((t) => `${idFor(t.column)} ${t.direction === \"desc\" ? \"DESC\" : \"ASC\"}`)\n .join(\", \");\n parts.push(`ORDER BY ${terms}`);\n }\n if (node.frame) parts.push(node.frame);\n return `${call} OVER (${parts.join(\" \")})`;\n }\n }\n }\n\n /**\n * Render a full-text relevance score.\n *\n * PostgreSQL has `ts_rank`; the others have nothing equivalent, and they\n * override this to a constant so that ordering by it is a no-op rather than a\n * compile error — the fallback keeps returning the right rows, only unranked.\n *\n * @param columns The columns making up the document.\n * @param term The search term.\n * @param language The text-search configuration.\n * @param params The parameter collector.\n * @param idFor Column-name resolver.\n * @returns The rendered score expression.\n */\n protected renderRank(\n columns: readonly string[],\n term: string,\n language: string,\n params: Params,\n idFor: (key: string) => string,\n ): string {\n const config = params.bind(language);\n return `ts_rank(${this.tsVector(columns, config, idFor)}, websearch_to_tsquery(${config}::regconfig, ${params.bind(term)}))`;\n }\n\n /**\n * Build the `to_tsvector(...)` document out of the searched columns.\n *\n * `coalesce(col, '')` matters: in SQL a `NULL` anywhere in a concatenation makes\n * the whole document `NULL`, so one empty column would silently exclude the row.\n *\n * @param columns The columns making up the document.\n * @param config The already-bound placeholder for the text-search config.\n * @param idFor Column-name resolver.\n * @returns The rendered `to_tsvector(...)` call.\n */\n protected tsVector(\n columns: readonly string[],\n config: string,\n idFor: (key: string) => string,\n ): string {\n const document = columns.map((c) => `coalesce(${idFor(c)}, '')`).join(\" || ' ' || \");\n return `to_tsvector(${config}::regconfig, ${document})`;\n }\n\n /**\n * The SQL type name this dialect accepts in a `CAST`.\n *\n * The base mapping is the standard one PostgreSQL takes; SQLite and MySQL\n * override it, because the names genuinely differ (MySQL's `CAST(x AS SIGNED)`\n * is not `INTEGER`, and SQLite only has five storage classes to aim at).\n *\n * @param to The portable cast target.\n * @returns The dialect's own type name.\n */\n protected castTypeName(to: CastType): string {\n switch (to) {\n case \"integer\":\n return \"INTEGER\";\n case \"bigint\":\n return \"BIGINT\";\n case \"real\":\n return \"DOUBLE PRECISION\";\n case \"numeric\":\n return \"NUMERIC\";\n case \"text\":\n return \"TEXT\";\n case \"boolean\":\n return \"BOOLEAN\";\n case \"date\":\n return \"DATE\";\n case \"datetime\":\n case \"timestamp\":\n return \"TIMESTAMP\";\n case \"uuid\":\n return \"UUID\";\n case \"json\":\n return \"JSON\";\n case \"jsonb\":\n return \"JSONB\";\n case \"blob\":\n return \"BYTEA\";\n }\n }\n\n /**\n * Compile a comparison whose right-hand side is another expression rather than\n * a bound value (`total > paid`, `lower(a) = lower(b)`).\n *\n * The list and null operators are excluded: `IN`, `BETWEEN` and `IS NULL` take\n * a value operand, and accepting an expression there would silently compile to\n * something else.\n *\n * @param left The rendered left-hand side.\n * @param op The operator name.\n * @param right The rendered right-hand side.\n * @returns The SQL text of the predicate.\n * @throws Error When the operator needs a value operand.\n */\n private compileExprOperator(left: string, op: string, right: string): string {\n switch (op) {\n case \"eq\":\n return `${left} = ${right}`;\n case \"ne\":\n return `${left} <> ${right}`;\n case \"gt\":\n return `${left} > ${right}`;\n case \"gte\":\n return `${left} >= ${right}`;\n case \"lt\":\n return `${left} < ${right}`;\n case \"lte\":\n return `${left} <= ${right}`;\n case \"like\":\n return `${left} LIKE ${right}`;\n case \"ilike\":\n return this.ilike(left, right);\n case \"ieq\":\n return `lower(${left}) = lower(${right})`;\n case \"iContains\":\n throw new Error(\n 'The \"iContains\" operator matches a literal, so it takes a value, not an expression.',\n );\n case \"contains\":\n case \"containedBy\":\n case \"overlaps\":\n return `${left} ${this.arrayOperator(op)} ${right}`;\n default:\n throw new Error(`The \"${op}\" operator takes a value operand, not an expression.`);\n }\n }\n\n private compileOperator(\n id: string,\n op: string,\n operand: unknown,\n params: Params,\n ): string {\n switch (op) {\n case \"eq\":\n return operand === null ? `${id} IS NULL` : `${id} = ${params.bind(operand)}`;\n case \"ne\":\n return operand === null\n ? `${id} IS NOT NULL`\n : `${id} <> ${params.bind(operand)}`;\n case \"gt\":\n return `${id} > ${params.bind(operand)}`;\n case \"gte\":\n return `${id} >= ${params.bind(operand)}`;\n case \"lt\":\n return `${id} < ${params.bind(operand)}`;\n case \"lte\":\n return `${id} <= ${params.bind(operand)}`;\n case \"like\":\n return `${id} LIKE ${params.bind(operand)}`;\n case \"ilike\":\n return this.ilike(id, params.bind(operand));\n case \"ieq\":\n return operand === null\n ? `${id} IS NULL`\n : `lower(${id}) = lower(${params.bind(operand)})`;\n case \"iContains\":\n return this.ilikeEscaped(id, params.bind(`%${escapeLike(String(operand))}%`));\n case \"contains\":\n return `${id} ${this.arrayOperator(\"contains\")} ${params.bind(operand)}`;\n case \"containedBy\":\n return `${id} ${this.arrayOperator(\"containedBy\")} ${params.bind(operand)}`;\n case \"overlaps\":\n return `${id} ${this.arrayOperator(\"overlaps\")} ${params.bind(operand)}`;\n case \"in\":\n return this.compileIn(id, operand, params, false);\n case \"notIn\":\n return this.compileIn(id, operand, params, true);\n case \"between\": {\n const [lo, hi] = operand as readonly [unknown, unknown];\n return `${id} BETWEEN ${params.bind(lo)} AND ${params.bind(hi)}`;\n }\n case \"isNull\":\n return operand ? `${id} IS NULL` : `${id} IS NOT NULL`;\n default:\n throw new Error(`Unknown operator ${JSON.stringify(op)}`);\n }\n }\n\n /**\n * Compile `IN` / `NOT IN`, whose operand is either a value list or a\n * single-column subquery.\n *\n * The subquery is rendered at the position it appears in the outer statement\n * and shares the same parameter collector, so its own placeholders land in the\n * right order — and it keeps its own `names` map, since the inner model may use\n * a different naming convention than the outer one.\n *\n * @param id The quoted column identifier being tested.\n * @param operand A list of values, or a {@link Subquery}.\n * @param params The parameter collector for the statement being compiled.\n * @param negate True for `NOT IN`.\n * @returns The SQL text of the predicate.\n */\n private compileIn(\n id: string,\n operand: unknown,\n params: Params,\n negate: boolean,\n ): string {\n const keyword = negate ? \"NOT IN\" : \"IN\";\n if (isSubquery(operand)) {\n this.checkSubquery(operand.node);\n return `${id} ${keyword} (${this.compileSelect(operand.node, params)})`;\n }\n const values = operand as readonly unknown[];\n if (values.length === 0) {\n // empty IN matches nothing; empty NOT IN matches everything\n return negate ? \"1 = 1\" : \"1 = 0\";\n }\n const list = values.map((v) => params.bind(v)).join(\", \");\n return `${id} ${keyword} (${list})`;\n }\n}\n\n/** SQLite dialect: `?` placeholders; `ILIKE` falls back to `LIKE` (ASCII-insensitive). */\nexport class SqliteDialect extends BaseDialect {\n readonly name = \"sqlite\" as const;\n\n /**\n * SQLite explains with `EXPLAIN QUERY PLAN`, and has no `ANALYZE` — the plain\n * `EXPLAIN` there dumps bytecode, which answers a different question.\n */\n override explainPrefix(analyze: boolean): string {\n if (analyze) {\n throw new Error(\n \"SQLite has no EXPLAIN ANALYZE; use EXPLAIN QUERY PLAN (analyze: false).\",\n );\n }\n return \"EXPLAIN QUERY PLAN\";\n }\n\n /**\n * SQLite has `UPDATE ... FROM` (3.33+) but no `DELETE ... USING`.\n *\n * The portable shape there is a subquery — `where({ id: { in: … } })` — so this\n * throws and says so, rather than emitting a clause SQLite does not parse.\n */\n protected override compileExtraSources(\n keyword: \"FROM\" | \"USING\",\n sources: readonly { readonly table: string; readonly alias: string }[] | undefined,\n ): string {\n if (keyword === \"USING\" && sources && sources.length > 0) {\n throw new Error(\n 'SQLite has no DELETE ... USING; filter with a subquery instead: where({ id: { in: select(Other, [\"id\"]).asSubquery(\"id\") } }).',\n );\n }\n return super.compileExtraSources(keyword, sources);\n }\n\n /**\n * SQLite has no text-search engine, so the prebuilt substring fallback is\n * compiled instead. The rows are right; the ranking is what is missing.\n */\n protected override compileFullText(\n node: Extract<CondNode, { kind: \"fullText\" }>,\n params: Params,\n idFor: (key: string) => string,\n ): string {\n return this.compileCondition(node.fallback, params, idFor);\n }\n\n /** No text-search engine means no score: a constant, so ordering by it is inert. */\n protected override renderRank(): string {\n return \"0\";\n }\n\n /**\n * SQLite has five storage classes, so most targets collapse onto `TEXT` or\n * `INTEGER`. Naming a type it does not know would not fail — SQLite applies the\n * closest affinity — but it would make the cast mean something different here\n * than on the other databases, which is what this mapping avoids.\n */\n protected override castTypeName(to: CastType): string {\n switch (to) {\n case \"integer\":\n case \"bigint\":\n case \"boolean\":\n return \"INTEGER\";\n case \"real\":\n return \"REAL\";\n case \"numeric\":\n return \"NUMERIC\";\n case \"blob\":\n return \"BLOB\";\n default:\n return \"TEXT\";\n }\n }\n\n protected placeholder(): string {\n return \"?\";\n }\n\n protected ilike(column: string, param: string): string {\n return `${column} LIKE ${param}`;\n }\n\n /**\n * SQLite runs one writer at a time, so its only isolation level **is**\n * serializable — there is no syntax to ask for another, and no weaker level to\n * fall back to. Asking for one is an error rather than a silent no-op, since a\n * caller who wrote `repeatable read` was reasoning about a guarantee.\n *\n * `readOnly` likewise has no per-transaction form here (`PRAGMA query_only` is\n * per connection), so it is refused instead of quietly ignored.\n */\n override beginStatements(options?: TransactionOptions): string[] {\n if (options?.isolation && options.isolation !== \"serializable\") {\n throw new Error(\n `SQLite only implements the \"serializable\" isolation level; ${JSON.stringify(options.isolation)} has no equivalent here.`,\n );\n }\n if (options?.readOnly) {\n throw new Error(\n \"SQLite has no read-only transaction; open the engine with { sqlite: { ... } } on a read-only connection instead.\",\n );\n }\n return [\"BEGIN\"];\n }\n\n /**\n * SQLite has no row-level locking, so a lock request is an error rather than a\n * silently unlocked `SELECT` — a lock that does not exist only shows up as\n * duplicated work under production concurrency.\n */\n protected override renderLock(): string {\n throw new Error(\n \"SQLite has no row-level locking — FOR UPDATE / FOR SHARE is unsupported. Serialize the claim inside a transaction instead.\",\n );\n }\n}\n\n/** PostgreSQL dialect: `$1` placeholders; native `ILIKE`; native array operators. */\nexport class PostgresDialect extends BaseDialect {\n readonly name = \"postgresql\" as const;\n\n protected placeholder(index: number): string {\n return `$${index}`;\n }\n\n protected ilike(column: string, param: string): string {\n return `${column} ILIKE ${param}`;\n }\n\n protected override arrayOperator(op: \"contains\" | \"containedBy\" | \"overlaps\"): string {\n if (op === \"contains\") return \"@>\";\n if (op === \"containedBy\") return \"<@\";\n return \"&&\";\n }\n}\n\n/** Backtick-quoted identifier cache for MySQL (its quoting differs from the base). */\nconst mysqlQuotedIds = new Map<string, string>();\n\n/**\n * MySQL dialect: `?` placeholders, backtick identifiers, `ON DUPLICATE KEY\n * UPDATE` for upsert, and case-insensitive `LIKE` (default collation). MySQL has\n * no `RETURNING`, so requesting it throws.\n */\nexport class MysqlDialect extends BaseDialect {\n readonly name = \"mysql\" as const;\n\n protected placeholder(): string {\n return \"?\";\n }\n\n protected ilike(column: string, param: string): string {\n return `${column} LIKE ${param}`; // MySQL LIKE is case-insensitive by default\n }\n\n /** MySQL's `EXPLAIN FORMAT=JSON` spells the option differently. */\n override explainPrefix(analyze: boolean): string {\n return analyze ? \"EXPLAIN ANALYZE\" : \"EXPLAIN FORMAT=JSON\";\n }\n\n /**\n * MySQL only gained `INTERSECT`/`EXCEPT` in 8.0.31, and this project does not\n * invest in MySQL beyond what already works — so they are refused here rather\n * than emitted against a server that may reject them.\n */\n protected override setOperator(op: SetOperator): string {\n if (op === \"intersect\" || op === \"except\") {\n throw new Error(\n `MySQL support for ${op.toUpperCase()} is out of scope for tempest-db-js; express it with a join or NOT EXISTS.`,\n );\n }\n return super.setOperator(op);\n }\n\n /**\n * MySQL writes multi-table updates as `UPDATE a JOIN b`, and has no\n * `DELETE ... USING` in this shape. Both are out of the project's active scope,\n * so they are refused rather than emitted against a server that rejects them.\n */\n protected override compileExtraSources(\n keyword: \"FROM\" | \"USING\",\n sources: readonly { readonly table: string; readonly alias: string }[] | undefined,\n ): string {\n if (sources && sources.length > 0) {\n throw new Error(\n `MySQL does not take ${keyword} on a write in this form; it spells multi-table writes as UPDATE a JOIN b, which is out of scope for tempest-db-js.`,\n );\n }\n return \"\";\n }\n\n /**\n * MySQL's full-text search needs a `FULLTEXT` index and different syntax, and it\n * is outside this project's active scope — the substring fallback is compiled,\n * like on SQLite.\n */\n protected override compileFullText(\n node: Extract<CondNode, { kind: \"fullText\" }>,\n params: Params,\n idFor: (key: string) => string,\n ): string {\n return this.compileCondition(node.fallback, params, idFor);\n }\n\n /** No `ts_rank` equivalent in scope: a constant, so ordering by it is inert. */\n protected override renderRank(): string {\n return \"0\";\n }\n\n /**\n * MySQL sets the level with a statement **before** the transaction opens, and\n * spells the read-only flag on `START TRANSACTION` rather than on `BEGIN`.\n */\n override beginStatements(options?: TransactionOptions): string[] {\n const statements: string[] = [];\n if (options?.isolation) {\n statements.push(\n `SET TRANSACTION ISOLATION LEVEL ${options.isolation.toUpperCase()}`,\n );\n }\n statements.push(options?.readOnly ? \"START TRANSACTION READ ONLY\" : \"BEGIN\");\n return statements;\n }\n\n /**\n * MySQL's `CAST` takes its own vocabulary — `SIGNED`, not `INTEGER`; `CHAR`,\n * not `TEXT` — and rejects the standard names outright.\n */\n protected override castTypeName(to: CastType): string {\n switch (to) {\n case \"integer\":\n case \"bigint\":\n case \"boolean\":\n return \"SIGNED\";\n case \"real\":\n case \"numeric\":\n return \"DECIMAL\";\n case \"text\":\n case \"uuid\":\n return \"CHAR\";\n case \"date\":\n return \"DATE\";\n case \"datetime\":\n case \"timestamp\":\n return \"DATETIME\";\n case \"json\":\n case \"jsonb\":\n return \"JSON\";\n case \"blob\":\n return \"BINARY\";\n }\n }\n\n protected override quoteId(name: string): string {\n const cached = mysqlQuotedIds.get(name);\n if (cached !== undefined) return cached;\n const quoted = `\\`${name.replace(/`/g, \"``\")}\\``;\n mysqlQuotedIds.set(name, quoted);\n return quoted;\n }\n\n /**\n * MySQL rejects `LIMIT` inside an `IN` subquery with\n * `ER_NOT_SUPPORTED_YET: This version of MySQL doesn't yet support\n * 'LIMIT & IN/ALL/ANY/SOME subquery'`. Failing at compile time names the fix\n * instead of surfacing that error from the driver at runtime.\n */\n protected override checkSubquery(node: SelectNode): void {\n if (node.limit !== undefined || node.offset !== undefined) {\n throw new Error(\n \"MySQL does not support LIMIT/OFFSET inside an IN subquery. Select the ids first and pass them as a list, or wrap the subquery in a derived table.\",\n );\n }\n }\n\n protected override renderConflict(\n onConflict: NonNullable<InsertNode[\"onConflict\"]>,\n conflictCols: readonly string[],\n nextValue: () => string,\n names: NameMap | undefined,\n ): string {\n if (onConflict.targetWhere || onConflict.updateWhere) {\n throw new Error(\n \"MySQL's ON DUPLICATE KEY UPDATE has no conflict-target predicate — a partial unique index is PostgreSQL/SQLite only.\",\n );\n }\n if (onConflict.update === \"nothing\") {\n // MySQL has no DO NOTHING; a no-op self-assignment on a target column is\n // the idiomatic equivalent (keeps the existing row untouched).\n const col = this.columnId(onConflict.target[0] ?? \"id\", names);\n return ` ON DUPLICATE KEY UPDATE ${col} = ${col}`;\n }\n const assignments = conflictCols\n .map((c) => `${this.columnId(c, names)} = ${nextValue()}`)\n .join(\", \");\n return ` ON DUPLICATE KEY UPDATE ${assignments}`;\n }\n\n /**\n * MySQL has no `RETURNING`, so it cannot be compiled into a statement.\n *\n * `session.execute()` still honors `.returning()` on a **single-row INSERT** by\n * running the insert and reading the row back by key on the same connection —\n * that is execution, not compilation, so it never reaches here. Compiling a\n * node with `returning` directly is an error, rather than SQL that silently\n * returns nothing.\n */\n protected override compileReturning(returning: readonly string[] | \"*\" | null): string {\n if (returning === null) return \"\";\n throw new Error(\n \"RETURNING cannot be compiled for MySQL. session.execute() reads a single-row INSERT back by key (LAST_INSERT_ID()); UPDATE/DELETE have no equivalent — run a SELECT yourself.\",\n );\n }\n}\n\n/** Get a dialect instance by name. */\nexport function getDialect(name: Dialect): BaseDialect {\n switch (name) {\n case \"sqlite\":\n return new SqliteDialect();\n case \"postgresql\":\n return new PostgresDialect();\n case \"mysql\":\n return new MysqlDialect();\n }\n}\n","/**\n * tempest-db-js — Phase 5: typed joins with composite result types.\n *\n * `join(User, \"user\").innerJoin(Order, \"order\", { \"user.id\": \"order.userId\" })`\n * yields rows shaped `{ user: UserRow; order: OrderRow }`. A `leftJoin` makes the\n * joined side nullable (`OrderRow | null`), matching SQL outer-join semantics.\n *\n * Columns are aliased in SQL (`\"user\".\"id\" AS \"user.id\"`) so a flat driver row is\n * split back into one nested object per source, each coerced by its model.\n */\n\nimport { aliasOf } from \"./aliased.js\";\nimport { type CondNode, type Condition, toCondNode } from \"./conditions.js\";\nimport {\n type InferModel,\n type ModelClass,\n type NameMap,\n columnNamesOf,\n columnsOf,\n} from \"./index.js\";\nimport type { OperatorsFor, SortDirection } from \"./query.js\";\n\n// ---------------------------------------------------------------------------\n// AST\n// ---------------------------------------------------------------------------\n\n/** One joined table. */\nexport interface JoinClause {\n readonly kind: \"inner\" | \"left\";\n readonly table: string;\n readonly alias: string;\n /** Equality pairs of qualified columns: `[\"user.id\", \"order.userId\"]`. */\n readonly on: readonly (readonly [string, string])[];\n}\n\n/** A selected column, qualified by source alias. */\nexport interface JoinSelection {\n readonly alias: string;\n readonly column: string;\n}\n\n/** Collapse a union of object types into their intersection. */\ntype UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/**\n * `where` filter for a join. Keys are `alias.column` refs; each value accepts a\n * bare value (shorthand for `eq`) or an operator object restricted to the\n * operators valid for that column's type — exactly like the single-table\n * {@link WhereInput}, but qualified per source. `like` on a numeric join column,\n * or `gt` on a string one, is a compile error.\n */\nexport type JoinWhereInput<S extends Sources> = Partial<\n UnionToIntersection<\n {\n [A in keyof S]: {\n [C in keyof NonNullable<S[A]> & string as `${A & string}.${C}`]:\n | NonNullable<S[A]>[C]\n | OperatorsFor<NonNullable<NonNullable<S[A]>[C]>>;\n };\n }[keyof S]\n >\n>;\n\n/** Serializable AST for a multi-table SELECT. */\nexport interface JoinNode {\n readonly kind: \"join_select\";\n readonly base: { readonly table: string; readonly alias: string };\n readonly joins: readonly JoinClause[];\n readonly selections: readonly JoinSelection[];\n readonly where: CondNode | undefined;\n readonly orderBy: readonly {\n readonly ref: string;\n readonly direction: SortDirection;\n }[];\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n /** Per-alias property → column maps, for the sources that rename columns. */\n readonly names?: Readonly<Record<string, NameMap>> | undefined;\n /**\n * Project only this source, with **bare** column names instead of the\n * `alias.column` labels a composite row needs.\n *\n * Set by {@link JoinBuilder.pick}. It is what lets a join stand where a plain\n * `SELECT` of one table would — the recursive branch of a `WITH RECURSIVE`, for\n * instance, whose columns have to line up with the CTE's.\n */\n readonly pick?: string | undefined;\n /** `WITH` entries this statement carries, in order. */\n readonly with?: readonly import(\"./cte.js\").CteNode[] | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// type helpers\n// ---------------------------------------------------------------------------\n\n/** A map of source alias → its (possibly nullable) row type. */\nexport type Sources = Record<string, object | null>;\n\n/** Every `alias.column` reference across the current sources. */\nexport type ColRef<S extends Sources> = {\n [A in keyof S]: `${A & string}.${keyof NonNullable<S[A]> & string}`;\n}[keyof S];\n\n/** Valid `alias.column` references for a newly joined model. */\ntype RightRef<\n A extends string,\n C extends ModelClass,\n> = `${A}.${keyof InferModel<C> & string}`;\n\n/** The `on` condition: map existing-source refs to new-table refs (equality). */\nexport type JoinOn<S extends Sources, A extends string, C extends ModelClass> = Partial<\n Record<ColRef<S>, RightRef<A, C>>\n>;\n\n// ---------------------------------------------------------------------------\n// builder\n// ---------------------------------------------------------------------------\n\n/** Build the qualified selection list for a model under an alias. */\nfunction selectionsFor(alias: string, model: ModelClass): JoinSelection[] {\n return Object.keys(columnsOf(model)).map((column) => ({ alias, column }));\n}\n\n/**\n * Register a source's property → column map under its alias, or keep the node\n * map untouched when the model renames nothing.\n *\n * @param current The node's existing per-alias maps.\n * @param alias The alias the model is joined under.\n * @param model The joined model.\n * @returns The updated map, or `undefined` when no source renames anything.\n */\nfunction withAliasNames(\n current: Readonly<Record<string, NameMap>> | undefined,\n alias: string,\n model: ModelClass,\n): Readonly<Record<string, NameMap>> | undefined {\n const names = columnNamesOf(model);\n if (!names) return current;\n return { ...(current ?? {}), [alias]: names };\n}\n\n/**\n * Immutable, chainable multi-table SELECT builder.\n *\n * @typeParam S - the accumulated sources (alias → row type; nullable for left joins).\n */\nexport class JoinBuilder<S extends Sources> {\n /** Phantom: the composite result row type. */\n declare readonly __row: { [A in keyof S]: S[A] };\n\n constructor(\n readonly node: JoinNode,\n /** Source models keyed by alias, for SQL expansion and row coercion. */\n readonly sources: Readonly<Record<string, ModelClass>>,\n ) {}\n\n private add<S2 extends Sources>(\n clause: JoinClause,\n model: ModelClass,\n ): JoinBuilder<S2> {\n return new JoinBuilder<S2>(\n {\n ...this.node,\n joins: [...this.node.joins, clause],\n selections: [...this.node.selections, ...selectionsFor(clause.alias, model)],\n names: withAliasNames(this.node.names, clause.alias, model),\n },\n { ...this.sources, [clause.alias]: model },\n );\n }\n\n private clause(\n kind: \"inner\" | \"left\",\n model: ModelClass,\n alias: string,\n on: Record<string, string>,\n ): JoinClause {\n return {\n kind,\n table: aliasOf(model)?.tablename ?? model.tablename,\n alias,\n on: Object.entries(on) as [string, string][],\n };\n }\n\n /** Inner join another model under `alias`. */\n innerJoin<C extends ModelClass, A extends string>(\n model: C,\n alias: A,\n on: JoinOn<S, A, C>,\n ): JoinBuilder<S & { [K in A]: InferModel<C> }> {\n return this.add(\n this.clause(\"inner\", model, alias, on as Record<string, string>),\n model,\n );\n }\n\n /** Left (outer) join another model under `alias` — its side becomes nullable. */\n leftJoin<C extends ModelClass, A extends string>(\n model: C,\n alias: A,\n on: JoinOn<S, A, C>,\n ): JoinBuilder<S & { [K in A]: InferModel<C> | null }> {\n return this.add(\n this.clause(\"left\", model, alias, on as Record<string, string>),\n model,\n );\n }\n\n /**\n * Project **one** source, flat, instead of the composite row.\n *\n * The join still happens — it just stops being what comes back. Needed wherever\n * the result has to match a single table's shape: the recursive branch of a\n * CTE, an `INSERT ... SELECT`, a `UNION` branch.\n *\n * @param alias The source to project.\n * @returns A builder whose rows are that source's rows.\n *\n * @example\n * ```ts\n * join(Category, \"c\").innerJoin(subtree, \"s\", { \"c.parentId\": \"s.id\" }).pick(\"c\");\n * // SELECT \"c\".\"id\" AS \"id\", \"c\".\"name\" AS \"name\" ... — not \"c.id\"\n * ```\n */\n pick<A extends keyof S & string>(\n alias: A,\n ): JoinBuilder<S> & { readonly __row: NonNullable<S[A]> } {\n const model = this.sources[alias];\n if (!model) {\n throw new Error(\n `pick(${JSON.stringify(alias)}): no source is joined under that alias.`,\n );\n }\n return new JoinBuilder<S>(\n {\n ...this.node,\n selections: selectionsFor(alias, model),\n pick: alias,\n },\n this.sources,\n ) as JoinBuilder<S> & { readonly __row: NonNullable<S[A]> };\n }\n\n /** Filter by `alias.column` references (object form) or an `and`/`or`/`not`. */\n where(input: JoinWhereInput<S> | Condition): JoinBuilder<S> {\n return new JoinBuilder<S>(\n { ...this.node, where: toCondNode(input as Record<string, unknown>) },\n this.sources,\n );\n }\n\n /** Order by an `alias.column` reference. */\n orderBy(ref: ColRef<S>, direction: SortDirection = \"asc\"): JoinBuilder<S> {\n return new JoinBuilder<S>(\n {\n ...this.node,\n orderBy: [...this.node.orderBy, { ref: ref as string, direction }],\n },\n this.sources,\n );\n }\n\n limit(n: number): JoinBuilder<S> {\n return new JoinBuilder<S>({ ...this.node, limit: n }, this.sources);\n }\n\n offset(n: number): JoinBuilder<S> {\n return new JoinBuilder<S>({ ...this.node, offset: n }, this.sources);\n }\n}\n\n// ---------------------------------------------------------------------------\n// entrypoint\n// ---------------------------------------------------------------------------\n\n/**\n * Start a multi-table query from a base model under `alias`.\n *\n * @param model The base model.\n * @param alias The alias to key the base table's rows under in the result.\n * @returns A `JoinBuilder` with the base source registered.\n */\nexport function join<C extends ModelClass, A extends string>(\n model: C,\n alias: A,\n): JoinBuilder<{ [K in A]: InferModel<C> }> {\n return new JoinBuilder(\n {\n kind: \"join_select\",\n base: { table: aliasOf(model)?.tablename ?? model.tablename, alias },\n joins: [],\n selections: selectionsFor(alias, model),\n where: undefined,\n orderBy: [],\n limit: undefined,\n offset: undefined,\n names: withAliasNames(undefined, alias, model),\n },\n { [alias]: model },\n );\n}\n","/**\n * tempest-db-js — opt-in model mixins.\n *\n * The same four or five columns show up on every real table: when the row was\n * created and last touched, whether it was soft-deleted, who changed it. Writing\n * them out per model is repetition that drifts — one table gets `updated_at`\n * without `onUpdate`, another spells it `updatedOn`.\n *\n * These mixins are functions that take a base class and return a subclass\n * carrying the extra columns, mirroring `tempest-fastapi-sdk`'s\n * `SoftDeleteMixin` / `AuditMixin`. They compose:\n *\n * ```ts\n * class Order extends withSoftDelete(withTimestamps(Model)) {\n * static override tablename = \"orders\";\n * id = column.integer().primaryKey();\n * }\n * ```\n *\n * The columns are real columns: they appear in `InferModel`, in the migration IR\n * and in the generated DDL, exactly as if you had typed them.\n */\n\nimport {\n type Column,\n type ColumnFlags,\n type Model,\n type WhereInput,\n column,\n sql,\n} from \"./index.js\";\n\n/** Any class usable as a mixin base — `Model` itself, or another mixin's result. */\n// biome-ignore lint/suspicious/noExplicitAny: a mixin base accepts any constructor shape.\nexport type ModelBase = abstract new (...args: any[]) => Model;\n\n/**\n * Add `createdAt` / `updatedAt` to a model.\n *\n * Both default to the database's own clock (`sql.now()`), and `updatedAt` carries\n * `onUpdate(sql.now())`, so an `UPDATE` refreshes it without the call site\n * remembering to. Both are `NOT NULL` with a default, so neither shows up as\n * required in `InferInsert`.\n *\n * @param Base The class to extend (`Model`, or another mixin's result).\n * @returns A subclass carrying the two timestamp columns.\n */\nexport function withTimestamps<TBase extends ModelBase>(Base: TBase) {\n abstract class WithTimestamps extends Base {\n /** When the row was inserted. */\n createdAt = column.datetime().notNull().default(sql.now());\n /** When the row was last updated — refreshed by every `UPDATE`. */\n updatedAt = column.datetime().notNull().default(sql.now()).onUpdate(sql.now());\n }\n return WithTimestamps;\n}\n\n/**\n * Add `deletedAt` to a model, for non-destructive deletes.\n *\n * A row is alive while `deletedAt IS NULL`. **Filtering is the caller's job** —\n * the mixin only declares the column, so it composes with whatever query strategy\n * a table needs (a partial index, a repository default, a view). Use\n * {@link notDeleted} to spell the predicate.\n *\n * @param Base The class to extend.\n * @returns A subclass carrying the `deletedAt` column.\n */\nexport function withSoftDelete<TBase extends ModelBase>(Base: TBase) {\n abstract class WithSoftDelete extends Base {\n /** When the row was soft-deleted, or `null` while it is alive. */\n deletedAt = column.datetime();\n }\n return WithSoftDelete;\n}\n\n/**\n * The `where` fragment matching rows that are **not** soft-deleted.\n *\n * @typeParam Row - the row type being filtered.\n * @returns `{ deletedAt: { isNull: true } }`, typed for the row.\n */\nexport function notDeleted<Row>(): WhereInput<Row> {\n return { deletedAt: { isNull: true } } as WhereInput<Row>;\n}\n\n/**\n * The `where` fragment matching **only** soft-deleted rows.\n *\n * @typeParam Row - the row type being filtered.\n * @returns `{ deletedAt: { isNull: false } }`, typed for the row.\n */\nexport function onlyDeleted<Row>(): WhereInput<Row> {\n return { deletedAt: { isNull: false } } as WhereInput<Row>;\n}\n\n/**\n * Add `createdBy` / `updatedBy` to a model — *who* touched the row.\n *\n * The actor column defaults to `column.uuid()`, matching the SDK's user id. A\n * service whose users are keyed by something else passes a factory:\n * `withAudit(Model, () => column.integer())`. It must be a factory, not a column:\n * the two properties need two independent column instances.\n *\n * Both columns are nullable — a row created by a background job has no actor, and\n * forcing a sentinel value there is worse than a `NULL`.\n *\n * @param Base The class to extend.\n * @param actor Factory producing the actor column (default: `column.uuid()`).\n * @returns A subclass carrying the two actor columns.\n */\nexport function withAudit<TBase extends ModelBase, A = string>(\n Base: TBase,\n actor: () => Column<A, ColumnFlags> = () =>\n column.uuid() as unknown as Column<A, ColumnFlags>,\n) {\n abstract class WithAudit extends Base {\n /** Who created the row, or `null` when nobody was attributed. */\n createdBy = actor();\n /** Who last updated the row, or `null`. */\n updatedBy = actor();\n }\n return WithAudit;\n}\n","/**\n * tempest-db-js — read a constraint violation back out of the driver's error.\n *\n * A database says *why* it refused a write, and says it in prose whose shape is\n * the driver's, not the application's. Answering `409 {\"code\":\"EMAIL_TAKEN\"}`\n * instead of a generic conflict otherwise means every service writing its own\n * regular expression against whichever dialect the author had running.\n *\n * The two dialects in scope say the same five things two different ways:\n * PostgreSQL names the constraint and lists the columns in a `DETAIL:` line,\n * while SQLite spells the table and columns into the message and says nothing\n * about the constraint's name.\n */\n\nimport { type ModelClass, columnPropsOf } from \"./index.js\";\n\n/** What kind of constraint refused the write. */\nexport type IntegrityViolation =\n | \"unique\"\n | \"foreignKey\"\n | \"notNull\"\n | \"check\"\n | \"exclusion\";\n\n/** A constraint violation, read out of the driver's error. */\nexport interface IntegrityFailure {\n /** Which kind of constraint refused the write. */\n readonly violation: IntegrityViolation;\n /** The constraint's name, when the database reported one (PostgreSQL does). */\n readonly constraint: string | null;\n /** The table, when the database reported one. */\n readonly table: string | null;\n /**\n * The columns the constraint covers.\n *\n * Empty when the database did not say — a SQLite `FOREIGN KEY constraint\n * failed` carries no names at all.\n */\n readonly columns: readonly string[];\n /** The driver's own message, kept verbatim for logging. */\n readonly detail: string;\n}\n\n/** SQLSTATE codes for the integrity classes PostgreSQL reports. */\nconst POSTGRES_VIOLATIONS: Readonly<Record<string, IntegrityViolation>> = {\n \"23505\": \"unique\",\n \"23503\": \"foreignKey\",\n \"23502\": \"notNull\",\n \"23514\": \"check\",\n \"23P01\": \"exclusion\",\n};\n\n/** SQLite extended result codes, as `node:sqlite` reports them numerically. */\nconst SQLITE_ERRCODES: Readonly<Record<number, IntegrityViolation>> = {\n 1555: \"unique\", // SQLITE_CONSTRAINT_PRIMARYKEY\n 2067: \"unique\", // SQLITE_CONSTRAINT_UNIQUE\n 787: \"foreignKey\", // SQLITE_CONSTRAINT_FOREIGNKEY\n 1299: \"notNull\", // SQLITE_CONSTRAINT_NOTNULL\n 275: \"check\", // SQLITE_CONSTRAINT_CHECK\n};\n\n/** SQLite extended result codes, as `better-sqlite3` reports them by name. */\nconst SQLITE_CODES: Readonly<Record<string, IntegrityViolation>> = {\n SQLITE_CONSTRAINT_PRIMARYKEY: \"unique\",\n SQLITE_CONSTRAINT_UNIQUE: \"unique\",\n SQLITE_CONSTRAINT_FOREIGNKEY: \"foreignKey\",\n SQLITE_CONSTRAINT_NOTNULL: \"notNull\",\n SQLITE_CONSTRAINT_CHECK: \"check\",\n};\n\n/** Read the string property `key` off an unknown error, if it has one. */\nfunction str(error: Record<string, unknown>, key: string): string | null {\n const value = error[key];\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/**\n * Pull the column list out of a PostgreSQL `DETAIL:` line.\n *\n * `Key (email)=(a@b) already exists.` → `[\"email\"]`, and a composite key lists\n * every column, which is why this exists instead of reading `column_name`.\n */\nfunction postgresDetailColumns(detail: string | null): string[] {\n if (!detail) return [];\n const match = /Key \\(([^)]+)\\)=/.exec(detail);\n if (!match?.[1]) return [];\n return match[1].split(\",\").map((c) => c.trim().replace(/^\"|\"$/g, \"\"));\n}\n\n/** Split SQLite's `table.column, table.column` list into table + columns. */\nfunction sqliteTargets(list: string): { table: string | null; columns: string[] } {\n const columns: string[] = [];\n let table: string | null = null;\n for (const entry of list.split(\",\")) {\n const [left, right] = entry.trim().split(\".\");\n if (right === undefined) {\n if (left) columns.push(left);\n continue;\n }\n table = left ?? null;\n columns.push(right);\n }\n return { table, columns };\n}\n\n/** Classify a PostgreSQL error, or return `null` when it is not an integrity one. */\nfunction fromPostgres(error: Record<string, unknown>): IntegrityFailure | null {\n const code = str(error, \"code\");\n const violation = code ? POSTGRES_VIOLATIONS[code] : undefined;\n if (!violation) return null;\n const detail = str(error, \"detail\");\n const columns = postgresDetailColumns(detail);\n const column = str(error, \"column_name\");\n return {\n violation,\n constraint: str(error, \"constraint_name\"),\n table: str(error, \"table_name\"),\n columns: columns.length > 0 ? columns : column ? [column] : [],\n detail: str(error, \"message\") ?? detail ?? \"\",\n };\n}\n\n/** Classify a SQLite error from either driver, or return `null`. */\nfunction fromSqlite(error: Record<string, unknown>): IntegrityFailure | null {\n const code = str(error, \"code\");\n const errcode = error.errcode;\n const violation =\n (code ? SQLITE_CODES[code] : undefined) ??\n (typeof errcode === \"number\" ? SQLITE_ERRCODES[errcode] : undefined);\n if (!violation) return null;\n const message = str(error, \"message\") ?? \"\";\n if (violation === \"check\") {\n const named = /CHECK constraint failed: (.+)$/.exec(message);\n return {\n violation,\n constraint: named?.[1] ?? null,\n table: null,\n columns: [],\n detail: message,\n };\n }\n const targets = /constraint failed: (.+)$/.exec(message);\n if (!targets?.[1]) {\n return { violation, constraint: null, table: null, columns: [], detail: message };\n }\n const { table, columns } = sqliteTargets(targets[1]);\n return { violation, constraint: null, table, columns, detail: message };\n}\n\n/**\n * Read a driver error back into the constraint that refused the write.\n *\n * @param error Anything thrown by a write — a `QueryExecutionError` from this\n * package, or the driver's own error; the cause chain is followed either way.\n * @param model Optional. When given, database column names are translated back to\n * the model's property names, so a `snake_case` schema reports `idempotencyKey`\n * rather than `idempotency_key`.\n * @returns The violation, or `null` when the error is not an integrity violation\n * (or came from MySQL, which is out of scope — see the recipe).\n *\n * @example\n * ```ts\n * try {\n * await users.create({ email });\n * } catch (err) {\n * const failure = parseIntegrityError(err, User);\n * if (failure?.violation === \"unique\" && failure.columns.includes(\"email\")) {\n * throw new EmailTaken();\n * }\n * throw err;\n * }\n * ```\n */\nexport function parseIntegrityError(\n error: unknown,\n model?: ModelClass,\n): IntegrityFailure | null {\n let current: unknown = error;\n for (let depth = 0; depth < 5 && current !== null && current !== undefined; depth++) {\n if (typeof current === \"object\") {\n const record = current as Record<string, unknown>;\n const failure = fromPostgres(record) ?? fromSqlite(record);\n if (failure) return model ? withModelNames(failure, model) : failure;\n current = record.cause;\n continue;\n }\n return null;\n }\n return null;\n}\n\n/**\n * Translate database column names back to the model's property names.\n *\n * @param failure The failure as the driver described it.\n * @param model The model whose naming applies.\n * @returns The failure with property names, unchanged when the model renames nothing.\n */\nfunction withModelNames(failure: IntegrityFailure, model: ModelClass): IntegrityFailure {\n const props = columnPropsOf(model);\n if (!props || failure.columns.length === 0) return failure;\n return { ...failure, columns: failure.columns.map((c) => props[c] ?? c) };\n}\n","/**\n * tempest-db-js — lifecycle signals around the repository's write path.\n *\n * Reacting to persistence — busting a cache, enqueuing an outbox event, syncing a\n * search index, writing an audit row — otherwise means wrapping every call site\n * by hand, and the one call site somebody forgets is the bug.\n *\n * Handlers run **inside** whatever transaction is open, because they are handed\n * the same session the write used: a handler that writes commits with the write,\n * or rolls back with it.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport type { InferModel, ModelClass } from \"./index.js\";\n\n/** The points a repository write is observable at. */\nexport type RepositorySignal = \"preSave\" | \"postSave\" | \"preDelete\" | \"postDelete\";\n\n/** What a handler receives. */\nexport interface SignalPayload<C extends ModelClass> {\n /**\n * The row the signal is about.\n *\n * `preSave` on an insert carries what was passed to `create`, so a\n * database-generated id is not there yet — `postSave` carries the stored row.\n * `preDelete` carries the row as it was just before it was deleted.\n */\n readonly row: InferModel<C>;\n /** The model being written. */\n readonly model: C;\n /** The session the write is running on — the same transaction, if one is open. */\n readonly session: AsyncSession;\n /** True when the write that fired this was an insert rather than an update. */\n readonly isInsert: boolean;\n}\n\n/** A signal handler; may be async, and is awaited. */\nexport type SignalHandler<C extends ModelClass> = (\n payload: SignalPayload<C>,\n) => void | Promise<void>;\n\n/* biome-ignore lint/suspicious/noExplicitAny: the registry mixes models. */\ntype AnyHandler = SignalHandler<any>;\n\n/** Handlers per model, per signal. Keyed weakly so a model class can be collected. */\nconst registry = new WeakMap<ModelClass, Map<RepositorySignal, Set<AnyHandler>>>();\n\n/** Models that have ever had a handler, so `clearSignals()` can reach them all. */\nconst registered = new Set<ModelClass>();\n\n/**\n * Register a handler for one signal on one model.\n *\n * @param model The model to observe.\n * @param signal Which point to observe.\n * @param handler The handler; awaited, and free to use the payload's session.\n * @returns A function that unregisters this handler.\n *\n * @example\n * ```ts\n * const off = onSignal(User, \"postSave\", async ({ row }) => {\n * await cache.del(`user:${row.id}`);\n * });\n * ```\n */\nexport function onSignal<C extends ModelClass>(\n model: C,\n signal: RepositorySignal,\n handler: SignalHandler<C>,\n): () => void {\n let bySignal = registry.get(model);\n if (!bySignal) {\n bySignal = new Map();\n registry.set(model, bySignal);\n registered.add(model);\n }\n let handlers = bySignal.get(signal);\n if (!handlers) {\n handlers = new Set();\n bySignal.set(signal, handlers);\n }\n handlers.add(handler as AnyHandler);\n return () => {\n handlers?.delete(handler as AnyHandler);\n };\n}\n\n/**\n * Whether anything is listening to a signal on a model.\n *\n * The repository asks before doing work only a handler would need — reading the\n * rows a filter-based `update`/`delete` is about to touch costs a `SELECT`, and\n * nobody should pay it when no handler exists.\n *\n * @param model The model.\n * @param signal The signal.\n * @returns True when at least one handler is registered.\n */\nexport function hasHandlers(model: ModelClass, signal: RepositorySignal): boolean {\n return (registry.get(model)?.get(signal)?.size ?? 0) > 0;\n}\n\n/**\n * Fire a signal, awaiting every handler in registration order.\n *\n * A handler that throws **propagates**: on `preSave`/`preDelete` that vetoes the\n * write, which is the point — a veto that could be swallowed would be a\n * suggestion.\n *\n * @param signal The signal to fire.\n * @param payload What to hand the handlers.\n */\nexport async function emitSignal<C extends ModelClass>(\n signal: RepositorySignal,\n payload: SignalPayload<C>,\n): Promise<void> {\n const handlers = registry.get(payload.model)?.get(signal);\n if (!handlers || handlers.size === 0) return;\n for (const handler of [...handlers]) {\n await handler(payload);\n }\n}\n\n/**\n * Drop registered handlers — for tests, which otherwise leak them across cases.\n *\n * @param model Only this model's handlers; omitted, every model's.\n */\nexport function clearSignals(model?: ModelClass): void {\n if (model) {\n registry.delete(model);\n registered.delete(model);\n return;\n }\n for (const registeredModel of registered) registry.delete(registeredModel);\n registered.clear();\n}\n","/**\n * tempest-db-js — set operations (`UNION`, `INTERSECT`, `EXCEPT`).\n *\n * Combining two queries in any way other than a join meant dropping to\n * `session.raw`, losing the row type, the coercion and the composition. A set\n * operation is also the one place a typed builder can catch a mistake the\n * database only reports at runtime: branches whose projections do not line up.\n */\n\nimport type { ModelClass } from \"./index.js\";\nimport type { JoinNode } from \"./join.js\";\nimport type { OrderTerm, SelectNode, SortDirection } from \"./query.js\";\n\n/** Which set operation combines the branches. */\nexport type SetOperator = \"union\" | \"unionAll\" | \"intersect\" | \"except\";\n\n/** Serializable AST for a set operation. */\nexport interface SetNode {\n readonly kind: \"set_op\";\n readonly op: SetOperator;\n /** The combined SELECTs, in order. A branch may be a join projecting one source. */\n readonly branches: readonly (SelectNode | JoinNode)[];\n /** Ordering applied to the **result**, not to a branch. */\n readonly orderBy: readonly OrderTerm[];\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n}\n\n/**\n * A combined query, executable like a `SelectBuilder`.\n *\n * `orderBy` / `limit` / `offset` here apply to the **combined** result, which is\n * what SQL does: a branch that needs its own limit keeps it, and the dialect\n * parenthesizes that branch.\n *\n * @typeParam Row - the row type every branch projects.\n */\nexport class SetBuilder<Row> {\n /** Phantom: the result element type, read only by the type system. */\n declare readonly __row: Row;\n\n constructor(\n readonly node: SetNode,\n /** The first branch's model, used to coerce the returned rows. */\n readonly source: ModelClass,\n ) {}\n\n private with(patch: Partial<SetNode>): SetBuilder<Row> {\n return new SetBuilder<Row>({ ...this.node, ...patch }, this.source);\n }\n\n /**\n * Order the combined result.\n *\n * @param column A column of the projected row.\n * @param direction Sort direction (default ascending).\n * @returns A builder carrying the ordering.\n */\n orderBy(column: keyof Row & string, direction: SortDirection = \"asc\"): SetBuilder<Row> {\n return this.with({ orderBy: [...this.node.orderBy, { column, direction }] });\n }\n\n /** Limit the combined result. */\n limit(count: number): SetBuilder<Row> {\n return this.with({ limit: count });\n }\n\n /** Skip rows of the combined result. */\n offset(count: number): SetBuilder<Row> {\n return this.with({ offset: count });\n }\n}\n\n/**\n * What a set operation combines: anything that compiles to a SELECT and yields\n * `Row` — a `select()`, or a join narrowed to one source with `.pick()`.\n */\nexport interface Branch<Row> {\n /** The branch's AST. */\n readonly node: SelectNode | JoinNode;\n /** Phantom: the row type this branch yields. */\n readonly __row: Row;\n /** The model rows are coerced through, when the branch has a single source. */\n readonly source?: ModelClass;\n /** Source models by alias, for a join branch. */\n readonly sources?: Readonly<Record<string, ModelClass>>;\n}\n\n/**\n * The model a branch's rows should be coerced through.\n *\n * @param branch The branch.\n * @returns Its model, or `undefined` when it has none to offer.\n */\nfunction branchSource(branch: Branch<unknown>): ModelClass | undefined {\n if (branch.source) return branch.source;\n const pick = (branch.node as JoinNode).pick;\n return pick ? branch.sources?.[pick] : undefined;\n}\n\n/**\n * Build a set operation over two or more branches.\n *\n * @param op The operator.\n * @param branches The SELECTs to combine.\n * @returns The combined builder.\n * @throws Error When fewer than two branches are given.\n */\nfunction combine<Row>(\n op: SetOperator,\n branches: readonly Branch<Row>[],\n): SetBuilder<Row> {\n if (branches.length < 2) {\n throw new Error(`${op}() combines at least two queries.`);\n }\n const first = branches[0] as Branch<Row>;\n const source = branchSource(first as Branch<unknown>);\n if (!source) {\n throw new Error(\n `${op}(): the first branch must project a single source — narrow a join with .pick(alias).`,\n );\n }\n return new SetBuilder<Row>(\n {\n kind: \"set_op\",\n op,\n branches: branches.map((b) => b.node),\n orderBy: [],\n limit: undefined,\n offset: undefined,\n },\n source,\n );\n}\n\n/**\n * `UNION` — every row of either branch, **duplicates removed**.\n *\n * Every branch must project the same shape; that is checked at compile time here,\n * where the database would only report it at runtime.\n *\n * @param branches The queries to combine.\n * @returns The combined builder.\n *\n * @example\n * ```ts\n * union(\n * select(Post, [\"id\", \"createdAt\"]).where({ authorId: me }),\n * select(Comment, [\"id\", \"createdAt\"]).where({ authorId: me }),\n * ).orderBy(\"createdAt\", \"desc\").limit(50);\n * ```\n */\nexport function union<Row>(...branches: Branch<Row>[]): SetBuilder<Row> {\n return combine(\"union\", branches);\n}\n\n/**\n * `UNION ALL` — every row of either branch, duplicates **kept**.\n *\n * Cheaper than `UNION`, which has to sort or hash to deduplicate. Prefer it\n * whenever the branches cannot overlap.\n *\n * @param branches The queries to combine.\n * @returns The combined builder.\n */\nexport function unionAll<Row>(...branches: Branch<Row>[]): SetBuilder<Row> {\n return combine(\"unionAll\", branches);\n}\n\n/**\n * `INTERSECT` — only the rows present in every branch.\n *\n * @param branches The queries to combine.\n * @returns The combined builder.\n */\nexport function intersect<Row>(...branches: Branch<Row>[]): SetBuilder<Row> {\n return combine(\"intersect\", branches);\n}\n\n/**\n * `EXCEPT` — the rows of the first branch that are not in the others.\n *\n * @param branches The queries to combine.\n * @returns The combined builder.\n */\nexport function except<Row>(...branches: Branch<Row>[]): SetBuilder<Row> {\n return combine(\"except\", branches);\n}\n","/**\n * tempest-db-js — Phase 7: typed repository + pagination.\n *\n * `BaseRepository<Model>` mirrors the `tempest-fastapi-sdk` repository: a thin,\n * fully-typed CRUD + pagination layer over a model and an async session. The\n * 404-convention is honored — `getById` throws when absent, collection methods\n * return `[]` (never a \"not found\" error for an empty list).\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport {\n type Column,\n type Condition,\n type InferInsert,\n type InferModel,\n type ModelClass,\n type WhereInput,\n and,\n columnsOf,\n decodeColumnValue,\n del,\n encodeColumnValue,\n insert,\n not,\n or,\n primaryKeyFilter,\n primaryKeysOf,\n select,\n sql,\n update,\n} from \"./index.js\";\nimport { type RepositorySignal, emitSignal, hasHandlers } from \"./signals.js\";\n\n/** Pagination request — 1-indexed page. */\nexport interface PaginationFilter<Row> {\n readonly page?: number;\n readonly pageSize?: number;\n readonly orderBy?: keyof Row & string;\n readonly ascending?: boolean;\n readonly filters?: WhereInput<Row>;\n}\n\n/** A page of results plus metadata (mirrors `BasePaginationSchema`). */\nexport interface PaginationResult<Row> {\n readonly items: Row[];\n readonly total: number;\n readonly page: number;\n readonly pageSize: number;\n readonly pages: number;\n}\n\n/**\n * Cursor-pagination request.\n *\n * Cursor paging trades random access for two things offset paging cannot give on a\n * large table: no `COUNT(*)`, and a page boundary that does not shift when rows are\n * inserted while the user is reading.\n *\n * @typeParam Row - the row type being paginated.\n */\nexport interface CursorPaginationFilter<Row> {\n /** Opaque cursor from the previous page. Absent/`null` asks for the first page. */\n readonly cursor?: string | null;\n /** Maximum rows to return (default 20). */\n readonly limit?: number;\n /** Column to sort by. Defaults to the first primary-key column. */\n readonly orderBy?: keyof Row & string;\n /** Sort ascending. Defaults to `false`, so the newest rows come first. */\n readonly ascending?: boolean;\n /** Domain filters, applied to every page. */\n readonly filters?: WhereInput<Row>;\n}\n\n/** One cursor-paginated page. */\nexport interface CursorPage<Row> {\n /** The rows of this page. */\n readonly items: Row[];\n /** Cursor for the next page, or `null` when this was the last one. */\n readonly nextCursor: string | null;\n}\n\n/** Raised when a cursor is not one this repository produced. */\nexport class InvalidCursor extends Error {\n constructor(reason: string) {\n super(`Invalid pagination cursor: ${reason}`);\n this.name = \"InvalidCursor\";\n }\n}\n\n/** Payload carried inside a cursor: the ordering keys of the last row seen. */\ninterface CursorPayload {\n readonly v: 1;\n readonly k: Record<string, unknown>;\n}\n\n/** Encode the ordering-key values of a row into an opaque cursor. */\nfunction encodeCursor(\n columns: Record<string, Column<unknown>>,\n keys: readonly string[],\n row: Record<string, unknown>,\n): string {\n const k: Record<string, unknown> = {};\n for (const key of keys) {\n k[key] = encodeColumnValue(columns[key] as Column<unknown>, row[key]);\n }\n const payload: CursorPayload = { v: 1, k };\n return Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\");\n}\n\n/**\n * Read a cursor back into native key values.\n *\n * @param columns The model's columns, for per-column decoding.\n * @param keys The ordering keys this page is using.\n * @param cursor The opaque cursor.\n * @returns The key values, coerced to their column types.\n * @throws InvalidCursor When the cursor is malformed, of another version, or was\n * produced for a different ordering.\n */\nfunction decodeCursor(\n columns: Record<string, Column<unknown>>,\n keys: readonly string[],\n cursor: string,\n): Record<string, unknown> {\n let payload: CursorPayload;\n try {\n payload = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\"));\n } catch {\n throw new InvalidCursor(\"not a cursor this repository produced\");\n }\n if (payload === null || typeof payload !== \"object\" || payload.v !== 1) {\n throw new InvalidCursor(\"unknown cursor version\");\n }\n const values: Record<string, unknown> = {};\n for (const key of keys) {\n if (!(key in payload.k)) {\n throw new InvalidCursor(\n `it does not carry ${JSON.stringify(key)} — the ordering changed between pages`,\n );\n }\n values[key] = decodeColumnValue(columns[key] as Column<unknown>, payload.k[key]);\n }\n return values;\n}\n\n/**\n * The `where` fragment for \"strictly after the row this cursor points at\".\n *\n * Written as the expanded comparison (`a > v OR (a = v AND b > w)`) rather than a\n * row-value comparison (`(a, b) > (v, w)`): PostgreSQL supports the tuple form,\n * SQLite's support varies by version, and the expanded form compiles the same\n * everywhere.\n *\n * @param keys The ordering keys, most significant first.\n * @param values The key values of the last row of the previous page.\n * @param ascending Whether the page is ordered ascending.\n * @returns A condition selecting rows strictly after that one.\n */\nfunction afterCursor<Row>(\n keys: readonly string[],\n values: Record<string, unknown>,\n ascending: boolean,\n): WhereInput<Row> {\n const op = ascending ? \"gt\" : \"lt\";\n const build = (index: number): WhereInput<Row> => {\n const key = keys[index] as string;\n const strict = { [key]: { [op]: values[key] } } as WhereInput<Row>;\n if (index === keys.length - 1) return strict;\n return or<Row>(\n strict,\n and<Row>({ [key]: values[key] } as WhereInput<Row>, build(index + 1)),\n ) as unknown as WhereInput<Row>;\n };\n return build(0);\n}\n\n/** Request for {@link BaseRepository.changesSince}. */\nexport interface ChangesSinceFilter<Row> {\n /**\n * The client's high-water mark. Rows changed **strictly after** it are\n * returned; `null` (or absent) asks for everything, which is the first sync.\n */\n readonly since?: Date | null;\n /** Cursor from the previous page of this same pull. */\n readonly cursor?: string | null;\n /** Maximum rows per page (default 50). */\n readonly limit?: number;\n /** Domain filters, applied to every page. */\n readonly filters?: WhereInput<Row>;\n}\n\n/** One page of changes, plus the watermark to persist for the next pull. */\nexport interface ChangesPage<Row> extends CursorPage<Row> {\n /**\n * The server's clock, read **before** the query ran.\n *\n * This is what a client persists as its next `since` — not the newest\n * `updatedAt` it saw. A row committed while this page was being built carries\n * a later timestamp, so it surfaces on the following pull instead of falling\n * into the gap between the two.\n */\n readonly serverTime: Date;\n}\n\n/** Options for {@link BaseRepository.bulkUpsert}. */\nexport interface BulkUpsertOptions<Row> {\n /** The columns forming the conflict target (a unique constraint or index). */\n readonly conflictColumns: readonly (keyof Row & string)[];\n /**\n * Which columns to overwrite on conflict. Omitted, every column present in the\n * incoming rows except the conflict target is written.\n */\n readonly update?: readonly (keyof Row & string)[];\n}\n\n/** Raised by single-record lookups (`getById`) when nothing matches (404). */\nexport class RecordNotFound extends Error {\n constructor(table: string, key: unknown) {\n super(`${table} not found for key ${JSON.stringify(key)}`);\n this.name = \"RecordNotFound\";\n }\n}\n\n/**\n * A fully-typed CRUD + pagination repository over a model and an async session.\n *\n * @typeParam C - the model class.\n */\nexport class BaseRepository<C extends ModelClass> {\n private readonly pks: string[];\n\n constructor(\n protected readonly model: C,\n protected readonly session: AsyncSession,\n ) {\n this.pks = primaryKeysOf(model);\n }\n\n /**\n * Narrow every read this repository performs.\n *\n * The extension point a scoped repository overrides: returning a filter that\n * always carries the scope's predicate is what makes it impossible for one\n * query site to forget it. The base implementation adds nothing.\n *\n * @param filters The caller's filters.\n * @returns The filters actually sent to the database.\n */\n protected scopeFilters(\n filters?: WhereInput<InferModel<C>>,\n ): WhereInput<InferModel<C>> | undefined {\n return filters;\n }\n\n /**\n * Stamp every row this repository writes.\n *\n * The write-side counterpart of {@link scopeFilters}. The base implementation\n * writes the row unchanged.\n *\n * @param data The row being written.\n * @returns The row actually written.\n */\n protected scopeWrite<T extends Record<string, unknown>>(data: T): T {\n return data;\n }\n\n /** All rows matching `filters` (or everything). Empty list when none match. */\n async list(input?: WhereInput<InferModel<C>>): Promise<InferModel<C>[]> {\n const filters = this.scopeFilters(input);\n const query = filters ? select(this.model).where(filters) : select(this.model);\n return this.session.execute(query).all();\n }\n\n /** The first row matching `filters`, or `null`. */\n async first(input?: WhereInput<InferModel<C>>): Promise<InferModel<C> | null> {\n const filters = this.scopeFilters(input);\n const query = filters ? select(this.model).where(filters) : select(this.model);\n return this.session.execute(query).first();\n }\n\n /**\n * A single row by primary key, or `null`.\n *\n * @param id The key — a bare value for a single-column key, an object\n * (`{ orderId, lineNumber }`) for a composite one.\n * @returns The row, or `null` when nothing matches.\n * @throws Error When a scalar is given for a composite key, or the key is\n * incomplete.\n */\n async getByIdOrNull(id: unknown): Promise<InferModel<C> | null> {\n const filter = this.scopeFilters(\n primaryKeyFilter(this.model, id) as WhereInput<InferModel<C>>,\n ) as WhereInput<InferModel<C>>;\n return this.session.execute(select(this.model).where(filter)).first();\n }\n\n /**\n * A single row by primary key; throws `RecordNotFound` when absent.\n *\n * @param id The key — see {@link getByIdOrNull}.\n * @returns The row.\n * @throws RecordNotFound When no row carries that key.\n */\n async getById(id: unknown): Promise<InferModel<C>> {\n const filter = this.scopeFilters(\n primaryKeyFilter(this.model, id) as WhereInput<InferModel<C>>,\n ) as WhereInput<InferModel<C>>;\n const row = await this.session.execute(select(this.model).where(filter)).first();\n if (row === null) throw new RecordNotFound(this.model.tablename, filter);\n return row;\n }\n\n /** Whether any row matches `filters`. */\n async exists(filters: WhereInput<InferModel<C>>): Promise<boolean> {\n return (await this.first(filters)) !== null;\n }\n\n /** How many rows match `filters` (or the whole table). */\n async count(input?: WhereInput<InferModel<C>>): Promise<number> {\n const filters = this.scopeFilters(input);\n const query = filters\n ? select(this.model, [this.pks[0] as keyof InferModel<C> & string]).where(filters)\n : select(this.model, [this.pks[0] as keyof InferModel<C> & string]);\n return (await this.session.execute(query).all()).length;\n }\n\n /**\n * Insert one row, returning the created row.\n *\n * Fires `preSave` (which can veto by throwing) and then `postSave`.\n *\n * @param data The row to insert.\n * @returns The stored row.\n */\n async create(data: InferInsert<C>): Promise<InferModel<C>> {\n const scoped = this.scopeWrite(data as unknown as Record<string, unknown>);\n await this.fire(\"preSave\", scoped as unknown as InferModel<C>, true);\n const row = await this.session\n .execute(\n insert(this.model)\n .values(scoped as InferInsert<C>)\n .returning(),\n )\n .one();\n await this.fire(\"postSave\", row, true);\n return row;\n }\n\n /**\n * Insert many rows, returning the created rows.\n *\n * Signals fire per row, so a handler sees one row at a time whether it was\n * inserted alone or in a batch.\n *\n * @param data The rows to insert.\n * @returns The stored rows.\n */\n async createMany(data: readonly InferInsert<C>[]): Promise<InferModel<C>[]> {\n if (data.length === 0) return [];\n const scoped = data.map((row) =>\n this.scopeWrite(row as unknown as Record<string, unknown>),\n );\n for (const row of scoped) {\n await this.fire(\"preSave\", row as unknown as InferModel<C>, true);\n }\n const rows = await this.session\n .execute(\n insert(this.model)\n .values(scoped as unknown as InferInsert<C>[])\n .returning(),\n )\n .all();\n for (const row of rows) await this.fire(\"postSave\", row, true);\n return rows;\n }\n\n /**\n * Update rows matching `filters`; returns the number of rows affected.\n *\n * With a `preSave`/`postSave` handler registered, the matching rows are read\n * first so the handler can see them — that extra `SELECT` is skipped entirely\n * when nothing is listening.\n *\n * @param filters Which rows to update.\n * @param set The columns to change.\n * @returns The number of rows affected.\n */\n async update(\n input: WhereInput<InferModel<C>>,\n set: Partial<InferModel<C>>,\n ): Promise<number> {\n const filters = this.scopeFilters(input) as WhereInput<InferModel<C>>;\n const listening =\n hasHandlers(this.model, \"preSave\") || hasHandlers(this.model, \"postSave\");\n const before = listening ? await this.list(filters) : [];\n for (const row of before) await this.fire(\"preSave\", { ...row, ...set }, false);\n const affected = await this.session\n .execute(update(this.model).set(set).where(filters))\n .rowsAffected();\n if (hasHandlers(this.model, \"postSave\")) {\n for (const row of await this.list(filters)) await this.fire(\"postSave\", row, false);\n }\n return affected;\n }\n\n /**\n * Delete rows matching `filters`; returns the number of rows affected.\n *\n * `preDelete` and `postDelete` receive the row as it was **before** the delete —\n * the only chance to see it. Reading it costs a `SELECT`, which is skipped when\n * no handler is registered.\n *\n * @param filters Which rows to delete.\n * @returns The number of rows affected.\n */\n async delete(input: WhereInput<InferModel<C>>): Promise<number> {\n const filters = this.scopeFilters(input) as WhereInput<InferModel<C>>;\n const listening =\n hasHandlers(this.model, \"preDelete\") || hasHandlers(this.model, \"postDelete\");\n const doomed = listening ? await this.list(filters) : [];\n for (const row of doomed) await this.fire(\"preDelete\", row, false);\n const affected = await this.session\n .execute(del(this.model).where(filters))\n .rowsAffected();\n for (const row of doomed) await this.fire(\"postDelete\", row, false);\n return affected;\n }\n\n /**\n * Fire one signal for one row on this repository's model and session.\n *\n * @param signal Which signal.\n * @param row The row it is about.\n * @param isInsert Whether the write was an insert.\n */\n private async fire(\n signal: RepositorySignal,\n row: InferModel<C>,\n isInsert: boolean,\n ): Promise<void> {\n await emitSignal(signal, {\n row,\n model: this.model,\n session: this.session,\n isInsert,\n });\n }\n\n /**\n * A page of rows plus metadata. `total` counts all matching rows.\n *\n * @param filter Page, size, ordering and filters.\n * @returns The page and pagination metadata.\n */\n async paginate(\n filter: PaginationFilter<InferModel<C>> = {},\n ): Promise<PaginationResult<InferModel<C>>> {\n const page = Math.max(1, filter.page ?? 1);\n const pageSize = Math.max(1, filter.pageSize ?? 20);\n const where = this.scopeFilters(filter.filters);\n\n let query = where ? select(this.model).where(where) : select(this.model);\n if (filter.orderBy) {\n query = query.orderBy(filter.orderBy, filter.ascending === false ? \"desc\" : \"asc\");\n }\n query = query.limit(pageSize).offset((page - 1) * pageSize);\n\n const items = await this.session.execute(query).all();\n const total = await this.count(where);\n return {\n items,\n total,\n page,\n pageSize,\n pages: Math.max(1, Math.ceil(total / pageSize)),\n };\n }\n\n /**\n * A cursor-paginated page: the rows after `cursor`, plus the cursor for the\n * next page.\n *\n * No `COUNT(*)` runs, and the page boundary is stable under concurrent inserts —\n * the two reasons to reach for this instead of {@link paginate} on a large table.\n * The trade-off is losing random access: there is no \"page 7\".\n *\n * The primary key is always appended as a tie-break, so rows sharing an\n * `orderBy` value cannot be skipped or repeated across pages.\n *\n * @param filter Cursor, page size, ordering and filters.\n * @returns The page and the next cursor (`null` on the last page).\n * @throws InvalidCursor When the cursor is malformed or was built for a\n * different ordering.\n */\n async cursorPaginate(\n filter: CursorPaginationFilter<InferModel<C>> = {},\n ): Promise<CursorPage<InferModel<C>>> {\n const limit = Math.max(1, Math.trunc(filter.limit ?? 20));\n const ascending = filter.ascending === true;\n const columns = columnsOf(this.model);\n const primary = filter.orderBy ?? (this.pks[0] as keyof InferModel<C> & string);\n const keys = [primary as string, ...this.pks.filter((k) => k !== primary)];\n\n const parts: WhereInput<InferModel<C>>[] = [];\n const scoped = this.scopeFilters(filter.filters);\n if (scoped) parts.push(scoped);\n if (filter.cursor) {\n parts.push(\n afterCursor<InferModel<C>>(\n keys,\n decodeCursor(columns, keys, filter.cursor),\n ascending,\n ),\n );\n }\n\n let query =\n parts.length === 0\n ? select(this.model)\n : select(this.model).where(\n parts.length === 1\n ? (parts[0] as WhereInput<InferModel<C>>)\n : (and<InferModel<C>>(...parts) as unknown as WhereInput<InferModel<C>>),\n );\n for (const key of keys) {\n query = query.orderBy(\n key as keyof InferModel<C> & string,\n ascending ? \"asc\" : \"desc\",\n );\n }\n\n const rows = await this.session.execute(query.limit(limit + 1)).all();\n const items = rows.slice(0, limit);\n const last = items[items.length - 1];\n return {\n items,\n nextCursor:\n rows.length > limit && last !== undefined\n ? encodeCursor(columns, keys, last as Record<string, unknown>)\n : null,\n };\n }\n\n /**\n * Whether any **other** row matches `filters`.\n *\n * The uniqueness check for an update: \"is this e-mail taken by somebody else?\"\n * A plain `exists` would find the row being edited and report a false conflict.\n *\n * @param filters What to look for.\n * @param key The primary key to exclude — the row being updated.\n * @returns True when a different row matches.\n */\n async existsExcluding(\n filters: WhereInput<InferModel<C>>,\n key: unknown,\n ): Promise<boolean> {\n const excluded = primaryKeyFilter(this.model, key) as WhereInput<InferModel<C>>;\n const condition = and<InferModel<C>>(filters, not<InferModel<C>>(excluded));\n return (await this.first(condition as unknown as WhereInput<InferModel<C>>)) !== null;\n }\n\n /**\n * The rows that changed since a high-water mark — the delta-sync read.\n *\n * Rows come back oldest change first, tie-broken by primary key, so a client\n * can advance its watermark monotonically and resume mid-stream with the\n * cursor. The filter is **strict** (`updatedAt > since`).\n *\n * Soft-deleted rows are included on purpose: they are the tombstones that tell\n * the client to delete its local copy. Filtering them out would strand deleted\n * rows on the device forever.\n *\n * @param filter The watermark, cursor, page size and domain filters.\n * @returns The page, plus the `serverTime` to persist as the next watermark.\n * @throws Error When the model has no `updatedAt` column (see `withTimestamps`).\n */\n async changesSince(\n filter: ChangesSinceFilter<InferModel<C>> = {},\n ): Promise<ChangesPage<InferModel<C>>> {\n this.requireColumn(\"updatedAt\", \"changesSince\");\n const serverTime = new Date();\n const clauses: WhereInput<InferModel<C>>[] = [];\n if (filter.filters) clauses.push(filter.filters);\n if (filter.since) {\n clauses.push({\n updatedAt: { gt: filter.since },\n } as unknown as WhereInput<InferModel<C>>);\n }\n const page = await this.cursorPaginate({\n cursor: filter.cursor ?? null,\n limit: filter.limit ?? 50,\n orderBy: \"updatedAt\" as keyof InferModel<C> & string,\n ascending: true,\n ...(clauses.length === 0\n ? {}\n : {\n filters:\n clauses.length === 1\n ? (clauses[0] as WhereInput<InferModel<C>>)\n : (and<InferModel<C>>(...clauses) as unknown as WhereInput<\n InferModel<C>\n >),\n }),\n });\n return { ...page, serverTime };\n }\n\n /**\n * Insert many rows, overwriting the ones that conflict — one statement.\n *\n * @param rows The rows to write.\n * @param options The conflict target, and optionally which columns to overwrite.\n * @returns The stored rows.\n * @throws Error When no conflict column is given.\n */\n async bulkUpsert(\n rows: readonly InferInsert<C>[],\n options: BulkUpsertOptions<InferModel<C>>,\n ): Promise<InferModel<C>[]> {\n if (rows.length === 0) return [];\n if (options.conflictColumns.length === 0) {\n throw new Error(\"bulkUpsert needs at least one conflict column.\");\n }\n const target = new Set<string>(options.conflictColumns as readonly string[]);\n const columns =\n options.update ??\n ([\n ...new Set(rows.flatMap((row) => Object.keys(row as Record<string, unknown>))),\n ].filter((name) => !target.has(name)) as (keyof InferModel<C> & string)[]);\n const patch: Record<string, unknown> = {};\n for (const name of columns) patch[name] = sql.excluded(name);\n return this.session\n .execute(\n insert(this.model)\n .values(rows)\n .onConflictDoUpdate(options.conflictColumns, patch as Partial<InferModel<C>>)\n .returning(),\n )\n .all();\n }\n\n /**\n * Mark a row deleted without removing it (`deletedAt = now()`).\n *\n * @param key The primary key.\n * @returns The updated row.\n * @throws Error When the model has no `deletedAt` column (see `withSoftDelete`).\n * @throws RecordNotFound When no row carries that key.\n */\n async softDelete(key: unknown): Promise<InferModel<C>> {\n this.requireColumn(\"deletedAt\", \"softDelete\");\n const filter = primaryKeyFilter(this.model, key) as WhereInput<InferModel<C>>;\n const affected = await this.update(filter, {\n deletedAt: sql.now(),\n } as unknown as Partial<InferModel<C>>);\n if (affected === 0) throw new RecordNotFound(this.model.tablename, filter);\n return this.getById(key);\n }\n\n /**\n * Bring a soft-deleted row back (`deletedAt = null`).\n *\n * @param key The primary key.\n * @returns The updated row.\n * @throws Error When the model has no `deletedAt` column.\n * @throws RecordNotFound When no row carries that key.\n */\n async restore(key: unknown): Promise<InferModel<C>> {\n this.requireColumn(\"deletedAt\", \"restore\");\n const filter = primaryKeyFilter(this.model, key) as WhereInput<InferModel<C>>;\n const affected = await this.update(filter, {\n deletedAt: null,\n } as unknown as Partial<InferModel<C>>);\n if (affected === 0) throw new RecordNotFound(this.model.tablename, filter);\n return this.getById(key);\n }\n\n /**\n * Delete many rows by primary key, in one statement.\n *\n * @param keys The primary keys.\n * @returns The number of rows actually deleted (keys that matched nothing are\n * not an error — deleting what is already gone is the desired end state).\n * @throws Error When the model has a composite primary key: `IN` over a tuple is\n * not portable, and the caller should loop or build the condition explicitly.\n */\n async deleteBatch(keys: readonly unknown[]): Promise<number> {\n if (keys.length === 0) return 0;\n if (this.pks.length > 1) {\n throw new Error(\n `${this.model.tablename} has a composite primary key (${this.pks.join(\", \")}); deleteBatch takes single-column keys only.`,\n );\n }\n const pk = this.pks[0] as string;\n const values = keys.map(\n (key) => (primaryKeyFilter(this.model, key) as Record<string, unknown>)[pk],\n );\n return this.delete({ [pk]: { in: values } } as WhereInput<InferModel<C>>);\n }\n\n /**\n * Fail loudly when a method needs a column the model does not declare.\n *\n * @param column The property name required.\n * @param method The method asking, for the message.\n * @throws Error When the column is absent.\n */\n private requireColumn(column: string, method: string): void {\n if (column in columnsOf(this.model)) return;\n throw new Error(\n `${this.model.tablename} has no \"${column}\" column, which ${method}() requires — add it with the matching mixin.`,\n );\n }\n}\n","/**\n * tempest-db-js — the transactional outbox.\n *\n * The dual-write problem: a handler that writes a row **and** publishes an event\n * cannot do both safely as two independent operations. Die after the commit and\n * the event is lost; die after the publish and a phantom event points at a row\n * that never existed.\n *\n * The fix is to write the business row and an `outbox` row in the **same\n * transaction** — either both commit or neither does — and let a separate relay\n * read pending rows and publish them. The broker can be down for minutes; the\n * events wait durably in the table.\n *\n * Atomicity here comes from `session.transaction()`, which is re-entrant: the\n * repository writes and the `publish()` run on the same session, inside one\n * block, so there is no second mechanism to learn.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport {\n type InferInsert,\n type InferModel,\n Model,\n type ModelClass,\n column,\n sql,\n} from \"./index.js\";\nimport { update } from \"./mutations.js\";\nimport { select } from \"./query.js\";\n// Imported from its own module, not from the barrel: `index.ts` re-exports this\n// module too, and a class cannot extend a binding the barrel has not initialized\n// yet.\nimport { BaseRepository } from \"./repository.js\";\n\n/** Where an outbox row is in its lifecycle. */\nexport type OutboxStatus = \"pending\" | \"sending\" | \"sent\" | \"failed\";\n\n/**\n * Build the base class for a service's outbox table.\n *\n * @param tablename The table to store events in.\n * @returns A model base carrying the outbox columns; extend it to add your own.\n *\n * @example\n * ```ts\n * class OutboxEvent extends outboxModel(\"outbox\") {}\n * ```\n */\nexport function outboxModel(name: string) {\n abstract class OutboxBase extends Model {\n static override tablename = name;\n /** Monotonic id; also the claim order, so events publish in the order written. */\n id = column.bigInteger().primaryKey();\n /** The routing key the relay publishes under. */\n topic = column.varchar(200).notNull();\n /** The event body. */\n payload = column.json<Record<string, unknown>>().notNull();\n /** Lifecycle state. */\n status = column\n .enum(\"pending\", \"sending\", \"sent\", \"failed\")\n .notNull()\n .default(\"pending\");\n /** How many publish attempts have been made. */\n attempts = column.integer().notNull().default(0);\n /** Epoch milliseconds before which the row must not be claimed (backoff). */\n availableAt = column.bigInteger().notNull().default(0n);\n /** When the row was written. */\n createdAt = column.datetime().notNull().default(sql.now());\n /** When the relay confirmed the publish. */\n sentAt = column.datetime();\n /** The last failure's message, kept for triage. */\n lastError = column.text();\n }\n return OutboxBase;\n}\n\n/** An event to write to the outbox. */\nexport interface OutboxEventInput {\n /** The routing key. */\n readonly topic: string;\n /** The event body. */\n readonly payload: Record<string, unknown>;\n /** Delay the first attempt by this many milliseconds. */\n readonly delayMs?: number;\n}\n\n/** Options for {@link OutboxRepository.claim}. */\nexport interface ClaimOptions {\n /** Only claim events on these topics. */\n readonly topics?: readonly string[];\n /** Treat the clock as this instant (tests). */\n readonly now?: number;\n}\n\n/** Options for {@link OutboxRepository.markFailed}. */\nexport interface FailOptions {\n /** Wait this long before the row can be claimed again. */\n readonly retryInMs?: number;\n /** Give up permanently instead of scheduling a retry. */\n readonly permanent?: boolean;\n}\n\n/**\n * The relay's half of the outbox: claim, confirm, and fail with backoff.\n *\n * @typeParam C - the outbox model class.\n */\nexport class OutboxRepository<C extends ModelClass> extends BaseRepository<C> {\n /**\n * Write events to the outbox.\n *\n * Call it inside the same `transaction()` as the business write — that is the\n * whole point, and it is why this does not open a transaction of its own.\n *\n * @param events One event, or many.\n * @returns The stored rows.\n */\n async publish(\n events: OutboxEventInput | readonly OutboxEventInput[],\n ): Promise<InferModel<C>[]> {\n const list = Array.isArray(events) ? events : [events as OutboxEventInput];\n if (list.length === 0) return [];\n const now = Date.now();\n return this.createMany(\n list.map(\n (event) =>\n ({\n topic: event.topic,\n payload: event.payload,\n status: \"pending\",\n attempts: 0,\n availableAt: BigInt(now + (event.delayMs ?? 0)),\n }) as unknown as InferInsert<C>,\n ),\n );\n }\n\n /**\n * Claim a batch of due events for this relay, in one statement.\n *\n * Uses `FOR UPDATE SKIP LOCKED` over a subquery, so two relays running at once\n * take **disjoint** batches instead of fighting over the same rows. SQLite has\n * no row locking and throws — a single-process relay there can claim with\n * `pending()` plus an update.\n *\n * @param limit How many events to take.\n * @param options Topic filter, and a clock override for tests.\n * @returns The claimed rows, oldest first.\n */\n async claim(limit: number, options?: ClaimOptions): Promise<InferModel<C>[]> {\n const now = options?.now ?? Date.now();\n const due = this.dueQuery(now, options?.topics)\n .orderBy(\"id\" as keyof InferModel<C> & string)\n .limit(limit)\n .forUpdate({ skipLocked: true })\n .asSubquery(\"id\" as keyof InferModel<C> & string);\n\n return this.session\n .execute(\n update(this.model)\n .set({\n status: \"sending\",\n attempts: sql.raw(\"attempts + 1\"),\n } as unknown as Partial<InferModel<C>>)\n .where({ id: { in: due } } as never)\n .returning(),\n )\n .all() as Promise<InferModel<C>[]>;\n }\n\n /**\n * The events that are due, without claiming them.\n *\n * @param limit How many to read.\n * @param options Topic filter and clock override.\n * @returns The due rows, oldest first.\n */\n async pending(limit: number, options?: ClaimOptions): Promise<InferModel<C>[]> {\n const now = options?.now ?? Date.now();\n return this.session\n .execute(\n this.dueQuery(now, options?.topics)\n .orderBy(\"id\" as keyof InferModel<C> & string)\n .limit(limit),\n )\n .all() as Promise<InferModel<C>[]>;\n }\n\n /**\n * Confirm that events were published.\n *\n * @param ids The claimed ids.\n * @returns How many rows were marked sent.\n */\n async markSent(ids: readonly bigint[]): Promise<number> {\n if (ids.length === 0) return 0;\n return this.update(\n { id: { in: ids } } as never,\n {\n status: \"sent\",\n sentAt: sql.now(),\n } as unknown as Partial<InferModel<C>>,\n );\n }\n\n /**\n * Record a failed publish, scheduling a retry unless it is permanent.\n *\n * The attempt counter was already incremented by {@link claim}, so a row that\n * keeps failing carries its own history — which is what a dead-letter policy\n * reads.\n *\n * @param id The event's id.\n * @param error The failure, for triage.\n * @param options Backoff delay, or `permanent` to stop retrying.\n * @returns How many rows were updated (0 or 1).\n */\n async markFailed(id: bigint, error: unknown, options?: FailOptions): Promise<number> {\n const message = error instanceof Error ? error.message : String(error);\n return this.update(\n { id } as never,\n {\n status: options?.permanent ? \"failed\" : \"pending\",\n availableAt: BigInt(Date.now() + (options?.retryInMs ?? 0)),\n lastError: message.slice(0, 1000),\n } as unknown as Partial<InferModel<C>>,\n );\n }\n\n /**\n * The SELECT of events that may be claimed now.\n *\n * @param now The current epoch milliseconds.\n * @param topics Optional topic filter.\n * @returns The builder, unordered.\n */\n private dueQuery(now: number, topics?: readonly string[]) {\n const where: Record<string, unknown> = {\n status: \"pending\",\n availableAt: { lte: BigInt(now) },\n };\n if (topics && topics.length > 0) where.topic = { in: topics };\n return select(this.model).where(where as never);\n }\n}\n","/**\n * tempest-db-js — capture the query plans of everything a block runs.\n *\n * A development tool for \"why is this endpoint slow?\", where the honest answer\n * usually needs the database's own opinion rather than a wall-clock number.\n * Wrapping the code beats copying SQL out of a log by hand, because the\n * parameters that go into the plan are the ones the code actually used.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\n\n/** One statement's plan. */\nexport interface QueryPlan {\n /** The statement that was explained. */\n readonly sql: string;\n /** The parameters it ran with. */\n readonly params: readonly unknown[];\n /** The database's plan, in its own shape (JSON on PostgreSQL, rows on SQLite). */\n readonly plan: unknown;\n /** A one-line, human-readable digest of the plan. */\n summary(): string;\n}\n\n/** Everything a block ran, with a plan each. */\nexport interface ExplainReport {\n /** One entry per statement, in execution order. */\n readonly plans: readonly QueryPlan[];\n /** A multi-line digest of every plan, for a test failure message or a log. */\n summary(): string;\n}\n\n/** Options for {@link explainQueries}. */\nexport interface ExplainOptions {\n /**\n * Run `EXPLAIN ANALYZE`, which **executes** the statement to measure it.\n *\n * Refused for anything that is not a `SELECT`: analyzing an `UPDATE` would\n * apply it a second time.\n */\n readonly analyze?: boolean;\n /** Explain only the statements matching this predicate. */\n readonly filter?: (sql: string) => boolean;\n}\n\n/** True for a statement that only reads. */\nexport function isReadOnlyStatement(sql: string): boolean {\n return /^\\s*(select|with)\\b/i.test(sql);\n}\n\n/**\n * Build the digest of a PostgreSQL JSON plan or a SQLite plan row set.\n *\n * @param plan The raw plan.\n * @returns One line describing it.\n */\nexport function summarizePlan(plan: unknown): string {\n if (Array.isArray(plan)) {\n const rows = plan as Record<string, unknown>[];\n const details = rows\n .map((row) => row.detail ?? row[\"QUERY PLAN\"])\n .filter((detail): detail is string => typeof detail === \"string\");\n if (details.length > 0) return details.join(\" | \");\n }\n const node = (plan as { Plan?: Record<string, unknown> } | undefined)?.Plan;\n if (node) return describePostgresNode(node);\n return JSON.stringify(plan);\n}\n\n/**\n * Describe a PostgreSQL plan node and its children, depth-first.\n *\n * @param node The plan node.\n * @returns The digest.\n */\nfunction describePostgresNode(node: Record<string, unknown>): string {\n const parts: string[] = [];\n const type = node[\"Node Type\"];\n const relation = node[\"Relation Name\"];\n const index = node[\"Index Name\"];\n parts.push(\n [type, relation ? `on ${relation}` : \"\", index ? `using ${index}` : \"\"]\n .filter((piece) => piece !== \"\")\n .join(\" \"),\n );\n const children = node.Plans;\n if (Array.isArray(children)) {\n for (const child of children as Record<string, unknown>[]) {\n parts.push(describePostgresNode(child));\n }\n }\n return parts.join(\" -> \");\n}\n\n/** A statement recorded while the block ran. */\nexport interface RecordedStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\n/**\n * Turn recorded statements into a report by explaining each one.\n *\n * Kept separate from the recording so the engine owns the driver (which is\n * private) and this module owns the plan shapes.\n *\n * @param session The session to run the `EXPLAIN` statements on.\n * @param statements What the block ran.\n * @param prefix Builds the dialect's `EXPLAIN` prefix.\n * @param options Whether to `ANALYZE`, and which statements to explain.\n * @returns The report.\n * @throws Error When `analyze` is asked for a statement that writes.\n */\nexport async function buildReport(\n session: AsyncSession,\n statements: readonly RecordedStatement[],\n prefix: (analyze: boolean) => string,\n options?: ExplainOptions,\n): Promise<ExplainReport> {\n const analyze = options?.analyze === true;\n const plans: QueryPlan[] = [];\n for (const statement of statements) {\n if (options?.filter && !options.filter(statement.sql)) continue;\n if (analyze && !isReadOnlyStatement(statement.sql)) {\n throw new Error(\n `EXPLAIN ANALYZE executes the statement, so it is refused for a write: ${statement.sql.slice(0, 80)}`,\n );\n }\n const rows = await session\n .raw(`${prefix(analyze)} ${statement.sql}`, statement.params)\n .all();\n const plan = extractPlan(rows as Record<string, unknown>[]);\n plans.push({\n sql: statement.sql,\n params: statement.params,\n plan,\n summary: () => summarizePlan(plan),\n });\n }\n return {\n plans,\n summary: () => plans.map((p) => `${p.summary()}\\n ${p.sql}`).join(\"\\n\"),\n };\n}\n\n/**\n * Unwrap the rows an `EXPLAIN` returned into the plan itself.\n *\n * PostgreSQL's `FORMAT JSON` returns one row holding an array with one plan;\n * SQLite returns one row per plan step.\n *\n * @param rows The rows the EXPLAIN returned.\n * @returns The plan, in the database's own shape.\n */\nfunction extractPlan(rows: Record<string, unknown>[]): unknown {\n const first = rows[0];\n if (rows.length === 1 && first) {\n const value = first[\"QUERY PLAN\"] ?? Object.values(first)[0];\n const parsed = typeof value === \"string\" ? tryParseJson(value) : value;\n if (Array.isArray(parsed) && parsed.length === 1) return parsed[0];\n if (parsed !== undefined && typeof parsed === \"object\") return parsed;\n }\n return rows;\n}\n\n/**\n * Parse a JSON string, returning it unchanged when it is not JSON.\n *\n * @param value The text.\n * @returns The parsed value, or the original string.\n */\nfunction tryParseJson(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n","/**\n * tempest-db-js — a repository scoped to one tenant.\n *\n * In a shared-schema multi-tenant database every tenant's rows live in the same\n * table, told apart by a column. The danger is plain: forget one\n * `WHERE tenantId = ?` and tenant A reads — or deletes — tenant B's data. The\n * footgun is not the missing predicate, it is that **every query site** has to\n * remember it.\n *\n * This binds the tenant once, at construction, and injects the predicate into\n * every read and every write the repository performs.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport type { InferModel, ModelClass, WhereInput } from \"./index.js\";\nimport { and, columnsOf } from \"./index.js\";\nimport { BaseRepository } from \"./repository.js\";\n\n/** How a repository is bound to one tenant. */\nexport interface TenantScope {\n /** The column carrying the tenant, by property name. */\n readonly column: string;\n /** The tenant's identifier. */\n readonly id: unknown;\n}\n\n/**\n * A repository whose every read and write is confined to one tenant.\n *\n * @typeParam C - the model class.\n */\nexport class TenantScopedRepository<C extends ModelClass> extends BaseRepository<C> {\n private readonly scope: TenantScope;\n\n /**\n * Bind a repository to one tenant.\n *\n * @param model The model class.\n * @param session The session to run on.\n * @param scope The tenant column and id.\n * @throws Error When the model has no such column — a scope that silently\n * matches nothing is worse than no scope at all.\n */\n constructor(model: C, session: AsyncSession, scope: TenantScope) {\n super(model, session);\n if (!(scope.column in columnsOf(model))) {\n throw new Error(\n `${model.tablename} has no \"${scope.column}\" column to scope by tenant.`,\n );\n }\n this.scope = scope;\n }\n\n /** The tenant this repository is bound to. */\n get tenantId(): unknown {\n return this.scope.id;\n }\n\n /**\n * Merge the tenant predicate into every read.\n *\n * The caller's filters are **added to**, never replaced: passing another\n * tenant's id produces a contradiction that matches nothing, which is the safe\n * outcome.\n *\n * @param filters The caller's filters.\n * @returns The filters plus the tenant predicate.\n */\n protected override scopeFilters(\n filters?: WhereInput<InferModel<C>>,\n ): WhereInput<InferModel<C>> | undefined {\n const tenant = { [this.scope.column]: this.scope.id } as WhereInput<InferModel<C>>;\n if (!filters) return tenant;\n return and<InferModel<C>>(filters, tenant) as unknown as WhereInput<InferModel<C>>;\n }\n\n /**\n * Stamp the tenant onto every row written.\n *\n * A row that arrives carrying a **different** tenant is refused rather than\n * overwritten: silently rewriting it would turn a caller's bug into data that\n * looks deliberate.\n *\n * @param data The row being written.\n * @returns The row with the tenant column set.\n * @throws Error When the row names another tenant.\n */\n protected override scopeWrite<T extends Record<string, unknown>>(data: T): T {\n const given = data[this.scope.column];\n if (given !== undefined && given !== null && given !== this.scope.id) {\n throw new Error(\n `Refusing to write ${this.model.tablename}.${this.scope.column} = ${JSON.stringify(given)} from a repository scoped to ${JSON.stringify(this.scope.id)}.`,\n );\n }\n return { ...data, [this.scope.column]: this.scope.id };\n }\n}\n","/**\n * tempest-db-js — an append-only audit trail.\n *\n * `withTimestamps` records *when* a row changed and `withAudit` records *who*\n * touched it last. Neither keeps the **history**: one entry per create, update\n * and delete, with the actor, the action and a before/after diff.\n *\n * The entries are written through the repository signals, so they land in the\n * **same transaction** as the change itself — an audit row can never reference a\n * change that was rolled back.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport {\n type InferInsert,\n type InferModel,\n Model,\n type ModelClass,\n column,\n columnsOf,\n encodeColumnValue,\n primaryKeyFilter,\n sql,\n} from \"./index.js\";\nimport { BaseRepository } from \"./repository.js\";\nimport { type SignalPayload, onSignal } from \"./signals.js\";\n\n/** What happened to the row. */\nexport type AuditAction = \"insert\" | \"update\" | \"delete\";\n\n/** A before/after pair per changed column. */\nexport type AuditDiff = Record<string, readonly [unknown, unknown]>;\n\n/**\n * Build the base class for a service's audit-log table.\n *\n * @param name The table to store entries in.\n * @returns A model base carrying the audit columns; extend it to add your own.\n *\n * @example\n * ```ts\n * class AuditLog extends auditLogModel(\"audit_log\") {}\n * ```\n */\nexport function auditLogModel(name: string) {\n abstract class AuditBase extends Model {\n static override tablename = name;\n /** Monotonic id — also the order the changes happened in. */\n id = column.bigInteger().primaryKey();\n /** The audited table. */\n tableName = column.varchar(200).notNull();\n /** The audited row's primary key, as an object. */\n rowKey = column.json<Record<string, unknown>>().notNull();\n /** What happened. */\n action = column.enum(\"insert\", \"update\", \"delete\").notNull();\n /** Who did it, when the caller could say. */\n actor = column.varchar(200);\n /** The changed columns as `[before, after]`; the whole row on insert/delete. */\n changes = column.json<AuditDiff>().notNull();\n /** When the entry was written. */\n at = column.datetime().notNull().default(sql.now());\n }\n return AuditBase;\n}\n\n/** How auditing is wired for one model. */\nexport interface AuditOptions<L extends ModelClass> {\n /** The audit-log model to write entries into. */\n readonly log: L;\n /**\n * Who is making the change.\n *\n * Called at write time, so it can read whatever request-scoped context the\n * service keeps. Return `null` for a change with no human behind it.\n */\n readonly actor?: () => string | null;\n /** Columns never worth recording (a password hash, a big blob). */\n readonly exclude?: readonly string[];\n}\n\n/**\n * The columns of a row, encoded for storage in the log's JSON column.\n *\n * @param model The audited model.\n * @param row The row.\n * @param exclude Columns to leave out.\n * @returns The row as JSON-safe values.\n */\nexport function snapshot(\n model: ModelClass,\n row: Record<string, unknown>,\n exclude: readonly string[] = [],\n): Record<string, unknown> {\n const columns = columnsOf(model);\n const out: Record<string, unknown> = {};\n for (const [name, col] of Object.entries(columns)) {\n if (exclude.includes(name)) continue;\n if (!(name in row)) continue;\n out[name] = encodeColumnValue(col, row[name]);\n }\n return out;\n}\n\n/**\n * The columns that differ between two snapshots.\n *\n * Compared **after** encoding, so a `Date` and its stored string do not read as a\n * change; a column missing from one side counts as a change to `null`.\n *\n * @param before The earlier snapshot.\n * @param after The later snapshot.\n * @returns One `[before, after]` pair per changed column.\n */\nexport function diffSnapshots(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): AuditDiff {\n const diff: Record<string, readonly [unknown, unknown]> = {};\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const from = before[key] ?? null;\n const to = after[key] ?? null;\n if (JSON.stringify(from) !== JSON.stringify(to)) diff[key] = [from, to];\n }\n return diff;\n}\n\n/** Rows read before a write, per session, so the diff has a \"before\" side. */\nconst pending = new WeakMap<AsyncSession, Map<string, Record<string, unknown>>>();\n\n/** Key a row within a session's pending map. */\nfunction pendingKey(model: ModelClass, key: Record<string, unknown>): string {\n return `${model.tablename}:${JSON.stringify(key)}`;\n}\n\n/**\n * Record every create, update and delete of a model into an audit log.\n *\n * Wired through the repository signals, so entries are written on the same\n * session — and therefore inside the same transaction — as the change. A change\n * that rolls back takes its audit entry with it.\n *\n * @param model The model to audit.\n * @param options The log model, the actor resolver and any excluded columns.\n * @returns A function that turns auditing off again.\n *\n * @example\n * ```ts\n * class AuditLog extends auditLogModel(\"audit_log\") {}\n * enableAudit(Order, { log: AuditLog, actor: () => currentUser()?.id ?? null });\n * ```\n */\nexport function enableAudit<C extends ModelClass, L extends ModelClass>(\n model: C,\n options: AuditOptions<L>,\n): () => void {\n const exclude = options.exclude ?? [];\n\n /** Write one entry through the same session the change is on. */\n const write = async (\n session: AsyncSession,\n action: AuditAction,\n row: Record<string, unknown>,\n changes: AuditDiff,\n ): Promise<void> => {\n await new BaseRepository(options.log, session).create({\n tableName: model.tablename,\n rowKey: primaryKeyFilter(model, row),\n action,\n actor: options.actor?.() ?? null,\n changes,\n } as unknown as InferInsert<L>);\n };\n\n const offs = [\n onSignal(model, \"preSave\", async ({ row, session, isInsert }: SignalPayload<C>) => {\n if (isInsert) return;\n const key = primaryKeyFilter(model, row as Record<string, unknown>);\n const before = await new BaseRepository(model, session).first(key as never);\n if (!before) return;\n let bySession = pending.get(session);\n if (!bySession) {\n bySession = new Map();\n pending.set(session, bySession);\n }\n bySession.set(\n pendingKey(model, key),\n snapshot(model, before as Record<string, unknown>, exclude),\n );\n }),\n\n onSignal(model, \"postSave\", async ({ row, session, isInsert }: SignalPayload<C>) => {\n const record = row as Record<string, unknown>;\n const after = snapshot(model, record, exclude);\n if (isInsert) {\n await write(session, \"insert\", record, toInsertDiff(after));\n return;\n }\n const key = pendingKey(model, primaryKeyFilter(model, record));\n const before = pending.get(session)?.get(key) ?? {};\n pending.get(session)?.delete(key);\n const changes = diffSnapshots(before, after);\n if (Object.keys(changes).length === 0) return;\n await write(session, \"update\", record, changes);\n }),\n\n onSignal(model, \"preDelete\", async ({ row, session }: SignalPayload<C>) => {\n const record = row as Record<string, unknown>;\n await write(\n session,\n \"delete\",\n record,\n toDeleteDiff(snapshot(model, record, exclude)),\n );\n }),\n ];\n\n return () => {\n for (const off of offs) off();\n };\n}\n\n/** An insert has no \"before\": every column reads as `[null, value]`. */\nfunction toInsertDiff(after: Record<string, unknown>): AuditDiff {\n const diff: Record<string, readonly [unknown, unknown]> = {};\n for (const [key, value] of Object.entries(after)) diff[key] = [null, value];\n return diff;\n}\n\n/** A delete has no \"after\": every column reads as `[value, null]`. */\nfunction toDeleteDiff(before: Record<string, unknown>): AuditDiff {\n const diff: Record<string, readonly [unknown, unknown]> = {};\n for (const [key, value] of Object.entries(before)) diff[key] = [value, null];\n return diff;\n}\n\n/** The row type of an audit-log model, for the reader's convenience. */\nexport type AuditEntry<L extends ModelClass> = InferModel<L>;\n","/**\n * tempest-db-js — an opt-in unit of work with an identity map.\n *\n * The default stays what it has always been: a row is a plain object, and a write\n * happens when you ask for it. This adds the other model, for the code that wants\n * it — load a row once, mutate it, and let one `flush()` work out the statements.\n *\n * Two things it buys, both of which the plain path cannot:\n *\n * - **Identity.** Loading the same row twice returns the **same object**, so two\n * references cannot drift apart in memory while both believe they are the row.\n * - **Batching.** Ten mutations become the statements the changes actually\n * require, in one transaction, instead of ten round trips.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport {\n type InferInsert,\n type InferModel,\n type ModelClass,\n type WhereInput,\n columnsOf,\n primaryKeyFilter,\n} from \"./index.js\";\nimport { BaseRepository } from \"./repository.js\";\n\n/** Phantom brand distinguishing a tracked row from a plain one. */\ndeclare const TRACKED: unique symbol;\n\n/**\n * A row the unit of work is watching.\n *\n * The brand is what makes \"tracked\" visible in the type: a function taking a\n * `Tracked<Row>` cannot be handed a plain object that nothing will ever flush.\n */\nexport type Tracked<Row> = Row & { readonly [TRACKED]?: true };\n\n/** What a flush did. */\nexport interface FlushResult {\n /** Rows inserted. */\n readonly inserted: number;\n /** Rows updated. */\n readonly updated: number;\n /** Rows deleted. */\n readonly deleted: number;\n}\n\n/** One row being tracked, with the snapshot the diff is taken against. */\ninterface Entry {\n readonly model: ModelClass;\n readonly row: Record<string, unknown>;\n /** The values as loaded; `null` for a row that does not exist yet. */\n snapshot: Record<string, unknown> | null;\n state: \"clean\" | \"new\" | \"removed\";\n}\n\n/**\n * An identity map plus a change log, flushed as one transaction.\n *\n * Scope it explicitly — one per request, one per job — and flush it before it\n * goes away. Nothing here is global.\n */\nexport class UnitOfWork {\n private readonly entries = new Map<string, Entry>();\n\n constructor(private readonly session: AsyncSession) {}\n\n /** How many rows are being tracked. */\n get size(): number {\n return this.entries.size;\n }\n\n /**\n * Load a row by primary key, or return the one already loaded.\n *\n * The second call for the same key does **not** hit the database and returns\n * the **same object** as the first.\n *\n * @param model The model class.\n * @param key The primary key — a value, or an object for a composite key.\n * @returns The tracked row, or `null` when there is none.\n */\n async get<C extends ModelClass>(\n model: C,\n key: unknown,\n ): Promise<Tracked<InferModel<C>> | null> {\n const id = this.identity(model, key);\n const known = this.entries.get(id);\n if (known)\n return known.state === \"removed\" ? null : (known.row as Tracked<InferModel<C>>);\n\n const row = await new BaseRepository(model, this.session).getByIdOrNull(key);\n if (row === null) return null;\n const tracked = { ...(row as Record<string, unknown>) };\n this.entries.set(id, {\n model,\n row: tracked,\n snapshot: { ...tracked },\n state: \"clean\",\n });\n return tracked as Tracked<InferModel<C>>;\n }\n\n /**\n * Track an existing row that was loaded elsewhere.\n *\n * @param model The model class.\n * @param row The row, as loaded.\n * @returns The tracked object — the same one, if this row is already known.\n */\n track<C extends ModelClass>(model: C, row: InferModel<C>): Tracked<InferModel<C>> {\n const id = this.identity(model, row);\n const known = this.entries.get(id);\n if (known) return known.row as Tracked<InferModel<C>>;\n const tracked = { ...(row as Record<string, unknown>) };\n this.entries.set(id, {\n model,\n row: tracked,\n snapshot: { ...tracked },\n state: \"clean\",\n });\n return tracked as Tracked<InferModel<C>>;\n }\n\n /**\n * Schedule an insert.\n *\n * @param model The model class.\n * @param data The row to insert; it must carry the primary key, since the\n * identity map is keyed by it and a database-generated id is not known yet.\n * @returns The tracked row.\n * @throws Error When the key is incomplete.\n */\n add<C extends ModelClass>(model: C, data: InferInsert<C>): Tracked<InferModel<C>> {\n const row = { ...(data as Record<string, unknown>) };\n const id = this.identity(model, row);\n this.entries.set(id, { model, row, snapshot: null, state: \"new\" });\n return row as Tracked<InferModel<C>>;\n }\n\n /**\n * Schedule a delete.\n *\n * A row added and then removed before the flush simply disappears — no\n * statement is emitted for it.\n *\n * @param model The model class.\n * @param row The row to delete.\n */\n remove<C extends ModelClass>(model: C, row: InferModel<C>): void {\n const id = this.identity(model, row);\n const known = this.entries.get(id);\n if (known?.state === \"new\") {\n this.entries.delete(id);\n return;\n }\n if (known) {\n known.state = \"removed\";\n return;\n }\n this.entries.set(id, {\n model,\n row: { ...(row as Record<string, unknown>) },\n snapshot: { ...(row as Record<string, unknown>) },\n state: \"removed\",\n });\n }\n\n /**\n * Write every pending change, in one transaction.\n *\n * Order is inserts, then updates, then deletes — the order that keeps a\n * foreign key satisfied when a new parent and its children are flushed\n * together. It is **not** a topological sort: a graph that needs one should be\n * flushed in stages.\n *\n * A statement that fails takes the whole flush with it, since it all runs in\n * one transaction. The tracked state is left untouched in that case, so the\n * caller can fix and flush again.\n *\n * @returns How many rows were inserted, updated and deleted.\n */\n async flush(): Promise<FlushResult> {\n const inserts = [...this.entries.values()].filter((e) => e.state === \"new\");\n const removals = [...this.entries.values()].filter((e) => e.state === \"removed\");\n const updates = [...this.entries.values()]\n .filter((e) => e.state === \"clean\" && e.snapshot !== null)\n .map((entry) => ({ entry, patch: diffRow(entry) }))\n .filter(({ patch }) => Object.keys(patch).length > 0);\n\n if (inserts.length === 0 && updates.length === 0 && removals.length === 0) {\n return { inserted: 0, updated: 0, deleted: 0 };\n }\n\n const result = await this.session.transaction(async (tx) => {\n let inserted = 0;\n let updated = 0;\n let deleted = 0;\n for (const entry of inserts) {\n await new BaseRepository(entry.model, tx).create(\n entry.row as InferInsert<ModelClass>,\n );\n inserted += 1;\n }\n for (const { entry, patch } of updates) {\n updated += await new BaseRepository(entry.model, tx).update(\n primaryKeyFilter(entry.model, entry.row) as WhereInput<InferModel<ModelClass>>,\n patch as Partial<InferModel<ModelClass>>,\n );\n }\n for (const entry of removals) {\n deleted += await new BaseRepository(entry.model, tx).delete(\n primaryKeyFilter(entry.model, entry.row) as WhereInput<InferModel<ModelClass>>,\n );\n }\n return { inserted, updated, deleted };\n });\n\n for (const entry of inserts) entry.state = \"clean\";\n for (const { entry } of updates) entry.snapshot = { ...entry.row };\n for (const entry of inserts) entry.snapshot = { ...entry.row };\n for (const entry of removals) {\n this.entries.delete(this.identity(entry.model, entry.row));\n }\n return result;\n }\n\n /** Forget everything tracked, without writing. */\n clear(): void {\n this.entries.clear();\n }\n\n /**\n * The identity-map key for a row or a primary key.\n *\n * @param model The model class.\n * @param key The row, or the key.\n * @returns A stable string key.\n */\n private identity(model: ModelClass, key: unknown): string {\n return `${model.tablename}:${JSON.stringify(primaryKeyFilter(model, key))}`;\n }\n}\n\n/**\n * The columns of a tracked row that differ from its snapshot.\n *\n * Only real columns are compared, so a property somebody hung on the object does\n * not turn into a write.\n *\n * @param entry The tracked entry.\n * @returns The patch to write, empty when nothing changed.\n */\nfunction diffRow(entry: Entry): Record<string, unknown> {\n const patch: Record<string, unknown> = {};\n const snapshot = entry.snapshot ?? {};\n for (const name of Object.keys(columnsOf(entry.model))) {\n if (!(name in entry.row)) continue;\n const before = snapshot[name] ?? null;\n const after = entry.row[name] ?? null;\n if (!sameValue(before, after)) patch[name] = entry.row[name];\n }\n return patch;\n}\n\n/**\n * Compare two column values for the diff.\n *\n * `Date` and `Uint8Array` are compared by content: two objects holding the same\n * instant are not a change, and reference equality would report one on every\n * flush.\n *\n * @param a The snapshot's value.\n * @param b The current value.\n * @returns True when they are the same value.\n */\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (a instanceof Uint8Array && b instanceof Uint8Array) {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n }\n if (typeof a === \"object\" && typeof b === \"object\" && a !== null && b !== null) {\n return JSON.stringify(a) === JSON.stringify(b);\n }\n return false;\n}\n","/**\n * tempest-db-js — Phase 4b: engine, session, real execution.\n *\n * Async by default (`createEngine`), with an optional sync engine for SQLite\n * (`createSyncEngine`). The database is identified by its URL (Phase 4a's\n * `parseDatabaseUrl`); the dialect compiles the builder AST to `{ sql, params }`\n * (Phase 4a's `getDialect`); a driver runs it; rows are coerced back to native\n * types via `coerceRow` (the serialization layer).\n *\n * SQLite execution is real and tested here through Node's built-in `node:sqlite`.\n * `better-sqlite3` and `postgres` (postgres.js) are lazy-loaded peer drivers.\n */\n\nimport { createRequire } from \"node:module\";\nimport { col, fn } from \"./conditions.js\";\nimport { type BaseDialect, getDialect } from \"./dialect.js\";\nimport {\n type ExplainOptions,\n type ExplainReport,\n type RecordedStatement,\n buildReport,\n} from \"./explain.js\";\nimport { type ModelClass, columnNamesOf, columnsOf } from \"./index.js\";\nimport type { JoinBuilder, JoinNode } from \"./join.js\";\nimport type { InsertBuilder, InsertNode, UpdateBuilder } from \"./mutations.js\";\nimport { type SelectBuilder, select } from \"./query.js\";\nimport { coerceRow } from \"./serialize.js\";\nimport type { SetBuilder } from \"./setops.js\";\nimport { UnitOfWork } from \"./unit-of-work.js\";\nimport { type Dialect, type ParsedDatabaseUrl, parseDatabaseUrl } from \"./url.js\";\n\n/** A synchronous `require`, usable from both ESM and CJS builds. */\nconst nodeRequire = createRequire(import.meta.url);\n\n// ---------------------------------------------------------------------------\n// driver layer\n// ---------------------------------------------------------------------------\n\n/** The outcome of running one statement. */\nexport interface DriverResult {\n /** Returned rows (SELECT or `RETURNING`); empty otherwise. */\n readonly rows: Record<string, unknown>[];\n /** Rows affected by an INSERT/UPDATE/DELETE. */\n readonly changes: number;\n}\n\n/** A synchronous driver (SQLite). */\nexport interface SyncDriver {\n execute(sql: string, params: readonly unknown[]): DriverResult;\n /** Lazily iterate rows (for `.stream()`), if the driver supports it. */\n iterate?(\n sql: string,\n params: readonly unknown[],\n ): IterableIterator<Record<string, unknown>>;\n close(): void;\n}\n\n/** An asynchronous driver (PostgreSQL, or an async-wrapped SQLite). */\nexport interface AsyncDriver {\n execute(sql: string, params: readonly unknown[]): Promise<DriverResult>;\n /** Lazily iterate rows (for `.stream()`), if the driver supports it. */\n iterate?(\n sql: string,\n params: readonly unknown[],\n ): AsyncIterableIterator<Record<string, unknown>>;\n /**\n * Reserve a single pinned connection for the duration of a transaction.\n * Pooled drivers (PostgreSQL) MUST implement this so `BEGIN`/`COMMIT` and the\n * statements between them all run on the same connection. Single-connection\n * drivers (SQLite) may omit it — `transaction` then runs on the shared handle.\n */\n reserve?(): Promise<ReservedAsyncDriver>;\n close(): Promise<void>;\n}\n\n/** An {@link AsyncDriver} pinned to one connection, used inside a transaction. */\nexport interface ReservedAsyncDriver extends AsyncDriver {\n /** Return the pinned connection to the pool. */\n release(): Promise<void>;\n}\n\n/** Encode a JS value into something a SQLite driver can bind. */\nfunction encodeSqliteParam(value: unknown): unknown {\n if (value === undefined || value === null) return null;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Uint8Array) return value;\n if (typeof value === \"object\") return JSON.stringify(value);\n return value; // number, bigint, string\n}\n\n/** SQLite driver backed by Node's built-in `node:sqlite` (zero install). */\nexport class NodeSqliteDriver implements SyncDriver {\n // biome-ignore lint/suspicious/noExplicitAny: node:sqlite DatabaseSync has no shipped types here.\n private readonly db: any;\n /**\n * Prepared-statement cache keyed by SQL text. tempest-db-js always\n * parameterizes, so a query shape maps to one stable SQL string — reusing the\n * compiled statement avoids re-`prepare()` on every call (the dominant cost of\n * per-row inserts and point lookups).\n */\n // biome-ignore lint/suspicious/noExplicitAny: node:sqlite StatementSync has no shipped types here.\n private readonly statements = new Map<string, any>();\n\n // biome-ignore lint/suspicious/noExplicitAny: accept an already-open DatabaseSync handle.\n constructor(database: any) {\n this.db = database;\n }\n\n /**\n * Open a `node:sqlite` database at the given path (or `:memory:`).\n *\n * @param path The database file, or `\":memory:\"`.\n * @param options Passed straight to `DatabaseSync` (`readOnly`, `timeout`, …).\n * @returns A driver over the open handle.\n */\n static open(\n path: string,\n options?: Readonly<Record<string, unknown>>,\n ): NodeSqliteDriver {\n // Lazy require so importing tempest-db-js never forces the built-in module to load.\n const { DatabaseSync } = nodeRequire(\"node:sqlite\") as {\n DatabaseSync: new (path: string, options?: Record<string, unknown>) => unknown;\n };\n return new NodeSqliteDriver(\n options ? new DatabaseSync(path, { ...options }) : new DatabaseSync(path),\n );\n }\n\n /** Return the cached prepared statement for `sql`, preparing it on first use. */\n // biome-ignore lint/suspicious/noExplicitAny: statement type is unavailable here.\n private prepare(sql: string): any {\n const cached = this.statements.get(sql);\n if (cached) return cached;\n const stmt = this.db.prepare(sql);\n this.statements.set(sql, stmt);\n return stmt;\n }\n\n execute(sql: string, params: readonly unknown[]): DriverResult {\n const stmt = this.prepare(sql);\n const bound = params.map(encodeSqliteParam);\n if (returnsRows(sql)) {\n return { rows: stmt.all(...bound) as Record<string, unknown>[], changes: 0 };\n }\n const info = stmt.run(...bound);\n return { rows: [], changes: Number(info.changes ?? 0) };\n }\n\n *iterate(\n sql: string,\n params: readonly unknown[],\n ): IterableIterator<Record<string, unknown>> {\n const stmt = this.prepare(sql);\n const bound = params.map(encodeSqliteParam);\n yield* stmt.iterate(...bound) as IterableIterator<Record<string, unknown>>;\n }\n\n close(): void {\n this.statements.clear();\n this.db.close();\n }\n}\n\n/**\n * SQLite driver backed by the `better-sqlite3` peer dependency.\n *\n * Selected with `{ driver: \"better-sqlite3\" }` or the URL suffix\n * `sqlite+better-sqlite3://…`; the built-in `node:sqlite` stays the default, so\n * nothing has to be installed to use SQLite. Pick this one when the service\n * already runs on better-sqlite3, or needs what it exposes and `node:sqlite`\n * does not — `pragma()`, loadable extensions, its own WAL helpers.\n *\n * Row shape matches {@link NodeSqliteDriver}: plain objects, BLOBs as `Buffer`\n * (a `Uint8Array` subclass), which is what `coerceRow` already expects.\n */\nexport class BetterSqliteDriver implements SyncDriver {\n // biome-ignore lint/suspicious/noExplicitAny: the peer dep's types are optional here.\n private readonly db: any;\n /** Prepared-statement cache keyed by SQL text — see {@link NodeSqliteDriver}. */\n // biome-ignore lint/suspicious/noExplicitAny: see above.\n private readonly statements = new Map<string, any>();\n\n // biome-ignore lint/suspicious/noExplicitAny: accept an already-open Database handle.\n constructor(database: any) {\n this.db = database;\n }\n\n /**\n * Open a `better-sqlite3` database at the given path (or `\":memory:\"`).\n *\n * @param path The database file, or `\":memory:\"`.\n * @param options Passed straight to `new Database()` (`readonly`, `timeout`, …).\n * @returns A driver over the open handle.\n * @throws If `better-sqlite3` is not installed — it is an optional peer\n * dependency, so the error names the package to install.\n */\n static open(\n path: string,\n options?: Readonly<Record<string, unknown>>,\n ): BetterSqliteDriver {\n let Database: new (path: string, options?: Record<string, unknown>) => unknown;\n try {\n const mod = nodeRequire(\"better-sqlite3\") as\n | { default?: typeof Database }\n | typeof Database;\n Database = ((mod as { default?: typeof Database }).default ??\n mod) as typeof Database;\n } catch (cause) {\n throw new Error(\n 'The \"better-sqlite3\" driver requires the better-sqlite3 package: npm install better-sqlite3',\n { cause },\n );\n }\n return new BetterSqliteDriver(\n options ? new Database(path, { ...options }) : new Database(path),\n );\n }\n\n /** Return the cached prepared statement for `sql`, preparing it on first use. */\n // biome-ignore lint/suspicious/noExplicitAny: statement type is optional here.\n private prepare(sql: string): any {\n const cached = this.statements.get(sql);\n if (cached) return cached;\n const stmt = this.db.prepare(sql);\n this.statements.set(sql, stmt);\n return stmt;\n }\n\n execute(sql: string, params: readonly unknown[]): DriverResult {\n const stmt = this.prepare(sql);\n const bound = params.map(encodeSqliteParam);\n // better-sqlite3 throws when all()/run() is called on the wrong statement\n // kind, and it already knows which is which — ask it instead of guessing.\n if (stmt.reader) {\n return { rows: stmt.all(...bound) as Record<string, unknown>[], changes: 0 };\n }\n const info = stmt.run(...bound);\n return { rows: [], changes: Number(info.changes ?? 0) };\n }\n\n *iterate(\n sql: string,\n params: readonly unknown[],\n ): IterableIterator<Record<string, unknown>> {\n const stmt = this.prepare(sql);\n const bound = params.map(encodeSqliteParam);\n yield* stmt.iterate(...bound) as IterableIterator<Record<string, unknown>>;\n }\n\n close(): void {\n this.statements.clear();\n this.db.close();\n }\n}\n\n/**\n * True when a statement yields rows.\n *\n * `node:sqlite` needs this decided up front (`all()` vs `run()`), and getting it\n * wrong is silent: a statement that returns rows, run through `run()`, reports\n * zero rows instead of failing. So the list covers every row-producing form —\n * `WITH` (a CTE query), `EXPLAIN`, `VALUES` and `TABLE`, not only `SELECT`.\n */\nfunction returnsRows(sql: string): boolean {\n return (\n /^\\s*(select|with|values|table|pragma|explain)\\b/i.test(sql) ||\n /\\breturning\\b/i.test(sql)\n );\n}\n\n// ---------------------------------------------------------------------------\n// executable builders & row extraction\n// ---------------------------------------------------------------------------\n\n/* biome-ignore lint/suspicious/noExplicitAny: builder generics are irrelevant to execution dispatch. */\ntype AnySelect = SelectBuilder<any, any, any>;\n/* biome-ignore lint/suspicious/noExplicitAny: see above. */\ntype AnyInsert = InsertBuilder<any, any, any>;\n/* biome-ignore lint/suspicious/noExplicitAny: only the guarded flag matters. */\ntype GuardedUpdate = UpdateBuilder<any, true, any>;\n/* biome-ignore lint/suspicious/noExplicitAny: only the guarded flag matters. */\ntype GuardedDelete = import(\"./mutations.js\").DeleteBuilder<any, true, any>;\n/* biome-ignore lint/suspicious/noExplicitAny: join sources are irrelevant to dispatch. */\ntype AnyJoin = JoinBuilder<any>;\n/* biome-ignore lint/suspicious/noExplicitAny: the row type is irrelevant to dispatch. */\ntype AnySet = SetBuilder<any>;\n\n/**\n * A builder that is safe to execute. UPDATE/DELETE are accepted only once\n * guarded (after `.where()` or `.unguarded()`) — an unguarded full-table write\n * is a compile error at the execution boundary.\n */\nexport type Executable =\n | AnySelect\n | AnyInsert\n | GuardedUpdate\n | GuardedDelete\n | AnyJoin\n | AnySet;\n\n/** The element type a builder yields on execution. */\nexport type RowOf<B> = B extends { readonly __row: infer R } ? R : never;\n\n/** Internals shared between single-table builders, read structurally at runtime. */\ninterface SingleBuilder {\n readonly node: Parameters<BaseDialect[\"compile\"]>[0];\n readonly source: ModelClass;\n}\n\n/** Internals of a join builder, read structurally at runtime. */\ninterface JoinRunnable {\n readonly node: JoinNode;\n readonly sources: Readonly<Record<string, ModelClass>>;\n}\n\n/** Split one flat `alias.column` row into a coerced composite `{ alias: {...} }`. */\nfunction splitJoinRow(\n node: JoinNode,\n sources: Readonly<Record<string, ModelClass>>,\n raw: Record<string, unknown>,\n): Record<string, unknown> {\n const leftAliases = new Set(\n node.joins.filter((j) => j.kind === \"left\").map((j) => j.alias),\n );\n const out: Record<string, unknown> = {};\n for (const [alias, model] of Object.entries(sources)) {\n const sub: Record<string, unknown> = {};\n const names = columnNamesOf(model);\n let allNull = true;\n for (const colName of Object.keys(columnsOf(model))) {\n const value = raw[`${alias}.${colName}`];\n if (value !== null && value !== undefined) allNull = false;\n sub[names?.[colName] ?? colName] = value;\n }\n out[alias] = leftAliases.has(alias) && allNull ? null : coerceRow(model, sub);\n }\n return out;\n}\n\n/** Coerce one raw driver row into the builder's native row shape. */\nfunction coerceOne(builder: unknown, raw: Record<string, unknown>): unknown {\n const node = (builder as { node: { kind: string; pick?: string } }).node;\n if (node.kind === \"join_select\") {\n const b = builder as unknown as JoinRunnable;\n // `pick` asked for one source, flat: coerce it like a single-table row\n // instead of splitting the composite.\n if (node.pick) {\n const model = b.sources[node.pick];\n if (model) return coerceRow(model, raw);\n }\n return splitJoinRow(b.node, b.sources, raw);\n }\n const b = builder as unknown as SingleBuilder;\n return coerceRow(b.source, raw);\n}\n\n/** Coerce raw driver rows into the builder's native row shape. */\nfunction mapRows(builder: unknown, raw: Record<string, unknown>[]): unknown[] {\n return raw.map((r) => coerceOne(builder, r));\n}\n\n// ---------------------------------------------------------------------------\n// results\n// ---------------------------------------------------------------------------\n\n/** Raised by `.one()` when the row count is not exactly one. */\nexport class NoResultError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NoResultError\";\n }\n}\n\n/** A short, safe preview of a bound parameter for an error message. */\nfunction previewParam(value: unknown): string {\n if (value === null || value === undefined) return \"null\";\n if (value instanceof Uint8Array) return `<${value.length} bytes>`;\n const text = typeof value === \"string\" ? value : String(value);\n return text.length > 64 ? `${text.slice(0, 61)}...` : text;\n}\n\n/**\n * Raised when the driver rejects a statement. Wraps the original driver error\n * and attaches the offending SQL and its bound parameters, so a failure points\n * at the exact query instead of an opaque driver message.\n */\nexport class QueryExecutionError extends Error {\n constructor(\n /** The original error thrown by the driver. */\n override readonly cause: unknown,\n /** The SQL that failed. */\n readonly sql: string,\n /** The bound parameters, in order. */\n readonly params: readonly unknown[],\n ) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n super(\n `Query failed: ${reason}\\n SQL: ${sql}\\n params: [${params\n .map(previewParam)\n .join(\", \")}]`,\n );\n this.name = \"QueryExecutionError\";\n }\n}\n\n/**\n * A hook invoked for every statement a session runs (query logging / tracing).\n * Errors thrown by the logger are ignored so logging never breaks execution.\n */\nexport type QueryLogger = (event: {\n readonly sql: string;\n readonly params: readonly unknown[];\n}) => void;\n\n/**\n * What a statement did, reported **after** it ran.\n *\n * `onQuery` fires before execution, so it cannot time anything; this is the other\n * half. It fires on the failure path too, with `error` set — a slow statement that\n * then fails is exactly the one worth seeing.\n */\nexport interface QueryEndEvent {\n /** The statement text. */\n readonly sql: string;\n /** The bound parameters, in placeholder order. */\n readonly params: readonly unknown[];\n /** Wall-clock time the driver took, in milliseconds. */\n readonly durationMs: number;\n /** Rows returned (a SELECT or `RETURNING`), or rows affected by a write. */\n readonly rowCount: number;\n /** The driver's error, when the statement failed. */\n readonly error?: unknown;\n}\n\n/**\n * Called after every statement, with its duration.\n *\n * Errors thrown by the hook are ignored, like {@link QueryLogger}.\n */\nexport type QueryEndLogger = (event: QueryEndEvent) => void;\n\n/** The per-statement hooks a session carries. */\nexport interface QueryHooks {\n /** Called before a statement runs. */\n readonly onQuery?: QueryLogger | undefined;\n /** Called after a statement runs, with its duration. */\n readonly onQueryEnd?: QueryEndLogger | undefined;\n /** When set, `onQueryEnd` fires only for statements at least this slow (ms). */\n readonly slowQueryMs?: number | undefined;\n}\n\n/** Invoke a query logger, swallowing any error it throws. */\nfunction emitLog(\n hooks: QueryHooks | undefined,\n sql: string,\n params: readonly unknown[],\n): void {\n const logger = hooks?.onQuery;\n if (!logger) return;\n try {\n logger({ sql, params });\n } catch {\n // logging must never break execution\n }\n}\n\n/** Read a monotonic clock, in milliseconds. */\nfunction now(): number {\n return performance.now();\n}\n\n/**\n * Invoke the end-of-statement hook, swallowing any error it throws.\n *\n * @param hooks The session's hooks.\n * @param event What the statement did.\n */\nfunction emitQueryEnd(hooks: QueryHooks | undefined, event: QueryEndEvent): void {\n const logger = hooks?.onQueryEnd;\n if (!logger) return;\n const threshold = hooks?.slowQueryMs;\n if (threshold !== undefined && event.durationMs < threshold) return;\n try {\n logger(event);\n } catch {\n // logging must never break execution\n }\n}\n\n/** Rows a driver result reports — returned rows, or rows affected by a write. */\nfunction resultRowCount(result: DriverResult): number {\n return result.rows.length > 0 ? result.rows.length : result.changes;\n}\n\nfunction firstScalar(row: Record<string, unknown> | undefined): unknown {\n if (!row) return null;\n const keys = Object.keys(row);\n return keys.length > 0 ? row[keys[0] as string] : null;\n}\n\n/** Synchronous result view over already-fetched rows. */\nexport class SyncResult<Row> {\n constructor(\n private readonly rows: Row[],\n private readonly changes: number,\n ) {}\n\n all(): Row[] {\n return this.rows;\n }\n first(): Row | null {\n return this.rows[0] ?? null;\n }\n one(): Row {\n if (this.rows.length !== 1) {\n throw new NoResultError(`expected exactly one row, got ${this.rows.length}`);\n }\n return this.rows[0] as Row;\n }\n oneOrNull(): Row | null {\n if (this.rows.length > 1) {\n throw new NoResultError(`expected at most one row, got ${this.rows.length}`);\n }\n return this.rows[0] ?? null;\n }\n scalar(): unknown {\n return firstScalar(this.rows[0] as Record<string, unknown> | undefined);\n }\n scalars(): unknown[] {\n return this.rows.map((r) => firstScalar(r as Record<string, unknown>));\n }\n rowsAffected(): number {\n return this.changes;\n }\n}\n\n/** Asynchronous result view (terminals return Promises). */\nexport class AsyncResult<Row> {\n constructor(private readonly inner: Promise<SyncResult<Row>>) {}\n\n async all(): Promise<Row[]> {\n return (await this.inner).all();\n }\n async first(): Promise<Row | null> {\n return (await this.inner).first();\n }\n async one(): Promise<Row> {\n return (await this.inner).one();\n }\n async oneOrNull(): Promise<Row | null> {\n return (await this.inner).oneOrNull();\n }\n async scalar(): Promise<unknown> {\n return (await this.inner).scalar();\n }\n async scalars(): Promise<unknown[]> {\n return (await this.inner).scalars();\n }\n async rowsAffected(): Promise<number> {\n return (await this.inner).rowsAffected();\n }\n}\n\n// ---------------------------------------------------------------------------\n// sessions\n// ---------------------------------------------------------------------------\n\nlet savepointCounter = 0;\n\n/**\n * True when a builder asks for `RETURNING` on a dialect that has none, so the\n * session must insert and read the row back instead of compiling one statement.\n */\nfunction needsInsertReadBack(\n dialect: BaseDialect,\n node: Parameters<BaseDialect[\"compile\"]>[0],\n): node is InsertNode {\n return dialect.name === \"mysql\" && node.kind === \"insert\" && node.returning !== null;\n}\n\n/** The model's single primary-key property name, for the insert read-back. */\nfunction singlePrimaryKey(model: ModelClass): string {\n const keys = Object.entries(columnsOf(model))\n .filter(([, column]) => column.flags.primaryKey)\n .map(([name]) => name);\n if (keys.length !== 1) {\n throw new Error(\n `${model.tablename} needs exactly one primary key to read an insert back on a dialect without RETURNING; found ${keys.length}.`,\n );\n }\n return keys[0] as string;\n}\n\n/** Reject a `raw()` call whose parameters are not an array. */\nfunction assertRawParams(params: readonly unknown[]): void {\n if (!Array.isArray(params)) {\n throw new TypeError(\n \"session.raw(sql, params) takes an array of bound parameters — never interpolate values into the SQL string.\",\n );\n }\n}\n\n/**\n * A transaction isolation level, in the SQL standard's names.\n *\n * The database's default is what you get without asking: `read committed` on\n * PostgreSQL and MySQL's `repeatable read`. SQLite has only `serializable`.\n */\nexport type IsolationLevel =\n | \"read uncommitted\"\n | \"read committed\"\n | \"repeatable read\"\n | \"serializable\";\n\n/** Characteristics for one transaction block. */\nexport interface TransactionOptions {\n /**\n * The isolation level for this block.\n *\n * Raising it is how the queue and outbox patterns get their invariants: under\n * `read committed` two workers can both pass the same check before either\n * commits. Asking for a level a dialect does not implement throws.\n */\n readonly isolation?: IsolationLevel;\n /**\n * Open the block read-only, so the database itself rejects a write in it.\n * PostgreSQL and MySQL only; SQLite throws.\n */\n readonly readOnly?: boolean;\n}\n\n/**\n * Refuse transaction characteristics on a block that is only joining an outer one.\n *\n * Isolation is fixed when the transaction opens; asking for it on a nested block\n * cannot take effect, and silently ignoring the request would leave the caller\n * believing they got a guarantee they do not have.\n *\n * @param options The options passed to the nested call.\n * @throws Error When any characteristic was requested.\n */\nfunction assertNoNestedOptions(options?: TransactionOptions): void {\n if (options?.isolation || options?.readOnly) {\n throw new Error(\n \"Transaction characteristics can only be set on the outermost transaction() — a nested block joins the one already open.\",\n );\n }\n}\n\n/** A synchronous unit of work (SQLite). */\nexport class SyncSession {\n constructor(\n private readonly driver: SyncDriver,\n private readonly dialect: BaseDialect,\n /** Optional per-statement hooks (query tracing and timing). */\n private readonly hooks?: QueryHooks,\n ) {}\n\n /** Open `transaction()` blocks on this session; only the outermost commits. */\n private depth = 0;\n\n /** Log, run, time, and error-wrap one raw statement. */\n private exec(sql: string, params: readonly unknown[]): DriverResult {\n emitLog(this.hooks, sql, params);\n const startedAt = now();\n try {\n const result = this.driver.execute(sql, params);\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount: resultRowCount(result),\n });\n return result;\n } catch (error) {\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount: 0,\n error,\n });\n throw new QueryExecutionError(error, sql, params);\n }\n }\n\n /**\n * Run a raw, parameterized SQL statement (synchronous) — the runtime counterpart of the\n * migrations' `Op.execute`.\n *\n * A query builder never covers all of SQL, and without an escape hatch a single\n * unsupported query forces a whole second database stack alongside this one. Use\n * it for what the builder cannot yet express, and keep everything else typed.\n *\n * The statement goes through the same path as a compiled one: it is logged via\n * `onQuery`, wrapped in {@link QueryExecutionError} on failure, and runs on the\n * reserved connection inside `transaction()`.\n *\n * @param sql The statement text. Placeholders only (`$1` / `?` per dialect) —\n * never interpolate a value into this string.\n * @param params The bound parameters, in placeholder order.\n * @param options Pass `as` to coerce the returned rows with a model's column\n * types (and its column-name mapping).\n * @returns The result view over the returned rows.\n * @throws Error When `params` is not an array — the guard against calling this\n * with an interpolated string and no parameters by mistake.\n *\n * @example\n * ```ts\n * const claimed = await session.raw<OutboundRow>(\n * `UPDATE outbound_messages SET status = 'sending'\n * WHERE id = ANY($1) RETURNING *`,\n * [ids],\n * { as: Outbound },\n * ).all();\n * ```\n */\n raw<Row = Record<string, unknown>>(\n sql: string,\n params: readonly unknown[] = [],\n options?: { readonly as?: ModelClass },\n ): SyncResult<Row> {\n assertRawParams(params);\n const result = this.exec(sql, params);\n const model = options?.as;\n const rows = (\n model ? result.rows.map((row) => coerceRow(model, row)) : result.rows\n ) as Row[];\n return new SyncResult<Row>(rows, result.changes);\n }\n\n /** Compile, run, and coerce a builder into a result. */\n execute<B extends Executable>(builder: B): SyncResult<RowOf<B>> {\n const node = (builder as unknown as { node: Parameters<BaseDialect[\"compile\"]>[0] })\n .node;\n const { sql, params } = this.dialect.compile(node);\n const result = this.exec(sql, params);\n const rows = mapRows(builder, result.rows) as RowOf<B>[];\n return new SyncResult<RowOf<B>>(rows, result.changes);\n }\n\n /** Run `fn` inside a transaction: commit on success, rollback on throw. */\n /**\n * How many `transaction()` blocks are open on this session.\n *\n * The counter is what makes a service that orchestrates two repositories work:\n * both hold the same session, so an inner block **joins** the outer one instead\n * of emitting a second `BEGIN`, and only the outermost exit commits.\n */\n get transactionDepth(): number {\n return this.depth;\n }\n\n /** Whether a `transaction()` block is currently open on this session. */\n get inTransaction(): boolean {\n return this.depth > 0;\n }\n\n /**\n * Run `fn` inside a transaction, committing on a clean exit and rolling back on\n * a throw.\n *\n * **Re-entrant:** a nested call joins the block already open on this session —\n * one `BEGIN`, one `COMMIT`, and an inner failure rolls the whole thing back.\n * To recover from an inner failure without discarding the outer work, use\n * {@link beginNested}, which is a real savepoint.\n *\n * @param fn The body; receives the session to work through.\n * @returns Whatever `fn` returned.\n */\n transaction<T>(fn: (tx: SyncSession) => T, options?: TransactionOptions): T {\n if (this.depth > 0) {\n assertNoNestedOptions(options);\n this.depth += 1;\n try {\n return fn(this);\n } finally {\n this.depth -= 1;\n }\n }\n for (const stmt of this.dialect.beginStatements(options)) this.exec(stmt, []);\n this.depth = 1;\n try {\n const out = fn(this);\n this.exec(\"COMMIT\", []);\n return out;\n } catch (error) {\n this.exec(\"ROLLBACK\", []);\n throw error;\n } finally {\n this.depth = 0;\n }\n }\n\n /** Run `fn` inside a SAVEPOINT (nested transaction). */\n beginNested<T>(fn: (sp: SyncSession) => T): T {\n savepointCounter += 1;\n const name = `qsp_${savepointCounter}`;\n this.exec(`SAVEPOINT ${name}`, []);\n try {\n const out = fn(this);\n this.exec(`RELEASE ${name}`, []);\n return out;\n } catch (error) {\n this.exec(`ROLLBACK TO ${name}`, []);\n throw error;\n }\n }\n\n /**\n * Lazily iterate result rows without materializing them all. Falls back to a\n * buffered fetch when the driver has no native iteration.\n */\n *stream<B extends Executable>(builder: B): IterableIterator<RowOf<B>> {\n const node = (builder as unknown as { node: Parameters<BaseDialect[\"compile\"]>[0] })\n .node;\n const { sql, params } = this.dialect.compile(node);\n emitLog(this.hooks, sql, params);\n if (this.driver.iterate) {\n const startedAt = now();\n let rowCount = 0;\n try {\n for (const raw of this.driver.iterate(sql, params)) {\n rowCount++;\n yield coerceOne(builder, raw) as RowOf<B>;\n }\n } catch (error) {\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount,\n error,\n });\n throw new QueryExecutionError(error, sql, params);\n }\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount,\n });\n return;\n }\n for (const raw of this.exec(sql, params).rows) {\n yield coerceOne(builder, raw) as RowOf<B>;\n }\n }\n\n close(): void {\n this.driver.close();\n }\n\n /** `using session = ...` closes the driver when the scope exits. */\n [Symbol.dispose](): void {\n this.close();\n }\n}\n\n/** An asynchronous unit of work. */\nexport class AsyncSession {\n constructor(\n private readonly driver: AsyncDriver,\n private readonly dialect: BaseDialect,\n /** Optional per-statement hooks (query tracing and timing). */\n private readonly hooks?: QueryHooks,\n ) {}\n\n /** Open `transaction()` blocks on this session; only the outermost commits. */\n private depth = 0;\n\n /** Log, run, time, and error-wrap one raw statement. */\n private async exec(sql: string, params: readonly unknown[]): Promise<DriverResult> {\n emitLog(this.hooks, sql, params);\n const startedAt = now();\n try {\n const result = await this.driver.execute(sql, params);\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount: resultRowCount(result),\n });\n return result;\n } catch (error) {\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount: 0,\n error,\n });\n throw new QueryExecutionError(error, sql, params);\n }\n }\n\n /**\n * Run a raw, parameterized SQL statement — the runtime counterpart of the\n * migrations' `Op.execute`.\n *\n * A query builder never covers all of SQL, and without an escape hatch a single\n * unsupported query forces a whole second database stack alongside this one. Use\n * it for what the builder cannot yet express, and keep everything else typed.\n *\n * The statement goes through the same path as a compiled one: it is logged via\n * `onQuery`, wrapped in {@link QueryExecutionError} on failure, and runs on the\n * reserved connection inside `transaction()`.\n *\n * @param sql The statement text. Placeholders only (`$1` / `?` per dialect) —\n * never interpolate a value into this string.\n * @param params The bound parameters, in placeholder order.\n * @param options Pass `as` to coerce the returned rows with a model's column\n * types (and its column-name mapping).\n * @returns The result view over the returned rows.\n * @throws Error When `params` is not an array — the guard against calling this\n * with an interpolated string and no parameters by mistake.\n *\n * @example\n * ```ts\n * const claimed = await session.raw<OutboundRow>(\n * `UPDATE outbound_messages SET status = 'sending'\n * WHERE id = ANY($1) RETURNING *`,\n * [ids],\n * { as: Outbound },\n * ).all();\n * ```\n */\n raw<Row = Record<string, unknown>>(\n sql: string,\n params: readonly unknown[] = [],\n options?: { readonly as?: ModelClass },\n ): AsyncResult<Row> {\n assertRawParams(params);\n const model = options?.as;\n const inner = this.exec(sql, params).then((result) => {\n const rows = (\n model ? result.rows.map((row) => coerceRow(model, row)) : result.rows\n ) as Row[];\n return new SyncResult<Row>(rows, result.changes);\n });\n return new AsyncResult<Row>(inner);\n }\n\n execute<B extends Executable>(builder: B): AsyncResult<RowOf<B>> {\n const node = (builder as unknown as { node: Parameters<BaseDialect[\"compile\"]>[0] })\n .node;\n if (needsInsertReadBack(this.dialect, node)) {\n return new AsyncResult<RowOf<B>>(\n this.insertAndReadBack(builder as unknown as SingleBuilder, node),\n );\n }\n const { sql, params } = this.dialect.compile(node);\n const inner = this.exec(sql, params).then((result) => {\n const rows = mapRows(builder, result.rows) as RowOf<B>[];\n return new SyncResult<RowOf<B>>(rows, result.changes);\n });\n return new AsyncResult<RowOf<B>>(inner);\n }\n\n /**\n * Honor `.returning()` on a dialect without `RETURNING`, by inserting and then\n * reading the row back by key.\n *\n * Both statements must run on **one** connection, because `LAST_INSERT_ID()` is\n * per-connection: outside a transaction the pooled driver is reserved for the\n * pair; inside one, the session already holds a pinned connection (a reserved\n * driver exposes no `reserve`), so it runs there directly.\n *\n * @param builder The insert builder, for its source model.\n * @param node The insert AST, whose `returning` drives the read-back.\n * @returns The result view over the read-back row.\n * @throws Error When the insert writes more than one row — `LAST_INSERT_ID()`\n * identifies only the first, and the rest are consecutive only under some\n * auto-increment lock modes.\n */\n private async insertAndReadBack<Row>(\n builder: SingleBuilder,\n node: InsertNode,\n ): Promise<SyncResult<Row>> {\n if (node.values.length !== 1) {\n throw new Error(\n `${this.dialect.name} has no RETURNING, and reading back a multi-row insert is not reliable — insert one row at a time, or drop .returning().`,\n );\n }\n const model = builder.source;\n const pk = singlePrimaryKey(model);\n const supplied = (node.values[0] as Record<string, unknown>)[pk];\n const readBack = select(model).where(\n supplied === undefined || supplied === null\n ? col(pk).eq(fn.call(\"LAST_INSERT_ID\"))\n : { [pk]: supplied },\n );\n const insertSql = this.dialect.compile({ ...node, returning: null });\n const selectSql = this.dialect.compile(\n node.returning === \"*\" || node.returning === null\n ? readBack.node\n : { ...readBack.node, columns: node.returning },\n );\n const run = async (driver: AsyncDriver): Promise<SyncResult<Row>> => {\n const scoped = new AsyncSession(driver, this.dialect, this.hooks);\n const written = await scoped.exec(insertSql.sql, insertSql.params);\n const read = await scoped.exec(selectSql.sql, selectSql.params);\n const rows = read.rows.map((row) => coerceRow(model, row)) as Row[];\n return new SyncResult<Row>(rows, written.changes);\n };\n if (!this.driver.reserve) return run(this.driver);\n const reserved = await this.driver.reserve();\n try {\n return await run(reserved);\n } finally {\n await reserved.release();\n }\n }\n\n /** Lazily iterate result rows. Uses driver streaming when available. */\n async *stream<B extends Executable>(builder: B): AsyncIterableIterator<RowOf<B>> {\n const node = (builder as unknown as { node: Parameters<BaseDialect[\"compile\"]>[0] })\n .node;\n const { sql, params } = this.dialect.compile(node);\n emitLog(this.hooks, sql, params);\n if (this.driver.iterate) {\n const startedAt = now();\n let rowCount = 0;\n try {\n for await (const raw of this.driver.iterate(sql, params)) {\n rowCount++;\n yield coerceOne(builder, raw) as RowOf<B>;\n }\n } catch (error) {\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount,\n error,\n });\n throw new QueryExecutionError(error, sql, params);\n }\n emitQueryEnd(this.hooks, {\n sql,\n params,\n durationMs: now() - startedAt,\n rowCount,\n });\n return;\n }\n const result = await this.exec(sql, params);\n for (const raw of result.rows) {\n yield coerceOne(builder, raw) as RowOf<B>;\n }\n }\n\n /**\n * How many `transaction()` blocks are open on this session.\n *\n * The counter is what makes a service that orchestrates two repositories work:\n * both hold the same session, so an inner block **joins** the outer one instead\n * of emitting a second `BEGIN`, and only the outermost exit commits.\n */\n get transactionDepth(): number {\n return this.depth;\n }\n\n /** Whether a `transaction()` block is currently open on this session. */\n get inTransaction(): boolean {\n return this.depth > 0;\n }\n\n /**\n * Run `fn` inside a transaction, committing on a clean exit and rolling back on\n * a throw.\n *\n * **Re-entrant:** a nested call joins the block already open on this session,\n * so a service orchestrating several repositories bound to the same session\n * gets one `BEGIN` and one `COMMIT`, not two of each. An inner failure rolls the\n * whole block back; use {@link beginNested} for a savepoint that can be\n * recovered from.\n *\n * Pooled drivers (PostgreSQL) pin one connection for the block: `BEGIN`/`COMMIT`\n * and every statement between them have to run on the same connection, or\n * postgres.js rejects the raw transaction. Single-connection drivers (SQLite)\n * skip the reservation.\n *\n * @param fn The body; receives the session to work through (the pinned one, on a\n * pooled driver).\n * @returns Whatever `fn` returned.\n */\n async transaction<T>(\n fn: (tx: AsyncSession) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T> {\n if (this.depth > 0) {\n assertNoNestedOptions(options);\n this.depth += 1;\n try {\n return await fn(this);\n } finally {\n this.depth -= 1;\n }\n }\n const begin = this.dialect.beginStatements(options);\n if (this.driver.reserve) {\n const reserved = await this.driver.reserve();\n const scoped = new AsyncSession(reserved, this.dialect, this.hooks);\n try {\n for (const stmt of begin) await scoped.exec(stmt, []);\n scoped.depth = 1;\n const out = await fn(scoped);\n await scoped.exec(\"COMMIT\", []);\n return out;\n } catch (error) {\n await scoped.exec(\"ROLLBACK\", []);\n throw error;\n } finally {\n scoped.depth = 0;\n await reserved.release();\n }\n }\n for (const stmt of begin) await this.exec(stmt, []);\n this.depth = 1;\n try {\n const out = await fn(this);\n await this.exec(\"COMMIT\", []);\n return out;\n } catch (error) {\n await this.exec(\"ROLLBACK\", []);\n throw error;\n } finally {\n this.depth = 0;\n }\n }\n\n /**\n * Run `fn` inside a `SAVEPOINT` (a nested transaction that can be rolled back on\n * its own).\n *\n * This is the difference from a nested {@link transaction}: a savepoint that\n * fails discards **only** its own work, so the enclosing block can catch the\n * error and carry on. A nested `transaction()` joins the outer block, and its\n * failure takes the whole block down.\n *\n * Must run inside an open transaction — PostgreSQL rejects a savepoint outside a\n * transaction block.\n *\n * @param fn The body; receives the same session.\n * @returns Whatever `fn` returned.\n */\n async beginNested<T>(fn: (sp: AsyncSession) => Promise<T>): Promise<T> {\n savepointCounter += 1;\n const name = `qsp_${savepointCounter}`;\n await this.exec(`SAVEPOINT ${name}`, []);\n try {\n const out = await fn(this);\n await this.exec(`RELEASE ${name}`, []);\n return out;\n } catch (error) {\n await this.exec(`ROLLBACK TO ${name}`, []);\n throw error;\n }\n }\n\n /**\n * Open an opt-in {@link UnitOfWork} over this session.\n *\n * The default stays a plain object written when you ask; this is the other\n * model, for code that prefers to mutate and flush once.\n *\n * @returns A new, empty unit of work.\n */\n unitOfWork(): UnitOfWork {\n return new UnitOfWork(this);\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n /** `await using session = ...` closes the driver when the scope exits. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// engines\n// ---------------------------------------------------------------------------\n\n/** Connection-pool tuning (PostgreSQL; ignored by SQLite). */\nexport interface PoolOptions {\n /** Max connections in the pool. */\n readonly size?: number;\n /** Close a connection after it sits idle this long (ms). */\n readonly idleTimeoutMs?: number;\n /** Give up acquiring a connection after this long (ms). */\n readonly connectTimeoutMs?: number;\n /**\n * Validate a connection before pinning it for a transaction.\n *\n * A pooled connection can die without the pool noticing — a failover, a\n * pgbouncer restart, a firewall dropping an idle socket. The damage lands on\n * whoever picks it up next, and it lands worst on a transaction: `BEGIN`\n * succeeds, a statement mid-block fails, and the block dies halfway.\n *\n * With this on, `transaction()` runs `SELECT 1` on the reserved connection\n * first and reserves another one if that fails. It costs a round trip per\n * transaction, which is why it is opt-in.\n *\n * PostgreSQL only — MySQL throws, and SQLite has no pool.\n */\n readonly prePing?: boolean;\n /**\n * Close and reopen a connection older than this (ms), regardless of activity.\n *\n * The blunt companion to {@link prePing}: it bounds how long a connection can\n * have been alive, which is what keeps a slow leak (a server-side timeout, a\n * load balancer's idle cap) from becoming a mystery error hours later.\n *\n * PostgreSQL only — MySQL throws, and SQLite has no pool.\n */\n readonly recycleMs?: number;\n}\n\n/**\n * A server-side notice (a PostgreSQL `NOTICE`). The shape is the driver's own —\n * passed through untouched rather than normalized, since what is useful in it\n * differs per database.\n */\nexport type NoticeLogger = (notice: Record<string, unknown>) => void;\n\n/**\n * SQLite journal modes accepted by `PRAGMA journal_mode`.\n *\n * `\"wal\"` is the one worth reaching for on a server: readers stop blocking the\n * writer. It needs a real file — an in-memory database refuses it and stays on\n * `\"memory\"`, which this layer reports as an error rather than a silent no-op.\n */\nexport type SqliteJournalMode =\n | \"delete\"\n | \"truncate\"\n | \"persist\"\n | \"memory\"\n | \"wal\"\n | \"off\";\n\n/** Durability levels accepted by `PRAGMA synchronous`. */\nexport type SqliteSynchronous = \"off\" | \"normal\" | \"full\" | \"extra\";\n\n/**\n * Per-connection SQLite settings, applied right after the handle opens.\n *\n * Pragmas are **per connection**, not per database file, so they belong to the\n * engine rather than to a migration. Only `foreignKeys` has a default that\n * changes behavior; every other field is emitted only when given, so an existing\n * database keeps whatever it was configured with.\n */\nexport interface SqliteOptions {\n /**\n * Enforce `FOREIGN KEY` constraints. **Defaults to `true`.**\n *\n * SQLite ships with enforcement `OFF`, per connection, so a declared foreign\n * key is decorative until someone turns it on: an orphan `INSERT` is accepted\n * and `ON DELETE CASCADE` never fires. tempest-db-js turns it on, which makes\n * the same model behave the same on all three databases.\n *\n * Set it to `false` only for the case it exists for — loading a dump whose\n * insert order does not respect the graph.\n */\n readonly foreignKeys?: boolean;\n /** `PRAGMA journal_mode`. Omitted: the database keeps its current mode. */\n readonly journalMode?: SqliteJournalMode;\n /** `PRAGMA busy_timeout`, in milliseconds. How long a writer waits on a lock. */\n readonly busyTimeoutMs?: number;\n /** `PRAGMA synchronous`. Durability vs write throughput. */\n readonly synchronous?: SqliteSynchronous;\n}\n\n/** Options shared by both engine flavors. */\nexport interface EngineOptions {\n /**\n * Override the driver detected from the URL.\n *\n * SQLite ships two: `\"node:sqlite\"` (the built-in, default — nothing to\n * install) and `\"better-sqlite3\"` (the optional peer dependency). PostgreSQL\n * runs on `\"postgres\"` (postgres.js) and MySQL on `\"mysql2\"`; naming those is\n * a no-op today, kept so the option means the same thing everywhere.\n *\n * A name this dialect does not have throws — passing `{ driver: \"sqlite3\" }`\n * is a decision that would otherwise be silently ignored.\n *\n * The `+suffix` in the URL (`sqlite+better-sqlite3:///app.db`) selects the same\n * way, with one difference: a suffix naming a driver from another ecosystem\n * (`sqlite+aiosqlite`, `postgresql+asyncpg`) is ignored rather than rejected,\n * so a URL copied from a Python service still connects.\n */\n readonly driver?: string;\n /** Connection-pool tuning (PostgreSQL only). */\n readonly pool?: PoolOptions;\n /**\n * Called for every statement a session runs — SQL + bound params. Use for\n * query logging/tracing. Thrown errors are swallowed so it never breaks a query.\n */\n readonly onQuery?: QueryLogger;\n /**\n * Called for every server-side notice (`CREATE TABLE IF NOT EXISTS` on an\n * existing table, `DROP ... IF EXISTS` on a missing one, and so on).\n *\n * **Without this, notices are silenced.** postgres.js defaults to printing them\n * with `console.log`, which drops a nine-line object into the host service's\n * stdout in the middle of its structured log — on every boot, since a migration\n * runner is usually the first thing to run. Writing to the host's stdout is the\n * application's decision, not a library's, so the default is to say nothing and\n * let you route them:\n *\n * ```ts\n * createEngine(url, { onNotice: (n) => logger.debug({ pg: n }, \"postgres notice\") });\n * ```\n *\n * Thrown errors are swallowed, like `onQuery`.\n */\n readonly onNotice?: NoticeLogger;\n /**\n * Options passed straight to the underlying driver, applied **last** so they\n * win over everything this layer derives (`pool`, `onNotice`).\n *\n * The escape hatch for what the typed surface does not model and is not going\n * to — postgres.js `connection`/`types`/`transform`/`ssl`, mysql2's own\n * settings, `node:sqlite`'s `readOnly` — so a gap need not become a feature\n * request.\n */\n readonly driverOptions?: Readonly<Record<string, unknown>>;\n /**\n * Per-connection SQLite pragmas (`foreign_keys`, `journal_mode`, …), applied\n * as soon as the handle opens. Passing it to a PostgreSQL or MySQL engine\n * throws — the settings have no meaning there, and silently ignoring them is\n * how a durability choice gets lost.\n */\n readonly sqlite?: SqliteOptions;\n /**\n * Called **after** every statement, with how long the driver took.\n *\n * `onQuery` fires before execution, so it cannot time anything; this is the\n * other half, and it fires on the failure path too (with `error` set). Use it\n * for latency metrics, tracing spans, and finding the query dragging p99.\n *\n * Errors thrown by the hook are swallowed, like `onQuery`.\n */\n readonly onQueryEnd?: QueryEndLogger;\n /**\n * Only report statements at least this slow (milliseconds) to `onQueryEnd`.\n *\n * The cheapest slow-query log there is: set a threshold, log what crosses it.\n * Without it every statement is reported.\n */\n readonly slowQueryMs?: number;\n}\n\n/**\n * Collect the per-statement hooks out of the engine options.\n *\n * @param options The engine options, if any.\n * @returns The hook bundle a session carries, or `undefined` when none is set.\n */\nfunction queryHooks(options?: EngineOptions): QueryHooks | undefined {\n if (!options?.onQuery && !options?.onQueryEnd) return undefined;\n return {\n onQuery: options.onQuery,\n onQueryEnd: options.onQueryEnd,\n slowQueryMs: options.slowQueryMs,\n };\n}\n\n/** Invoke a notice logger, swallowing any error it throws. */\nfunction emitNotice(logger: NoticeLogger | undefined, notice: unknown): void {\n if (!logger) return;\n try {\n logger(notice as Record<string, unknown>);\n } catch {\n // logging must never break a connection\n }\n}\n\n/** A synchronous engine (SQLite only). */\nexport class SyncEngine {\n readonly dialect: Dialect = \"sqlite\";\n\n constructor(\n private readonly driver: SyncDriver,\n private readonly hooks?: QueryHooks,\n ) {}\n\n session(): SyncSession {\n return new SyncSession(this.driver, getDialect(\"sqlite\"), this.hooks);\n }\n\n transaction<T>(fn: (tx: SyncSession) => T, options?: TransactionOptions): T {\n return this.session().transaction(fn, options);\n }\n\n close(): void {\n this.driver.close();\n }\n\n /** `using engine = createSyncEngine(...)` closes the pool when the scope exits. */\n [Symbol.dispose](): void {\n this.close();\n }\n}\n\n/** An asynchronous engine. */\nexport class AsyncEngine {\n constructor(\n private readonly driver: AsyncDriver,\n readonly dialect: Dialect,\n private readonly hooks?: QueryHooks,\n ) {}\n\n session(): AsyncSession {\n return new AsyncSession(this.driver, getDialect(this.dialect), this.hooks);\n }\n\n transaction<T>(\n fn: (tx: AsyncSession) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T> {\n return this.session().transaction(fn, options);\n }\n\n /**\n * Run `fn` and return the query plan of every statement it ran.\n *\n * The block gets its own session over a **recording** driver, so the plans are\n * built from the statements and the parameters the code really used — not from\n * SQL copied out of a log by hand. A development tool: it runs the block once\n * and then one `EXPLAIN` per statement, so keep it out of the hot path.\n *\n * @param fn The code to observe; receives the recording session.\n * @param options `analyze: true` to measure (refused for writes), `filter` to\n * explain only some statements.\n * @returns The report, one plan per statement in execution order.\n * @throws Error When `analyze` is requested for a statement that writes, or on\n * a dialect that has no `EXPLAIN ANALYZE`.\n *\n * @example\n * ```ts\n * const report = await engine.explain(async (session) => {\n * await new BaseRepository(Order, session).paginate({ page: 3 });\n * });\n * console.log(report.summary());\n * ```\n */\n async explain(\n fn: (session: AsyncSession) => Promise<unknown>,\n options?: ExplainOptions,\n ): Promise<ExplainReport> {\n const statements: RecordedStatement[] = [];\n const recorder: AsyncDriver = {\n execute: async (sql, params) => {\n statements.push({ sql, params });\n return this.driver.execute(sql, params);\n },\n close: () => Promise.resolve(),\n ...(this.driver.iterate\n ? {\n iterate: (sql: string, params: readonly unknown[]) => {\n statements.push({ sql, params });\n return (this.driver.iterate as NonNullable<AsyncDriver[\"iterate\"]>)(\n sql,\n params,\n );\n },\n }\n : {}),\n };\n await fn(new AsyncSession(recorder, getDialect(this.dialect), this.hooks));\n return buildReport(\n this.session(),\n statements,\n (analyze) => getDialect(this.dialect).explainPrefix(analyze),\n options,\n );\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n /** `await using engine = createEngine(...)` closes the pool when the scope exits. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.close();\n }\n}\n\n/**\n * Adapt a sync **or** async driver to the async interface.\n *\n * `await` normalizes both: a sync driver returns a plain value, an async one a\n * promise, and awaiting either yields the result. That is what lets the migration\n * CLI take one code path instead of branching on a difference it cannot detect\n * from the object's shape.\n *\n * @param driver Either driver flavor.\n * @returns An async driver delegating to it.\n */\nexport function toAsyncDriver(driver: SyncDriver | AsyncDriver): AsyncDriver {\n return {\n async execute(sql: string, params: readonly unknown[]): Promise<DriverResult> {\n return await driver.execute(sql, params);\n },\n async close(): Promise<void> {\n await driver.close();\n },\n };\n}\n\n/** Wrap a sync driver so it satisfies the async interface (SQLite async path). */\nfunction asAsync(driver: SyncDriver): AsyncDriver {\n const syncIterate = driver.iterate?.bind(driver);\n return {\n execute: (sql, params) => Promise.resolve(driver.execute(sql, params)),\n close: () => Promise.resolve(driver.close()),\n ...(syncIterate\n ? {\n iterate: async function* (sql: string, params: readonly unknown[]) {\n yield* syncIterate(sql, params);\n },\n }\n : {}),\n };\n}\n\n/** The SQLite drivers this package can open. */\ntype SqliteDriverName = \"node:sqlite\" | \"better-sqlite3\";\n\n/** Accepted spellings of each SQLite driver, lowercased. */\nconst SQLITE_DRIVER_ALIASES: Readonly<Record<string, SqliteDriverName>> = {\n \"node:sqlite\": \"node:sqlite\",\n \"node-sqlite\": \"node:sqlite\",\n node: \"node:sqlite\",\n \"better-sqlite3\": \"better-sqlite3\",\n better_sqlite3: \"better-sqlite3\",\n bettersqlite3: \"better-sqlite3\",\n};\n\n/** Accepted spellings of the one driver each server dialect runs on. */\nconst SERVER_DRIVER_ALIASES: Readonly<Record<string, readonly string[]>> = {\n postgresql: [\"postgres\", \"postgres.js\", \"postgresjs\", \"pg\"],\n mysql: [\"mysql\", \"mysql2\"],\n};\n\n/**\n * Validate an explicit `options.driver` against a server dialect.\n *\n * PostgreSQL and MySQL each have exactly one driver here, so the option can only\n * confirm it. Confirming is allowed; naming something else is the error the\n * silent no-op used to hide.\n *\n * @param dialect The dialect parsed from the URL.\n * @param driver The explicit override, if any.\n * @throws If `driver` is not a spelling of that dialect's driver.\n */\nfunction checkServerDriver(dialect: Dialect, driver: string | undefined): void {\n if (!driver) return;\n const accepted = SERVER_DRIVER_ALIASES[dialect] ?? [];\n if (accepted.includes(driver.toLowerCase())) return;\n throw new Error(\n `Unknown ${dialect} driver ${JSON.stringify(driver)}; tempest-db-js runs ${dialect} on ${JSON.stringify(accepted[0])}.`,\n );\n}\n\n/**\n * Decide which SQLite driver to open: the explicit option first, then the URL\n * suffix, then the built-in.\n *\n * @param parsed The parsed URL, for its `+suffix`.\n * @param options Engine options, for an explicit `driver`.\n * @returns The driver to open.\n * @throws If `options.driver` names a driver this package does not ship. An\n * unrecognized URL suffix does not throw — `sqlite+aiosqlite:///app.db` comes\n * from a Python service and means \"SQLite\", so it falls through to the default.\n */\nfunction resolveSqliteDriver(\n parsed: ParsedDatabaseUrl,\n options?: EngineOptions,\n): SqliteDriverName {\n const explicit = options?.driver;\n if (explicit) {\n const resolved = SQLITE_DRIVER_ALIASES[explicit.toLowerCase()];\n if (!resolved) {\n throw new Error(\n `Unknown SQLite driver ${JSON.stringify(explicit)}; supported: \"node:sqlite\" (built-in, default) and \"better-sqlite3\".`,\n );\n }\n return resolved;\n }\n const fromUrl = parsed.driver\n ? SQLITE_DRIVER_ALIASES[parsed.driver.toLowerCase()]\n : undefined;\n return fromUrl ?? \"node:sqlite\";\n}\n\n/** `PRAGMA synchronous` names, in the numeric order SQLite reports them back. */\nconst SQLITE_SYNCHRONOUS_LEVELS: readonly SqliteSynchronous[] = [\n \"off\",\n \"normal\",\n \"full\",\n \"extra\",\n];\n\n/**\n * Read the single value a query-form pragma returns.\n *\n * @param driver The open SQLite driver.\n * @param name The pragma to read.\n * @returns Its value, or `null` when the pragma reported nothing.\n */\nfunction readPragma(driver: SyncDriver, name: string): unknown {\n const { rows } = driver.execute(`PRAGMA ${name}`, []);\n const first = rows[0];\n if (!first) return null;\n return Object.values(first)[0] ?? null;\n}\n\n/**\n * Apply the configured pragmas to a freshly opened SQLite connection.\n *\n * Every pragma is **verified by reading it back**. SQLite answers a setting it\n * cannot honor by keeping the old value and saying nothing — `journal_mode=wal`\n * on an in-memory database is the common case — so writing the pragma and moving\n * on would report success for a setting that never took.\n *\n * @param driver The open driver.\n * @param options The requested settings; `foreignKeys` defaults to `true`.\n * @param path The database path, used only to explain a refused setting.\n * @throws Error When a value is out of range, or when SQLite refused a setting.\n */\nfunction applySqlitePragmas(\n driver: SyncDriver,\n options: SqliteOptions | undefined,\n path: string,\n): void {\n const foreignKeys = options?.foreignKeys ?? true;\n driver.execute(`PRAGMA foreign_keys = ${foreignKeys ? \"ON\" : \"OFF\"}`, []);\n if (Number(readPragma(driver, \"foreign_keys\")) !== (foreignKeys ? 1 : 0)) {\n throw new Error(\n `SQLite refused PRAGMA foreign_keys = ${foreignKeys ? \"ON\" : \"OFF\"} — the build may lack foreign-key support.`,\n );\n }\n\n const journalMode = options?.journalMode;\n if (journalMode) {\n driver.execute(`PRAGMA journal_mode = ${journalMode}`, []);\n const actual = String(readPragma(driver, \"journal_mode\") ?? \"\").toLowerCase();\n if (actual !== journalMode) {\n const hint =\n journalMode === \"wal\" && actual === \"memory\"\n ? \" — an in-memory database cannot use WAL.\"\n : \".\";\n throw new Error(\n `SQLite refused PRAGMA journal_mode = ${journalMode} for ${JSON.stringify(path)} and stayed on ${JSON.stringify(actual)}${hint}`,\n );\n }\n }\n\n const busyTimeoutMs = options?.busyTimeoutMs;\n if (busyTimeoutMs !== undefined) {\n if (!Number.isInteger(busyTimeoutMs) || busyTimeoutMs < 0) {\n throw new Error(\n `busyTimeoutMs must be a non-negative integer, got ${JSON.stringify(busyTimeoutMs)}.`,\n );\n }\n driver.execute(`PRAGMA busy_timeout = ${busyTimeoutMs}`, []);\n if (Number(readPragma(driver, \"busy_timeout\")) !== busyTimeoutMs) {\n throw new Error(`SQLite refused PRAGMA busy_timeout = ${busyTimeoutMs}.`);\n }\n }\n\n const synchronous = options?.synchronous;\n if (synchronous) {\n driver.execute(`PRAGMA synchronous = ${synchronous}`, []);\n const actual = SQLITE_SYNCHRONOUS_LEVELS[Number(readPragma(driver, \"synchronous\"))];\n if (actual !== synchronous) {\n throw new Error(\n `SQLite refused PRAGMA synchronous = ${synchronous} and stayed on ${JSON.stringify(actual ?? \"unknown\")}.`,\n );\n }\n }\n}\n\n/**\n * Reject SQLite-only settings on a dialect that has no such thing.\n *\n * @param dialect The dialect parsed from the URL.\n * @param options The engine options.\n * @throws Error When `sqlite` options are given for a server dialect.\n */\nfunction checkSqliteOptions(dialect: Dialect, options?: EngineOptions): void {\n if (!options?.sqlite) return;\n throw new Error(\n `The \"sqlite\" engine options are SQLite-only; ${dialect} has no per-connection pragmas.`,\n );\n}\n\n/** Open a SQLite sync driver from a parsed URL, passing driver options through. */\nfunction openSqliteDriver(\n parsed: ParsedDatabaseUrl,\n options?: EngineOptions,\n): SyncDriver {\n const path = parsed.database ?? \":memory:\";\n const driver =\n resolveSqliteDriver(parsed, options) === \"better-sqlite3\"\n ? BetterSqliteDriver.open(path, options?.driverOptions)\n : NodeSqliteDriver.open(path, options?.driverOptions);\n try {\n applySqlitePragmas(driver, options?.sqlite, path);\n } catch (error) {\n driver.close();\n throw error;\n }\n return driver;\n}\n\n/**\n * Create a **synchronous** engine from a database URL. SQLite only — PostgreSQL\n * has no sane synchronous driver in Node, so a Postgres URL throws, pointing at\n * the async `createEngine`.\n *\n * @param url A SQLite URL, e.g. `\"sqlite:///app.db\"` or `\"sqlite://:memory:\"`.\n * @param options Engine options.\n * @returns A `SyncEngine`.\n */\nexport function createSyncEngine(url: string, options?: EngineOptions): SyncEngine {\n const parsed = parseDatabaseUrl(url);\n if (parsed.dialect !== \"sqlite\") {\n throw new Error(\n `createSyncEngine supports only SQLite; ${parsed.dialect} is async-only — use createEngine.`,\n );\n }\n return new SyncEngine(openSqliteDriver(parsed, options), queryHooks(options));\n}\n\n/**\n * Create an **asynchronous** engine from a database URL (the default). Works for\n * both SQLite (sync driver wrapped as async) and PostgreSQL (postgres.js,\n * lazy-loaded).\n *\n * @param url A database URL, e.g. `\"postgresql://app@localhost/app\"` or\n * `\"sqlite:///app.db\"`.\n * @param options Engine options.\n * @returns An `AsyncEngine`.\n */\nexport function createEngine(url: string, options?: EngineOptions): AsyncEngine {\n const parsed = parseDatabaseUrl(url);\n if (parsed.dialect === \"sqlite\") {\n return new AsyncEngine(\n asAsync(openSqliteDriver(parsed, options)),\n \"sqlite\",\n queryHooks(options),\n );\n }\n if (parsed.dialect === \"mysql\") {\n checkServerDriver(\"mysql\", options?.driver);\n checkSqliteOptions(\"mysql\", options);\n // MySQL: mysql2 is lazy-loaded the first time a query runs.\n return new AsyncEngine(\n createMysqlDriver(parsed.raw, options),\n \"mysql\",\n queryHooks(options),\n );\n }\n checkServerDriver(\"postgresql\", options?.driver);\n checkSqliteOptions(\"postgresql\", options);\n // PostgreSQL: postgres.js is lazy-loaded the first time a query runs.\n return new AsyncEngine(\n createPostgresDriver(parsed.raw, options),\n \"postgresql\",\n queryHooks(options),\n );\n}\n\n/** Encode a JS value into something the MySQL driver (mysql2) can bind. */\nfunction encodeMysqlParam(value: unknown): unknown {\n if (value === undefined || value === null) return null;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value instanceof Uint8Array) return value;\n if (value instanceof Date) return value;\n if (typeof value === \"object\") return JSON.stringify(value);\n return value; // number, bigint, string\n}\n\n/** Shape a mysql2 result into our `DriverResult`. */\nfunction toMysqlResult(rows: unknown): DriverResult {\n if (Array.isArray(rows)) {\n return { rows: rows as Record<string, unknown>[], changes: 0 };\n }\n // A ResultSetHeader (INSERT/UPDATE/DELETE): no rows, affectedRows is the count.\n const header = rows as { affectedRows?: number };\n return { rows: [], changes: header.affectedRows ?? 0 };\n}\n\n/**\n * MySQL driver backed by mysql2/promise (lazy-loaded peer dependency).\n *\n * Transactions reserve a single pooled connection via {@link AsyncDriver.reserve}\n * so `BEGIN`/`COMMIT` and the statements between them run on one connection.\n * MySQL has no `RETURNING`; the dialect throws if it is requested.\n */\nfunction createMysqlDriver(url: string, options?: EngineOptions): AsyncDriver {\n const pool = options?.pool;\n // biome-ignore lint/suspicious/noExplicitAny: mysql2 pool typed at call site.\n let poolHandle: any;\n const ensure = async (): Promise<void> => {\n if (poolHandle) return;\n const moduleName = \"mysql2/promise\";\n // biome-ignore lint/suspicious/noExplicitAny: dynamic import of the peer dep.\n const mod = (await import(/* @vite-ignore */ moduleName)) as any;\n const opts: Record<string, unknown> = { uri: url };\n if (pool?.prePing || pool?.recycleMs !== undefined) {\n throw new Error(\n \"pool.prePing and pool.recycleMs are PostgreSQL-only; mysql2 has no equivalent knob.\",\n );\n }\n if (pool?.size !== undefined) opts.connectionLimit = pool.size;\n if (pool?.idleTimeoutMs !== undefined) opts.idleTimeout = pool.idleTimeoutMs;\n if (pool?.connectTimeoutMs !== undefined) opts.connectTimeout = pool.connectTimeoutMs;\n Object.assign(opts, options?.driverOptions ?? {});\n poolHandle = mod.createPool(opts);\n };\n const runOn = async (\n // biome-ignore lint/suspicious/noExplicitAny: mysql2 queryable (pool or connection).\n queryable: any,\n sql: string,\n params: readonly unknown[],\n ): Promise<DriverResult> => {\n const [rows] = await queryable.query(sql, params.map(encodeMysqlParam));\n return toMysqlResult(rows);\n };\n return {\n async execute(sql: string, params: readonly unknown[]): Promise<DriverResult> {\n await ensure();\n return runOn(poolHandle, sql, params);\n },\n async reserve(): Promise<ReservedAsyncDriver> {\n await ensure();\n // biome-ignore lint/suspicious/noExplicitAny: reserved connection from mysql2.\n const conn: any = await poolHandle.getConnection();\n return {\n execute: (sql, params) => runOn(conn, sql, params),\n async release(): Promise<void> {\n conn.release();\n },\n async close(): Promise<void> {\n conn.release();\n },\n };\n },\n async close(): Promise<void> {\n if (poolHandle) await poolHandle.end();\n },\n };\n}\n\n/** Shape a postgres.js result array into our `DriverResult`. */\nfunction toPostgresResult(rows: unknown): DriverResult {\n const arr = rows as Record<string, unknown>[] & { count?: number };\n return { rows: Array.from(arr), changes: arr.count ?? arr.length };\n}\n\n/**\n * PostgreSQL driver backed by postgres.js (lazy-loaded peer dependency).\n *\n * Transactions reserve a single connection via {@link AsyncDriver.reserve} —\n * postgres.js pools connections, so a raw `BEGIN` on the shared client would run\n * on a different connection than the statements that follow (and is rejected with\n * `UNSAFE_TRANSACTION`). The reserved connection runs `BEGIN`/`COMMIT`/`ROLLBACK`\n * and every statement between them on one socket, then is released back.\n */\nfunction createPostgresDriver(url: string, options?: EngineOptions): AsyncDriver {\n const pool = options?.pool;\n // biome-ignore lint/suspicious/noExplicitAny: postgres.js client typed at call site.\n let client: any;\n const ensure = async (): Promise<void> => {\n if (client) return;\n // Non-literal specifier so the optional peer dep is not type-resolved at build.\n const moduleName = \"postgres\";\n // biome-ignore lint/suspicious/noExplicitAny: dynamic import of the peer dep.\n const mod = (await import(/* @vite-ignore */ moduleName)) as any;\n // Map our PoolOptions onto postgres.js's option names (seconds, not ms).\n const opts: Record<string, unknown> = {};\n if (pool?.size !== undefined) opts.max = pool.size;\n if (pool?.idleTimeoutMs !== undefined)\n opts.idle_timeout = Math.ceil(pool.idleTimeoutMs / 1000);\n if (pool?.connectTimeoutMs !== undefined) {\n opts.connect_timeout = Math.ceil(pool.connectTimeoutMs / 1000);\n }\n if (pool?.recycleMs !== undefined) {\n opts.max_lifetime = Math.ceil(pool.recycleMs / 1000);\n }\n opts.onnotice = (notice: unknown): void => emitNotice(options?.onNotice, notice);\n Object.assign(opts, options?.driverOptions ?? {});\n client = (mod.default ?? mod)(url, opts);\n };\n return {\n async execute(sql: string, params: readonly unknown[]): Promise<DriverResult> {\n await ensure();\n // postgres.js `unsafe` runs a parameterized string with positional params.\n return toPostgresResult(await client.unsafe(sql, params as unknown[]));\n },\n async reserve(): Promise<ReservedAsyncDriver> {\n await ensure();\n // biome-ignore lint/suspicious/noExplicitAny: reserved connection from postgres.js.\n let conn: any = await client.reserve();\n if (pool?.prePing) {\n try {\n await conn.unsafe(\"SELECT 1\", []);\n } catch {\n // The connection died while it sat in the pool. Drop it and take\n // another one — the pool opens a fresh one when none is idle.\n conn.release();\n conn = await client.reserve();\n await conn.unsafe(\"SELECT 1\", []);\n }\n }\n return {\n async execute(sql: string, params: readonly unknown[]): Promise<DriverResult> {\n return toPostgresResult(await conn.unsafe(sql, params as unknown[]));\n },\n async release(): Promise<void> {\n conn.release();\n },\n async close(): Promise<void> {\n conn.release();\n },\n };\n },\n async close(): Promise<void> {\n if (client) await client.end();\n },\n };\n}\n","/**\n * tempest-db-js — backup and restore, driven from the CLI.\n *\n * The step every runbook asks for before a migration, wrapped so it is the same\n * command against both databases in scope. It shells out to the canonical tooling\n * rather than reimplementing a dump format: `pg_dump`/`pg_restore`/`psql` on\n * PostgreSQL, and SQLite's own `VACUUM INTO` — which, unlike copying the file, is\n * consistent while the database is being written to.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { copyFile } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\nimport { NodeSqliteDriver } from \"./engine.js\";\nimport { parseDatabaseUrl } from \"./url.js\";\n\nconst run = promisify(execFile);\n\n/** Raised when the tool a dialect needs is not on the PATH. */\nexport class BackupToolMissing extends Error {\n constructor(tool: string) {\n super(`${tool} is not on the PATH; install the PostgreSQL client tools to back up.`);\n this.name = \"BackupToolMissing\";\n }\n}\n\n/** Raised for a dialect that has no backup path here. */\nexport class UnsupportedBackupBackend extends Error {\n constructor(dialect: string) {\n super(\n `Backups are implemented for PostgreSQL and SQLite; ${dialect} is not covered.`,\n );\n this.name = \"UnsupportedBackupBackend\";\n }\n}\n\n/** Options shared by backup and restore. */\nexport interface BackupOptions {\n /** Overwrite the target if it already exists (restore only). */\n readonly force?: boolean;\n /** Extra arguments appended to the underlying tool's command line. */\n readonly extraArgs?: readonly string[];\n}\n\n/** What a backup or restore did. */\nexport interface BackupResult {\n /** The file written (backup) or read (restore). */\n readonly file: string;\n /** The dialect it was taken from. */\n readonly dialect: string;\n /** The tool used, or `\"VACUUM INTO\"` / `\"copy\"` for SQLite. */\n readonly via: string;\n}\n\n/**\n * The dump format implied by a file's extension.\n *\n * `.dump` is `pg_dump`'s custom format, which `pg_restore` reads selectively and\n * in parallel; `.sql` is plain text, restored by piping it through `psql`. The\n * extension decides so the two commands cannot disagree about the file.\n *\n * @param file The backup file's path.\n * @returns Which format it is.\n */\nexport function backupFormat(file: string): \"custom\" | \"plain\" {\n return file.endsWith(\".sql\") ? \"plain\" : \"custom\";\n}\n\n/**\n * The environment a PostgreSQL tool runs with.\n *\n * The password goes in `PGPASSWORD`, never in `argv`: every process on the\n * machine can read another's command line.\n *\n * @param password The password from the URL, if any.\n * @returns The environment to spawn with.\n */\nfunction postgresEnv(password: string | null): NodeJS.ProcessEnv {\n return password ? { ...process.env, PGPASSWORD: password } : { ...process.env };\n}\n\n/**\n * The connection URL with the driver suffix removed.\n *\n * `postgresql+asyncpg://…` is a URL a Python service wrote; `pg_dump` does not\n * know that scheme.\n *\n * @param url The URL as configured.\n * @returns The URL a client tool accepts.\n */\nexport function toolUrl(url: string): string {\n return url.replace(/^([a-z0-9]+)\\+[a-z0-9_-]+:/i, \"$1:\");\n}\n\n/**\n * Run a tool, turning \"not found\" into a named error.\n *\n * @param tool The executable.\n * @param args Its arguments.\n * @param env The environment.\n * @throws BackupToolMissing When the executable is not on the PATH.\n */\nasync function spawn(\n tool: string,\n args: readonly string[],\n env: NodeJS.ProcessEnv,\n): Promise<void> {\n try {\n await run(tool, [...args], { env, maxBuffer: 1024 * 1024 * 64 });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new BackupToolMissing(tool);\n }\n throw error;\n }\n}\n\n/**\n * Write a backup of the database to a file.\n *\n * @param url The database URL.\n * @param file Where to write. On PostgreSQL the extension picks the format\n * (`.sql` plain, anything else custom).\n * @param options Extra arguments for the underlying tool.\n * @returns What was done.\n * @throws BackupToolMissing When PostgreSQL's client tools are absent.\n * @throws UnsupportedBackupBackend On a dialect without a backup path.\n */\nexport async function backupDatabase(\n url: string,\n file: string,\n options?: BackupOptions,\n): Promise<BackupResult> {\n const parsed = parseDatabaseUrl(url);\n if (parsed.dialect === \"sqlite\") {\n const source = parsed.database ?? \":memory:\";\n // VACUUM INTO, not a file copy: it is consistent even while another\n // connection is writing, and it works with WAL, where the .db file alone is\n // not the whole database.\n const driver = NodeSqliteDriver.open(source);\n try {\n driver.execute(\"VACUUM INTO ?\", [file]);\n } finally {\n driver.close();\n }\n return { file, dialect: \"sqlite\", via: \"VACUUM INTO\" };\n }\n if (parsed.dialect !== \"postgresql\") {\n throw new UnsupportedBackupBackend(parsed.dialect);\n }\n const format = backupFormat(file);\n await spawn(\n \"pg_dump\",\n [\n \"--dbname\",\n toolUrl(url),\n ...(format === \"custom\" ? [\"--format=custom\"] : []),\n \"--file\",\n file,\n ...(options?.extraArgs ?? []),\n ],\n postgresEnv(parsed.password),\n );\n return { file, dialect: \"postgresql\", via: \"pg_dump\" };\n}\n\n/**\n * Restore a database from a backup file.\n *\n * @param url The database URL to restore **into**.\n * @param file The backup file.\n * @param options `force` to overwrite an existing SQLite file; extra tool args.\n * @returns What was done.\n * @throws Error When restoring SQLite over an existing file without `force`.\n * @throws BackupToolMissing When PostgreSQL's client tools are absent.\n * @throws UnsupportedBackupBackend On a dialect without a restore path.\n */\nexport async function restoreDatabase(\n url: string,\n file: string,\n options?: BackupOptions,\n): Promise<BackupResult> {\n const parsed = parseDatabaseUrl(url);\n if (parsed.dialect === \"sqlite\") {\n const target = parsed.database ?? \":memory:\";\n await copyFile(file, target);\n return { file, dialect: \"sqlite\", via: \"copy\" };\n }\n if (parsed.dialect !== \"postgresql\") {\n throw new UnsupportedBackupBackend(parsed.dialect);\n }\n const env = postgresEnv(parsed.password);\n if (backupFormat(file) === \"plain\") {\n await spawn(\n \"psql\",\n [\"--dbname\", toolUrl(url), \"--file\", file, ...(options?.extraArgs ?? [])],\n env,\n );\n return { file, dialect: \"postgresql\", via: \"psql\" };\n }\n await spawn(\n \"pg_restore\",\n [\n \"--dbname\",\n toolUrl(url),\n ...(options?.force ? [\"--clean\", \"--if-exists\"] : []),\n file,\n ...(options?.extraArgs ?? []),\n ],\n env,\n );\n return { file, dialect: \"postgresql\", via: \"pg_restore\" };\n}\n","/**\n * tempest-db-js — common table expressions (`WITH`).\n *\n * A CTE names a query so the rest of the statement can select from it, and —\n * when it is recursive — so it can select from **itself**. That second form is\n * the only way to walk a tree (a category hierarchy, a reply chain, a dependency\n * graph) in one statement instead of one query per level.\n *\n * The alias is a real model class with the CTE's name as its table, so everything\n * that already takes a model — `select`, `join`, `where` — takes a CTE with no\n * special casing anywhere else.\n */\n\nimport type { InferModel, ModelClass, NamingStrategy } from \"./index.js\";\nimport { type SelectBuilder, type SelectNode, select } from \"./query.js\";\nimport type { SetBuilder, SetNode } from \"./setops.js\";\n\n/** A query that can be the body of a CTE. */\n/* biome-ignore lint/suspicious/noExplicitAny: any select or set shape may be a body. */\nexport type CteBody<Row> = SelectBuilder<any, Row, any> | SetBuilder<Row>;\n\n/** One `WITH` entry, as the AST carries it. */\nexport interface CteNode {\n /** The name the rest of the statement refers to. */\n readonly name: string;\n /** True for `WITH RECURSIVE`. */\n readonly recursive: boolean;\n /** The body query. */\n readonly body: SelectNode | SetNode;\n /**\n * `MATERIALIZED` / `NOT MATERIALIZED`, or `null` to let the planner decide.\n * PostgreSQL 12+ only.\n */\n readonly materialized: boolean | null;\n}\n\n/** Options for {@link cte} and {@link cteRecursive}. */\nexport interface CteOptions {\n /**\n * Force (or forbid) materialization of the CTE.\n *\n * PostgreSQL 12+ inlines a CTE used once, which is usually what you want;\n * `true` pins the old behavior when the body is expensive and used twice.\n * Ignored where the dialect has no such syntax.\n */\n readonly materialized?: boolean;\n}\n\n/**\n * Build the model that reads from the CTE.\n *\n * Unlike {@link aliased}, the name here **is** the relation — `FROM \"subtree\"`,\n * not `FROM \"categories\" AS \"subtree\"` — so this does not mark the class as an\n * alias of the underlying table.\n *\n * @param model The model whose shape the CTE yields.\n * @param name The CTE's name.\n * @returns A model class reading from the CTE.\n */\nfunction cteModel<C extends ModelClass>(model: C, name: string): C {\n const relation = class extends (model as unknown as new () => object) {};\n Object.defineProperty(relation, \"tablename\", { value: name, writable: true });\n Object.defineProperty(relation, \"naming\", {\n value: (model as { naming?: NamingStrategy }).naming,\n writable: true,\n });\n Object.defineProperty(relation, \"tableArgs\", { value: undefined, writable: true });\n return relation as unknown as C;\n}\n\n/**\n * A named query, usable anywhere a model is.\n *\n * @typeParam C - the model class whose rows the CTE yields.\n */\nexport class Cte<C extends ModelClass> {\n constructor(\n /** The alias model: the same columns, under the CTE's name. */\n readonly model: C,\n /** The `WITH` entry this attaches to a statement. */\n readonly node: CteNode,\n ) {}\n\n /**\n * Select from the CTE, with the `WITH` clause attached.\n *\n * @param columns Optional projection.\n * @returns A builder over the CTE.\n */\n select(): SelectBuilder<InferModel<C>, InferModel<C>>;\n select<K extends keyof InferModel<C> & string>(\n columns: readonly K[],\n ): SelectBuilder<InferModel<C>, Pick<InferModel<C>, K>>;\n select(columns?: readonly string[]): SelectBuilder<unknown, unknown> {\n const builder = (columns\n ? select(this.model, columns as never)\n : select(this.model)) as unknown as SelectBuilder<unknown, unknown>;\n return attach(builder, this.node);\n }\n}\n\n/**\n * Attach a `WITH` entry to a builder that reads from the CTE.\n *\n * Use it when the outer query is not a plain `select(cte.model)` — a join, for\n * instance, whose builder was assembled elsewhere.\n *\n * @param builder The outer query.\n * @param node The `WITH` entry.\n * @returns The same builder shape, carrying the clause.\n */\nexport function attach<B extends { node: object }>(builder: B, node: CteNode): B {\n const current = (builder.node as { with?: readonly CteNode[] }).with ?? [];\n const next = { ...builder.node, with: [...current, node] };\n return Object.assign(Object.create(Object.getPrototypeOf(builder)), builder, {\n node: next,\n }) as B;\n}\n\n/**\n * A named query the rest of the statement can select from.\n *\n * @param name The CTE's name.\n * @param model The model whose row shape the body yields.\n * @param body The query to name.\n * @param options Materialization hint.\n * @returns The CTE, whose `.model` is usable anywhere a model is.\n *\n * @example\n * ```ts\n * const recent = cte(\"recent\", Order, select(Order).where({ createdAt: { gte: since } }));\n * const rows = await session.execute(recent.select().where({ status: \"open\" })).all();\n * // WITH \"recent\" AS (SELECT * FROM \"orders\" WHERE ...) SELECT * FROM \"recent\" WHERE ...\n * ```\n */\nexport function cte<C extends ModelClass>(\n name: string,\n model: C,\n body: CteBody<InferModel<C>>,\n options?: CteOptions,\n): Cte<C> {\n return new Cte(cteModel(model, name), {\n name,\n recursive: false,\n body: body.node as SelectNode | SetNode,\n materialized: options?.materialized ?? null,\n });\n}\n\n/**\n * A CTE whose body refers to itself — the way to walk a tree in one statement.\n *\n * The builder receives the CTE's own alias model, so the recursive branch can\n * join against it.\n *\n * @param name The CTE's name.\n * @param model The model whose row shape the body yields.\n * @param build Receives the self-reference and returns the body (a `union`/\n * `unionAll` of the seed and the step).\n * @param options Materialization hint.\n * @returns The CTE.\n *\n * @example\n * ```ts\n * const subtree = cteRecursive(\"subtree\", Category, (self) =>\n * unionAll(\n * select(Category).where({ id: rootId }),\n * join(Category, \"c\").innerJoin(self, \"s\", { \"c.parentId\": \"s.id\" }).select(\"c\"),\n * ),\n * );\n * ```\n */\nexport function cteRecursive<C extends ModelClass>(\n name: string,\n model: C,\n build: (self: C) => CteBody<InferModel<C>>,\n options?: CteOptions,\n): Cte<C> {\n const self = cteModel(model, name);\n return new Cte(self, {\n name,\n recursive: true,\n body: build(self).node as SelectNode | SetNode,\n materialized: options?.materialized ?? null,\n });\n}\n","/**\n * tempest-db-js — opt-in active-record layer.\n *\n * The library's default return shape is a plain inferred object (a locked design\n * decision — see the roadmap). This module adds an **opt-in** wrapper for code\n * that prefers instance methods: `ActiveRecord` holds the plain row on `.data`\n * and exposes `save` / `update` / `delete` / `reload` over an async session. It\n * never replaces the default plain-object return — you reach for it explicitly.\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport {\n type InferInsert,\n type InferModel,\n type ModelClass,\n columnsOf,\n primaryKeyFilter,\n primaryKeysOf,\n} from \"./index.js\";\nimport { insert } from \"./mutations.js\";\nimport { del, update } from \"./mutations.js\";\nimport { type WhereInput, select } from \"./query.js\";\n\n/**\n * An opt-in active-record wrapper around a single row.\n *\n * The current field values live on {@link data} (a plain, typed row object).\n * Mutating methods persist through the bound session and refresh `data`.\n *\n * @typeParam C - the model class.\n */\nexport class ActiveRecord<C extends ModelClass> {\n private readonly pks: string[];\n\n constructor(\n private readonly model: C,\n private readonly session: AsyncSession,\n /** The current field values (a plain, typed row). */\n public data: InferModel<C>,\n ) {\n this.pks = primaryKeysOf(model);\n }\n\n /**\n * The primary-key values of the wrapped row, as an object.\n *\n * Composite keys are the reason this is an object and not a value: identifying\n * the row by one column of a two-column key hits the wrong row.\n */\n private pkValue(): Record<string, unknown> {\n const row = this.data as Record<string, unknown>;\n const key: Record<string, unknown> = {};\n for (const name of this.pks) key[name] = row[name];\n return key;\n }\n\n private pkFilter(): WhereInput<InferModel<C>> {\n return this.pkValue() as WhereInput<InferModel<C>>;\n }\n\n /**\n * Persist the current `data` — insert if new, otherwise overwrite the existing\n * row (upsert on the primary key). Refreshes `data` from the returned row.\n *\n * @returns This wrapper, for chaining.\n */\n async save(): Promise<this> {\n // Overwrite only the columns actually present in `data` (an absent column\n // would otherwise be set to null and could violate NOT NULL / clobber a\n // DB-side default).\n const cols = columnsOf(this.model);\n const rowData = this.data as Record<string, unknown>;\n const setPatch: Record<string, unknown> = {};\n for (const c of Object.keys(rowData)) {\n if (!this.pks.includes(c) && c in cols) setPatch[c] = rowData[c];\n }\n const saved = await this.session\n .execute(\n insert(this.model)\n .values(this.data as InferInsert<C>)\n .onConflictDoUpdate(\n this.pks as (keyof InferModel<C> & string)[],\n setPatch as Partial<InferModel<C>>,\n )\n .returning(),\n )\n .one();\n this.data = saved as InferModel<C>;\n return this;\n }\n\n /**\n * Update the given columns for this row and merge them into `data`.\n *\n * @param patch The columns to change.\n * @returns This wrapper, for chaining.\n */\n async update(patch: Partial<InferModel<C>>): Promise<this> {\n await this.session.execute(update(this.model).set(patch).where(this.pkFilter()));\n this.data = { ...this.data, ...patch };\n return this;\n }\n\n /**\n * Delete this row.\n *\n * @returns The number of rows affected (0 or 1).\n */\n async delete(): Promise<number> {\n return this.session.execute(del(this.model).where(this.pkFilter())).rowsAffected();\n }\n\n /**\n * Re-fetch this row by primary key and refresh `data`.\n *\n * @returns This wrapper, for chaining.\n * @throws When the row no longer exists.\n */\n async reload(): Promise<this> {\n const fresh = await this.session\n .execute(select(this.model).where(this.pkFilter()))\n .first();\n if (fresh === null) {\n throw new Error(\n `${this.model.tablename} row ${JSON.stringify(this.pkValue())} not found on reload`,\n );\n }\n this.data = fresh as InferModel<C>;\n return this;\n }\n}\n\n/** A small factory binding a model + session for producing {@link ActiveRecord}s. */\nexport interface ActiveRecordManager<C extends ModelClass> {\n /** Wrap an existing row (already loaded) as an active record. */\n wrap(row: InferModel<C>): ActiveRecord<C>;\n /** Build an unsaved active record from insert data; call `.save()` to persist. */\n create(data: InferInsert<C>): ActiveRecord<C>;\n /** Fetch a row by primary key and wrap it, or `null` if absent. */\n get(id: unknown): Promise<ActiveRecord<C> | null>;\n}\n\n/**\n * Create an {@link ActiveRecordManager} for a model over a session.\n *\n * @param model The model class.\n * @param session The async session to persist through.\n * @returns A manager that wraps/fetches rows as active records.\n *\n * @example\n * ```ts\n * const users = activeRecord(User, engine.session());\n * const u = users.create({ name: \"Ana\", age: 30 });\n * await u.save();\n * await u.update({ age: 31 });\n * await u.delete();\n * ```\n */\nexport function activeRecord<C extends ModelClass>(\n model: C,\n session: AsyncSession,\n): ActiveRecordManager<C> {\n primaryKeysOf(model);\n return {\n wrap: (row) => new ActiveRecord(model, session, row),\n create: (data) => new ActiveRecord(model, session, data as unknown as InferModel<C>),\n async get(id) {\n const filter = primaryKeyFilter(model, id) as WhereInput<InferModel<C>>;\n const row = await session.execute(select(model).where(filter)).first();\n return row === null ? null : new ActiveRecord(model, session, row as InferModel<C>);\n },\n };\n}\n","/**\n * tempest-db-js — typed relations (hasMany / belongsTo) with eager loading.\n *\n * Relations are plain descriptors that reference another model plus the local /\n * foreign key. `loadRelations` fetches the related rows in **one query per\n * relation** (no N+1), groups them, and attaches them to the base rows — with\n * the result type widened so each relation key is typed (`Row[]` for hasMany,\n * `Row | null` for belongsTo).\n */\n\nimport type { AsyncSession } from \"./engine.js\";\nimport { type InferModel, type ModelClass, type WhereInput, select } from \"./index.js\";\n\n/** A one-to-many relation: each base row owns many target rows. */\nexport interface HasMany<C extends ModelClass> {\n readonly kind: \"hasMany\";\n readonly target: () => C;\n /** Column on the base row (usually its primary key). */\n readonly localKey: string;\n /** Column on the target row pointing back to the base row. */\n readonly foreignKey: string;\n}\n\n/** A many-to-one relation: each base row points to one target row. */\nexport interface BelongsTo<C extends ModelClass> {\n readonly kind: \"belongsTo\";\n readonly target: () => C;\n /** Column on the base row holding the foreign key. */\n readonly localKey: string;\n /** Column on the target row (usually its primary key). */\n readonly foreignKey: string;\n}\n\n/* biome-ignore lint/suspicious/noExplicitAny: a relation map mixes target models. */\nexport type Relation = HasMany<any> | BelongsTo<any>;\n\n/** Declare a one-to-many relation. */\nexport function hasMany<C extends ModelClass>(\n target: () => C,\n keys: { localKey: string; foreignKey: string },\n): HasMany<C> {\n return {\n kind: \"hasMany\",\n target,\n localKey: keys.localKey,\n foreignKey: keys.foreignKey,\n };\n}\n\n/** Declare a many-to-one relation. */\nexport function belongsTo<C extends ModelClass>(\n target: () => C,\n keys: { localKey: string; foreignKey: string },\n): BelongsTo<C> {\n return {\n kind: \"belongsTo\",\n target,\n localKey: keys.localKey,\n foreignKey: keys.foreignKey,\n };\n}\n\n/** The value a relation contributes to a loaded row. */\nexport type RelationValue<R> = R extends HasMany<infer C>\n ? InferModel<C>[]\n : R extends BelongsTo<infer C>\n ? InferModel<C> | null\n : never;\n\n/** A base row augmented with its loaded relations. */\nexport type WithRelations<Row, Spec extends Record<string, Relation>> = Row & {\n [K in keyof Spec]: RelationValue<Spec[K]>;\n};\n\n/**\n * Eager-load relations onto a set of base rows. One query per relation.\n *\n * @param session The async session to query through.\n * @param rows The already-loaded base rows.\n * @param spec A map of relation name → relation descriptor.\n * @returns The base rows, each augmented with its relation values.\n */\nexport async function loadRelations<\n Row extends Record<string, unknown>,\n Spec extends Record<string, Relation>,\n>(session: AsyncSession, rows: Row[], spec: Spec): Promise<WithRelations<Row, Spec>[]> {\n const out = rows.map((r) => ({ ...r })) as Record<string, unknown>[];\n\n for (const [name, rel] of Object.entries(spec)) {\n const target = rel.target();\n const localValues = [...new Set(rows.map((r) => r[rel.localKey]))];\n const related =\n localValues.length > 0\n ? await session\n .execute(\n select(target).where({\n [rel.foreignKey]: { in: localValues },\n } as WhereInput<InferModel<typeof target>>),\n )\n .all()\n : [];\n\n if (rel.kind === \"hasMany\") {\n const grouped = new Map<unknown, Record<string, unknown>[]>();\n for (const row of related as Record<string, unknown>[]) {\n const key = row[rel.foreignKey];\n const list = grouped.get(key) ?? [];\n list.push(row);\n grouped.set(key, list);\n }\n out.forEach((r, i) => {\n r[name] = grouped.get(rows[i]?.[rel.localKey]) ?? [];\n });\n } else {\n const byKey = new Map<unknown, Record<string, unknown>>();\n for (const row of related as Record<string, unknown>[]) {\n byKey.set(row[rel.foreignKey], row);\n }\n out.forEach((r, i) => {\n r[name] = byKey.get(rows[i]?.[rel.localKey]) ?? null;\n });\n }\n }\n\n return out as WithRelations<Row, Spec>[];\n}\n","/**\n * tempest-db-js — feasibility spike for Phase 1.\n *\n * Proves the central design claim: a class-based, SQLAlchemy-style model whose\n * fields are runtime column-builders can drive full static row-type inference in\n * TypeScript, despite TS erasing types at runtime.\n *\n * This is a SPIKE, not the final API. It validates the type machinery only.\n */\n\nimport {\n type CondNode,\n type Condition,\n type ExprNode,\n toCondNode,\n} from \"./conditions.js\";\n\n/** Phantom marker carrying the static TS type a column maps to. */\ndeclare const TYPE: unique symbol;\n\n/** Column flags that influence the inferred row/insert shape. */\ninterface ColumnFlags {\n readonly primaryKey: boolean;\n readonly notNull: boolean;\n readonly hasDefault: boolean;\n /**\n * A `UNIQUE` constraint on the column. Does NOT influence the inferred type —\n * it is DDL-only metadata (mirrors SQLAlchemy's `mapped_column(unique=True)`).\n */\n readonly unique: boolean;\n}\n\nconst DEFAULT_FLAGS: ColumnFlags = {\n primaryKey: false,\n notNull: false,\n hasDefault: false,\n unique: false,\n};\n\n/**\n * The canonical, dialect-neutral kind of a column type. Mirrors SQLAlchemy's\n * generic types (e.g. `String` → varchar, `Text` → text). Dialect renderers\n * (Phase 4/6) map each kind + meta to concrete SQL per database.\n */\nexport type ColumnTypeKind =\n | \"smallint\"\n | \"integer\"\n | \"bigint\"\n | \"numeric\"\n | \"real\"\n | \"double\"\n | \"varchar\"\n | \"text\"\n | \"char\"\n | \"boolean\"\n | \"date\"\n | \"time\"\n | \"datetime\"\n | \"timestamp\"\n | \"blob\"\n | \"json\"\n | \"uuid\"\n | \"enum\"\n | \"array\";\n\n/** Parameters that refine a column type and feed the migration IR / DDL. */\nexport interface ColumnTypeMeta {\n /** Max length for `varchar`/`char`. */\n readonly length?: number | undefined;\n /** Total digits for `numeric`. */\n readonly precision?: number | undefined;\n /** Digits after the decimal point for `numeric`. */\n readonly scale?: number | undefined;\n /** `WITH TIME ZONE` for `timestamp`/`time`. */\n readonly withTimezone?: boolean | undefined;\n /** Allowed values for `enum`. */\n readonly values?: readonly string[] | undefined;\n /** Render as `JSONB` (PostgreSQL) instead of `JSON`. */\n readonly jsonb?: boolean | undefined;\n /** The element type of an `array` column (`text[]`, `integer[]`). */\n readonly element?: ColumnType | undefined;\n}\n\n/** A structured, dialect-neutral column type descriptor. */\nexport interface ColumnType {\n readonly kind: ColumnTypeKind;\n readonly meta: ColumnTypeMeta;\n}\n\n/**\n * A portable default expression. The token is dialect-neutral; the renderer\n * (Phase 4/6) maps it to the right SQL per database — e.g. `\"now\"` becomes\n * `CURRENT_TIMESTAMP` on SQLite and `now()` on PostgreSQL. Use `{ raw }` as an\n * escape hatch for a verbatim SQL fragment, or `{ parts }` for a parameterized\n * fragment built by the `sql.expr` tagged template (one bound parameter per gap\n * between consecutive parts).\n */\nexport type PortableExpression =\n | \"now\"\n | \"current_date\"\n | \"current_time\"\n | \"uuidv4\"\n | { readonly raw: string }\n | { readonly parts: readonly string[] }\n /** The incoming value of a column, inside an upsert's `DO UPDATE` clause. */\n | { readonly excluded: string };\n\n/**\n * A column default. Either a constant literal value or a server-side expression\n * evaluated by the database (mirrors SQLAlchemy's `default` vs `server_default`).\n * Feeds the migration IR (`DefaultIR`).\n */\nexport type DefaultValue =\n | { readonly kind: \"literal\"; readonly value: unknown }\n | { readonly kind: \"expression\"; readonly expression: PortableExpression };\n\n/**\n * Brand marking a value as a SQL expression rather than a bound parameter.\n *\n * A plain object reaching `set()`/`values()` is a mistake (it would be bound as a\n * parameter and silently written as JSON or null); an object carrying this symbol\n * is deliberate, and the dialect renders it inline instead of binding it. Mirrors\n * how `Condition` is branded, so the check is a symbol lookup, not duck typing.\n */\nconst EXPRESSION = Symbol.for(\"tempest-db-js.expression\");\n\n/**\n * A SQL expression, usable both as a column default (`.default(sql.now())`) and\n * as a write value (`.set({ attempts: sql.raw(\"attempts + 1\") })`). The dialect\n * renders `expression` inline and binds `params` in the order of the fragment's\n * gaps.\n */\nexport interface SqlExpression {\n readonly [EXPRESSION]: true;\n readonly kind: \"expression\";\n readonly expression: PortableExpression;\n /** Parameters bound into the fragment's gaps, in order (empty for a token). */\n readonly params: readonly unknown[];\n}\n\n/** Build a branded {@link SqlExpression} from a portable token or fragment. */\nfunction expression(\n token: PortableExpression,\n params: readonly unknown[] = [],\n): SqlExpression {\n return { [EXPRESSION]: true, kind: \"expression\", expression: token, params };\n}\n\n/**\n * Turn a stored column default (or `onUpdate` value) into something the write\n * path can render.\n *\n * A default is kept as a {@link DefaultValue} — the shape the migration IR wants\n * — while `set()` and `values()` want either a bindable value or a branded\n * {@link SqlExpression}. This is the one conversion between the two.\n *\n * @param value The stored default.\n * @returns A literal to bind, or a branded expression to render inline.\n */\nexport function defaultAsWriteValue(value: DefaultValue): unknown {\n return value.kind === \"literal\" ? value.value : expression(value.expression);\n}\n\n/**\n * Runtime guard: is this value a branded {@link SqlExpression}?\n *\n * @param value Any value handed to `set()`, `values()` or `.default()`.\n * @returns True when the value carries the expression brand.\n */\nexport function isSqlExpression(value: unknown): value is SqlExpression {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[EXPRESSION] === true\n );\n}\n\n/**\n * Portable server-side expressions, à la SQLAlchemy's `func`.\n *\n * Every entry doubles as a column default and as a write value, so\n * `.default(sql.now())` and `.set({ updatedAt: sql.now() })` both work.\n */\nexport const sql = {\n /** Current timestamp at insert (`CURRENT_TIMESTAMP` / `now()`). */\n now: (): SqlExpression => expression(\"now\"),\n /** Current date. */\n currentDate: (): SqlExpression => expression(\"current_date\"),\n /** Current time. */\n currentTime: (): SqlExpression => expression(\"current_time\"),\n /** A freshly generated UUID v4 (`gen_random_uuid()` / portable fallback). */\n uuidv4: (): SqlExpression => expression(\"uuidv4\"),\n /**\n * The **incoming** value of a column, valid only inside an upsert's\n * `onConflictDoUpdate` patch.\n *\n * A multi-row upsert cannot spell the new value as a literal — each row has its\n * own — so the assignment has to name the row being inserted:\n * `EXCLUDED.\"total\"` on PostgreSQL and SQLite, `VALUES(total)` on MySQL.\n *\n * @param column The column's property name.\n * @returns The expression, for use as a write value.\n */\n excluded: (column: string): SqlExpression => expression({ excluded: column }),\n /**\n * Escape hatch: a verbatim SQL expression rendered as-is, with no parameters.\n *\n * The fragment is interpolated into the statement untouched, so it must never\n * carry user input — use {@link sql.expr} when a value has to be bound.\n *\n * @param fragment The SQL text (e.g. `\"attempts + 1\"`).\n * @returns The expression, usable as a default and as a write value.\n */\n raw: (fragment: string): SqlExpression => expression({ raw: fragment }),\n /**\n * A parameterized SQL expression, written as a tagged template. Static text is\n * SQL; every `${...}` interpolation becomes a bound parameter, so the fragment\n * is injection-safe by construction.\n *\n * Cannot be used as a column default — a `DEFAULT` clause has nowhere to bind\n * parameters; use {@link sql.raw} there.\n *\n * @param parts The static SQL segments supplied by the template tag.\n * @param values The interpolated values, bound in order.\n * @returns The expression, usable as a write value.\n *\n * @example\n * ```ts\n * update(Account).set({ balance: sql.expr`balance - ${amount}` }).where({ id });\n * // UPDATE \"accounts\" SET \"balance\" = balance - $1 WHERE \"id\" = $2\n * ```\n */\n expr: (parts: TemplateStringsArray, ...values: unknown[]): SqlExpression =>\n expression({ parts: Array.from(parts) }, values),\n} as const;\n\n/** Narrow a `.default()` argument to a `DefaultValue` expression/literal marker. */\nfunction isDefaultValue(value: unknown): value is DefaultValue {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n ((value as { kind: unknown }).kind === \"literal\" ||\n (value as { kind: unknown }).kind === \"expression\")\n );\n}\n\n/** True when an expression carries bound parameters (illegal in a DDL default). */\nfunction bindsParameters(value: DefaultValue): boolean {\n return (\n value.kind === \"expression\" &&\n typeof value.expression === \"object\" &&\n \"parts\" in value.expression\n );\n}\n\n/**\n * A referential action for a foreign key's `ON DELETE` / `ON UPDATE` clause.\n * Dialect-neutral tokens rendered uppercase at the DDL edge (mirrors\n * SQLAlchemy's `ForeignKey(ondelete=..., onupdate=...)`).\n */\nexport type FkAction = \"cascade\" | \"restrict\" | \"set null\" | \"set default\" | \"no action\";\n\n/**\n * A resolved foreign-key reference: the target `table.column` plus optional\n * referential actions. Produced by `Column.references(\"table.column\", ...)`.\n */\nexport interface ForeignKeyRef {\n readonly table: string;\n readonly column: string;\n readonly onDelete?: FkAction | undefined;\n readonly onUpdate?: FkAction | undefined;\n}\n\n/** Options for a foreign-key reference (referential actions). */\nexport interface ForeignKeyOptions {\n readonly onDelete?: FkAction | undefined;\n readonly onUpdate?: FkAction | undefined;\n}\n\n/** Parse a `\"table.column\"` reference string into a {@link ForeignKeyRef}. */\nfunction parseReference(ref: string, options?: ForeignKeyOptions): ForeignKeyRef {\n const dot = ref.lastIndexOf(\".\");\n if (dot <= 0 || dot === ref.length - 1) {\n throw new Error(`Invalid foreign key reference \"${ref}\"; expected \"table.column\".`);\n }\n return {\n table: ref.slice(0, dot),\n column: ref.slice(dot + 1),\n onDelete: options?.onDelete,\n onUpdate: options?.onUpdate,\n };\n}\n\n/**\n * A typed column builder. Holds runtime metadata (structured `type`, `flags`,\n * `default`, `onUpdate`, foreign-key `reference`) and a phantom static type `T`\n * used purely for inference.\n */\nclass Column<T, F extends ColumnFlags = ColumnFlags> {\n /** Phantom: never read at runtime, only inspected by the type system. */\n declare readonly [TYPE]: T;\n\n constructor(\n readonly type: ColumnType,\n readonly flags: F,\n /** The default applied on insert, or `null` for none. */\n readonly defaultValue: DefaultValue | null = null,\n /** The value re-applied on update (e.g. `updated_at`), or `null`. */\n readonly onUpdateValue: DefaultValue | null = null,\n /** The foreign-key reference this column points to, or `null` for none. */\n readonly reference: ForeignKeyRef | null = null,\n /** An explicit database column name overriding the property name, or `null`. */\n readonly dbName: string | null = null,\n /** Conversion to and from the stored representation, or `null` for none. */\n readonly codec: ColumnCodec | null = null,\n ) {}\n\n /** Clone this column with one facet replaced, carrying every other over. */\n private derive<F2 extends ColumnFlags>(patch: {\n flags?: F2;\n defaultValue?: DefaultValue | null;\n onUpdateValue?: DefaultValue | null;\n reference?: ForeignKeyRef | null;\n dbName?: string | null;\n codec?: ColumnCodec | null;\n }): Column<T, F2> {\n return new Column<T, F2>(\n this.type,\n (patch.flags ?? this.flags) as F2,\n patch.defaultValue !== undefined ? patch.defaultValue : this.defaultValue,\n patch.onUpdateValue !== undefined ? patch.onUpdateValue : this.onUpdateValue,\n patch.reference !== undefined ? patch.reference : this.reference,\n patch.dbName !== undefined ? patch.dbName : this.dbName,\n patch.codec !== undefined ? patch.codec : this.codec,\n );\n }\n\n primaryKey(): Column<T, F & { primaryKey: true; hasDefault: true }> {\n return this.derive({ flags: { ...this.flags, primaryKey: true, hasDefault: true } });\n }\n\n notNull(): Column<T, F & { notNull: true }> {\n return this.derive({ flags: { ...this.flags, notNull: true } });\n }\n\n /**\n * Add a `UNIQUE` constraint to the column (mirrors SQLAlchemy's\n * `mapped_column(unique=True)`). DDL-only — does not change the inferred type.\n */\n unique(): Column<T, F & { unique: true }> {\n return this.derive({ flags: { ...this.flags, unique: true } });\n }\n\n /**\n * Map this property to a differently-named database column, à la SQLAlchemy's\n * `mapped_column(\"consumer_name\")` (Django's `db_column`, Prisma's `@map`).\n *\n * The override applies everywhere the name reaches SQL — select, insert,\n * update, delete, where, order by, group by, returning, conflict targets, the\n * migration IR and the drift check — while the TypeScript row keeps the\n * property name. Use it to keep a `snake_case` schema behind a `camelCase`\n * model; {@link Model.naming} does the same for a whole table at once.\n *\n * @param dbName The real column name in the database.\n * @returns A new column bound to that name.\n * @throws Error When `dbName` is empty.\n *\n * @example\n * ```ts\n * class ApiKey extends Model {\n * static tablename = \"api_keys\";\n * consumerName = column.text().name(\"consumer_name\").notNull();\n * }\n * ```\n */\n name(dbName: string): Column<T, F> {\n if (dbName.length === 0) {\n throw new Error(\"column.name() requires a non-empty database column name.\");\n }\n return this.derive({ dbName });\n }\n\n /**\n * Declare a foreign-key reference to another table's column, à la SQLAlchemy's\n * `mapped_column(ForeignKey(\"table.column\", ondelete=...))`. DDL-only — does\n * not change the inferred type.\n *\n * @param ref The target as `\"table.column\"` (e.g. `\"users.id\"`).\n * @param options Optional `onDelete` / `onUpdate` referential actions.\n * @returns A new column carrying the reference.\n * @throws Error When `ref` is not a valid `\"table.column\"` string.\n */\n references(ref: string, options?: ForeignKeyOptions): Column<T, F> {\n return this.derive({ reference: parseReference(ref, options) });\n }\n\n /**\n * Set the insert-time default: a constant value of type `T`, or a portable\n * server-side expression from {@link sql} (e.g. `sql.now()`, `sql.uuidv4()`).\n *\n * @param value The literal default, or a {@link sql} expression.\n * @returns A new column carrying the default.\n * @throws Error When given a `sql.expr` fragment — a `DEFAULT` clause has\n * nowhere to bind parameters; use `sql.raw()` for a verbatim expression.\n */\n default(value: T | DefaultValue): Column<T, F & { hasDefault: true }> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n if (bindsParameters(resolved)) {\n throw new Error(\n \"sql.expr`...` binds parameters and cannot be a column default — use sql.raw() for a verbatim DEFAULT expression.\",\n );\n }\n return this.derive({\n flags: { ...this.flags, hasDefault: true },\n defaultValue: resolved,\n });\n }\n\n /**\n * Re-apply a value whenever the row is updated (e.g. an `updated_at` column\n * with `sql.now()`). Mirrors SQLAlchemy's `onupdate`.\n *\n * @param value The literal value, or a {@link sql} expression.\n * @returns A new column carrying the on-update value.\n * @throws Error When given a `sql.expr` fragment (see {@link Column.default}).\n */\n onUpdate(value: T | DefaultValue): Column<T, F> {\n const resolved: DefaultValue = isDefaultValue(value)\n ? value\n : { kind: \"literal\", value };\n if (bindsParameters(resolved)) {\n throw new Error(\n \"sql.expr`...` binds parameters and cannot be an onUpdate default — use sql.raw() for a verbatim expression.\",\n );\n }\n return this.derive({ onUpdateValue: resolved });\n }\n}\n\n/**\n * Conversion between a domain value and what the database stores.\n *\n * The pair is applied on **both** paths — writes and reads — plus on a `where`\n * operand, so a custom-typed column cannot be compared against the wrong shape by\n * accident.\n */\nexport interface ColumnCodec {\n /** Domain value → stored value. */\n readonly toDb: (value: unknown) => unknown;\n /** Stored value → domain value. */\n readonly fromDb: (value: unknown) => unknown;\n}\n\n/**\n * Declare a column type of your own, over one this package already has.\n *\n * Money as integer cents, a `Temporal.Instant`, a branded id, a value object —\n * the conversion belongs to the column, not to every call site that forgets it.\n * The DDL and the migration IR keep using the **base** type, so a custom type is\n * invisible to the schema and cannot cause drift.\n *\n * @param spec `base` is a factory for the underlying column; `toDb`/`fromDb`\n * convert. `base` is a factory, not a column, because each declaration needs\n * its own instance.\n * @returns A factory producing columns of the custom type.\n *\n * @example\n * ```ts\n * const money = customType<Money, bigint>({\n * base: () => column.bigInteger(),\n * toDb: (m) => m.cents,\n * fromDb: (cents) => Money.fromCents(cents),\n * });\n *\n * class Order extends Model {\n * total = money().notNull();\n * }\n * ```\n */\nexport function customType<Domain, Stored>(spec: {\n base: () => Column<Stored, ColumnFlags>;\n toDb: (value: Domain) => Stored;\n fromDb: (value: Stored) => Domain;\n}): () => Column<Domain, ColumnFlags> {\n const codec: ColumnCodec = {\n toDb: (value) =>\n value === null || value === undefined ? value : spec.toDb(value as Domain),\n fromDb: (value) =>\n value === null || value === undefined ? value : spec.fromDb(value as Stored),\n };\n return () => {\n const base = spec.base();\n return new Column<Domain, ColumnFlags>(\n base.type,\n base.flags,\n base.defaultValue,\n base.onUpdateValue,\n base.reference,\n base.dbName,\n codec,\n );\n };\n}\n\n/** The per-column codecs of a model, keyed by property name, or `null` if none. */\nconst codecCache = new WeakMap<ModelClass, Record<string, ColumnCodec> | null>();\n\n/**\n * The codecs a model declares, by property name.\n *\n * `null` when the model has no custom type, which is the common case — the write\n * and read paths skip the whole conversion step on that answer.\n *\n * @param model The model class.\n * @returns The codec map, or `null`.\n */\nexport function codecsOf(model: ModelClass): Record<string, ColumnCodec> | null {\n const cached = codecCache.get(model);\n if (cached !== undefined) return cached;\n const codecs: Record<string, ColumnCodec> = {};\n let found = false;\n for (const [prop, col] of Object.entries(columnsOf(model))) {\n if (col.codec) {\n codecs[prop] = col.codec;\n found = true;\n }\n }\n const result = found ? codecs : null;\n codecCache.set(model, result);\n return result;\n}\n\n/** Build a `Column` of static type `T` from a kind + optional meta. */\nfunction makeColumn<T>(\n kind: ColumnTypeKind,\n meta: ColumnTypeMeta = {},\n): Column<T, ColumnFlags> {\n return new Column<T, ColumnFlags>({ kind, meta }, DEFAULT_FLAGS);\n}\n\n/**\n * Column factory mirroring SQLAlchemy's typed column constructors. Each entry\n * pairs a distinct SQL type with the TypeScript type it maps to.\n *\n * Notable mappings:\n * - `varchar(n)` (`VARCHAR(n)`) is distinct from `text` (`TEXT`).\n * - `bigInteger` maps to `bigint` (not `number`) to keep 64-bit precision.\n * - `numeric`/`decimal` map to `string` — JavaScript has no exact decimal, and\n * stringifying preserves precision instead of losing it to a float.\n * - `json<T>()` carries the parsed value type; `jsonb` is the PostgreSQL variant.\n * - `enum(...)` infers a string-literal union from its values.\n */\nexport const column = {\n /** `SMALLINT` → `number`. */\n smallInteger: (): Column<number, ColumnFlags> => makeColumn<number>(\"smallint\"),\n /** `INTEGER` → `number`. */\n integer: (): Column<number, ColumnFlags> => makeColumn<number>(\"integer\"),\n /** `BIGINT` → `bigint` (64-bit precision preserved). */\n bigInteger: (): Column<bigint, ColumnFlags> => makeColumn<bigint>(\"bigint\"),\n /** `NUMERIC(precision, scale)` → `string` (exact decimal, no float loss). */\n numeric: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** Alias of {@link column.numeric}. */\n decimal: (precision?: number, scale?: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"numeric\", { precision, scale }),\n /** `REAL` → `number`. */\n real: (): Column<number, ColumnFlags> => makeColumn<number>(\"real\"),\n /** `DOUBLE PRECISION` → `number`. */\n double: (): Column<number, ColumnFlags> => makeColumn<number>(\"double\"),\n /** `VARCHAR(length)` → `string`. Distinct from {@link column.text}. */\n varchar: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** Alias of {@link column.varchar} (SQLAlchemy's `String`). */\n string: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"varchar\", { length }),\n /** `CHAR(length)` → `string` (fixed-width). */\n char: (length: number): Column<string, ColumnFlags> =>\n makeColumn<string>(\"char\", { length }),\n /** `TEXT` → `string` (unbounded). Distinct from {@link column.varchar}. */\n text: (): Column<string, ColumnFlags> => makeColumn<string>(\"text\"),\n /** `BOOLEAN` → `boolean`. */\n boolean: (): Column<boolean, ColumnFlags> => makeColumn<boolean>(\"boolean\"),\n /** `DATE` → `Date`. */\n date: (): Column<Date, ColumnFlags> => makeColumn<Date>(\"date\"),\n /** `TIME` → `string`. Pass `{ timezone: true }` for `WITH TIME ZONE`. */\n time: (options?: { timezone?: boolean }): Column<string, ColumnFlags> =>\n makeColumn<string>(\"time\", { withTimezone: options?.timezone }),\n /**\n * `DATETIME`/`TIMESTAMP` → `Date` (SQLAlchemy's generic `DateTime`). Pass\n * `{ timezone: true }` for `WITH TIME ZONE`. Pair with `.default(sql.now())`\n * and `.onUpdate(sql.now())` for managed `created_at`/`updated_at` columns.\n */\n datetime: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"datetime\", { withTimezone: options?.timezone }),\n /** `TIMESTAMP` → `Date` (SQL-specific). Pass `{ timezone: true }`. */\n timestamp: (options?: { timezone?: boolean }): Column<Date, ColumnFlags> =>\n makeColumn<Date>(\"timestamp\", { withTimezone: options?.timezone }),\n /** `BLOB`/`BYTEA` → `Uint8Array`. */\n blob: (): Column<Uint8Array, ColumnFlags> => makeColumn<Uint8Array>(\"blob\"),\n /** `JSON` → the given parsed value type `T` (defaults to `unknown`). */\n json: <T = unknown>(): Column<T, ColumnFlags> => makeColumn<T>(\"json\"),\n /** `JSONB` (PostgreSQL) → the given parsed value type `T`. */\n jsonb: <T = unknown>(): Column<T, ColumnFlags> =>\n makeColumn<T>(\"json\", { jsonb: true }),\n /** `UUID` → `string`. */\n uuid: (): Column<string, ColumnFlags> => makeColumn<string>(\"uuid\"),\n /** `ENUM(...values)` → a string-literal union of the given values. */\n enum: <const E extends string>(...values: E[]): Column<E, ColumnFlags> =>\n makeColumn<E>(\"enum\", { values }),\n /**\n * A PostgreSQL array column (`text[]`, `integer[]`) → `T[]`.\n *\n * PostgreSQL only: SQLite and MySQL have no native array type, and rendering\n * one as JSON there would give the same model different semantics per dialect\n * (`@>` and `&&` work on one and not the other), so the DDL renderer throws\n * for those dialects instead of falling back silently.\n *\n * @param element The element column (its type, not its flags, is what is used).\n * @returns A column whose inferred type is an array of the element's type.\n *\n * @example\n * ```ts\n * class ApiKey extends Model {\n * static tablename = \"api_keys\";\n * scopes = column.array(column.text()).notNull().default([\"send\"]);\n * }\n * ```\n */\n array: <T>(element: Column<T, ColumnFlags>): Column<T[], ColumnFlags> =>\n makeColumn<T[]>(\"array\", { element: element.type }),\n} as const;\n\n/**\n * A table-level constraint declared via a model's `static tableArgs`. Mirrors\n * SQLAlchemy's `__table_args__` entries (`UniqueConstraint`, `ForeignKeyConstraint`).\n * Use the {@link unique} and {@link foreignKey} helpers to build these.\n */\nexport type TableConstraint =\n | {\n readonly kind: \"unique\";\n readonly name?: string | undefined;\n readonly columns: readonly string[];\n }\n | {\n readonly kind: \"check\";\n readonly name?: string | undefined;\n /** The invariant, in the same condition language `where` uses. */\n readonly expression: CondNode;\n /** Columns the expression mentions, for the generated name. */\n readonly columns: readonly string[];\n }\n | {\n readonly kind: \"index\";\n readonly name?: string | undefined;\n readonly columns: readonly string[];\n /** A unique index rather than a plain one. */\n readonly unique?: boolean | undefined;\n /** The predicate of a **partial** index, or `undefined` for a full one. */\n readonly where?: CondNode | undefined;\n }\n | {\n readonly kind: \"foreignKey\";\n readonly name?: string | undefined;\n readonly columns: readonly string[];\n readonly refTable: string;\n readonly refColumns: readonly string[];\n readonly onDelete?: FkAction | undefined;\n readonly onUpdate?: FkAction | undefined;\n };\n\n/**\n * Declare a (possibly composite) `UNIQUE` table constraint over the given\n * columns. Mirrors SQLAlchemy's `UniqueConstraint(\"a\", \"b\")`.\n *\n * @param columns The column names covered by the constraint.\n * @returns A unique {@link TableConstraint}.\n * @throws Error When no columns are given.\n */\nexport function unique(...columns: string[]): TableConstraint {\n if (columns.length === 0) {\n throw new Error(\"unique() requires at least one column.\");\n }\n return { kind: \"unique\", columns };\n}\n\n/**\n * Declare a (possibly composite) foreign-key table constraint. Mirrors\n * SQLAlchemy's `ForeignKeyConstraint([...], [...], ondelete=...)`.\n *\n * @param columns The local column names.\n * @param refTable The referenced table name.\n * @param refColumns The referenced column names (same length as `columns`).\n * @param options Optional constraint `name` and referential actions.\n * @returns A foreign-key {@link TableConstraint}.\n * @throws Error When the column arrays are empty or mismatched in length.\n */\n/**\n * Declare a `CHECK` constraint — an invariant the **database** enforces.\n *\n * The expression uses the same condition language as `where`, not a raw string:\n * a string would have to be compared textually to decide whether the schema\n * drifted, and two spellings of the same rule would read as a change.\n *\n * @param expression The invariant, e.g. `col(\"total\").gte(0)`.\n * @param options `name` to pin the constraint's name; `columns` to name the\n * generated one after something other than the expression's own columns.\n * @returns A check {@link TableConstraint}.\n *\n * @example\n * ```ts\n * class Order extends Model {\n * static override tableArgs = () => [check(col(\"total\").gte(0))];\n * }\n * ```\n */\nexport function check(\n expression: Condition | Record<string, unknown>,\n options?: { name?: string; columns?: readonly string[] },\n): TableConstraint {\n const node = toCondNode(expression);\n return {\n kind: \"check\",\n name: options?.name,\n expression: node,\n columns: options?.columns ?? conditionColumns(node),\n };\n}\n\n/**\n * Declare an index.\n *\n * An index the model does not declare is invisible to migrations: it never gets\n * created, and a table rebuild on SQLite drops it. Declaring it puts it in the\n * same place as the columns it covers.\n *\n * @param columns The indexed columns, in order.\n * @param options `unique` for a unique index, `where` for a **partial** one, and\n * `name` to pin the name.\n * @returns An index {@link TableConstraint}.\n * @throws Error When no column is given.\n *\n * @example\n * ```ts\n * static override tableArgs = () => [\n * index([\"customerId\", \"createdAt\"]),\n * index([\"email\"], { unique: true, where: { deletedAt: { isNull: true } } }),\n * ];\n * ```\n */\nexport function index(\n columns: readonly string[],\n options?: {\n name?: string;\n unique?: boolean;\n where?: Condition | Record<string, unknown>;\n },\n): TableConstraint {\n if (columns.length === 0) {\n throw new Error(\"index() requires at least one column.\");\n }\n return {\n kind: \"index\",\n name: options?.name,\n columns: [...columns],\n unique: options?.unique,\n where: options?.where === undefined ? undefined : toCondNode(options.where),\n };\n}\n\n/**\n * The columns a condition mentions, in first-seen order.\n *\n * Used to name a generated `CHECK` after what it constrains.\n *\n * @param node The condition.\n * @returns The column names.\n */\nfunction conditionColumns(node: CondNode): string[] {\n const found: string[] = [];\n const visitExpr = (expr: ExprNode): void => {\n if (expr.kind === \"column\") {\n if (!found.includes(expr.name)) found.push(expr.name);\n return;\n }\n if (expr.kind === \"fn\") for (const arg of expr.args) visitExpr(arg);\n if (expr.kind === \"cast\") visitExpr(expr.operand);\n };\n const visit = (current: CondNode): void => {\n switch (current.kind) {\n case \"fields\":\n for (const key of Object.keys(current.fields)) {\n if (!found.includes(key)) found.push(key);\n }\n return;\n case \"and\":\n case \"or\":\n for (const part of current.parts) visit(part);\n return;\n case \"not\":\n visit(current.part);\n return;\n case \"compare\":\n visitExpr(current.left);\n visitExpr(current.right);\n return;\n default:\n return;\n }\n };\n visit(node);\n return found;\n}\n\nexport function foreignKey(\n columns: string[],\n refTable: string,\n refColumns: string[],\n options?: { name?: string; onDelete?: FkAction; onUpdate?: FkAction },\n): TableConstraint {\n if (columns.length === 0 || columns.length !== refColumns.length) {\n throw new Error(\n \"foreignKey() requires matching, non-empty local and referenced column lists.\",\n );\n }\n return {\n kind: \"foreignKey\",\n name: options?.name,\n columns,\n refTable,\n refColumns,\n onDelete: options?.onDelete,\n onUpdate: options?.onUpdate,\n };\n}\n\n/**\n * How property names map to database column names when a column declares no\n * explicit {@link Column.name}.\n *\n * - `\"preserve\"` (default) — the column name is the property name, verbatim.\n * - `\"snake_case\"` — `consumerName` becomes `consumer_name`.\n */\nexport type NamingStrategy = \"preserve\" | \"snake_case\";\n\n/** Convert a `camelCase` / `PascalCase` identifier to `snake_case`. */\nexport function toSnakeCase(name: string): string {\n return name\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .toLowerCase();\n}\n\n/** Base class every model extends, SQLAlchemy-declarative style. */\n// biome-ignore lint/complexity/noStaticOnlyClass: declarative base users subclass; column fields live on instances.\nexport abstract class Model {\n static tablename: string;\n /**\n * Optional table-level constraints (composite unique / foreign keys), returned\n * by a thunk so forward references resolve lazily. Mirrors SQLAlchemy's\n * `__table_args__`.\n */\n static tableArgs?: () => readonly TableConstraint[];\n /**\n * How to derive column names from property names (default `\"preserve\"`). Set\n * `\"snake_case\"` to keep a `snake_case` schema behind a `camelCase` model\n * without annotating every column; {@link Column.name} overrides it per column.\n */\n static naming?: NamingStrategy;\n}\n\n/** Memoized column maps, keyed by model class (identity is stable per class). */\nconst columnsCache = new WeakMap<ModelClass, Record<string, Column<unknown>>>();\n\n/**\n * Reflect a model class into its column map at runtime, keyed by column name.\n *\n * Instantiates the class once and collects every field that is a `Column`. Used\n * by the serialization layer and (Phase 6) the migration schema reflector.\n *\n * The result is **memoized per class** — a model's columns never change at\n * runtime, and this is called once per row on hot read paths (coercion, joins),\n * so re-instantiating the class every time would dominate large result sets.\n *\n * @param model The model class (subclass of `Model`).\n * @returns A record of column name → `Column` instance (do not mutate).\n */\nexport function columnsOf(model: ModelClass): Record<string, Column<unknown>> {\n const cached = columnsCache.get(model);\n if (cached) return cached;\n const instance = new (model as new () => Model)();\n const out: Record<string, Column<unknown>> = {};\n for (const [key, value] of Object.entries(instance)) {\n if (value instanceof Column) {\n out[key] = value as Column<unknown>;\n }\n }\n columnsCache.set(model, out);\n return out;\n}\n\n/** A mapping between property names and database column names. */\nexport type NameMap = Readonly<Record<string, string>>;\n\n/** Memoized property → column maps (`null` when every name is the identity). */\nconst nameMapCache = new WeakMap<ModelClass, NameMap | null>();\n\n/** Memoized column → property maps (`null` when every name is the identity). */\nconst propMapCache = new WeakMap<ModelClass, NameMap | null>();\n\n/**\n * The property → database-column map for a model, or `null` when every column\n * keeps its property name.\n *\n * `null` is the common case and the fast path: builders and the row coercer skip\n * translation entirely, so a model that renames nothing costs nothing. The map\n * is memoized per class, like {@link columnsOf}.\n *\n * @param model The model class.\n * @returns The name map, or `null` when no column is renamed.\n * @throws Error When two properties resolve to the same column name.\n */\nexport function columnNamesOf(model: ModelClass): NameMap | null {\n const cached = nameMapCache.get(model);\n if (cached !== undefined) return cached;\n const strategy: NamingStrategy = model.naming ?? \"preserve\";\n const map: Record<string, string> = {};\n const seen = new Map<string, string>();\n let renamed = false;\n for (const [prop, col] of Object.entries(columnsOf(model))) {\n const dbName = col.dbName ?? (strategy === \"snake_case\" ? toSnakeCase(prop) : prop);\n const collision = seen.get(dbName);\n if (collision !== undefined) {\n throw new Error(\n `${model.tablename}: properties \"${collision}\" and \"${prop}\" both map to column \"${dbName}\".`,\n );\n }\n seen.set(dbName, prop);\n map[prop] = dbName;\n if (dbName !== prop) renamed = true;\n }\n const result = renamed ? (map as NameMap) : null;\n nameMapCache.set(model, result);\n return result;\n}\n\n/**\n * The database-column → property map for a model, or `null` when every column\n * keeps its property name. The inverse of {@link columnNamesOf}, used to map\n * driver rows back into property space.\n *\n * @param model The model class.\n * @returns The inverse name map, or `null` when no column is renamed.\n */\nexport function columnPropsOf(model: ModelClass): NameMap | null {\n const cached = propMapCache.get(model);\n if (cached !== undefined) return cached;\n const forward = columnNamesOf(model);\n let result: NameMap | null = null;\n if (forward) {\n const inverse: Record<string, string> = {};\n for (const [prop, dbName] of Object.entries(forward)) inverse[dbName] = prop;\n result = inverse as NameMap;\n }\n propMapCache.set(model, result);\n return result;\n}\n\n/** Resolve one property name to its database column name. */\nexport function dbColumn(names: NameMap | null | undefined, prop: string): string {\n return names?.[prop] ?? prop;\n}\n\n/**\n * Every primary-key column of a model, in declaration order.\n *\n * A composite key is a list of more than one name — which is why this returns an\n * array and not a single name. Reading only the first entry is how a repository\n * ends up filtering half a key and touching the wrong row.\n *\n * @param model The model class.\n * @returns The primary-key column names (property names, not database names).\n * @throws Error When the model declares no primary key.\n */\nexport function primaryKeysOf(model: ModelClass): string[] {\n const keys: string[] = [];\n for (const [name, col] of Object.entries(columnsOf(model))) {\n if (col.flags.primaryKey) keys.push(name);\n }\n if (keys.length === 0) throw new Error(`${model.tablename} has no primary key`);\n return keys;\n}\n\n/**\n * Turn a primary-key argument into the filter that identifies exactly one row.\n *\n * A single-column key takes the bare value (or an object carrying it); a\n * composite key **requires** the object, because a scalar cannot say which of the\n * key columns it is. Passing a scalar for a composite key throws instead of\n * silently matching on one column.\n *\n * @param model The model class.\n * @param id The key: a scalar, or an object with every key column.\n * @returns A filter object covering the whole key.\n * @throws Error When the key is incomplete, or a scalar was given for a composite key.\n */\nexport function primaryKeyFilter(\n model: ModelClass,\n id: unknown,\n): Record<string, unknown> {\n const keys = primaryKeysOf(model);\n const asObject =\n typeof id === \"object\" && id !== null && !Array.isArray(id) && !(id instanceof Date)\n ? (id as Record<string, unknown>)\n : null;\n const first = keys[0] as string;\n if (keys.length === 1) {\n return { [first]: asObject && first in asObject ? asObject[first] : id };\n }\n if (asObject === null) {\n throw new Error(\n `${model.tablename} has a composite primary key (${keys.join(\", \")}); pass an object like { ${keys.join(\", \")} } instead of a scalar.`,\n );\n }\n const filter: Record<string, unknown> = {};\n for (const key of keys) {\n if (!(key in asObject)) {\n throw new Error(\n `${model.tablename} has a composite primary key (${keys.join(\", \")}); the key is missing ${JSON.stringify(key)}.`,\n );\n }\n filter[key] = asObject[key];\n }\n return filter;\n}\n\n/** Pull the static type out of a Column. */\ntype ColType<C> = C extends Column<infer T, infer _F> ? T : never;\n\n/** Keys of the model instance whose values are Columns. */\ntype ColumnKeys<M> = {\n [K in keyof M]: M[K] extends Column<unknown, ColumnFlags> ? K : never;\n}[keyof M];\n\n/** Constructor type for a Model subclass. */\ntype ModelClass = (new () => Model) & {\n tablename: string;\n tableArgs?: () => readonly TableConstraint[];\n naming?: NamingStrategy;\n};\n\n/** Flatten an intersection into a single object literal for clean inference. */\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The nullability-aware value a column contributes to a row. */\ntype ColValue<Col> = Col extends Column<infer T, infer F>\n ? F extends { notNull: true } | { primaryKey: true }\n ? T\n : T | null\n : never;\n\n/** True when a column has a default (or is a PK) — i.e. optional on insert. */\ntype HasDefault<Col> = Col extends Column<unknown, infer F>\n ? F extends { hasDefault: true }\n ? true\n : false\n : false;\n\n/** True when a column accepts NULL — neither `notNull` nor a primary key. */\ntype IsNullable<Col> = Col extends Column<unknown, infer F>\n ? F extends { notNull: true } | { primaryKey: true }\n ? false\n : true\n : false;\n\n/**\n * Keys of the model whose columns may be omitted on insert.\n *\n * A column is optional when it has a default **or** when it accepts NULL: SQL\n * applies `NULL` to an omitted column that declares no other default, so\n * requiring the caller to write `note: null` adds noise that reads like a\n * deliberate decision to blank the column. Passing `null` explicitly still works.\n */\ntype OptionalInsertKeys<I> = {\n [K in ColumnKeys<I>]: HasDefault<I[K]> extends true\n ? K\n : IsNullable<I[K]> extends true\n ? K\n : never;\n}[ColumnKeys<I>];\n\n/**\n * Infer the SELECT row shape from a model class: every column field becomes its\n * mapped static type. Columns marked notNull/primaryKey are non-nullable; others\n * are `T | null` (SQL semantics — an unconstrained column can be NULL).\n */\nexport type InferModel<C extends ModelClass> = {\n [K in ColumnKeys<InstanceType<C>>]: ColValue<InstanceType<C>[K]>;\n};\n\n/**\n * Infer the INSERT shape: a column is optional when it has a default (or is a PK)\n * **or** when it is nullable — matching SQL, where an omitted column with no\n * `DEFAULT` clause is written as `NULL`. Only `notNull` columns without a default\n * are required. Nullability is preserved on both sides.\n */\nexport type InferInsert<C extends ModelClass> = Simplify<\n {\n [K in OptionalInsertKeys<InstanceType<C>>]?: ColValue<InstanceType<C>[K]>;\n } & {\n [K in Exclude<\n ColumnKeys<InstanceType<C>>,\n OptionalInsertKeys<InstanceType<C>>\n >]: ColValue<InstanceType<C>[K]>;\n }\n>;\n\nexport { Column, type ColType, type ColumnFlags, type ModelClass };\n\nexport {\n and,\n caseWhen,\n cast,\n type CastType,\n col,\n type CondNode,\n type Condition,\n Expression,\n type ExprNode,\n fn,\n isCondition,\n isExpression,\n not,\n or,\n toCondNode,\n val,\n type WhereArg,\n} from \"./conditions.js\";\n\nexport {\n denseRank,\n firstValue,\n lag,\n lastValue,\n lead,\n over,\n percentRank,\n rank,\n rowNumber,\n type WindowFn,\n type WindowSpec,\n} from \"./window.js\";\n\nexport {\n Agg,\n type AggregateTerm,\n avg,\n count,\n type LockClause,\n type LockOptions,\n max,\n min,\n exists,\n isSubquery,\n notExists,\n scalar,\n type SubqueryLike,\n type Operator,\n type OperatorsFor,\n OPERATORS,\n type OrderTerm,\n type SelectNode,\n SelectBuilder,\n select,\n type SortDirection,\n type Subquery,\n sum,\n type WhereInput,\n} from \"./query.js\";\n\nexport {\n DeleteBuilder,\n type DeleteNode,\n del,\n InsertBuilder,\n type InsertNode,\n insert,\n type OnConflict,\n type OnConflictOptions,\n type OnConflictUpdateOptions,\n type Returning,\n type WritePatch,\n type WriteValues,\n UpdateBuilder,\n type UpdateNode,\n update,\n} from \"./mutations.js\";\n\nexport {\n type Dialect,\n detectDialect,\n InvalidDatabaseUrl,\n type ParsedDatabaseUrl,\n parseDatabaseUrl,\n} from \"./url.js\";\n\nexport {\n decodeValue as decodeColumnValue,\n encodeValue as encodeColumnValue,\n fromDict,\n parse,\n stringify,\n toDict,\n toJSON,\n ValidationError,\n} from \"./serialize.js\";\n\nexport {\n BaseDialect,\n type CompiledQuery,\n getDialect,\n MysqlDialect,\n Params,\n PostgresDialect,\n type QueryNode,\n SqliteDialect,\n} from \"./dialect.js\";\n\nexport {\n type ColRef,\n join,\n JoinBuilder,\n type JoinClause,\n type JoinNode,\n type JoinOn,\n type JoinSelection,\n type JoinWhereInput,\n type Sources,\n} from \"./join.js\";\n\nexport {\n type ModelBase,\n notDeleted,\n onlyDeleted,\n withAudit,\n withSoftDelete,\n withTimestamps,\n} from \"./mixins.js\";\n\nexport {\n type IntegrityFailure,\n type IntegrityViolation,\n parseIntegrityError,\n} from \"./integrity.js\";\n\nexport {\n type ContainsOptions,\n contains,\n escapeLike,\n fullText,\n fullTextRank,\n type TextSearchLanguage,\n type TextSearchOptions,\n tokenize,\n} from \"./search.js\";\n\nexport {\n clearSignals,\n emitSignal,\n hasHandlers,\n onSignal,\n type RepositorySignal,\n type SignalHandler,\n type SignalPayload,\n} from \"./signals.js\";\n\nexport {\n except,\n intersect,\n SetBuilder,\n type SetNode,\n type SetOperator,\n union,\n unionAll,\n} from \"./setops.js\";\n\nexport {\n type ClaimOptions,\n type FailOptions,\n type OutboxEventInput,\n OutboxRepository,\n type OutboxStatus,\n outboxModel,\n} from \"./outbox.js\";\n\nexport {\n type ExplainOptions,\n type ExplainReport,\n isReadOnlyStatement,\n type QueryPlan,\n summarizePlan,\n} from \"./explain.js\";\n\nexport { type TenantScope, TenantScopedRepository } from \"./tenant.js\";\n\nexport {\n type AuditAction,\n type AuditDiff,\n type AuditEntry,\n type AuditOptions,\n auditLogModel,\n diffSnapshots,\n enableAudit,\n snapshot,\n} from \"./audit.js\";\n\nexport {\n type BackupOptions,\n type BackupResult,\n BackupToolMissing,\n backupDatabase,\n backupFormat,\n restoreDatabase,\n toolUrl,\n UnsupportedBackupBackend,\n} from \"./backup.js\";\n\nexport {\n attach as attachCte,\n Cte,\n type CteBody,\n type CteNode,\n type CteOptions,\n cte,\n cteRecursive,\n} from \"./cte.js\";\n\nexport { aliasOf, aliased } from \"./aliased.js\";\n\nexport { type FlushResult, type Tracked, UnitOfWork } from \"./unit-of-work.js\";\n\nexport {\n BaseRepository,\n type BulkUpsertOptions,\n type ChangesPage,\n type ChangesSinceFilter,\n type CursorPage,\n type CursorPaginationFilter,\n InvalidCursor,\n type PaginationFilter,\n type PaginationResult,\n RecordNotFound,\n} from \"./repository.js\";\n\nexport {\n ActiveRecord,\n type ActiveRecordManager,\n activeRecord,\n} from \"./active-record.js\";\n\nexport {\n type BelongsTo,\n belongsTo,\n type HasMany,\n hasMany,\n loadRelations,\n type Relation,\n type RelationValue,\n type WithRelations,\n} from \"./relations.js\";\n\nexport {\n AsyncEngine,\n AsyncResult,\n AsyncSession,\n type AsyncDriver,\n BetterSqliteDriver,\n createEngine,\n createSyncEngine,\n type DriverResult,\n type EngineOptions,\n type IsolationLevel,\n type Executable,\n NoResultError,\n NodeSqliteDriver,\n type NoticeLogger,\n type PoolOptions,\n QueryExecutionError,\n type QueryEndEvent,\n type QueryEndLogger,\n type QueryHooks,\n type QueryLogger,\n type ReservedAsyncDriver,\n type SqliteJournalMode,\n type SqliteOptions,\n type SqliteSynchronous,\n type RowOf,\n type SyncDriver,\n SyncEngine,\n SyncResult,\n SyncSession,\n toAsyncDriver,\n type TransactionOptions,\n} from \"./engine.js\";\n"]}