@aeye/query 0.6.6 → 0.7.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.
package/dist/index.js CHANGED
@@ -210,11 +210,11 @@ function suggestionBudget(len) {
210
210
  return Math.min(3, Math.max(1, Math.floor(len / 3)));
211
211
  }
212
212
  function rankNear(input, candidates, budget) {
213
- const lower2 = input.toLowerCase();
213
+ const lower3 = input.toLowerCase();
214
214
  const scored = candidates.map((candidate, index) => ({
215
215
  candidate,
216
216
  index,
217
- ci: editDistance(lower2, candidate.toLowerCase()),
217
+ ci: editDistance(lower3, candidate.toLowerCase()),
218
218
  exact: editDistance(input, candidate)
219
219
  })).filter((s) => s.ci <= budget);
220
220
  scored.sort((a, b) => a.ci - b.ci || a.exact - b.exact || a.index - b.index);
@@ -748,10 +748,10 @@ function met(value2) {
748
748
  return { ok: true, value: value2 };
749
749
  }
750
750
  var MEET_CONFLICT = { ok: false };
751
- function meetExact(a, b, eq2 = Object.is) {
751
+ function meetExact(a, b, eq4 = Object.is) {
752
752
  if (a === void 0) return met(b);
753
753
  if (b === void 0) return met(a);
754
- return eq2(a, b) ? met(a) : MEET_CONFLICT;
754
+ return eq4(a, b) ? met(a) : MEET_CONFLICT;
755
755
  }
756
756
  function meetLower(a, b) {
757
757
  if (a === void 0) return b;
@@ -763,8 +763,8 @@ function meetUpper(a, b) {
763
763
  if (b === void 0) return a;
764
764
  return Math.min(a, b);
765
765
  }
766
- function emptyRange(lower2, upper) {
767
- return lower2 !== void 0 && upper !== void 0 && lower2 > upper;
766
+ function emptyRange(lower3, upper) {
767
+ return lower3 !== void 0 && upper !== void 0 && lower3 > upper;
768
768
  }
769
769
  function meetFlag(a, b) {
770
770
  if (a === void 0 && b === void 0) return void 0;
@@ -3708,8 +3708,8 @@ var QueryFunction = class _QueryFunction {
3708
3708
  */
3709
3709
  orderedArgs(namedArgs) {
3710
3710
  const out = [];
3711
- for (const param3 of this.params) {
3712
- const a = namedArgs.get(param3.name);
3711
+ for (const param4 of this.params) {
3712
+ const a = namedArgs.get(param4.name);
3713
3713
  if (a) out.push(a);
3714
3714
  }
3715
3715
  return out;
@@ -3800,38 +3800,38 @@ var FUNCTION_CALL_WORDS = {
3800
3800
  declared: "parameter",
3801
3801
  code: "function"
3802
3802
  };
3803
- function validateNamedCall(words, name, declared, namedArgs, p, paramArgs = EMPTY_PARAM_ARGS) {
3804
- const suppliedLower = words.supplied.toLowerCase();
3805
- for (const param3 of declared) {
3806
- if (param3.optional) continue;
3807
- if (!namedArgs.has(param3.name)) {
3803
+ function validateNamedCall(words2, name, declared, namedArgs, p, paramArgs = EMPTY_PARAM_ARGS) {
3804
+ const suppliedLower = words2.supplied.toLowerCase();
3805
+ for (const param4 of declared) {
3806
+ if (param4.optional) continue;
3807
+ if (!namedArgs.has(param4.name)) {
3808
3808
  p.error(
3809
- `${words.code}.missing-arg`,
3810
- `${words.noun} '${name}' is missing required ${suppliedLower} '${param3.name}'.`
3809
+ `${words2.code}.missing-arg`,
3810
+ `${words2.noun} '${name}' is missing required ${suppliedLower} '${param4.name}'.`
3811
3811
  );
3812
3812
  }
3813
3813
  }
3814
- const byName = new Map(declared.map((param3) => [param3.name, param3]));
3814
+ const byName = new Map(declared.map((param4) => [param4.name, param4]));
3815
3815
  for (const [argName, argType] of namedArgs) {
3816
- const param3 = byName.get(argName);
3817
- if (!param3) {
3816
+ const param4 = byName.get(argName);
3817
+ if (!param4) {
3818
3818
  p.at(["args", argName], () => {
3819
3819
  p.error(
3820
- `${words.code}.unknown-arg`,
3821
- `${words.noun} '${name}' has no ${words.declared} named '${argName}'.${didYouMean(argName, declared.map((d) => d.name))}`
3820
+ `${words2.code}.unknown-arg`,
3821
+ `${words2.noun} '${name}' has no ${words2.declared} named '${argName}'.${didYouMean(argName, declared.map((d) => d.name))}`
3822
3822
  );
3823
3823
  });
3824
3824
  continue;
3825
3825
  }
3826
- const declaredType = param3.fieldType;
3826
+ const declaredType = param4.fieldType;
3827
3827
  if (!declaredType) continue;
3828
3828
  if (paramArgs.has(argName)) continue;
3829
3829
  const argFt = asFieldType(argType);
3830
3830
  if (!argFt) {
3831
3831
  p.at(["args", argName], () => {
3832
3832
  p.error(
3833
- `${words.code}.arg-type`,
3834
- `${words.supplied} '${argName}' of '${name}' must be a ${declaredType.resolve()} value (a type cannot be passed here).`
3833
+ `${words2.code}.arg-type`,
3834
+ `${words2.supplied} '${argName}' of '${name}' must be a ${declaredType.resolve()} value (a type cannot be passed here).`
3835
3835
  );
3836
3836
  });
3837
3837
  continue;
@@ -3839,8 +3839,8 @@ function validateNamedCall(words, name, declared, namedArgs, p, paramArgs = EMPT
3839
3839
  if (!declaredType.comparableWith(argFt)) {
3840
3840
  p.at(["args", argName], () => {
3841
3841
  p.error(
3842
- `${words.code}.arg-type`,
3843
- `${words.supplied} '${argName}' of '${name}' expects ${declaredType.resolve()}, got ${argFt.resolve()}.`
3842
+ `${words2.code}.arg-type`,
3843
+ `${words2.supplied} '${argName}' of '${name}' expects ${declaredType.resolve()}, got ${argFt.resolve()}.`
3844
3844
  );
3845
3845
  });
3846
3846
  }
@@ -5134,7 +5134,7 @@ var SqlText = class _SqlText {
5134
5134
  sql += seg.text;
5135
5135
  } else {
5136
5136
  sql += dialect.bindPlaceholder(params.length);
5137
- params.push(seg.value);
5137
+ params.push(dialect.encodeParam(seg.value));
5138
5138
  }
5139
5139
  }
5140
5140
  return { sql, params };
@@ -5529,7 +5529,7 @@ var SchemaCache = class {
5529
5529
  const params = fn2.params.map((p) => `${p.name}${p.optional ? "?" : ""}`);
5530
5530
  return this.shared(`args ${params.join(",")}`, "Args", (id) => {
5531
5531
  const shape = {};
5532
- for (const param3 of fn2.params) shape[param3.name] = param3.optional ? child.optional() : child;
5532
+ for (const param4 of fn2.params) shape[param4.name] = param4.optional ? child.optional() : child;
5533
5533
  const named = params.length ? params.join(", ") : "none";
5534
5534
  return withSharedId(z18.strictObject(shape).describe(`Named arguments: ${named}.`), id);
5535
5535
  });
@@ -5828,8 +5828,8 @@ function functionObject(kind, functionField, argsField, child) {
5828
5828
  function typedArgsSchema(fn2, child, cache) {
5829
5829
  if (cache) return cache.typedArgs(fn2, child);
5830
5830
  const shape = {};
5831
- for (const param3 of fn2.params) {
5832
- shape[param3.name] = param3.optional ? child.optional() : child;
5831
+ for (const param4 of fn2.params) {
5832
+ shape[param4.name] = param4.optional ? child.optional() : child;
5833
5833
  }
5834
5834
  return z18.strictObject(shape).describe(`Named arguments for \`${fn2.name}\`.`);
5835
5835
  }
@@ -6572,18 +6572,18 @@ function triOf(v) {
6572
6572
  // src/exprs/_relation-compare.ts
6573
6573
  var HAS_MANY_ALIAS = "__rel";
6574
6574
  function relationCompare(operand, engine, typeOf2) {
6575
- const ref3 = operand.fieldRef();
6576
- if (!ref3) return void 0;
6577
- const owner = typeOf2(ref3.source);
6575
+ const ref4 = operand.fieldRef();
6576
+ if (!ref4) return void 0;
6577
+ const owner = typeOf2(ref4.source);
6578
6578
  if (!owner) return void 0;
6579
- const field = owner.field(ref3.field);
6579
+ const field = owner.field(ref4.field);
6580
6580
  if (!field || !(field.fieldType instanceof RelationFieldType)) return void 0;
6581
6581
  const ft = field.fieldType;
6582
6582
  const target = engine.type(ft.to);
6583
6583
  if (!target) return void 0;
6584
6584
  return {
6585
- source: ref3.source,
6586
- keys: ft.resolveKeys(engine, ref3.field, owner, target),
6585
+ source: ref4.source,
6586
+ keys: ft.resolveKeys(engine, ref4.field, owner, target),
6587
6587
  belongsTo: ft.isBelongsTo(),
6588
6588
  target
6589
6589
  };
@@ -6681,13 +6681,13 @@ function valueComponentsSql(value2, pkFields, ctx) {
6681
6681
  function emitHasMany(op, rel, value2, dialect, ctx) {
6682
6682
  const pkFields = rel.target.primaryKey().map((f) => f.name);
6683
6683
  const comps = valueComponentsSql(value2, pkFields, ctx);
6684
- const eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
6684
+ const eq4 = (left, right) => ({ kind: "comparison", op: "=", left, right });
6685
6685
  const col = (source, field) => ({ kind: "field-ref", source, field });
6686
6686
  const where = [
6687
6687
  // Correlation: each has-many key joins the target's FK-back column to this row's identity.
6688
- ...rel.keys.map((k) => eq2(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
6688
+ ...rel.keys.map((k) => eq4(col(HAS_MANY_ALIAS, k.foreign), col(rel.source, k.local))),
6689
6689
  // Membership: the target's PK equals the value's components.
6690
- ...pkFields.map((pk, i) => eq2(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
6690
+ ...pkFields.map((pk, i) => eq4(col(HAS_MANY_ALIAS, pk), { kind: "literal", value: comps[i] ?? null }))
6691
6691
  ];
6692
6692
  const def = {
6693
6693
  kind: "select",
@@ -6697,8 +6697,8 @@ function emitHasMany(op, rel, value2, dialect, ctx) {
6697
6697
  from: { kind: "aliased", type: rel.target.name, as: HAS_MANY_ALIAS },
6698
6698
  where
6699
6699
  };
6700
- const sub2 = emitSubquerySQL(dialect, ctx, def);
6701
- return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub2]);
6700
+ const sub3 = emitSubquerySQL(dialect, ctx, def);
6701
+ return SqlText.concat([SqlText.raw(op === "=" ? "EXISTS " : "NOT EXISTS "), sub3]);
6702
6702
  }
6703
6703
 
6704
6704
  // src/exprs/_field-guard.ts
@@ -6926,8 +6926,8 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
6926
6926
  /** An `=` against a column is an index point-probe (arity 1); other ops are not. */
6927
6927
  indexProbe() {
6928
6928
  if (this.op !== "=") return void 0;
6929
- const ref3 = this.left.fieldRef() ?? this.right.fieldRef();
6930
- return ref3 ? { ref: ref3, arity: 1 } : void 0;
6929
+ const ref4 = this.left.fieldRef() ?? this.right.fieldRef();
6930
+ return ref4 ? { ref: ref4, arity: 1 } : void 0;
6931
6931
  }
6932
6932
  /** Evaluate under 3VL: a NULL operand yields UNKNOWN; text folds case unless the governing {@link TextCasing} is `'exact'`. */
6933
6933
  async evaluateBool(ctx, row, group) {
@@ -6946,20 +6946,20 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
6946
6946
  if (l.isNull() || r.isNull()) return void 0;
6947
6947
  const sensitive = !foldsAtRuntime(effectiveCasing(l.textCasing(), r.textCasing(), ctx.engine.textCasing));
6948
6948
  if (LIKE_OPS.has(this.op)) return this.evalLike(l, r, sensitive);
6949
- const cmp = l.compareToCase(r, sensitive);
6949
+ const cmp2 = l.compareToCase(r, sensitive);
6950
6950
  switch (this.op) {
6951
6951
  case "=":
6952
- return cmp === 0;
6952
+ return cmp2 === 0;
6953
6953
  case "<>":
6954
- return cmp !== 0;
6954
+ return cmp2 !== 0;
6955
6955
  case "<":
6956
- return cmp < 0;
6956
+ return cmp2 < 0;
6957
6957
  case "<=":
6958
- return cmp <= 0;
6958
+ return cmp2 <= 0;
6959
6959
  case ">":
6960
- return cmp > 0;
6960
+ return cmp2 > 0;
6961
6961
  case ">=":
6962
- return cmp >= 0;
6962
+ return cmp2 >= 0;
6963
6963
  default:
6964
6964
  return false;
6965
6965
  }
@@ -7121,16 +7121,16 @@ var ALLOWED_DATE_FIELDS = /* @__PURE__ */ new Set([
7121
7121
  function validateRawArgs(fn2, args, p) {
7122
7122
  if (!fn2.rawArgs) return;
7123
7123
  for (const idx of fn2.rawArgs) {
7124
- const param3 = fn2.params[idx];
7125
- const e2 = args.get(param3.name);
7124
+ const param4 = fn2.params[idx];
7125
+ const e2 = args.get(param4.name);
7126
7126
  if (!e2) continue;
7127
7127
  const token = rawStringLiteral(e2);
7128
7128
  if (token === void 0 || !ALLOWED_DATE_FIELDS.has(token)) {
7129
7129
  p.at(
7130
- ["args", param3.name],
7130
+ ["args", param4.name],
7131
7131
  () => p.error(
7132
7132
  "function.raw-arg",
7133
- `Argument '${param3.name}' of '${fn2.name}' must be a literal date field (one of: ${[...ALLOWED_DATE_FIELDS].join(", ")}).`
7133
+ `Argument '${param4.name}' of '${fn2.name}' must be a literal date field (one of: ${[...ALLOWED_DATE_FIELDS].join(", ")}).`
7134
7134
  )
7135
7135
  );
7136
7136
  }
@@ -7138,7 +7138,7 @@ function validateRawArgs(fn2, args, p) {
7138
7138
  }
7139
7139
  function orderedArgSql(fnName, args, dialect, ctx) {
7140
7140
  const fn2 = ctx.engine.lookupFunction(fnName);
7141
- const order = fn2 ? fn2.params.map((param3) => param3.name) : [...args.keys()];
7141
+ const order = fn2 ? fn2.params.map((param4) => param4.name) : [...args.keys()];
7142
7142
  const rawSet = new Set(fn2?.rawArgs ?? []);
7143
7143
  const seen = /* @__PURE__ */ new Set();
7144
7144
  const out = [];
@@ -7155,14 +7155,14 @@ function orderedArgSql(fnName, args, dialect, ctx) {
7155
7155
  return out;
7156
7156
  }
7157
7157
  function observeNamedParams(args, declared, engine, scope, here, argTypes) {
7158
- const byName = new Map(declared.map((param3) => [param3.name, param3]));
7158
+ const byName = new Map(declared.map((param4) => [param4.name, param4]));
7159
7159
  const paramArgs = /* @__PURE__ */ new Set();
7160
7160
  for (const [name, e2] of args) {
7161
7161
  if (!(e2 instanceof ParamExpr)) continue;
7162
- const param3 = byName.get(name);
7163
- if (!param3?.fieldType) continue;
7162
+ const param4 = byName.get(name);
7163
+ if (!param4?.fieldType) continue;
7164
7164
  paramArgs.add(name);
7165
- scope.params.observe(e2.name, param3.fieldType, [...here, "args", name]);
7165
+ scope.params.observe(e2.name, param4.fieldType, [...here, "args", name]);
7166
7166
  argTypes.set(name, e2.resolve(engine, scope));
7167
7167
  }
7168
7168
  return paramArgs;
@@ -7425,7 +7425,7 @@ function describeRegistered(engine) {
7425
7425
  }
7426
7426
 
7427
7427
  // src/registry.ts
7428
- import { z as z40 } from "zod";
7428
+ import { z as z42 } from "zod";
7429
7429
 
7430
7430
  // src/type.ts
7431
7431
  import { z as z23 } from "zod";
@@ -8005,8 +8005,8 @@ function sortByKeys(entries, terms) {
8005
8005
  const decorated = [...entries];
8006
8006
  decorated.sort((a, b) => {
8007
8007
  for (let i = 0; i < terms.length; i++) {
8008
- const cmp = compareWithNulls(a.keys[i], b.keys[i], terms[i]);
8009
- if (cmp !== 0) return cmp;
8008
+ const cmp2 = compareWithNulls(a.keys[i], b.keys[i], terms[i]);
8009
+ if (cmp2 !== 0) return cmp2;
8010
8010
  }
8011
8011
  return 0;
8012
8012
  });
@@ -8045,8 +8045,8 @@ function compareWithNulls(a, b, term) {
8045
8045
  const nullIsA = aNull ? -1 : 1;
8046
8046
  return nullsFirst ? nullIsA : -nullIsA;
8047
8047
  }
8048
- const cmp = a.compareTo(b);
8049
- return term.dir === "desc" ? -cmp : cmp;
8048
+ const cmp2 = a.compareTo(b);
8049
+ return term.dir === "desc" ? -cmp2 : cmp2;
8050
8050
  }
8051
8051
 
8052
8052
  // src/exprs/sorter.ts
@@ -8670,7 +8670,7 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
8670
8670
  /** Emit as a parenthesized SqlText fragment (`NOT (...)`, or operands joined by `AND` / `OR`). */
8671
8671
  toSQL(dialect, ctx) {
8672
8672
  if (this.op === "not") {
8673
- const inner = this.operands[0]?.toSQL(dialect, ctx) ?? SqlText.raw("TRUE");
8673
+ const inner = this.operands[0]?.toSQL(dialect, ctx) ?? dialect.trueSql();
8674
8674
  return SqlText.concat([SqlText.raw("NOT "), inner.parens()]);
8675
8675
  }
8676
8676
  const sep = this.op === "and" ? " AND " : " OR ";
@@ -8939,8 +8939,8 @@ var InExpr = class _InExpr extends BoolExpr {
8939
8939
  */
8940
8940
  indexProbe() {
8941
8941
  if (!this.list || this.not) return void 0;
8942
- const ref3 = this.value.fieldRef();
8943
- return ref3 ? { ref: ref3, arity: this.list.length } : void 0;
8942
+ const ref4 = this.value.fieldRef();
8943
+ return ref4 ? { ref: ref4, arity: this.list.length } : void 0;
8944
8944
  }
8945
8945
  /** Evaluate under 3VL: TRUE if any element equals the value; else UNKNOWN if the value or any element is NULL; else FALSE (negated for `NOT IN`). */
8946
8946
  async evaluateBool(ctx, row, group) {
@@ -9035,10 +9035,10 @@ var InExpr = class _InExpr extends BoolExpr {
9035
9035
  import { z as z28 } from "zod";
9036
9036
  var BetweenExpr = class _BetweenExpr extends BoolExpr {
9037
9037
  /** Wrap `value [NOT] BETWEEN lower AND upper` as a range predicate. */
9038
- constructor(value2, lower2, upper, not2) {
9038
+ constructor(value2, lower3, upper, not2) {
9039
9039
  super();
9040
9040
  this.value = value2;
9041
- this.lower = lower2;
9041
+ this.lower = lower3;
9042
9042
  this.upper = upper;
9043
9043
  this.not = not2;
9044
9044
  }
@@ -10304,8 +10304,8 @@ var WindowExpr = class _WindowExpr extends Expr {
10304
10304
  /** Compare two rows by the ORDER BY clause. */
10305
10305
  compareByOrder(a, b) {
10306
10306
  for (let i = 0; i < this.orderBy.length; i++) {
10307
- const cmp = a[i].compareTo(b[i]);
10308
- if (cmp !== 0) return this.orderBy[i].dir === "desc" ? -cmp : cmp;
10307
+ const cmp2 = a[i].compareTo(b[i]);
10308
+ if (cmp2 !== 0) return this.orderBy[i].dir === "desc" ? -cmp2 : cmp2;
10309
10309
  }
10310
10310
  return 0;
10311
10311
  }
@@ -10882,8 +10882,8 @@ var SemanticExpr = class _SemanticExpr extends Expr {
10882
10882
  if (q.kind === "sourceField" || q.kind === "typeField") {
10883
10883
  p.at("query", () => this.validateQuerySide(scope, p, q));
10884
10884
  } else if (q.kind === "param") {
10885
- const param3 = q.param;
10886
- p.at("query", () => param3.validateWalk(engine, scope, p, ctx));
10885
+ const param4 = q.param;
10886
+ p.at("query", () => param4.validateWalk(engine, scope, p, ctx));
10887
10887
  }
10888
10888
  return this.resolve(engine, scope);
10889
10889
  }
@@ -11362,8 +11362,8 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
11362
11362
  }
11363
11363
  }
11364
11364
  if (this.query.kind === "param") {
11365
- const param3 = this.query.param;
11366
- p.at("query", () => param3.validateWalk(engine, scope, p, ctx));
11365
+ const param4 = this.query.param;
11366
+ p.at("query", () => param4.validateWalk(engine, scope, p, ctx));
11367
11367
  }
11368
11368
  return this.resolve(engine, scope);
11369
11369
  }
@@ -11521,8 +11521,8 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
11521
11521
  }
11522
11522
  }
11523
11523
  if (this.query.kind === "param") {
11524
- const param3 = this.query.param;
11525
- p.at("query", () => param3.validateWalk(engine, scope, p, ctx));
11524
+ const param4 = this.query.param;
11525
+ p.at("query", () => param4.validateWalk(engine, scope, p, ctx));
11526
11526
  }
11527
11527
  return this.resolve(engine, scope);
11528
11528
  }
@@ -11707,7 +11707,7 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
11707
11707
  /** Emit the execution-supplied bool expr's SQL, or `TRUE` when none is bound. */
11708
11708
  toSQL(dialect, ctx) {
11709
11709
  const expr = ctx.filtersFor(this.source);
11710
- if (!expr) return SqlText.raw("TRUE");
11710
+ if (!expr) return dialect.trueSql();
11711
11711
  return expr.toSQL(dialect, ctx);
11712
11712
  }
11713
11713
  /** Serialize back to its JSON ExprDef. */
@@ -12574,8 +12574,8 @@ var QuerySource = class _QuerySource {
12574
12574
  const table = ctx.engine.sourceTable(this.typeName);
12575
12575
  return SqlText.concat([dialect.ident(table), SqlText.raw(" AS "), dialect.ident(this.alias)]);
12576
12576
  }
12577
- const sub2 = this.subquery.toSQL(dialect, ctx).parens();
12578
- return SqlText.concat([sub2, SqlText.raw(" AS "), dialect.ident(this.alias)]);
12577
+ const sub3 = this.subquery.toSQL(dialect, ctx).parens();
12578
+ return SqlText.concat([sub3, SqlText.raw(" AS "), dialect.ident(this.alias)]);
12579
12579
  }
12580
12580
  /** Serialize back to a `SourceDef` (the plain `type` shape, or the `aliased` shape when the alias differs from the type name). */
12581
12581
  toJSON() {
@@ -12957,11 +12957,11 @@ function validateWriteValue(engine, scope, p, ctx, field, expr, owner) {
12957
12957
  }
12958
12958
  if (expr instanceof LiteralExpr && expr.isNullLiteral()) return;
12959
12959
  if (field.fieldType instanceof RelationFieldType) return;
12960
- const valueType = asFieldType(resolved);
12961
- if (valueType && !field.fieldType.comparableWith(valueType)) {
12960
+ const valueType2 = asFieldType(resolved);
12961
+ if (valueType2 && !field.fieldType.comparableWith(valueType2)) {
12962
12962
  p.error(
12963
12963
  "write.type",
12964
- `Cannot write a ${valueType.resolve()} value to field '${field.name}' (${field.fieldType.resolve()}).`
12964
+ `Cannot write a ${valueType2.resolve()} value to field '${field.name}' (${field.fieldType.resolve()}).`
12965
12965
  );
12966
12966
  return;
12967
12967
  }
@@ -13039,8 +13039,8 @@ function boundShape() {
13039
13039
  function selfBinding(type) {
13040
13040
  return { source: type.name, type };
13041
13041
  }
13042
- function boundDigest(ref3, at) {
13043
- return aliasedDigest(ref3.toJSON(), at.source, at.type.name);
13042
+ function boundDigest(ref4, at) {
13043
+ return aliasedDigest(ref4.toJSON(), at.source, at.type.name);
13044
13044
  }
13045
13045
  function scanCost(type) {
13046
13046
  return { rows: type.count, bytes: type.count * type.bytes };
@@ -13126,9 +13126,9 @@ function orFraction(ctx, scope, at, orExpr) {
13126
13126
  }
13127
13127
  function distinctEstimate(at, groupBy, scannedRows) {
13128
13128
  if (groupBy.length === 1) {
13129
- const ref3 = groupBy[0].fieldRef();
13130
- if (ref3) {
13131
- const reduction = bestPrefixReduction(at, [ref3]);
13129
+ const ref4 = groupBy[0].fieldRef();
13130
+ if (ref4) {
13131
+ const reduction = bestPrefixReduction(at, [ref4]);
13132
13132
  if (reduction !== void 0) return Math.max(1, reduction);
13133
13133
  }
13134
13134
  }
@@ -13178,19 +13178,19 @@ function backingCost(ctx, scope, fieldExprs, fromType, outputRows) {
13178
13178
  const counted = /* @__PURE__ */ new Set();
13179
13179
  for (const expr of fieldExprs) {
13180
13180
  expr.walk((e2) => {
13181
- const ref3 = e2.fieldRef();
13182
- if (!ref3) return;
13183
- const bound = scope.lookup(ref3.source);
13181
+ const ref4 = e2.fieldRef();
13182
+ if (!ref4) return;
13183
+ const bound = scope.lookup(ref4.source);
13184
13184
  if (!bound || bound.kind !== "type") return;
13185
- const names = engine.fieldBacking(bound.type.name, ref3.field)?.joins;
13185
+ const names = engine.fieldBacking(bound.type.name, ref4.field)?.joins;
13186
13186
  if (!names) return;
13187
13187
  for (const name of names) {
13188
- const alias = joinAlias(ref3.source, name);
13188
+ const alias = joinAlias(ref4.source, name);
13189
13189
  if (counted.has(alias)) continue;
13190
13190
  counted.add(alias);
13191
13191
  const jb = engine.joinBacking(bound.type.name, name);
13192
13192
  if (!jb?.expr) continue;
13193
- cost = addCost(cost, joinSpecCost(ctx, scope, ref3.source, jb.expr(ref3.source), outputRows));
13193
+ cost = addCost(cost, joinSpecCost(ctx, scope, ref4.source, jb.expr(ref4.source), outputRows));
13194
13194
  }
13195
13195
  });
13196
13196
  }
@@ -13544,7 +13544,7 @@ function rlsPredicate(rls, dialect, engine, planner, typeName, alias) {
13544
13544
  const acc = resolveAccessSql(access, alias, ctx);
13545
13545
  switch (acc.kind) {
13546
13546
  case "deny":
13547
- return SqlText.raw("FALSE");
13547
+ return ctx.dialect.falseSql();
13548
13548
  case "predicate":
13549
13549
  parts.push(acc.sql);
13550
13550
  break;
@@ -13811,7 +13811,7 @@ function defaultConditionPredicatesSql(active, ctx) {
13811
13811
  for (const { alias, cond } of active) {
13812
13812
  const acc = resolveDefaultConditionSql(cond, alias, ctx);
13813
13813
  if (acc.kind === "predicate") preds.push(acc.sql);
13814
- else if (acc.kind === "deny") preds.push(SqlText.raw("FALSE"));
13814
+ else if (acc.kind === "deny") preds.push(ctx.dialect.falseSql());
13815
13815
  }
13816
13816
  return preds;
13817
13817
  }
@@ -14615,14 +14615,6 @@ var SelectQuery = class _SelectQuery extends Query {
14615
14615
  fromSQL(dialect, ctx) {
14616
14616
  return this.from.fromSQL(dialect, ctx);
14617
14617
  }
14618
- /** One ORDER BY clause `<key> ASC|DESC [NULLS FIRST|LAST]` from a resolved key + dir/nulls. */
14619
- orderClauseSQL(key, dir, nulls) {
14620
- return SqlText.concat([
14621
- key,
14622
- SqlText.raw(` ${dir.toUpperCase()}`),
14623
- nulls ? SqlText.raw(` NULLS ${nulls.toUpperCase()}`) : SqlText.empty()
14624
- ]);
14625
- }
14626
14618
  /**
14627
14619
  * One ORDER BY term: `<expr> ASC|DESC [NULLS FIRST|LAST]`. A RELATION term
14628
14620
  * expands to ONE clause per key column (each inheriting the term's direction
@@ -14632,7 +14624,7 @@ var SelectQuery = class _SelectQuery extends Query {
14632
14624
  orderTermSQL(dialect, ctx, o) {
14633
14625
  const keys = relationKeySqls(o.expr, dialect, ctx);
14634
14626
  const sqls = keys ?? [o.expr.toSQL(dialect, ctx)];
14635
- return sqls.map((s) => this.orderClauseSQL(s, o.dir, o.nulls));
14627
+ return sqls.map((s) => dialect.orderTerm(s, o.dir, o.nulls));
14636
14628
  }
14637
14629
  /**
14638
14630
  * Emit the SELECT. A SELECT never prepends its own `WITH` (relation crossings
@@ -14666,11 +14658,11 @@ var SelectQuery = class _SelectQuery extends Query {
14666
14658
  const def = this.effectiveDefaultOrder(engine, isRoot);
14667
14659
  if (def) {
14668
14660
  orderSqls = resolveDefaultOrderSql(def, this.from.alias, outCtx).map(
14669
- (t) => this.orderClauseSQL(t.sql, t.dir, t.nulls)
14661
+ (t) => dialect.orderTerm(t.sql, t.dir, t.nulls)
14670
14662
  );
14671
14663
  }
14672
14664
  const fromSql = this.fromSQL(dialect, selCtx);
14673
- const lo = dialect.limitOffset(boundSQL(this.limit, selCtx), boundSQL(this.offset, selCtx));
14665
+ const lo = dialect.limitOffset(boundSQL(this.limit, selCtx), boundSQL(this.offset, selCtx), orderSqls.length > 0);
14674
14666
  const scan = [SqlText.raw(" FROM "), fromSql];
14675
14667
  for (const j of planner.emittedJoins()) scan.push(SqlText.raw(" "), j);
14676
14668
  if (wherePreds.length) scan.push(SqlText.raw(" WHERE "), SqlText.join(wherePreds, " AND "));
@@ -16357,18 +16349,14 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
16357
16349
  const terms = this.order.map((o) => this.orderTermSQL(dialect, ctx, o));
16358
16350
  parts.push(SqlText.raw(" ORDER BY "), SqlText.join(terms, ", "));
16359
16351
  }
16360
- const lo = dialect.limitOffset(boundSQL(this.limit, ctx), boundSQL(this.offset, ctx));
16352
+ const lo = dialect.limitOffset(boundSQL(this.limit, ctx), boundSQL(this.offset, ctx), this.order.length > 0);
16361
16353
  if (!lo.isEmpty()) parts.push(SqlText.raw(" "), lo);
16362
16354
  return SqlText.concat(parts);
16363
16355
  }
16364
16356
  /** One set-level ORDER BY term: an UNQUALIFIED output column + dir + nulls. */
16365
16357
  orderTermSQL(dialect, ctx, o) {
16366
16358
  const col = o.expr instanceof FieldRefExpr ? dialect.ident(o.expr.field) : o.expr.toSQL(dialect, ctx);
16367
- return SqlText.concat([
16368
- col,
16369
- SqlText.raw(` ${o.dir.toUpperCase()}`),
16370
- o.nulls ? SqlText.raw(` NULLS ${o.nulls.toUpperCase()}`) : SqlText.empty()
16371
- ]);
16359
+ return dialect.orderTerm(col, o.dir, o.nulls);
16372
16360
  }
16373
16361
  /** Serialize back to a `SetOperationDef`, omitting empty / default fields. */
16374
16362
  toJSON() {
@@ -16931,6 +16919,485 @@ var BUILTIN_QUERIES = [
16931
16919
  { KIND: "except", from: SetOperationQuery.from, SHAPE: SetOperationQuery.SHAPE_EXCEPT }
16932
16920
  ];
16933
16921
 
16922
+ // src/ddl/writer.ts
16923
+ import { z as z41 } from "zod";
16924
+
16925
+ // src/ddl/table.ts
16926
+ import { z as z40 } from "zod";
16927
+ var ColumnType = z40.discriminatedUnion("kind", [
16928
+ z40.object({ kind: z40.literal("text"), maxLength: z40.number().int().positive().optional() }),
16929
+ z40.object({ kind: z40.literal("integer"), big: z40.boolean().optional() }),
16930
+ z40.object({
16931
+ kind: z40.literal("decimal"),
16932
+ precision: z40.number().int().positive().optional(),
16933
+ scale: z40.number().int().nonnegative().optional()
16934
+ }),
16935
+ z40.object({ kind: z40.literal("float") }),
16936
+ z40.object({ kind: z40.literal("bool") }),
16937
+ z40.object({ kind: z40.literal("date") }),
16938
+ z40.object({ kind: z40.literal("timestamp"), timezone: z40.boolean().optional() }),
16939
+ z40.object({ kind: z40.literal("uuid") }),
16940
+ z40.object({ kind: z40.literal("json") }),
16941
+ z40.object({ kind: z40.literal("bytes") }),
16942
+ /** A native type with no portable equivalent, kept by name so it survives a round trip. */
16943
+ z40.object({ kind: z40.literal("other"), native: z40.string().min(1) })
16944
+ ]);
16945
+ var ColumnDefault = z40.discriminatedUnion("kind", [
16946
+ z40.object({ kind: z40.literal("value"), value: z40.union([z40.string(), z40.number(), z40.boolean(), z40.null()]) }),
16947
+ z40.object({ kind: z40.literal("now") }),
16948
+ z40.object({ kind: z40.literal("sql"), sql: z40.string().min(1) })
16949
+ ]);
16950
+ var ColumnSpec = z40.object({
16951
+ name: z40.string().min(1),
16952
+ type: ColumnType,
16953
+ nullable: z40.boolean(),
16954
+ default: ColumnDefault.optional(),
16955
+ /** The database assigns the value (an identity / autoincrement key). */
16956
+ generated: z40.boolean().optional(),
16957
+ /** The closed set of values the column may hold (a `CHECK (… IN …)` constraint). */
16958
+ values: z40.array(z40.union([z40.string(), z40.number()])).min(1).optional(),
16959
+ /** The name of that check constraint, when read from a database. */
16960
+ checkName: z40.string().optional(),
16961
+ /** The name of the default constraint (SQL Server), when read from a database. */
16962
+ defaultName: z40.string().optional(),
16963
+ /** A comment or description, when the database has one. */
16964
+ comment: z40.string().optional()
16965
+ });
16966
+ var ForeignKeySpec = z40.object({
16967
+ name: z40.string().optional(),
16968
+ columns: z40.array(z40.string().min(1)).min(1),
16969
+ table: z40.string().min(1),
16970
+ references: z40.array(z40.string().min(1)).min(1),
16971
+ onDelete: z40.enum(["no-action", "cascade", "set-null", "restrict"]).optional()
16972
+ });
16973
+ var UniqueSpec = z40.object({ name: z40.string().optional(), columns: z40.array(z40.string().min(1)).min(1) });
16974
+ var TableSpec = z40.object({
16975
+ name: z40.string().min(1),
16976
+ /** The schema (namespace) it lives in, when the database has them (`public`, `dbo`). */
16977
+ schema: z40.string().optional(),
16978
+ columns: z40.array(ColumnSpec).min(1),
16979
+ primaryKey: z40.array(z40.string().min(1)),
16980
+ primaryKeyName: z40.string().optional(),
16981
+ foreignKeys: z40.array(ForeignKeySpec),
16982
+ unique: z40.array(UniqueSpec),
16983
+ comment: z40.string().optional()
16984
+ });
16985
+ function sameColumnType(a, b) {
16986
+ return JSON.stringify(normalizeColumnType(a)) === JSON.stringify(normalizeColumnType(b));
16987
+ }
16988
+ function normalizeColumnType(t) {
16989
+ switch (t.kind) {
16990
+ case "text":
16991
+ return t.maxLength === void 0 ? { kind: "text" } : { kind: "text", maxLength: t.maxLength };
16992
+ case "integer":
16993
+ return t.big ? { kind: "integer", big: true } : { kind: "integer" };
16994
+ case "decimal":
16995
+ return { kind: "decimal", ...t.precision !== void 0 ? { precision: t.precision } : {}, ...t.scale !== void 0 ? { scale: t.scale } : {} };
16996
+ case "timestamp":
16997
+ return { kind: "timestamp", timezone: t.timezone !== false };
16998
+ default:
16999
+ return t;
17000
+ }
17001
+ }
17002
+ function columnTypeWidens(from, to) {
17003
+ if (sameColumnType(from, to)) return true;
17004
+ switch (to.kind) {
17005
+ case "text":
17006
+ if (to.maxLength === void 0) return from.kind !== "bytes";
17007
+ return from.kind === "text" && from.maxLength !== void 0 && from.maxLength <= to.maxLength;
17008
+ case "integer":
17009
+ return from.kind === "bool" || from.kind === "integer" && to.big === true;
17010
+ case "decimal":
17011
+ if (from.kind === "integer" || from.kind === "bool") return true;
17012
+ if (from.kind !== "decimal") return false;
17013
+ return (to.precision ?? 38) >= (from.precision ?? 38) && (to.scale ?? 0) >= (from.scale ?? 0);
17014
+ case "float":
17015
+ return from.kind === "integer" || from.kind === "bool";
17016
+ case "timestamp":
17017
+ return from.kind === "date" || from.kind === "timestamp" && to.timezone !== false;
17018
+ default:
17019
+ return false;
17020
+ }
17021
+ }
17022
+
17023
+ // src/ddl/writer.ts
17024
+ var DdlAction = z41.enum([
17025
+ "create-table",
17026
+ "drop-table",
17027
+ "rebuild-table",
17028
+ "add-column",
17029
+ "drop-column",
17030
+ "alter-column",
17031
+ "add-constraint",
17032
+ "drop-constraint"
17033
+ ]);
17034
+ var DdlStep = z41.object({
17035
+ action: DdlAction,
17036
+ table: z41.string(),
17037
+ /** The column or constraint the step is about, when it is about one. */
17038
+ target: z41.string().optional(),
17039
+ /** The statements to run, in order. */
17040
+ sql: z41.array(z41.string()).min(1),
17041
+ /** True when the step can lose data: a drop, or a type change that narrows. */
17042
+ irreversible: z41.boolean(),
17043
+ /** One plain sentence saying what the step does. */
17044
+ summary: z41.string()
17045
+ });
17046
+ var DdlError = class extends Error {
17047
+ name = "DdlError";
17048
+ };
17049
+ var SqlDdl = class {
17050
+ constructor(dialect) {
17051
+ this.dialect = dialect;
17052
+ }
17053
+ dialect;
17054
+ canonicalType(type) {
17055
+ return this.readColumnType(this.columnType(type));
17056
+ }
17057
+ readDefault(sql) {
17058
+ let s = sql.trim();
17059
+ while (s.startsWith("(") && s.endsWith(")") && balanced(s.slice(1, -1))) s = s.slice(1, -1).trim();
17060
+ s = s.replace(/::[\w\s"[\].]+(\(\d+(,\s*\d+)?\))?$/u, "").trim();
17061
+ if (/^null$/iu.test(s)) return void 0;
17062
+ if (/^(current_timestamp|now\(\)|getdate\(\)|sysdatetime\(\)|sysdatetimeoffset\(\)|getutcdate\(\)|sysutcdatetime\(\)|datetime\('now'\))$/iu.test(s)) {
17063
+ return { kind: "now" };
17064
+ }
17065
+ if (/^(true|false)$/iu.test(s)) return { kind: "value", value: s.toLowerCase() === "true" };
17066
+ if (/^-?\d+(\.\d+)?$/u.test(s)) return { kind: "value", value: Number(s) };
17067
+ const quoted = /^N?'((?:[^']|'')*)'$/u.exec(s);
17068
+ if (quoted) return { kind: "value", value: (quoted[1] ?? "").replace(/''/g, "'") };
17069
+ return { kind: "sql", sql: s };
17070
+ }
17071
+ diff(current, wanted) {
17072
+ const have = new Map(current.columns.map((c) => [c.name, c]));
17073
+ const want = new Map(wanted.columns.map((c) => [c.name, c]));
17074
+ const changed = [];
17075
+ for (const to of wanted.columns) {
17076
+ const from = have.get(to.name);
17077
+ if (!from) continue;
17078
+ const change = {
17079
+ from,
17080
+ to,
17081
+ type: !sameColumnType(this.canonicalType(from.type), this.canonicalType(to.type)),
17082
+ nullable: from.nullable !== to.nullable,
17083
+ default: this.comparableDefault(from) !== this.comparableDefault(to),
17084
+ values: JSON.stringify(from.values ?? null) !== JSON.stringify(to.values ?? null)
17085
+ };
17086
+ if (change.type || change.nullable || change.default || change.values) changed.push(change);
17087
+ }
17088
+ const fkKey = (f) => JSON.stringify([f.columns, f.table, f.references, f.onDelete ?? "no-action"]);
17089
+ const uqKey = (u) => JSON.stringify(u.columns);
17090
+ const haveFk = new Set(current.foreignKeys.map(fkKey));
17091
+ const wantFk = new Set(wanted.foreignKeys.map(fkKey));
17092
+ const haveUq = new Set(current.unique.map(uqKey));
17093
+ const wantUq = new Set(wanted.unique.map(uqKey));
17094
+ return {
17095
+ added: wanted.columns.filter((c) => !have.has(c.name)),
17096
+ dropped: current.columns.filter((c) => !want.has(c.name)),
17097
+ changed,
17098
+ primaryKey: JSON.stringify(current.primaryKey) !== JSON.stringify(wanted.primaryKey),
17099
+ foreignKeysAdded: wanted.foreignKeys.filter((f) => !haveFk.has(fkKey(f))),
17100
+ foreignKeysDropped: current.foreignKeys.filter((f) => !wantFk.has(fkKey(f))),
17101
+ uniqueAdded: wanted.unique.filter((u) => !haveUq.has(uqKey(u))),
17102
+ uniqueDropped: current.unique.filter((u) => !wantUq.has(uqKey(u)))
17103
+ };
17104
+ }
17105
+ createTable(table) {
17106
+ return {
17107
+ action: "create-table",
17108
+ table: table.name,
17109
+ sql: [this.createSql(table, table.name)],
17110
+ irreversible: false,
17111
+ summary: `Create table ${table.name} with ${table.columns.length} column${table.columns.length === 1 ? "" : "s"}.`
17112
+ };
17113
+ }
17114
+ dropTable(table) {
17115
+ return {
17116
+ action: "drop-table",
17117
+ table: table.name,
17118
+ sql: [`DROP TABLE ${this.tableName(table)}`],
17119
+ irreversible: true,
17120
+ summary: `Drop table ${table.name} and every row in it.`
17121
+ };
17122
+ }
17123
+ alterTable(current, wanted) {
17124
+ if (current.name !== wanted.name) {
17125
+ throw new DdlError(`Cannot alter table ${current.name} into ${wanted.name}: renaming a table is not a schema change DDL plans.`);
17126
+ }
17127
+ return this.planAlter(current, wanted, this.diff(current, wanted));
17128
+ }
17129
+ /**
17130
+ * The ALTER steps for a diff, in an order that never trips a constraint:
17131
+ * drop the constraints that go or change, drop columns, add columns, alter
17132
+ * columns, then add the constraints that are new or changed.
17133
+ */
17134
+ planAlter(current, wanted, diff) {
17135
+ const steps = [];
17136
+ const t = wanted.name;
17137
+ for (const f of diff.foreignKeysDropped) steps.push(this.dropConstraint(current, f.name ?? fkName(t, f.columns)));
17138
+ for (const u of diff.uniqueDropped) steps.push(this.dropConstraint(current, u.name ?? uqName(t, u.columns)));
17139
+ if (diff.primaryKey && current.primaryKey.length > 0) steps.push(this.dropConstraint(current, current.primaryKeyName ?? pkName(t)));
17140
+ for (const c of diff.changed) {
17141
+ if (c.values && c.from.values) steps.push(this.dropConstraint(current, c.from.checkName ?? ckName(t, c.from.name)));
17142
+ }
17143
+ for (const c of diff.dropped) {
17144
+ if (c.values) steps.push(this.dropConstraint(current, c.checkName ?? ckName(t, c.name)));
17145
+ steps.push({
17146
+ action: "drop-column",
17147
+ table: t,
17148
+ target: c.name,
17149
+ sql: [`ALTER TABLE ${this.tableName(current)} DROP COLUMN ${this.q(c.name)}`],
17150
+ irreversible: true,
17151
+ summary: `Drop column ${c.name} and its data.`
17152
+ });
17153
+ }
17154
+ for (const c of diff.added) {
17155
+ steps.push({
17156
+ action: "add-column",
17157
+ table: t,
17158
+ target: c.name,
17159
+ sql: [`ALTER TABLE ${this.tableName(wanted)} ${this.addColumnKeyword()} ${this.columnDefinition(wanted, c)}`],
17160
+ irreversible: false,
17161
+ summary: `Add column ${c.name} (${this.columnType(c.type)}${c.nullable ? "" : ", required"}).`
17162
+ });
17163
+ if (c.values) steps.push(this.addConstraint(wanted, ckName(t, c.name), this.checkClause(c)));
17164
+ }
17165
+ for (const c of diff.changed) {
17166
+ if (!(c.type || c.nullable || c.default)) continue;
17167
+ const narrows = c.type && !columnTypeWidens(c.from.type, c.to.type);
17168
+ steps.push({
17169
+ action: "alter-column",
17170
+ table: t,
17171
+ target: c.to.name,
17172
+ sql: this.alterColumn(wanted, c),
17173
+ irreversible: narrows,
17174
+ summary: changeSummary(c, this, narrows)
17175
+ });
17176
+ }
17177
+ for (const c of diff.changed) {
17178
+ if (c.values && c.to.values) steps.push(this.addConstraint(wanted, ckName(t, c.to.name), this.checkClause(c.to)));
17179
+ }
17180
+ if (diff.primaryKey && wanted.primaryKey.length > 0) {
17181
+ steps.push(this.addConstraint(wanted, pkName(t), `PRIMARY KEY (${this.list(wanted.primaryKey)})`));
17182
+ }
17183
+ for (const u of diff.uniqueAdded) steps.push(this.addConstraint(wanted, uqName(t, u.columns), `UNIQUE (${this.list(u.columns)})`));
17184
+ for (const f of diff.foreignKeysAdded) steps.push(this.addConstraint(wanted, fkName(t, f.columns), this.foreignKeyClause(f)));
17185
+ return steps;
17186
+ }
17187
+ // ─── Spelling hooks ─────────────────────────────────────────────────────────
17188
+ /** A quoted identifier. */
17189
+ q(name) {
17190
+ return this.dialect.quoteIdent(name);
17191
+ }
17192
+ /** The table's quoted, schema-qualified name. */
17193
+ tableName(table) {
17194
+ return table.schema ? `${this.q(table.schema)}.${this.q(table.name)}` : this.q(table.name);
17195
+ }
17196
+ /** Quoted, comma-separated column names. */
17197
+ list(columns) {
17198
+ return columns.map((c) => this.q(c)).join(", ");
17199
+ }
17200
+ /** The keyword between `ALTER TABLE t` and a new column (`ADD COLUMN`; SQL Server `ADD`). */
17201
+ addColumnKeyword() {
17202
+ return "ADD COLUMN";
17203
+ }
17204
+ /** The words after the type that make the database assign the value. */
17205
+ generatedClause() {
17206
+ return "GENERATED BY DEFAULT AS IDENTITY";
17207
+ }
17208
+ /** A constant as a SQL literal. */
17209
+ literal(value2) {
17210
+ if (value2 === null) return "NULL";
17211
+ if (typeof value2 === "boolean") return value2 ? "TRUE" : "FALSE";
17212
+ if (typeof value2 === "number") return String(value2);
17213
+ return `'${value2.replace(/'/g, "''")}'`;
17214
+ }
17215
+ /** A default as SQL. */
17216
+ defaultSql(d) {
17217
+ switch (d.kind) {
17218
+ case "value":
17219
+ return this.literal(d.value);
17220
+ case "now":
17221
+ return "CURRENT_TIMESTAMP";
17222
+ case "sql":
17223
+ return d.sql;
17224
+ }
17225
+ }
17226
+ /**
17227
+ * A column's default as it compares: the SQL this dialect would write for it,
17228
+ * so `false` and a read-back `0` match on SQLite, and absent and `NULL` are the same.
17229
+ */
17230
+ comparableDefault(c) {
17231
+ if (!c.default) return null;
17232
+ const d = c.default.kind === "sql" ? this.readDefault(c.default.sql) : c.default;
17233
+ if (!d || d.kind === "value" && d.value === null) return null;
17234
+ return this.defaultSql(d);
17235
+ }
17236
+ /** One column of a `CREATE TABLE` or `ADD COLUMN`. */
17237
+ columnDefinition(table, c) {
17238
+ const parts = [this.q(c.name), this.columnType(c.type)];
17239
+ if (c.generated) parts.push(this.generatedClause());
17240
+ if (!c.nullable) parts.push("NOT NULL");
17241
+ if (c.default) parts.push(this.defaultClause(table, c, c.default));
17242
+ return parts.join(" ");
17243
+ }
17244
+ /** `DEFAULT <sql>` (SQL Server names it). */
17245
+ defaultClause(_table, _c, d) {
17246
+ return `DEFAULT ${this.defaultSql(d)}`;
17247
+ }
17248
+ /** The `CREATE TABLE` statement; its constraints are named after `owner` (the table, unless it is a stand-in). */
17249
+ createSql(table, owner) {
17250
+ const lines = [...table.columns.map((c) => this.columnDefinition(table, c)), ...this.tableConstraints(table, owner)];
17251
+ return `CREATE TABLE ${this.tableName(table)} (
17252
+ ${lines.join(",\n ")}
17253
+ )`;
17254
+ }
17255
+ /** The table-level constraints of a `CREATE TABLE`, named after `owner`. */
17256
+ tableConstraints(table, owner) {
17257
+ const out = [];
17258
+ if (table.primaryKey.length > 0) out.push(`CONSTRAINT ${this.q(pkName(owner))} PRIMARY KEY (${this.list(table.primaryKey)})`);
17259
+ for (const u of table.unique) out.push(`CONSTRAINT ${this.q(uqName(owner, u.columns))} UNIQUE (${this.list(u.columns)})`);
17260
+ for (const f of table.foreignKeys) out.push(`CONSTRAINT ${this.q(fkName(owner, f.columns))} ${this.foreignKeyClause(f)}`);
17261
+ for (const c of table.columns) if (c.values) out.push(`CONSTRAINT ${this.q(ckName(owner, c.name))} ${this.checkClause(c)}`);
17262
+ return out;
17263
+ }
17264
+ /** `FOREIGN KEY (…) REFERENCES t (…) [ON DELETE …]`. */
17265
+ foreignKeyClause(f) {
17266
+ const onDelete = f.onDelete && f.onDelete !== "no-action" ? ` ON DELETE ${f.onDelete.replace("-", " ").toUpperCase()}` : "";
17267
+ return `FOREIGN KEY (${this.list(f.columns)}) REFERENCES ${this.q(f.table)} (${this.list(f.references)})${onDelete}`;
17268
+ }
17269
+ /** `CHECK (c IN (…))` for a column with a closed set of values. */
17270
+ checkClause(c) {
17271
+ return `CHECK (${this.q(c.name)} IN (${(c.values ?? []).map((v) => this.literal(v)).join(", ")}))`;
17272
+ }
17273
+ /** The statements that change one column's type, nullability or default (ANSI / Postgres). */
17274
+ alterColumn(table, c) {
17275
+ const head = `ALTER TABLE ${this.tableName(table)} ALTER COLUMN ${this.q(c.to.name)}`;
17276
+ const out = [];
17277
+ if (c.type) out.push(`${head} TYPE ${this.columnType(c.to.type)}`);
17278
+ if (c.nullable) out.push(`${head} ${c.to.nullable ? "DROP NOT NULL" : "SET NOT NULL"}`);
17279
+ if (c.default) out.push(c.to.default ? `${head} SET DEFAULT ${this.defaultSql(c.to.default)}` : `${head} DROP DEFAULT`);
17280
+ return out;
17281
+ }
17282
+ /** A step adding a named table constraint. */
17283
+ addConstraint(table, name, clause) {
17284
+ return {
17285
+ action: "add-constraint",
17286
+ table: table.name,
17287
+ target: name,
17288
+ sql: [`ALTER TABLE ${this.tableName(table)} ADD CONSTRAINT ${this.q(name)} ${clause}`],
17289
+ irreversible: false,
17290
+ summary: `Add constraint ${name}: ${clause}.`
17291
+ };
17292
+ }
17293
+ /** A step dropping a named table constraint. */
17294
+ dropConstraint(table, name) {
17295
+ return {
17296
+ action: "drop-constraint",
17297
+ table: table.name,
17298
+ target: name,
17299
+ sql: [`ALTER TABLE ${this.tableName(table)} DROP CONSTRAINT ${this.q(name)}`],
17300
+ irreversible: false,
17301
+ summary: `Drop constraint ${name}.`
17302
+ };
17303
+ }
17304
+ };
17305
+ var AnsiDdl = class extends SqlDdl {
17306
+ columnType(type) {
17307
+ switch (type.kind) {
17308
+ case "text":
17309
+ return type.maxLength === void 0 ? "varchar" : `varchar(${type.maxLength})`;
17310
+ case "integer":
17311
+ return type.big ? "bigint" : "integer";
17312
+ case "decimal":
17313
+ return decimalSpelling("numeric", type);
17314
+ case "float":
17315
+ return "double precision";
17316
+ case "bool":
17317
+ return "boolean";
17318
+ case "date":
17319
+ return "date";
17320
+ case "timestamp":
17321
+ return type.timezone === false ? "timestamp" : "timestamp with time zone";
17322
+ case "uuid":
17323
+ return "uuid";
17324
+ case "json":
17325
+ return "json";
17326
+ case "bytes":
17327
+ return "blob";
17328
+ case "other":
17329
+ return type.native;
17330
+ }
17331
+ }
17332
+ readColumnType(native) {
17333
+ return readCommonType(native);
17334
+ }
17335
+ };
17336
+ function decimalSpelling(word, type) {
17337
+ if (type.precision === void 0) return word;
17338
+ return type.scale === void 0 ? `${word}(${type.precision})` : `${word}(${type.precision},${type.scale})`;
17339
+ }
17340
+ function splitNative(native) {
17341
+ const m = /^\s*([^(]+?)\s*(?:\(([^)]*)\))?\s*(\[\])?\s*$/u.exec(native);
17342
+ const name = (m?.[1] ?? native).trim().toLowerCase().replace(/\s+/g, " ");
17343
+ const raw2 = (m?.[2] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "");
17344
+ return { name, args: raw2.map(Number).filter((n) => Number.isFinite(n)), max: raw2.some((a) => a.toLowerCase() === "max") };
17345
+ }
17346
+ function readCommonType(native) {
17347
+ const { name, args } = splitNative(native);
17348
+ const length = args[0];
17349
+ if (/^(n?varchar|character varying|varying character|n?char|character|nchar varying|string)$/u.test(name)) {
17350
+ return length === void 0 ? { kind: "text" } : { kind: "text", maxLength: length };
17351
+ }
17352
+ if (/^(n?text|clob|citext|ntext|xml|tinytext|mediumtext|longtext)$/u.test(name)) return { kind: "text" };
17353
+ if (/^(bigint|int8|bigserial|serial8)$/u.test(name)) return { kind: "integer", big: true };
17354
+ if (/^(int|integer|int2|int4|smallint|tinyint|mediumint|serial|serial4|smallserial)$/u.test(name)) return { kind: "integer" };
17355
+ if (/^(numeric|decimal|money|smallmoney)$/u.test(name)) {
17356
+ if (name === "money" || name === "smallmoney") return { kind: "decimal", precision: 19, scale: 4 };
17357
+ return {
17358
+ kind: "decimal",
17359
+ ...args[0] !== void 0 ? { precision: args[0] } : {},
17360
+ ...args[1] !== void 0 ? { scale: args[1] } : {}
17361
+ };
17362
+ }
17363
+ if (/^(real|float|float4|float8|double|double precision)$/u.test(name)) return { kind: "float" };
17364
+ if (/^(bool|boolean|bit)$/u.test(name)) return { kind: "bool" };
17365
+ if (name === "date") return { kind: "date" };
17366
+ if (/^(timestamptz|timestamp with time zone|datetimeoffset)$/u.test(name)) return { kind: "timestamp", timezone: true };
17367
+ if (/^(timestamp|timestamp without time zone|datetime|datetime2|smalldatetime)$/u.test(name)) return { kind: "timestamp", timezone: false };
17368
+ if (/^(uuid|uniqueidentifier)$/u.test(name)) return { kind: "uuid" };
17369
+ if (/^(json|jsonb)$/u.test(name)) return { kind: "json" };
17370
+ if (/^(bytea|blob|binary|varbinary|image)$/u.test(name)) return { kind: "bytes" };
17371
+ return { kind: "other", native: native.trim() };
17372
+ }
17373
+ function pkName(table) {
17374
+ return `pk_${table}`;
17375
+ }
17376
+ function fkName(table, columns) {
17377
+ return `fk_${table}_${columns.join("_")}`;
17378
+ }
17379
+ function uqName(table, columns) {
17380
+ return `uq_${table}_${columns.join("_")}`;
17381
+ }
17382
+ function ckName(table, column2) {
17383
+ return `ck_${table}_${column2}`;
17384
+ }
17385
+ function balanced(s) {
17386
+ let depth = 0;
17387
+ for (const ch of s) {
17388
+ if (ch === "(") depth++;
17389
+ else if (ch === ")" && --depth < 0) return false;
17390
+ }
17391
+ return depth === 0;
17392
+ }
17393
+ function changeSummary(c, w, narrows) {
17394
+ const parts = [];
17395
+ if (c.type) parts.push(`type ${w.columnType(c.from.type)} \u2192 ${w.columnType(c.to.type)}${narrows ? " (narrows: values that do not fit are lost or refused)" : ""}`);
17396
+ if (c.nullable) parts.push(c.to.nullable ? "allow empty values" : "require a value");
17397
+ if (c.default) parts.push(c.to.default ? "set the default" : "remove the default");
17398
+ return `Change column ${c.to.name}: ${parts.join("; ")}.`;
17399
+ }
17400
+
16934
17401
  // src/sql/dialect.ts
16935
17402
  function jsonObjectArgs(entries) {
16936
17403
  const args = [];
@@ -16993,13 +17460,57 @@ var Dialect = class {
16993
17460
  /**
16994
17461
  * The LIMIT / OFFSET clause for the (already-emitted) limit / offset
16995
17462
  * fragments. Returns empty when both are absent. ANSI `LIMIT n OFFSET m`.
17463
+ *
17464
+ * `ordered` says whether the statement already has an `ORDER BY`: a dialect
17465
+ * whose paging needs one (SQL Server's `OFFSET … FETCH`) supplies a neutral
17466
+ * order when it has none. Defaults to `true` for callers that predate it.
16996
17467
  */
16997
- limitOffset(limit, offset) {
17468
+ limitOffset(limit, offset, _ordered = true) {
16998
17469
  const parts = [];
16999
17470
  if (limit) parts.push(SqlText.concat([SqlText.raw("LIMIT "), limit]));
17000
17471
  if (offset) parts.push(SqlText.concat([SqlText.raw("OFFSET "), offset]));
17001
17472
  return SqlText.join(parts, " ");
17002
17473
  }
17474
+ /**
17475
+ * One `ORDER BY` term: `<key> ASC|DESC [NULLS FIRST|LAST]`. A dialect with no
17476
+ * `NULLS` clause (SQL Server) overrides to order by a null flag first.
17477
+ */
17478
+ orderTerm(key, dir, nulls) {
17479
+ return SqlText.concat([
17480
+ key,
17481
+ SqlText.raw(` ${dir.toUpperCase()}`),
17482
+ nulls ? SqlText.raw(` NULLS ${nulls.toUpperCase()}`) : SqlText.empty()
17483
+ ]);
17484
+ }
17485
+ /** A predicate that is always true (`TRUE`; SQL Server has no boolean literal). */
17486
+ trueSql() {
17487
+ return SqlText.raw("TRUE");
17488
+ }
17489
+ /** A predicate that is always false (`FALSE`; SQL Server has no boolean literal). */
17490
+ falseSql() {
17491
+ return SqlText.raw("FALSE");
17492
+ }
17493
+ /**
17494
+ * The value a driver is handed for a bound parameter. Identity by default; a
17495
+ * dialect whose driver cannot bind a JS boolean (SQLite) maps it to `1` / `0`.
17496
+ */
17497
+ encodeParam(value2) {
17498
+ return value2;
17499
+ }
17500
+ /**
17501
+ * This dialect's DDL writer: native column types, reading an introspected
17502
+ * type back, `CREATE TABLE`, and the ordered `ALTER` steps from one table
17503
+ * shape to another. Made once per dialect instance.
17504
+ */
17505
+ get ddl() {
17506
+ this.ddlWriter ??= this.makeDdl();
17507
+ return this.ddlWriter;
17508
+ }
17509
+ ddlWriter;
17510
+ /** Build this dialect's DDL writer (ANSI by default). */
17511
+ makeDdl() {
17512
+ return new AnsiDdl(this);
17513
+ }
17003
17514
  /**
17004
17515
  * Case-insensitive LIKE. ANSI has no `ILIKE`, so lower both sides; Postgres
17005
17516
  * overrides with the native operator.
@@ -17250,9 +17761,9 @@ var EXTRACT_PART = {
17250
17761
  function extract(part, arg2) {
17251
17762
  return SqlText.concat([SqlText.raw("EXTRACT("), part, SqlText.raw(" FROM "), arg2, SqlText.raw(")")]);
17252
17763
  }
17253
- function caseCount(agg2, pred) {
17764
+ function caseCount(agg3, pred) {
17254
17765
  return SqlText.concat([
17255
- SqlText.raw(`${agg2}(CASE WHEN `),
17766
+ SqlText.raw(`${agg3}(CASE WHEN `),
17256
17767
  pred,
17257
17768
  SqlText.raw(" THEN 1 ELSE 0 END)")
17258
17769
  ]);
@@ -17304,8 +17815,8 @@ var BaseDialect = class _BaseDialect extends Dialect {
17304
17815
  );
17305
17816
  }
17306
17817
  /** No vector type in portable SQL: the query param passes through unchanged. */
17307
- queryVectorParam(param3) {
17308
- return param3;
17818
+ queryVectorParam(param4) {
17819
+ return param4;
17309
17820
  }
17310
17821
  /** No ranking in portable SQL: degrade to a numeric match over the `LIKE` predicate. */
17311
17822
  textRank(col, query, sensitive = false) {
@@ -17377,10 +17888,246 @@ function assertNever8(value2) {
17377
17888
  throw new Error(`BaseDialect.sqlTypeFor: unhandled scalar kind ${JSON.stringify(value2)}`);
17378
17889
  }
17379
17890
 
17891
+ // src/ddl/dialects.ts
17892
+ var PostgresDdl = class extends SqlDdl {
17893
+ columnType(type) {
17894
+ switch (type.kind) {
17895
+ case "text":
17896
+ return type.maxLength === void 0 ? "text" : `varchar(${type.maxLength})`;
17897
+ case "integer":
17898
+ return type.big ? "bigint" : "integer";
17899
+ case "decimal":
17900
+ return decimalSpelling("numeric", type);
17901
+ case "float":
17902
+ return "double precision";
17903
+ case "bool":
17904
+ return "boolean";
17905
+ case "date":
17906
+ return "date";
17907
+ case "timestamp":
17908
+ return type.timezone === false ? "timestamp" : "timestamptz";
17909
+ case "uuid":
17910
+ return "uuid";
17911
+ case "json":
17912
+ return "jsonb";
17913
+ case "bytes":
17914
+ return "bytea";
17915
+ case "other":
17916
+ return type.native;
17917
+ }
17918
+ }
17919
+ readColumnType(native) {
17920
+ return readCommonType(native);
17921
+ }
17922
+ alterColumn(table, c) {
17923
+ const out = super.alterColumn(table, c);
17924
+ if (!c.type) return out;
17925
+ const type = this.columnType(c.to.type);
17926
+ return out.map((s) => s.endsWith(` TYPE ${type}`) ? `${s} USING ${this.q(c.to.name)}::${type}` : s);
17927
+ }
17928
+ };
17929
+ var SqlServerDdl = class extends SqlDdl {
17930
+ columnType(type) {
17931
+ switch (type.kind) {
17932
+ case "text":
17933
+ return type.maxLength === void 0 || type.maxLength > 4e3 ? "nvarchar(max)" : `nvarchar(${type.maxLength})`;
17934
+ case "integer":
17935
+ return type.big ? "bigint" : "int";
17936
+ case "decimal":
17937
+ return `decimal(${type.precision ?? 38},${type.scale ?? 10})`;
17938
+ case "float":
17939
+ return "float";
17940
+ case "bool":
17941
+ return "bit";
17942
+ case "date":
17943
+ return "date";
17944
+ case "timestamp":
17945
+ return type.timezone === false ? "datetime2" : "datetimeoffset";
17946
+ case "uuid":
17947
+ return "uniqueidentifier";
17948
+ case "json":
17949
+ return "nvarchar(max)";
17950
+ case "bytes":
17951
+ return "varbinary(max)";
17952
+ case "other":
17953
+ return type.native;
17954
+ }
17955
+ }
17956
+ readColumnType(native) {
17957
+ const { name, args, max: max2 } = splitNative(native);
17958
+ if (/^n?varchar$/u.test(name) && max2) return { kind: "text" };
17959
+ if (name === "bit") return { kind: "bool" };
17960
+ if (name === "float" && args[0] !== void 0 && args[0] <= 24) return { kind: "float" };
17961
+ return readCommonType(native);
17962
+ }
17963
+ addColumnKeyword() {
17964
+ return "ADD";
17965
+ }
17966
+ generatedClause() {
17967
+ return "IDENTITY(1,1)";
17968
+ }
17969
+ literal(value2) {
17970
+ if (typeof value2 === "boolean") return value2 ? "1" : "0";
17971
+ if (typeof value2 === "string") return `N'${value2.replace(/'/g, "''")}'`;
17972
+ return super.literal(value2);
17973
+ }
17974
+ defaultClause(table, c, d) {
17975
+ return `CONSTRAINT ${this.q(c.defaultName ?? dfName(table.name, c.name))} DEFAULT ${this.defaultSql(d)}`;
17976
+ }
17977
+ defaultSql(d) {
17978
+ return d.kind === "now" ? "SYSDATETIMEOFFSET()" : super.defaultSql(d);
17979
+ }
17980
+ alterColumn(table, c) {
17981
+ const name = this.tableName(table);
17982
+ const out = [];
17983
+ if (c.default && c.from.default) out.push(`ALTER TABLE ${name} DROP CONSTRAINT ${this.q(c.from.defaultName ?? dfName(table.name, c.from.name))}`);
17984
+ if (c.type || c.nullable) {
17985
+ out.push(`ALTER TABLE ${name} ALTER COLUMN ${this.q(c.to.name)} ${this.columnType(c.to.type)} ${c.to.nullable ? "NULL" : "NOT NULL"}`);
17986
+ }
17987
+ if (c.default && c.to.default) {
17988
+ out.push(`ALTER TABLE ${name} ADD CONSTRAINT ${this.q(dfName(table.name, c.to.name))} DEFAULT ${this.defaultSql(c.to.default)} FOR ${this.q(c.to.name)}`);
17989
+ }
17990
+ return out;
17991
+ }
17992
+ planAlter(current, wanted, diff) {
17993
+ const steps = super.planAlter(current, wanted, diff);
17994
+ const defaults = diff.dropped.filter((c) => c.default);
17995
+ if (defaults.length === 0) return steps;
17996
+ const first = steps.findIndex((s) => s.action === "drop-column");
17997
+ const drops = defaults.map((c) => this.dropConstraint(current, c.defaultName ?? dfName(current.name, c.name)));
17998
+ return [...steps.slice(0, first), ...drops, ...steps.slice(first)];
17999
+ }
18000
+ };
18001
+ var SqliteDdl = class extends SqlDdl {
18002
+ columnType(type) {
18003
+ switch (type.kind) {
18004
+ case "text":
18005
+ return type.maxLength === void 0 ? "TEXT" : `VARCHAR(${type.maxLength})`;
18006
+ case "integer":
18007
+ return type.big ? "BIGINT" : "INTEGER";
18008
+ case "decimal":
18009
+ return decimalSpelling("NUMERIC", type);
18010
+ case "float":
18011
+ return "REAL";
18012
+ case "bool":
18013
+ return "BOOLEAN";
18014
+ case "date":
18015
+ return "DATE";
18016
+ case "timestamp":
18017
+ return type.timezone === false ? "DATETIME" : "TIMESTAMPTZ";
18018
+ case "uuid":
18019
+ return "UUID";
18020
+ case "json":
18021
+ return "JSON";
18022
+ case "bytes":
18023
+ return "BLOB";
18024
+ case "other":
18025
+ return type.native;
18026
+ }
18027
+ }
18028
+ readColumnType(native) {
18029
+ if (native.trim() === "") return { kind: "other", native: "" };
18030
+ const read = readCommonType(native);
18031
+ if (read.kind !== "other") return read;
18032
+ const up = native.toUpperCase();
18033
+ if (up.includes("INT")) return { kind: "integer" };
18034
+ if (up.includes("CHAR") || up.includes("CLOB") || up.includes("TEXT")) return { kind: "text" };
18035
+ if (up.includes("REAL") || up.includes("FLOA") || up.includes("DOUB")) return { kind: "float" };
18036
+ return read;
18037
+ }
18038
+ literal(value2) {
18039
+ if (typeof value2 === "boolean") return value2 ? "1" : "0";
18040
+ return super.literal(value2);
18041
+ }
18042
+ columnDefinition(table, c) {
18043
+ if (!this.isRowidKey(table, c)) return super.columnDefinition(table, c);
18044
+ return `${this.q(c.name)} INTEGER PRIMARY KEY AUTOINCREMENT`;
18045
+ }
18046
+ tableConstraints(table, owner) {
18047
+ const rowid = table.columns.some((c) => this.isRowidKey(table, c));
18048
+ const all = super.tableConstraints(table, owner);
18049
+ return rowid ? all.filter((s) => !s.includes(" PRIMARY KEY (")) : all;
18050
+ }
18051
+ /** The one generated integer primary key, which SQLite spells inline as an alias of the rowid. */
18052
+ isRowidKey(table, c) {
18053
+ return c.generated === true && table.primaryKey.length === 1 && table.primaryKey[0] === c.name;
18054
+ }
18055
+ planAlter(current, wanted, diff) {
18056
+ const keyed = /* @__PURE__ */ new Set([...wanted.primaryKey, ...current.primaryKey, ...wanted.unique.flatMap((u) => u.columns), ...current.unique.flatMap((u) => u.columns)]);
18057
+ const fkColumns = new Set([...current.foreignKeys, ...wanted.foreignKeys].flatMap((f) => f.columns));
18058
+ const constraintsSame = !diff.primaryKey && diff.changed.length === 0 && diff.foreignKeysDropped.length === 0 && diff.uniqueAdded.length === 0 && diff.uniqueDropped.length === 0 && diff.foreignKeysAdded.every((f) => f.columns.every((col) => diff.added.some((a) => a.name === col)) && f.columns.length === 1);
18059
+ const plainAdds = diff.added.every((c) => !keyed.has(c.name) && !c.generated && (c.nullable || c.default !== void 0) && (c.default?.kind ?? "value") !== "now");
18060
+ const plainDrops = diff.dropped.every((c) => !keyed.has(c.name) && !fkColumns.has(c.name) && !c.values);
18061
+ if (constraintsSame && plainAdds && plainDrops) {
18062
+ const steps = [];
18063
+ for (const c of diff.dropped) {
18064
+ steps.push({
18065
+ action: "drop-column",
18066
+ table: wanted.name,
18067
+ target: c.name,
18068
+ sql: [`ALTER TABLE ${this.tableName(current)} DROP COLUMN ${this.q(c.name)}`],
18069
+ irreversible: true,
18070
+ summary: `Drop column ${c.name} and its data.`
18071
+ });
18072
+ }
18073
+ for (const c of diff.added) {
18074
+ const fk = wanted.foreignKeys.find((f) => f.columns[0] === c.name);
18075
+ const refs = fk ? ` REFERENCES ${this.q(fk.table)} (${this.list(fk.references)})` : "";
18076
+ const check = c.values ? ` ${this.checkClause(c)}` : "";
18077
+ steps.push({
18078
+ action: "add-column",
18079
+ table: wanted.name,
18080
+ target: c.name,
18081
+ sql: [`ALTER TABLE ${this.tableName(wanted)} ADD COLUMN ${super.columnDefinition(wanted, c)}${check}${refs}`],
18082
+ irreversible: false,
18083
+ summary: `Add column ${c.name} (${this.columnType(c.type)}${c.nullable ? "" : ", required"}).`
18084
+ });
18085
+ }
18086
+ return steps;
18087
+ }
18088
+ return [this.rebuild(current, wanted, diff)];
18089
+ }
18090
+ /** Make the wanted table beside the current one, copy the kept columns across, and swap it in. */
18091
+ rebuild(current, wanted, diff) {
18092
+ const temp = { ...wanted, name: `${wanted.name}__new` };
18093
+ const kept = wanted.columns.filter((c) => current.columns.some((h) => h.name === c.name)).map((c) => c.name);
18094
+ const narrows = diff.changed.some((c) => c.type && !columnTypeWidens(c.from.type, c.to.type));
18095
+ const what = [
18096
+ diff.added.length ? `add ${diff.added.map((c) => c.name).join(", ")}` : "",
18097
+ diff.dropped.length ? `drop ${diff.dropped.map((c) => c.name).join(", ")}` : "",
18098
+ diff.changed.length ? `change ${diff.changed.map((c) => c.to.name).join(", ")}` : "",
18099
+ diff.primaryKey ? "change the primary key" : "",
18100
+ diff.foreignKeysAdded.length || diff.foreignKeysDropped.length ? "change foreign keys" : "",
18101
+ diff.uniqueAdded.length || diff.uniqueDropped.length ? "change unique keys" : ""
18102
+ ].filter((s) => s !== "");
18103
+ return {
18104
+ action: "rebuild-table",
18105
+ table: wanted.name,
18106
+ sql: [
18107
+ "PRAGMA defer_foreign_keys = ON",
18108
+ // Constraint names follow the real table, not the stand-in.
18109
+ this.createSql(temp, wanted.name),
18110
+ `INSERT INTO ${this.tableName(temp)} (${this.list(kept)}) SELECT ${this.list(kept)} FROM ${this.tableName(current)}`,
18111
+ `DROP TABLE ${this.tableName(current)}`,
18112
+ `ALTER TABLE ${this.tableName(temp)} RENAME TO ${this.q(wanted.name)}`
18113
+ ],
18114
+ irreversible: diff.dropped.length > 0 || narrows,
18115
+ summary: `Rebuild table ${wanted.name} to ${what.join("; ")} (SQLite copies the rows into a new table).`
18116
+ };
18117
+ }
18118
+ };
18119
+ function dfName(table, column2) {
18120
+ return `df_${table}_${column2}`;
18121
+ }
18122
+
17380
18123
  // src/sql/postgres-dialect.ts
17381
18124
  var PostgresDialect = class extends BaseDialect {
17382
18125
  /** This dialect's name (`'postgres'`). */
17383
18126
  name = "postgres";
18127
+ /** Postgres DDL: native types, identity columns, `ALTER COLUMN … TYPE … USING`. */
18128
+ makeDdl() {
18129
+ return new PostgresDdl(this);
18130
+ }
17384
18131
  /** Postgres numbered placeholders are 1-based. */
17385
18132
  bindPlaceholder(index) {
17386
18133
  return `$${index + 1}`;
@@ -17483,8 +18230,8 @@ var PostgresDialect = class extends BaseDialect {
17483
18230
  ]);
17484
18231
  }
17485
18232
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
17486
- queryVectorParam(param3) {
17487
- return SqlText.concat([param3, SqlText.raw("::vector")]);
18233
+ queryVectorParam(param4) {
18234
+ return SqlText.concat([param4, SqlText.raw("::vector")]);
17488
18235
  }
17489
18236
  /**
17490
18237
  * `ts_rank(to_tsvector(col), plainto_tsquery(query))` — a numeric relevance.
@@ -17661,9 +18408,298 @@ function assertNever9(value2) {
17661
18408
  throw new Error(`PostgresDialect.sqlTypeFor: unhandled scalar kind ${JSON.stringify(value2)}`);
17662
18409
  }
17663
18410
 
18411
+ // src/sql/sqlite-dialect.ts
18412
+ var STRFTIME = {
18413
+ year: "%Y",
18414
+ month: "%m",
18415
+ week: "%W",
18416
+ day: "%d",
18417
+ hour: "%H",
18418
+ minute: "%M",
18419
+ second: "%S",
18420
+ dow: "%w",
18421
+ isodow: "%u",
18422
+ doy: "%j",
18423
+ epoch: "%s"
18424
+ };
18425
+ var EXTRACTOR = {
18426
+ year: "year",
18427
+ month: "month",
18428
+ day: "day",
18429
+ hour: "hour",
18430
+ minute: "minute",
18431
+ second: "second",
18432
+ dayOfWeek: "dow",
18433
+ dayOfYear: "doy",
18434
+ week: "week",
18435
+ epoch: "epoch"
18436
+ };
18437
+ var RENAMED = {
18438
+ substring: "substr",
18439
+ trimLeft: "ltrim",
18440
+ trimRight: "rtrim",
18441
+ stringAgg: "group_concat",
18442
+ power: "pow",
18443
+ indexOf: "instr"
18444
+ };
18445
+ var SqliteDialect = class extends BaseDialect {
18446
+ /** This dialect's name (`'sqlite'`). */
18447
+ name = "sqlite";
18448
+ /** An offset with no limit needs `LIMIT -1` in SQLite. */
18449
+ limitOffset(limit, offset, ordered = true) {
18450
+ if (!limit && offset) return super.limitOffset(SqlText.raw("-1"), offset, ordered);
18451
+ return super.limitOffset(limit, offset, ordered);
18452
+ }
18453
+ /** SQLite's driver binds no booleans: `true` / `false` become `1` / `0`. */
18454
+ encodeParam(value2) {
18455
+ return typeof value2 === "boolean" ? value2 ? 1 : 0 : value2;
18456
+ }
18457
+ jsonObject(entries) {
18458
+ return SqlText.concat([SqlText.raw("json_object("), SqlText.join(jsonObjectArgs(entries), ", "), SqlText.raw(")")]);
18459
+ }
18460
+ jsonSqlType() {
18461
+ return "text";
18462
+ }
18463
+ /** A JSON document is bound as its text and parsed by `json(…)`. */
18464
+ builtinJsonValue(value2, _fieldType, _site) {
18465
+ return SqlText.concat([SqlText.raw("json("), SqlText.param(JSON.stringify(value2)), SqlText.raw(")")]);
18466
+ }
18467
+ builtinSqlTypeFor(fieldType) {
18468
+ switch (fieldType.resolve()) {
18469
+ case "number":
18470
+ return fieldType instanceof NumberFieldType && fieldType.options.whole ? "integer" : "real";
18471
+ case "money":
18472
+ return "numeric";
18473
+ case "text":
18474
+ return fieldType instanceof TextFieldType && fieldType.options.maxLength !== void 0 ? `varchar(${fieldType.options.maxLength})` : "text";
18475
+ case "bool":
18476
+ return "integer";
18477
+ default:
18478
+ return "text";
18479
+ }
18480
+ }
18481
+ arrayLength(arg2) {
18482
+ return SqlText.concat([SqlText.raw("COALESCE(json_array_length("), arg2, SqlText.raw("), 0)")]);
18483
+ }
18484
+ /** Membership over a JSON array column through `json_each`. */
18485
+ arrayHas(col, value2) {
18486
+ return SqlText.concat([SqlText.raw("EXISTS (SELECT 1 FROM json_each("), col, SqlText.raw(") WHERE value = "), value2, SqlText.raw(")")]);
18487
+ }
18488
+ arrayContains(col, elements2) {
18489
+ if (elements2.length === 0) return this.trueSql();
18490
+ return SqlText.join(elements2.map((e2) => this.arrayHas(col, e2)), " AND ").parens();
18491
+ }
18492
+ arrayOverlaps(col, elements2) {
18493
+ if (elements2.length === 0) return this.falseSql();
18494
+ return SqlText.concat([SqlText.raw("EXISTS (SELECT 1 FROM json_each("), col, SqlText.raw(") WHERE value IN ("), SqlText.join(elements2, ", "), SqlText.raw("))")]);
18495
+ }
18496
+ lateralJoin(_subquery, _alias, _joinType) {
18497
+ throw new QueryTypeError({
18498
+ path: [],
18499
+ code: "lateral.unsupported-dialect",
18500
+ severity: "error",
18501
+ message: "SQLite has no LATERAL joins; rewrite the correlated source as a subquery or a join."
18502
+ });
18503
+ }
18504
+ /** A date-field token as its `strftime` format string. */
18505
+ rawArgLiteral(token) {
18506
+ return SqlText.raw(`'${STRFTIME[token] ?? "%Y"}'`);
18507
+ }
18508
+ emitBuiltinCall(name, args) {
18509
+ const part = EXTRACTOR[name];
18510
+ if (part && args.length === 1) return strftimeInt(SqlText.raw(`'${STRFTIME[part] ?? "%Y"}'`), args[0]);
18511
+ if (name === "datePart" && args.length === 2) return strftimeInt(args[0], args[1]);
18512
+ if (name === "dateDiff" && args.length === 3) {
18513
+ return SqlText.concat([SqlText.raw("("), strftimeInt(args[0], args[2]), SqlText.raw(" - "), strftimeInt(args[0], args[1]), SqlText.raw(")")]);
18514
+ }
18515
+ if (name === "dateTrunc" && args.length === 2) {
18516
+ const truncated = dateTrunc(args[0], args[1]);
18517
+ if (truncated) return truncated;
18518
+ }
18519
+ if (name === "boolAnd" && args.length === 1) return SqlText.concat([SqlText.raw("(MIN(CASE WHEN "), args[0], SqlText.raw(" THEN 1 ELSE 0 END) = 1)")]);
18520
+ if (name === "boolOr" && args.length === 1) return SqlText.concat([SqlText.raw("(MAX(CASE WHEN "), args[0], SqlText.raw(" THEN 1 ELSE 0 END) = 1)")]);
18521
+ if (name === "arrayAgg" && args.length === 1) return SqlText.concat([SqlText.raw("json_group_array("), args[0], SqlText.raw(")")]);
18522
+ if (name === "mod" && args.length === 2) return SqlText.concat([SqlText.raw("("), args[0], SqlText.raw(" % "), args[1], SqlText.raw(")")]);
18523
+ const renamed = RENAMED[name];
18524
+ if (renamed) return SqlText.concat([SqlText.raw(`${renamed}(`), SqlText.join(args, ", "), SqlText.raw(")")]);
18525
+ return super.emitBuiltinCall(name, args);
18526
+ }
18527
+ makeDdl() {
18528
+ return new SqliteDdl(this);
18529
+ }
18530
+ };
18531
+ function dateTrunc(field, date) {
18532
+ const token = field.segments.length === 1 && field.segments[0].kind === "raw" ? field.segments[0].text : "";
18533
+ const wrap = (open, close) => SqlText.concat([SqlText.raw(open), date, SqlText.raw(close)]);
18534
+ switch (token) {
18535
+ case "'%Y'":
18536
+ return wrap("date(", ", 'start of year')");
18537
+ case "'%m'":
18538
+ return wrap("date(", ", 'start of month')");
18539
+ case "'%W'":
18540
+ return wrap("date(", ", '-6 days', 'weekday 1')");
18541
+ case "'%d'":
18542
+ return wrap("date(", ")");
18543
+ case "'%H'":
18544
+ return wrap("strftime('%Y-%m-%d %H:00:00', ", ")");
18545
+ case "'%M'":
18546
+ return wrap("strftime('%Y-%m-%d %H:%M:00', ", ")");
18547
+ default:
18548
+ return void 0;
18549
+ }
18550
+ }
18551
+ function strftimeInt(format, date) {
18552
+ return SqlText.concat([SqlText.raw("CAST(strftime("), format, SqlText.raw(", "), date, SqlText.raw(") AS INTEGER)")]);
18553
+ }
18554
+
18555
+ // src/sql/sqlserver-dialect.ts
18556
+ var DATEPART = {
18557
+ year: "year",
18558
+ quarter: "quarter",
18559
+ month: "month",
18560
+ week: "week",
18561
+ day: "day",
18562
+ hour: "hour",
18563
+ minute: "minute",
18564
+ second: "second",
18565
+ dow: "weekday",
18566
+ isodow: "weekday",
18567
+ doy: "dayofyear",
18568
+ epoch: "second"
18569
+ };
18570
+ var EXTRACTOR2 = {
18571
+ year: "year",
18572
+ month: "month",
18573
+ day: "day",
18574
+ hour: "hour",
18575
+ minute: "minute",
18576
+ second: "second",
18577
+ dayOfWeek: "weekday",
18578
+ dayOfYear: "dayofyear",
18579
+ week: "week"
18580
+ };
18581
+ var RENAMED2 = {
18582
+ length: "LEN",
18583
+ ceil: "CEILING",
18584
+ ln: "LOG",
18585
+ trimLeft: "LTRIM",
18586
+ trimRight: "RTRIM",
18587
+ stddev: "STDEV",
18588
+ variance: "VAR",
18589
+ stringAgg: "STRING_AGG"
18590
+ };
18591
+ var SqlServerDialect = class extends BaseDialect {
18592
+ /** This dialect's name (`'sqlserver'`). */
18593
+ name = "sqlserver";
18594
+ quoteIdent(name) {
18595
+ return `[${name.replace(/]/g, "]]")}]`;
18596
+ }
18597
+ /** Named placeholders, 1-based, as the `mssql` driver binds them (`request.input('p1', …)`). */
18598
+ bindPlaceholder(index) {
18599
+ return `@p${index + 1}`;
18600
+ }
18601
+ limitOffset(limit, offset, ordered = true) {
18602
+ if (!limit && !offset) return SqlText.empty();
18603
+ return SqlText.concat([
18604
+ SqlText.raw(ordered ? "" : "ORDER BY (SELECT NULL) "),
18605
+ SqlText.raw("OFFSET "),
18606
+ offset ?? SqlText.raw("0"),
18607
+ SqlText.raw(" ROWS"),
18608
+ limit ? SqlText.concat([SqlText.raw(" FETCH NEXT "), limit, SqlText.raw(" ROWS ONLY")]) : SqlText.empty()
18609
+ ]);
18610
+ }
18611
+ /** No `NULLS FIRST|LAST`: order by a null flag first, then the key. */
18612
+ orderTerm(key, dir, nulls) {
18613
+ const plain2 = SqlText.concat([key, SqlText.raw(` ${dir.toUpperCase()}`)]);
18614
+ if (!nulls) return plain2;
18615
+ const [isNull3, notNull2] = nulls === "first" ? ["0", "1"] : ["1", "0"];
18616
+ return SqlText.concat([SqlText.raw("CASE WHEN "), key, SqlText.raw(` IS NULL THEN ${isNull3} ELSE ${notNull2} END, `), plain2]);
18617
+ }
18618
+ trueSql() {
18619
+ return SqlText.raw("(1 = 1)");
18620
+ }
18621
+ falseSql() {
18622
+ return SqlText.raw("(1 = 0)");
18623
+ }
18624
+ jsonObject(entries) {
18625
+ const pairs = entries.map((e2) => SqlText.concat([SqlText.raw(`'${e2.key.replace(/'/g, "''")}': `), e2.value]));
18626
+ return SqlText.concat([SqlText.raw("JSON_OBJECT("), SqlText.join(pairs, ", "), SqlText.raw(")")]);
18627
+ }
18628
+ jsonSqlType() {
18629
+ return "nvarchar(max)";
18630
+ }
18631
+ /** A precomputed text field matched by substring (`+` concatenation, not `||`). */
18632
+ tsvectorSearch(tsv, query, _language) {
18633
+ return SqlText.concat([SqlText.raw("LOWER("), tsv, SqlText.raw(") LIKE CONCAT('%', LOWER("), query, SqlText.raw("), '%')")]);
18634
+ }
18635
+ builtinSqlTypeFor(fieldType) {
18636
+ switch (fieldType.resolve()) {
18637
+ case "number":
18638
+ return fieldType instanceof NumberFieldType && fieldType.options.whole ? "int" : "float";
18639
+ case "money":
18640
+ return "decimal(19,4)";
18641
+ case "text":
18642
+ return fieldType instanceof TextFieldType && fieldType.options.maxLength !== void 0 && fieldType.options.maxLength <= 4e3 ? `nvarchar(${fieldType.options.maxLength})` : "nvarchar(max)";
18643
+ case "bool":
18644
+ return "bit";
18645
+ case "date":
18646
+ return "date";
18647
+ case "timestamp":
18648
+ return fieldType instanceof TimestampFieldType && fieldType.timezone === false ? "datetime2" : "datetimeoffset";
18649
+ default:
18650
+ return "nvarchar(max)";
18651
+ }
18652
+ }
18653
+ arrayLength(arg2) {
18654
+ return SqlText.concat([SqlText.raw("(SELECT COUNT(*) FROM OPENJSON("), arg2, SqlText.raw("))")]);
18655
+ }
18656
+ arrayHas(col, value2) {
18657
+ return SqlText.concat([SqlText.raw("EXISTS (SELECT 1 FROM OPENJSON("), col, SqlText.raw(") WHERE [value] = "), value2, SqlText.raw(")")]);
18658
+ }
18659
+ arrayContains(col, elements2) {
18660
+ if (elements2.length === 0) return this.trueSql();
18661
+ return SqlText.join(elements2.map((e2) => this.arrayHas(col, e2)), " AND ").parens();
18662
+ }
18663
+ arrayOverlaps(col, elements2) {
18664
+ if (elements2.length === 0) return this.falseSql();
18665
+ return SqlText.concat([SqlText.raw("EXISTS (SELECT 1 FROM OPENJSON("), col, SqlText.raw(") WHERE [value] IN ("), SqlText.join(elements2, ", "), SqlText.raw("))")]);
18666
+ }
18667
+ /** `OUTER APPLY` / `CROSS APPLY`, SQL Server's lateral join. */
18668
+ lateralJoin(subquery2, alias, joinType) {
18669
+ return SqlText.concat([SqlText.raw(joinType === "inner" ? "CROSS APPLY (" : "OUTER APPLY ("), subquery2, SqlText.raw(") AS "), this.ident(alias)]);
18670
+ }
18671
+ /** A date-field token as its bare `DATEPART` name. */
18672
+ rawArgLiteral(token) {
18673
+ return SqlText.raw(DATEPART[token] ?? "year");
18674
+ }
18675
+ emitBuiltinCall(name, args) {
18676
+ const call = (fn2, xs) => SqlText.concat([SqlText.raw(`${fn2}(`), SqlText.join(xs, ", "), SqlText.raw(")")]);
18677
+ if (args.length === 0) {
18678
+ if (name === "currentDate") return SqlText.raw("CAST(GETDATE() AS date)");
18679
+ if (name === "currentTime") return SqlText.raw("CAST(GETDATE() AS time)");
18680
+ }
18681
+ const part = EXTRACTOR2[name];
18682
+ if (part && args.length === 1) return call("DATEPART", [SqlText.raw(part), args[0]]);
18683
+ if (name === "epoch" && args.length === 1) return call("DATEDIFF_BIG", [SqlText.raw("second, '1970-01-01'"), args[0]]);
18684
+ if (name === "datePart" && args.length === 2) return call("DATEPART", args);
18685
+ if (name === "dateAdd" && args.length === 3) return call("DATEADD", args);
18686
+ if (name === "dateTrunc" && args.length === 2) return call("DATETRUNC", args);
18687
+ if (name === "dateDiff" && args.length === 3) {
18688
+ return SqlText.concat([SqlText.raw("("), call("DATEPART", [args[0], args[2]]), SqlText.raw(" - "), call("DATEPART", [args[0], args[1]]), SqlText.raw(")")]);
18689
+ }
18690
+ if (name === "mod" && args.length === 2) return SqlText.concat([SqlText.raw("("), args[0], SqlText.raw(" % "), args[1], SqlText.raw(")")]);
18691
+ const renamed = RENAMED2[name];
18692
+ if (renamed) return call(renamed, args);
18693
+ return super.emitBuiltinCall(name, args);
18694
+ }
18695
+ makeDdl() {
18696
+ return new SqlServerDdl(this);
18697
+ }
18698
+ };
18699
+
17664
18700
  // src/sql/index.ts
17665
18701
  function builtinDialects() {
17666
- return [new BaseDialect(), new PostgresDialect()];
18702
+ return [new BaseDialect(), new PostgresDialect(), new SqliteDialect(), new SqlServerDialect()];
17667
18703
  }
17668
18704
 
17669
18705
  // src/runtime/builtins.ts
@@ -17690,16 +18726,16 @@ function aggExample(fn2, args) {
17690
18726
  return JSON.stringify(def);
17691
18727
  }
17692
18728
  function windowExample(fn2, args, opts = {}) {
17693
- const win = {
18729
+ const win2 = {
17694
18730
  kind: "window",
17695
18731
  function: fn2,
17696
18732
  args,
17697
18733
  orderBy: [{ expr: ref("event", "score"), dir: "desc" }]
17698
18734
  };
17699
- if (opts.partition) win.partitionBy = [ref("event", "category")];
18735
+ if (opts.partition) win2.partitionBy = [ref("event", "category")];
17700
18736
  const def = {
17701
18737
  kind: "select",
17702
- fields: [{ expr: ref("event", "label") }, { expr: win, as: fn2 }],
18738
+ fields: [{ expr: ref("event", "label") }, { expr: win2, as: fn2 }],
17703
18739
  from: { kind: "type", type: "event" }
17704
18740
  };
17705
18741
  return JSON.stringify(def);
@@ -18890,7 +19926,7 @@ var Registry = class {
18890
19926
  message: `\`${name}\` already has an implementation. A second one is refused for the same reason a second DECLARATION is: every column naming it shares one compiled refinement, so the last registration would silently decide what all of them validate against.`
18891
19927
  });
18892
19928
  }
18893
- if (impl.value !== void 0 && !(impl.value instanceof z40.ZodType)) {
19929
+ if (impl.value !== void 0 && !(impl.value instanceof z42.ZodType)) {
18894
19930
  throw new QueryTypeError({
18895
19931
  path: ["registerFieldTypeImpl", name, "value"],
18896
19932
  code: "field-type.bad-refinement",
@@ -19550,10 +20586,10 @@ function checkLatticeLaws(types, opts) {
19550
20586
  const notAssociative = [];
19551
20587
  for (const x of names) {
19552
20588
  for (const y of names) {
19553
- for (const z42 of names) {
19554
- const left = metKey(pair(x, y), at(z42));
19555
- const right = metKey(at(x), pair(y, z42));
19556
- if (left !== right) notAssociative.push(`${x} \u2227 ${y} \u2227 ${z42}: ${left} vs ${right}`);
20589
+ for (const z44 of names) {
20590
+ const left = metKey(pair(x, y), at(z44));
20591
+ const right = metKey(at(x), pair(y, z44));
20592
+ if (left !== right) notAssociative.push(`${x} \u2227 ${y} \u2227 ${z44}: ${left} vs ${right}`);
19557
20593
  }
19558
20594
  }
19559
20595
  }
@@ -20355,11 +21391,11 @@ function isNull(v) {
20355
21391
  function notNull(v) {
20356
21392
  return new IsNullExpr(v, true);
20357
21393
  }
20358
- function between(v, lower2, upper) {
20359
- return new BetweenExpr(v, lower2, upper, false);
21394
+ function between(v, lower3, upper) {
21395
+ return new BetweenExpr(v, lower3, upper, false);
20360
21396
  }
20361
- function notBetween(v, lower2, upper) {
20362
- return new BetweenExpr(v, lower2, upper, true);
21397
+ function notBetween(v, lower3, upper) {
21398
+ return new BetweenExpr(v, lower3, upper, true);
20363
21399
  }
20364
21400
  function inList(v, items) {
20365
21401
  return new InExpr(v, items.map(asExpr), void 0, false);
@@ -20493,7 +21529,7 @@ function dateAdd(field, n, d) {
20493
21529
  function dateDiff(field, a, b) {
20494
21530
  return fn("dateDiff", { field: new LiteralExpr(field), a, b });
20495
21531
  }
20496
- function dateTrunc(field, d) {
21532
+ function dateTrunc2(field, d) {
20497
21533
  return fn("dateTrunc", { field: new LiteralExpr(field), d });
20498
21534
  }
20499
21535
  function makeDate(y, m, d) {
@@ -20655,7 +21691,7 @@ var e = {
20655
21691
  week,
20656
21692
  dateAdd,
20657
21693
  dateDiff,
20658
- dateTrunc,
21694
+ dateTrunc: dateTrunc2,
20659
21695
  makeDate,
20660
21696
  dateFormat,
20661
21697
  epoch,
@@ -21022,8 +22058,8 @@ var QueryEngine = class {
21022
22058
  const type = this.type(name);
21023
22059
  if (type) acc = foldChanges(acc, type.changes);
21024
22060
  }
21025
- for (const ref3 of refs.fields) {
21026
- const changes = this.type(ref3.type)?.field(ref3.field)?.changes();
22061
+ for (const ref4 of refs.fields) {
22062
+ const changes = this.type(ref4.type)?.field(ref4.field)?.changes();
21027
22063
  if (changes !== void 0) acc = foldChanges(acc, changes);
21028
22064
  }
21029
22065
  for (const name of refs.functions) {
@@ -21257,6 +22293,933 @@ function arrayExecutor(rows) {
21257
22293
  };
21258
22294
  }
21259
22295
 
22296
+ // src/ddl/gin.ts
22297
+ var UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
22298
+ function tableToGinType(table) {
22299
+ const props = {};
22300
+ for (const c of table.columns) props[c.name] = columnToProp(table, c);
22301
+ const key = table.primaryKey.length > 0 ? ` Key: ${table.primaryKey.join(", ")}.` : " No primary key.";
22302
+ return { name: "obj", docs: `${table.comment ?? `A row of table ${table.name}.`}${key}`, props };
22303
+ }
22304
+ function columnToProp(table, c) {
22305
+ const base = valueType(c);
22306
+ const docs = [
22307
+ c.comment,
22308
+ c.generated ? "Assigned by the database." : void 0,
22309
+ ...table.foreignKeys.filter((f) => f.columns.includes(c.name)).map((f) => `References ${f.table}.${f.references[f.columns.indexOf(c.name)] ?? f.references[0]}.`),
22310
+ c.default?.kind === "now" ? "Defaults to the current time." : void 0,
22311
+ c.default?.kind === "sql" ? `Defaults to \`${c.default.sql}\`.` : void 0
22312
+ ].filter((d) => d !== void 0 && d !== "");
22313
+ const prop = { type: c.nullable ? { name: "nullable", generic: { T: base } } : base };
22314
+ if (docs.length > 0) prop.docs = docs.join(" ");
22315
+ if (c.default?.kind === "value" && c.default.value !== null) prop.default = { kind: "new", type: scalarType(c.type), value: c.default.value };
22316
+ return prop;
22317
+ }
22318
+ function valueType(c) {
22319
+ const scalar3 = scalarType(c.type);
22320
+ if (!c.values) return scalar3;
22321
+ const values = {};
22322
+ for (const v of c.values) values[String(v)] = v;
22323
+ return { name: "enum", generic: { V: scalar3 }, options: { values } };
22324
+ }
22325
+ function scalarType(t) {
22326
+ switch (t.kind) {
22327
+ case "text":
22328
+ return t.maxLength === void 0 ? { name: "text" } : { name: "text", options: { maxLength: t.maxLength } };
22329
+ case "uuid":
22330
+ return { name: "text", options: { pattern: UUID_PATTERN } };
22331
+ case "integer":
22332
+ return { name: "num", options: { whole: true } };
22333
+ case "decimal":
22334
+ return t.scale === void 0 ? { name: "num" } : { name: "num", options: { maxPrecision: t.scale } };
22335
+ case "float":
22336
+ return { name: "num" };
22337
+ case "bool":
22338
+ return { name: "bool" };
22339
+ case "date":
22340
+ return { name: "date" };
22341
+ case "timestamp":
22342
+ return { name: "timestamp" };
22343
+ case "json":
22344
+ return { name: "any" };
22345
+ case "bytes":
22346
+ return { name: "text", docs: "Binary data, base64." };
22347
+ case "other":
22348
+ return { name: "any", docs: `Stored as ${t.native}.` };
22349
+ }
22350
+ }
22351
+ function ginTypeToTable(name, def, options = {}) {
22352
+ if (def.name !== "obj" || !def.props || Object.keys(def.props).length === 0) {
22353
+ throw new Error(`ginTypeToTable: ${name} must be an obj type with at least one prop (got '${def.name}').`);
22354
+ }
22355
+ const current = options.current;
22356
+ const refs = [];
22357
+ const columns = [];
22358
+ for (const [prop, spec] of Object.entries(def.props)) {
22359
+ if (spec.get) continue;
22360
+ const had = current?.columns.find((c) => c.name === prop);
22361
+ const { column: column2, ref: ref4 } = propToColumn(prop, spec, had, options.resolveTable);
22362
+ columns.push(column2);
22363
+ if (ref4) refs.push(ref4);
22364
+ }
22365
+ const names = new Set(columns.map((c) => c.name));
22366
+ const keep = (xs) => (xs ?? []).filter((x) => x.columns.every((c) => names.has(c)));
22367
+ const primaryKey = [...options.primaryKey ?? (current && keep([{ columns: current.primaryKey }]).length ? current.primaryKey : names.has("id") ? ["id"] : [])];
22368
+ const foreignKeys = options.foreignKeys ? [...options.foreignKeys] : keep(current?.foreignKeys);
22369
+ for (const r of refs) if (!foreignKeys.some((f) => f.columns.join() === r.columns.join())) foreignKeys.push(r);
22370
+ const key = primaryKey.length === 1 ? columns.find((c) => c.name === primaryKey[0]) : void 0;
22371
+ if (key && !current?.columns.some((c) => c.name === key.name) && key.type.kind === "integer" && !key.default) key.generated = true;
22372
+ for (const c of columns) if (primaryKey.includes(c.name)) c.nullable = false;
22373
+ const table = {
22374
+ name,
22375
+ columns,
22376
+ primaryKey,
22377
+ foreignKeys,
22378
+ unique: options.unique ? [...options.unique] : keep(current?.unique)
22379
+ };
22380
+ const schema = options.schema ?? current?.schema;
22381
+ if (schema !== void 0) table.schema = schema;
22382
+ if (current?.primaryKeyName !== void 0 && primaryKey.join() === current.primaryKey.join()) table.primaryKeyName = current.primaryKeyName;
22383
+ const comment = options.comment ?? current?.comment;
22384
+ if (comment !== void 0) table.comment = comment;
22385
+ return table;
22386
+ }
22387
+ function propToColumn(name, spec, had, resolveTable) {
22388
+ let type = spec.type;
22389
+ let nullable = false;
22390
+ while (type.name === "nullable" || type.name === "optional") {
22391
+ nullable = true;
22392
+ type = type.generic?.["T"] ?? { name: "any" };
22393
+ }
22394
+ let values;
22395
+ if (type.name === "enum") {
22396
+ values = enumValues(type);
22397
+ type = type.generic?.["V"] ?? { name: "text" };
22398
+ }
22399
+ let ref4;
22400
+ let columnType = ginToColumnType(type);
22401
+ const target = BUILTIN_NAMES.has(type.name) ? void 0 : resolveTable?.(type.name);
22402
+ if (target && target.primaryKey.length === 1) {
22403
+ const key = target.columns.find((c) => c.name === target.primaryKey[0]);
22404
+ if (key) {
22405
+ columnType = key.type;
22406
+ ref4 = { columns: [name], table: target.name, references: [key.name] };
22407
+ }
22408
+ }
22409
+ const sameStorage = had !== void 0 && JSON.stringify(storage(scalarType(had.type))) === JSON.stringify(storage(scalarType(columnType)));
22410
+ const column2 = { name, type: sameStorage && had ? had.type : columnType, nullable };
22411
+ const fallback = defaultOf(spec.default);
22412
+ const dflt = fallback ?? had?.default;
22413
+ if (dflt) column2.default = dflt;
22414
+ if (had?.generated) column2.generated = true;
22415
+ const keepValues = values && (!had || had.values) ? values : had?.values;
22416
+ if (keepValues) column2.values = keepValues;
22417
+ if (had?.checkName) column2.checkName = had.checkName;
22418
+ if (had?.defaultName) column2.defaultName = had.defaultName;
22419
+ if (had?.comment) column2.comment = had.comment;
22420
+ return ref4 ? { column: column2, ref: ref4 } : { column: column2 };
22421
+ }
22422
+ var BUILTIN_NAMES = /* @__PURE__ */ new Set([
22423
+ "any",
22424
+ "void",
22425
+ "null",
22426
+ "bool",
22427
+ "num",
22428
+ "text",
22429
+ "list",
22430
+ "map",
22431
+ "tuple",
22432
+ "obj",
22433
+ "optional",
22434
+ "nullable",
22435
+ "not",
22436
+ "or",
22437
+ "and",
22438
+ "enum",
22439
+ "literal",
22440
+ "function",
22441
+ "fn",
22442
+ "interface",
22443
+ "iface",
22444
+ "typ",
22445
+ "date",
22446
+ "timestamp",
22447
+ "duration",
22448
+ "color"
22449
+ ]);
22450
+ function ginToColumnType(type) {
22451
+ const o = isRecord4(type.options) ? type.options : {};
22452
+ switch (type.name) {
22453
+ case "text":
22454
+ if (o["pattern"] === UUID_PATTERN) return { kind: "uuid" };
22455
+ return typeof o["maxLength"] === "number" ? { kind: "text", maxLength: o["maxLength"] } : { kind: "text" };
22456
+ case "num":
22457
+ if (o["whole"] === true) return { kind: "integer" };
22458
+ return typeof o["maxPrecision"] === "number" ? { kind: "decimal", scale: o["maxPrecision"] } : { kind: "float" };
22459
+ case "bool":
22460
+ return { kind: "bool" };
22461
+ case "date":
22462
+ return { kind: "date" };
22463
+ case "timestamp":
22464
+ return { kind: "timestamp" };
22465
+ case "duration":
22466
+ return { kind: "integer", big: true };
22467
+ case "color":
22468
+ return { kind: "integer" };
22469
+ case "literal":
22470
+ return typeof o["value"] === "number" ? { kind: "float" } : typeof o["value"] === "boolean" ? { kind: "bool" } : { kind: "text" };
22471
+ default:
22472
+ return { kind: "json" };
22473
+ }
22474
+ }
22475
+ function storage(type) {
22476
+ const o = isRecord4(type.options) ? type.options : {};
22477
+ return { name: type.name, maxLength: o["maxLength"], whole: o["whole"], maxPrecision: o["maxPrecision"], uuid: o["pattern"] === UUID_PATTERN };
22478
+ }
22479
+ function enumValues(type) {
22480
+ const o = isRecord4(type.options) ? type.options : {};
22481
+ const values = o["values"];
22482
+ if (!isRecord4(values)) return void 0;
22483
+ const out = Object.values(values).filter((v) => typeof v === "string" || typeof v === "number");
22484
+ return out.length > 0 ? out : void 0;
22485
+ }
22486
+ function defaultOf(expr) {
22487
+ if (!expr || expr.kind !== "new" || !("value" in expr)) return void 0;
22488
+ const value2 = expr["value"];
22489
+ if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") return { kind: "value", value: value2 };
22490
+ return void 0;
22491
+ }
22492
+ function isRecord4(value2) {
22493
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
22494
+ }
22495
+
22496
+ // src/ddl/query-type.ts
22497
+ function tableToQueryType(table, options = {}) {
22498
+ const name = options.typeName ?? ((t) => t);
22499
+ const fields = table.columns.map((c) => {
22500
+ const field = { name: c.name, type: relationOf2(table, c, options, name) ?? fieldTypeOf(c) };
22501
+ if (c.nullable) field.nullable = true;
22502
+ if (c.comment) field.description = c.comment;
22503
+ if (c.generated) field.insertable = false;
22504
+ return field;
22505
+ });
22506
+ const indexes = [];
22507
+ const unique = [table.primaryKey, ...table.unique.map((u) => u.columns)].filter((cols) => cols.length > 0);
22508
+ for (const cols of unique) {
22509
+ indexes.push({ exprs: cols.map((field, i) => ({ expr: { kind: "field-ref", source: name(table.name), field }, count: i === cols.length - 1 ? 1 : 10 })) });
22510
+ }
22511
+ const def = { name: name(table.name), fields, count: options.rowCount ?? 1e3 };
22512
+ if (table.comment) def.description = table.comment;
22513
+ if (indexes.length > 0) def.indexes = indexes;
22514
+ if (table.primaryKey.length > 0) def.identity = table.primaryKey.length === 1 ? table.primaryKey[0] ?? "id" : [...table.primaryKey];
22515
+ return def;
22516
+ }
22517
+ function relationOf2(table, c, options, name) {
22518
+ const fk = table.foreignKeys.find((f) => f.columns.length === 1 && f.columns[0] === c.name);
22519
+ if (!fk) return void 0;
22520
+ const target = options.tables?.find((t) => t.name === fk.table);
22521
+ if (options.tables && (!target || target.primaryKey.length !== 1 || target.primaryKey[0] !== fk.references[0])) return void 0;
22522
+ return { kind: "relation", to: name(fk.table), count: 1 };
22523
+ }
22524
+ function fieldTypeOf(c) {
22525
+ const t = scalarFieldType(c.type);
22526
+ if (!c.values) return t;
22527
+ const values = c.values.map((value2) => ({ value: value2 }));
22528
+ if (t.kind === "text") return { ...t, values };
22529
+ if (t.kind === "number") return { ...t, values };
22530
+ return t;
22531
+ }
22532
+ function scalarFieldType(t) {
22533
+ switch (t.kind) {
22534
+ case "text":
22535
+ return t.maxLength === void 0 ? { kind: "text" } : { kind: "text", maxLength: t.maxLength };
22536
+ case "uuid":
22537
+ case "bytes":
22538
+ case "other":
22539
+ return { kind: "text" };
22540
+ case "integer":
22541
+ return { kind: "number", whole: true };
22542
+ case "decimal":
22543
+ return t.scale === void 0 ? { kind: "number" } : { kind: "number", maxPlaces: t.scale };
22544
+ case "float":
22545
+ return { kind: "number" };
22546
+ case "bool":
22547
+ return { kind: "bool" };
22548
+ case "date":
22549
+ return { kind: "date" };
22550
+ case "timestamp":
22551
+ return { kind: "timestamp", timezone: t.timezone !== false };
22552
+ case "json":
22553
+ return { kind: "json" };
22554
+ }
22555
+ }
22556
+
22557
+ // src/signature.ts
22558
+ import { argProblems, createRegistry as createGinRegistry } from "@aeye/gin";
22559
+ function fieldTypeToGin(def) {
22560
+ switch (def?.kind) {
22561
+ case void 0:
22562
+ return { name: "any" };
22563
+ case "number":
22564
+ case "money": {
22565
+ const options = def.kind === "number" ? def : def.number ?? {};
22566
+ if (options.values !== void 0) return enumOf3(options.values.map((v) => v.value), { name: "num" });
22567
+ const bounds = {
22568
+ ...options.min === void 0 ? {} : { min: options.min },
22569
+ ...options.max === void 0 ? {} : { max: options.max },
22570
+ ...options.whole === true ? { whole: true } : {}
22571
+ };
22572
+ return Object.keys(bounds).length === 0 ? { name: "num" } : { name: "num", options: bounds };
22573
+ }
22574
+ case "text": {
22575
+ if (def.values !== void 0) return enumOf3(def.values.map((v) => v.value), { name: "text" });
22576
+ const bounds = {
22577
+ ...def.minLength === void 0 ? {} : { minLength: def.minLength },
22578
+ ...def.maxLength === void 0 ? {} : { maxLength: def.maxLength },
22579
+ ...def.pattern === void 0 ? {} : { pattern: def.pattern }
22580
+ };
22581
+ return Object.keys(bounds).length === 0 ? { name: "text" } : { name: "text", options: bounds };
22582
+ }
22583
+ case "bool":
22584
+ return { name: "bool" };
22585
+ case "date":
22586
+ return { name: "date" };
22587
+ case "timestamp":
22588
+ return { name: "timestamp" };
22589
+ case "array":
22590
+ return { name: "list", generic: { V: fieldTypeToGin(def.item) } };
22591
+ case "json":
22592
+ case "relation":
22593
+ return { name: "any" };
22594
+ }
22595
+ }
22596
+ function enumOf3(values, scalar3) {
22597
+ const members = {};
22598
+ for (const value2 of values) members[String(value2)] = value2;
22599
+ return { name: "enum", generic: { V: scalar3 }, options: { values: members } };
22600
+ }
22601
+ var optional2 = (type) => ({ name: "optional", generic: { T: type } });
22602
+ function queryArgsType(params, options = {}) {
22603
+ const props = {};
22604
+ const loose = new Set(options.optional ?? []);
22605
+ for (const param4 of params) {
22606
+ const type = fieldTypeToGin(param4.type?.toJSON());
22607
+ const column2 = param4.uses.find((use) => use.field !== void 0)?.field;
22608
+ const fallback = options.defaults?.[param4.name];
22609
+ const docs = [column2 === void 0 ? void 0 : `Compared with ${column2.type}.${column2.field}.`, fallback === void 0 ? void 0 : `Default ${JSON.stringify(fallback)}.`].filter((d) => d !== void 0);
22610
+ props[param4.name] = {
22611
+ type: loose.has(param4.name) || fallback !== void 0 ? optional2(type) : type,
22612
+ ...docs.length === 0 ? {} : { docs: docs.join(" ") },
22613
+ ...fallback === void 0 ? {} : { default: { kind: "new", type, value: fallback } }
22614
+ };
22615
+ }
22616
+ if (options.paging) {
22617
+ props["limit"] ??= { type: optional2({ name: "num", options: { whole: true, min: 1, max: options.paging.max } }), docs: `How many rows (${options.paging.page} when empty).` };
22618
+ props["offset"] ??= { type: optional2({ name: "num", options: { whole: true, min: 0 } }), docs: "How many rows to skip, for the next page." };
22619
+ }
22620
+ const sorters = options.sorters ?? [];
22621
+ if (sorters.length > 0 && props["sort"] === void 0) {
22622
+ const entry = { name: "obj", props: { column: { type: enumOf3(sorters, { name: "text" }) }, dir: { type: enumOf3(["asc", "desc"], { name: "text" }) } } };
22623
+ props["sort"] = { type: optional2({ name: "list", generic: { V: entry } }), docs: "Sort by these columns, in order (the query's own order when empty)." };
22624
+ }
22625
+ return { name: "obj", props };
22626
+ }
22627
+ function withArgDefaults(type, args) {
22628
+ const out = { ...args };
22629
+ for (const [name, prop] of Object.entries(type.props ?? {})) {
22630
+ const fallback = prop.default;
22631
+ if (out[name] !== void 0 || fallback === void 0 || fallback.kind !== "new" || !("value" in fallback)) continue;
22632
+ out[name] = toJson(fallback.value);
22633
+ }
22634
+ return out;
22635
+ }
22636
+ function toJson(value2) {
22637
+ if (value2 === null || typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") return value2;
22638
+ if (Array.isArray(value2)) return value2.map(toJson);
22639
+ if (typeof value2 === "object") return Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, toJson(v)]));
22640
+ return null;
22641
+ }
22642
+ var ARGS_REGISTRY = createGinRegistry();
22643
+ function queryArgProblems(type, args) {
22644
+ return argProblems(ARGS_REGISTRY, type, args);
22645
+ }
22646
+ function typeWord(def) {
22647
+ switch (def.name) {
22648
+ case "optional":
22649
+ case "nullable":
22650
+ return typeWord(def.generic?.["T"] ?? { name: "any" });
22651
+ case "enum":
22652
+ return Object.values(def.options?.["values"] ?? {}).map((v) => JSON.stringify(v)).join(" | ");
22653
+ case "list":
22654
+ return `list<${typeWord(def.generic?.["V"] ?? { name: "any" })}>`;
22655
+ case "obj":
22656
+ return `{ ${Object.entries(def.props ?? {}).map(([name, prop]) => `${name}: ${typeWord(prop.type)}`).join(", ")} }`;
22657
+ default:
22658
+ return def.name;
22659
+ }
22660
+ }
22661
+ function signatureText(fn2, args) {
22662
+ const parts = Object.entries(args.props ?? {}).map(([name, prop]) => {
22663
+ const loose = prop.type.name === "optional" || prop.type.name === "nullable";
22664
+ return `${name}${loose ? "?" : ""}: ${typeWord(prop.type)}`;
22665
+ });
22666
+ return `${fn2}(${parts.join(", ")})`;
22667
+ }
22668
+
22669
+ // src/ddl/table-fns.ts
22670
+ var TableFnError = class extends Error {
22671
+ constructor(message) {
22672
+ super(message);
22673
+ this.name = "TableFnError";
22674
+ }
22675
+ };
22676
+ function canCompare(numerator, denominator) {
22677
+ return numerator.table === denominator.table && numerator.column === denominator.column;
22678
+ }
22679
+ function ratio(numerator, denominator) {
22680
+ if (!canCompare(numerator, denominator)) {
22681
+ throw new TableFnError(
22682
+ `${numerator.table}.${numerator.column ?? "*"} can't be divided by ${denominator.table}.${denominator.column ?? "*"}: a ratio needs the same table and column on both sides.`
22683
+ );
22684
+ }
22685
+ return div2(numerator.expr, denominator.expr);
22686
+ }
22687
+ function tableFns(table, tables, options = {}) {
22688
+ return new TableFnSchema(tables, options).list(table);
22689
+ }
22690
+ function tableFnQuery(op, tables, options = {}) {
22691
+ return new TableFnSchema(tables, options).fn(op);
22692
+ }
22693
+ function tableSchemaHash(table, tables) {
22694
+ const own = tables.find((t) => t.name === table);
22695
+ if (!own) throw new TableFnError(`There is no table ${table}.`);
22696
+ const related = tables.filter((t) => t.name === table || own.foreignKeys.some((f) => f.table === t.name) || t.foreignKeys.some((f) => f.table === table));
22697
+ const text = stableJson([...related].sort((a, b) => a.name < b.name ? -1 : 1));
22698
+ let hash = 0xcbf29ce484222325n;
22699
+ for (let i = 0; i < text.length; i++) {
22700
+ hash ^= BigInt(text.charCodeAt(i));
22701
+ hash = hash * 0x100000001b3n & 0xffffffffffffffffn;
22702
+ }
22703
+ return hash.toString(16).padStart(16, "0");
22704
+ }
22705
+ function stableJson(value2) {
22706
+ if (Array.isArray(value2)) return `[${value2.map(stableJson).join(",")}]`;
22707
+ if (typeof value2 !== "object" || value2 === null) return JSON.stringify(value2) ?? "null";
22708
+ const entries = Object.entries(value2).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : 1);
22709
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(",")}}`;
22710
+ }
22711
+ var ref3 = (source, field) => ({ kind: "field-ref", source, field });
22712
+ var lit3 = (value2) => ({ kind: "literal", value: value2 });
22713
+ var param3 = (name) => ({ kind: "param", name });
22714
+ var eq2 = (left, right) => ({ kind: "comparison", op: "=", left, right });
22715
+ var cmp = (op, left, right) => ({ kind: "comparison", op, left, right });
22716
+ var isNull2 = (value2) => ({ kind: "is-null", value: value2 });
22717
+ var maybe = (name, test) => ({ kind: "logical", op: "or", operands: [isNull2(param3(name)), test] });
22718
+ var agg2 = (fn2, value2) => ({ kind: "aggregate", function: fn2, args: value2 === void 0 ? {} : { value: value2 } });
22719
+ var win = (fn2, value2, partitionBy, orderBy) => ({
22720
+ kind: "window",
22721
+ function: fn2,
22722
+ args: value2 === void 0 ? {} : { value: value2 },
22723
+ ...partitionBy.length > 0 ? { partitionBy } : {},
22724
+ ...orderBy === void 0 ? {} : { orderBy: [{ expr: orderBy, dir: "desc", nulls: "last" }] }
22725
+ });
22726
+ var sub2 = (a, b) => ({ kind: "binary", op: "-", left: a, right: b });
22727
+ function div2(a, b) {
22728
+ return {
22729
+ kind: "binary",
22730
+ op: "/",
22731
+ left: { kind: "binary", op: "*", left: a, right: lit3(1) },
22732
+ right: { kind: "function-call", function: "nullif", args: { value: b, other: lit3(0) } }
22733
+ };
22734
+ }
22735
+ var words = (name) => name.replace(/([a-z0-9])([A-Z])/gu, "$1 $2").split(/[^A-Za-z0-9]+/u).filter((w) => w.length > 0).map((w) => w.toLowerCase());
22736
+ var cap = (word) => word.length === 0 ? word : `${word[0].toUpperCase()}${word.slice(1)}`;
22737
+ var camel = (name) => words(name).map((w, i) => i === 0 ? w : cap(w)).join("");
22738
+ function singular(name) {
22739
+ if (/ies$/u.test(name)) return `${name.slice(0, -3)}y`;
22740
+ if (/(s|x|ch|sh)es$/u.test(name)) return name.slice(0, -2);
22741
+ if (/[^s]s$/u.test(name)) return name.slice(0, -1);
22742
+ return name;
22743
+ }
22744
+ var relWord = (column2) => camel(column2.replace(/(_id|Id|_key)$/u, ""));
22745
+ var valueWord = (value2) => cap(camel(String(value2))) || "Empty";
22746
+ var human = (name) => words(name).join(" ");
22747
+ var isNumber = (c) => ["integer", "decimal", "float"].includes(c.type.kind);
22748
+ var isDate = (c) => c.type.kind === "date" || c.type.kind === "timestamp";
22749
+ var isEnum = (c) => c.values !== void 0 && c.values.length <= 12;
22750
+ var keyOf = (t) => t.primaryKey.length === 1 ? t.primaryKey[0] : void 0;
22751
+ var JoinSet = class {
22752
+ joins = [];
22753
+ #parents = /* @__PURE__ */ new Map();
22754
+ #next = 0;
22755
+ fresh(prefix) {
22756
+ this.#next += 1;
22757
+ return `${prefix}${this.#next}`;
22758
+ }
22759
+ /** The alias of `alias`'s parent across `column`, joining it the first time. */
22760
+ parent(alias, column2) {
22761
+ const key = `${alias}.${column2}`;
22762
+ const known = this.#parents.get(key);
22763
+ if (known !== void 0) return known;
22764
+ const as = this.fresh("p");
22765
+ this.joins.push({ on: { kind: "relation", source: alias, field: column2, as }, joinType: "left" });
22766
+ this.#parents.set(key, as);
22767
+ return as;
22768
+ }
22769
+ };
22770
+ var DEFAULT_PAGING = { max: 500, page: 50 };
22771
+ var TableFnSchema = class {
22772
+ #tables;
22773
+ #engine;
22774
+ #depth;
22775
+ #cap;
22776
+ #paging;
22777
+ constructor(tables, options = {}) {
22778
+ this.#tables = new Map(tables.map((t) => [t.name, t]));
22779
+ const registry = createRegistry();
22780
+ for (const t of tables) registry.registerType(registry.parseType(tableToQueryType(t, { tables })));
22781
+ registry.finalize();
22782
+ this.#engine = new QueryEngine(registry);
22783
+ this.#depth = options.depth ?? 2;
22784
+ this.#cap = options.cap ?? 60;
22785
+ this.#paging = options.paging ?? DEFAULT_PAGING;
22786
+ }
22787
+ /** The engine the queries are checked with. */
22788
+ get engine() {
22789
+ return this.#engine;
22790
+ }
22791
+ table(name) {
22792
+ const t = this.#tables.get(name);
22793
+ if (!t) throw new TableFnError(`There is no table ${name}.`);
22794
+ return t;
22795
+ }
22796
+ belongsTo(t) {
22797
+ const out = [];
22798
+ for (const fk of t.foreignKeys) {
22799
+ const column2 = fk.columns.length === 1 ? fk.columns[0] : void 0;
22800
+ const parent = this.#tables.get(fk.table);
22801
+ if (column2 === void 0 || !parent || keyOf(parent) !== fk.references[0]) continue;
22802
+ out.push({ word: relWord(column2), column: column2, parent, key: fk.references[0] });
22803
+ }
22804
+ return out;
22805
+ }
22806
+ hasMany(t) {
22807
+ const key = keyOf(t);
22808
+ if (key === void 0) return [];
22809
+ const out = [];
22810
+ for (const child of this.#tables.values()) {
22811
+ const fks = child.foreignKeys.filter((f) => f.table === t.name && f.columns.length === 1 && f.references[0] === key);
22812
+ for (const fk of fks) {
22813
+ const base = camel(singular(child.name));
22814
+ out.push({ word: fks.length > 1 ? `${base}By${cap(relWord(fk.columns[0]))}` : base, child, column: fk.columns[0] });
22815
+ }
22816
+ }
22817
+ return out;
22818
+ }
22819
+ /** Every derived field of a table (own number columns compared, relations followed to the depth). */
22820
+ derivations(t, depth = this.#depth, own = true) {
22821
+ const out = [];
22822
+ const key = keyOf(t);
22823
+ if (key !== void 0 && depth >= 1) {
22824
+ for (const rel of this.hasMany(t)) out.push(...this.#hasManyFields(t, key, rel));
22825
+ }
22826
+ if (depth >= 1) {
22827
+ for (const rel of this.belongsTo(t)) {
22828
+ for (const c of rel.parent.columns) {
22829
+ if (c.name === rel.key || this.belongsTo(rel.parent).some((b) => b.column === c.name)) continue;
22830
+ out.push({
22831
+ field: { name: `${rel.word}${cap(camel(c.name))}`, about: `The ${human(c.name)} of its ${human(rel.word)}.`, meaning: "measure", measure: "value", table: rel.parent.name, column: c.name, via: [rel.column] },
22832
+ rank: 40,
22833
+ group: rel.word,
22834
+ build: (joins, alias) => ref3(joins.parent(alias, rel.column), c.name)
22835
+ });
22836
+ }
22837
+ for (const d of this.derivations(rel.parent, depth - 1, false)) {
22838
+ out.push({
22839
+ field: { ...d.field, name: `${rel.word}${cap(d.field.name)}`, about: `Of its ${human(rel.word)}: ${lower2(d.field.about)}`, via: [rel.column, ...d.field.via] },
22840
+ rank: d.rank + 20,
22841
+ group: rel.word,
22842
+ build: (joins, alias) => d.build(joins, joins.parent(alias, rel.column))
22843
+ });
22844
+ }
22845
+ }
22846
+ }
22847
+ if (own) out.push(...this.#ownComparisons(t));
22848
+ return out;
22849
+ }
22850
+ #hasManyFields(t, key, rel) {
22851
+ const out = [];
22852
+ const child = rel.child;
22853
+ const group = rel.word;
22854
+ const many = (filter, measure, column2, rank) => {
22855
+ const split = filter === void 0 ? "" : `${cap(camel(filter.column.name))}${valueWord(filter.value)}`;
22856
+ const word = measure === "sum" ? "Total" : measure === "count" ? "Count" : cap(measure);
22857
+ const name = column2 === void 0 ? `${rel.word}${split}Count` : `${rel.word}${split}${word}${cap(camel(column2.name))}`;
22858
+ const whose = filter === void 0 ? `its ${human(child.name)}` : `its ${human(child.name)} with ${human(filter.column.name)} ${String(filter.value)}`;
22859
+ const about = column2 === void 0 ? `How many of ${whose} there are.` : `The ${measure === "sum" ? "total" : measure} ${human(column2.name)} of ${whose}.`;
22860
+ return {
22861
+ field: { name, about, meaning: "measure", measure, table: child.name, column: column2?.name ?? null, via: [`${child.name}.${rel.column}`] },
22862
+ rank,
22863
+ group,
22864
+ build: (joins, alias) => {
22865
+ const s = joins.fresh("s");
22866
+ const j = joins.fresh("j");
22867
+ const select = {
22868
+ kind: "select",
22869
+ fields: [{ expr: column2 === void 0 ? agg2("count") : agg2(measure, ref3(s, column2.name)), as: "v" }],
22870
+ from: { kind: "aliased", type: child.name, as: s },
22871
+ joins: [{ on: { kind: "relation", source: s, field: rel.column, as: j }, joinType: "inner" }],
22872
+ where: [eq2(ref3(j, key), ref3(alias, key)), ...filter === void 0 ? [] : [eq2(ref3(s, filter.column.name), lit3(filter.value))]]
22873
+ };
22874
+ return { kind: "subquery", query: select };
22875
+ }
22876
+ };
22877
+ };
22878
+ const numbers = child.columns.filter(isNumber).filter((c) => !child.foreignKeys.some((f) => f.columns.includes(c.name)) && !child.primaryKey.includes(c.name));
22879
+ const dates = child.columns.filter(isDate);
22880
+ const all = (filter, base) => [
22881
+ many(filter, "count", void 0, base),
22882
+ ...numbers.flatMap((c) => [many(filter, "sum", c, base + 1), many(filter, "avg", c, base + 2), many(filter, "min", c, base + 5), many(filter, "max", c, base + 5)]),
22883
+ ...dates.flatMap((c) => [many(filter, "min", c, base + 6), many(filter, "max", c, base + 6)])
22884
+ ];
22885
+ out.push(...all(void 0, 20));
22886
+ for (const e2 of child.columns.filter(isEnum)) {
22887
+ for (const value2 of e2.values ?? []) out.push(...all({ column: e2, value: value2 }, 30));
22888
+ }
22889
+ return out;
22890
+ }
22891
+ /** Table-wide totals and the normalized comparisons of each own number column. */
22892
+ #ownComparisons(t) {
22893
+ const out = [];
22894
+ const numbers = t.columns.filter(isNumber).filter((c) => !t.foreignKeys.some((f) => f.columns.includes(c.name)) && !t.primaryKey.includes(c.name));
22895
+ for (const c of numbers) {
22896
+ const col = cap(camel(c.name));
22897
+ const measured = { table: t.name, column: c.name };
22898
+ for (const m of ["sum", "avg", "min", "max"]) {
22899
+ out.push({
22900
+ field: { name: `${m === "sum" ? "total" : m}${col}`, about: `The ${m === "sum" ? "total" : m} ${human(c.name)} over the whole table.`, meaning: "measure", measure: m, ...measured, via: [] },
22901
+ rank: 35,
22902
+ group: "table",
22903
+ build: (_joins, alias) => win(m, ref3(alias, c.name), [])
22904
+ });
22905
+ }
22906
+ const scopes = [
22907
+ { word: "", about: "the whole table", group: "table", partition: () => [] },
22908
+ ...this.belongsTo(t).map((rel) => ({
22909
+ word: rel.word,
22910
+ about: `its ${human(rel.word)}'s ${human(t.name)}`,
22911
+ group: rel.word,
22912
+ partition: (joins, alias) => [ref3(joins.parent(alias, rel.column), rel.key)]
22913
+ }))
22914
+ ];
22915
+ for (const scope of scopes) {
22916
+ const pre = scope.word;
22917
+ const name = (plain2, scoped) => pre === "" ? plain2 : scoped;
22918
+ const compare = (field, rank, build) => ({
22919
+ field: { ...field, ...measured, via: [] },
22920
+ rank,
22921
+ group: scope.group,
22922
+ build: (joins, alias) => build(ref3(alias, c.name), scope.partition(joins, alias))
22923
+ });
22924
+ const whole = (fn2, value2, part) => ({ expr: win(fn2, value2, part), ...measured });
22925
+ out.push(
22926
+ compare({ name: name(`relative${col}Rank`, `${pre}Relative${col}Rank`), about: `Its place by ${human(c.name)} among ${scope.about} (1 is the highest).`, meaning: "relative", measure: "rank" }, 26, (v, part) => win("rank", void 0, part, v)),
22927
+ compare({ name: name(`${camel(c.name)}Percentile`, `${pre}${col}Percentile`), about: `Its rank by ${human(c.name)} over how many there are among ${scope.about} (near 0 is the top).`, meaning: "progress", measure: "percentile" }, 27, (v, part) => ratio({ expr: win("rank", void 0, part, v), table: t.name, column: null }, { expr: win("count", void 0, part), table: t.name, column: null })),
22928
+ compare({ name: name(`shareOfTotal${col}`, `shareOf${cap(pre)}Total${col}`), about: `Its ${human(c.name)} as a part of the total of ${scope.about} (0 to 1).`, meaning: "portion", measure: "share" }, 26, (v, part) => ratio({ expr: v, ...measured }, whole("sum", v, part))),
22929
+ compare({ name: name(`${camel(c.name)}Position`, `${pre}${col}Position`), about: `Where its ${human(c.name)} sits between the lowest (0) and highest (1) of ${scope.about}.`, meaning: "relative", measure: "position" }, 28, (v, part) => ratio({ expr: sub2(v, win("min", v, part)), ...measured }, { expr: sub2(win("max", v, part), win("min", v, part)), ...measured })),
22930
+ compare({ name: name(`${camel(c.name)}OfMax`, `${pre}${col}OfMax`), about: `Its ${human(c.name)} over the highest of ${scope.about}.`, meaning: "relative", measure: "ofMax" }, 28, (v, part) => ratio({ expr: v, ...measured }, whole("max", v, part)))
22931
+ );
22932
+ }
22933
+ }
22934
+ return out;
22935
+ }
22936
+ /** The table's fns, most useful first, capped. */
22937
+ list(table) {
22938
+ const t = this.table(table);
22939
+ const fns = this.#ops(t).map((op) => this.fn(op)).sort((a, b) => a.rank - b.rank || a.group.localeCompare(b.group) || a.name.localeCompare(b.name));
22940
+ return { table, hash: tableSchemaHash(table, [...this.#tables.values()]), fns: fns.slice(0, this.#cap), more: Math.max(0, fns.length - this.#cap) };
22941
+ }
22942
+ #ops(t) {
22943
+ const table = t.name;
22944
+ const ops = [{ kind: "selectPage", table }, { kind: "create", table }];
22945
+ if (keyOf(t) !== void 0) ops.push({ kind: "selectOne", table }, { kind: "update", table }, { kind: "remove", table });
22946
+ ops.push({ kind: "updateWhere", table }, { kind: "removeWhere", table });
22947
+ for (const u of t.unique.filter((u2) => u2.columns.length === 1)) {
22948
+ const column2 = u.columns[0];
22949
+ ops.push({ kind: "selectOne", table, column: column2 }, { kind: "exists", table, column: column2 }, { kind: "findOrCreate", table, column: column2 });
22950
+ }
22951
+ for (const c of t.columns) {
22952
+ if (isEnum(c) || c.type.kind === "bool") ops.push({ kind: "countBy", table, column: c.name });
22953
+ if (isNumber(c) && !t.primaryKey.includes(c.name) && !t.foreignKeys.some((f) => f.columns.includes(c.name))) ops.push({ kind: "stats", table, column: c.name });
22954
+ if (isDate(c)) for (const bucket of ["day", "week", "month"]) ops.push({ kind: "buckets", table, column: c.name, bucket });
22955
+ }
22956
+ for (const rel of this.belongsTo(t)) {
22957
+ ops.push({ kind: "countBy", table, column: rel.column });
22958
+ if (keyOf(t) !== void 0) ops.push({ kind: "update", table, column: rel.column });
22959
+ }
22960
+ for (const rel of this.hasMany(t)) {
22961
+ ops.push({ kind: "childrenOf", table, child: rel.child.name, column: rel.column }, { kind: "countPerParent", table, child: rel.child.name, column: rel.column });
22962
+ }
22963
+ for (const d of this.derivations(t)) ops.push({ kind: "derived", table, derived: [d.field.name] });
22964
+ return ops;
22965
+ }
22966
+ /** One fn from its op: its query (checked), args and signature. Throws `TableFnError` for what it can't build. */
22967
+ fn(op) {
22968
+ const t = this.table(op.table);
22969
+ const built = this.#build(t, op);
22970
+ const problems = this.#engine.validateQuery(built.query).list.filter((p) => p.severity === "error");
22971
+ if (problems.length > 0) throw new TableFnError(`${op.table}.${built.name} does not check: ${problems.map((p) => `${p.path.join(".")}: ${p.message}`).join("; ")}`);
22972
+ const params = this.#engine.parameters(built.query);
22973
+ const args = queryArgsType(params, { optional: built.optional, defaults: built.defaults, sorters: built.sorters, ...built.list ? { paging: this.#paging } : {} });
22974
+ return { ...built, table: t.name, op, args, signature: signatureText(built.name, args) };
22975
+ }
22976
+ #build(t, op) {
22977
+ const table = t.name;
22978
+ const key = keyOf(t);
22979
+ const noun = human(singular(table));
22980
+ const column2 = op.column === void 0 || op.kind === "childrenOf" || op.kind === "countPerParent" ? void 0 : columnOf(t, op.column);
22981
+ const base = { kind: op.kind, list: false, sorters: [], optional: [], defaults: {} };
22982
+ switch (op.kind) {
22983
+ case "selectPage": {
22984
+ const derived = (op.derived ?? []).map((name) => this.#derivation(t, name));
22985
+ const filters2 = t.columns.filter((c) => isEnum(c) || c.type.kind === "bool" || this.#isForeign(t, c));
22986
+ const where = filters2.map((c) => maybe(c.name, eq2(ref3("t", c.name), param3(c.name))));
22987
+ const optional3 = filters2.map((c) => c.name);
22988
+ for (const d of derived) {
22989
+ where.push(maybe(`min${cap(d.field.name)}`, cmp(">=", ref3("t", d.field.name), param3(`min${cap(d.field.name)}`))));
22990
+ where.push(maybe(`max${cap(d.field.name)}`, cmp("<=", ref3("t", d.field.name), param3(`max${cap(d.field.name)}`))));
22991
+ optional3.push(`min${cap(d.field.name)}`, `max${cap(d.field.name)}`);
22992
+ }
22993
+ const columns = [...t.columns.map((c) => c.name), ...derived.map((d) => d.field.name)];
22994
+ const query = this.#outer(t, derived, columns, where);
22995
+ return { ...base, name: "selectPage", about: `List ${human(table)}, filtered by any of ${optional3.map(human).join(", ") || "nothing"}, sorted and paged.`, group: "crud", rank: 0, mode: "read", query, list: true, sorters: columns, optional: optional3 };
22996
+ }
22997
+ case "selectOne": {
22998
+ const by = column2 ?? requireKey(t);
22999
+ const query = this.#outer(t, [], t.columns.map((c) => c.name), [eq2(ref3("t", by.name), param3(by.name))]);
23000
+ return { ...base, name: column2 === void 0 ? "selectOne" : `selectBy${cap(camel(by.name))}`, about: `The ${noun} with this ${human(by.name)}.`, group: "crud", rank: column2 === void 0 ? 1 : 3, mode: "read", query };
23001
+ }
23002
+ case "create": {
23003
+ const { row, optional: optional3, defaults } = this.#insertRow(t);
23004
+ const query = { kind: "insert", into: table, rows: [row], returning: this.#returning(t, table) };
23005
+ return { ...base, name: "create", about: `Add a ${noun}; leave out what has a default or may be empty.`, group: "crud", rank: 2, mode: "write", query, optional: optional3, defaults };
23006
+ }
23007
+ case "update":
23008
+ case "updateWhere": {
23009
+ if (op.kind === "update" && column2 !== void 0) {
23010
+ const rel = this.belongsTo(t).find((b) => b.column === column2.name);
23011
+ if (!rel) throw new TableFnError(`${table}.${column2.name} is not a foreign key.`);
23012
+ const k = requireKey(t);
23013
+ const query2 = { kind: "update", type: table, set: { [column2.name]: param3(column2.name) }, where: [eq2(ref3(table, k.name), param3(k.name))], returning: this.#returning(t, table) };
23014
+ return { ...base, name: `set${cap(rel.word)}`, about: `Give a ${noun} another ${human(rel.word)}.`, group: rel.word, rank: 6, mode: "write", query: query2 };
23015
+ }
23016
+ const settable = t.columns.filter((c) => !c.generated && !t.primaryKey.includes(c.name) && !this.#isForeign(t, c));
23017
+ const set = {};
23018
+ for (const c of settable) {
23019
+ const p = param3(`set${cap(camel(c.name))}`);
23020
+ set[c.name] = { kind: "case", branches: [{ when: { kind: "logical", op: "or", operands: [isNull2(p), eq2(ref3(table, c.name), p)] }, then: ref3(table, c.name) }], else: p };
23021
+ }
23022
+ const optional3 = settable.map((c) => `set${cap(camel(c.name))}`);
23023
+ if (op.kind === "update") {
23024
+ const k = requireKey(t);
23025
+ const query2 = { kind: "update", type: table, set, where: [eq2(ref3(table, k.name), param3(k.name))], returning: this.#returning(t, table) };
23026
+ return { ...base, name: "update", about: `Change a ${noun} by its ${human(k.name)}; only the set\u2026 args given change.`, group: "crud", rank: 3, mode: "write", query: query2, optional: optional3 };
23027
+ }
23028
+ const matches = this.#matchable(t);
23029
+ const query = { kind: "update", type: table, set, where: matches.map((c) => maybe(c.name, eq2(ref3(table, c.name), param3(c.name)))) };
23030
+ return { ...base, name: "updateWhere", about: `Change every ${noun} matching the given ${human(table)} values; only the set\u2026 args given change.`, group: "crud", rank: 8, mode: "write", query, optional: [...optional3, ...matches.map((c) => c.name)] };
23031
+ }
23032
+ case "remove": {
23033
+ const k = requireKey(t);
23034
+ const query = { kind: "delete", from: table, where: [eq2(ref3(table, k.name), param3(k.name))], returning: this.#returning(t, table) };
23035
+ return { ...base, name: "remove", about: `Delete a ${noun} by its ${human(k.name)}.`, group: "crud", rank: 4, mode: "delete", query };
23036
+ }
23037
+ case "removeWhere": {
23038
+ const matches = this.#matchable(t);
23039
+ const query = { kind: "delete", from: table, where: matches.map((c) => maybe(c.name, eq2(ref3(table, c.name), param3(c.name)))) };
23040
+ return { ...base, name: "removeWhere", about: `Delete every ${noun} matching the given values.`, group: "crud", rank: 9, mode: "delete", query, optional: matches.map((c) => c.name) };
23041
+ }
23042
+ case "exists": {
23043
+ const c = requireColumn(column2, op);
23044
+ const query = { kind: "select", fields: [{ expr: cmp(">=", agg2("count"), lit3(1)), as: "exists" }], from: { kind: "type", type: table }, where: [eq2(ref3(table, c.name), param3(c.name))] };
23045
+ return { ...base, name: `existsBy${cap(camel(c.name))}`, about: `Whether a ${noun} with this ${human(c.name)} exists.`, group: "columns", rank: 13, mode: "read", query };
23046
+ }
23047
+ case "findOrCreate": {
23048
+ const c = requireColumn(column2, op);
23049
+ const { row, optional: optional3, defaults } = this.#insertRow(t);
23050
+ const query = { kind: "insert", into: table, rows: [row], onConflict: { fields: [c.name], update: { [c.name]: { kind: "excluded", field: c.name } } }, returning: this.#returning(t, table) };
23051
+ return { ...base, name: `findOrCreateBy${cap(camel(c.name))}`, about: `The ${noun} with this ${human(c.name)}, added first when there is none.`, group: "columns", rank: 14, mode: "write", query, optional: optional3, defaults };
23052
+ }
23053
+ case "countBy": {
23054
+ const c = requireColumn(column2, op);
23055
+ const value2 = this.#isForeign(t, c) ? ref3(this.#parentAlias(t, c.name), this.#parentKey(t, c.name)) : ref3(table, c.name);
23056
+ const query = {
23057
+ kind: "select",
23058
+ fields: [{ expr: value2, as: c.name }, { expr: agg2("count"), as: "count" }],
23059
+ from: { kind: "type", type: table },
23060
+ ...this.#isForeign(t, c) ? { joins: [{ on: { kind: "relation", source: table, field: c.name, as: this.#parentAlias(t, c.name) }, joinType: "left" }] } : {},
23061
+ groupBy: [{ kind: "output", name: c.name }],
23062
+ order: [{ expr: { kind: "output", name: "count" }, dir: "desc" }]
23063
+ };
23064
+ return { ...base, name: `countBy${cap(camel(c.name))}`, about: `How many ${human(table)} there are per ${human(c.name)}.`, group: "columns", rank: 10, mode: "read", query, list: true, sorters: [c.name, "count"] };
23065
+ }
23066
+ case "stats": {
23067
+ const c = requireColumn(column2, op);
23068
+ const v = ref3(table, c.name);
23069
+ const query = {
23070
+ kind: "select",
23071
+ fields: [{ expr: agg2("count", v), as: "count" }, { expr: agg2("sum", v), as: "total" }, { expr: agg2("avg", v), as: "avg" }, { expr: agg2("min", v), as: "min" }, { expr: agg2("max", v), as: "max" }],
23072
+ from: { kind: "type", type: table }
23073
+ };
23074
+ return { ...base, name: `${camel(c.name)}Stats`, about: `The count, total, average, lowest and highest ${human(c.name)} of all ${human(table)}.`, group: "columns", rank: 11, mode: "read", query };
23075
+ }
23076
+ case "buckets": {
23077
+ const c = requireColumn(column2, op);
23078
+ const bucket = op.bucket ?? "month";
23079
+ const query = {
23080
+ kind: "select",
23081
+ fields: [{ expr: { kind: "function-call", function: "dateTrunc", args: { field: lit3(bucket), d: ref3(table, c.name) } }, as: bucket }, { expr: agg2("count"), as: "count" }],
23082
+ from: { kind: "type", type: table },
23083
+ where: [{ kind: "is-null", value: ref3(table, c.name), not: true }],
23084
+ groupBy: [{ kind: "output", name: bucket }],
23085
+ order: [{ expr: { kind: "output", name: bucket }, dir: "asc" }]
23086
+ };
23087
+ return { ...base, name: `${camel(c.name)}Per${cap(bucket)}`, about: `How many ${human(table)} there are per ${bucket} of ${human(c.name)}.`, group: "columns", rank: 12, mode: "read", query, list: true, sorters: [bucket, "count"] };
23088
+ }
23089
+ case "childrenOf":
23090
+ case "countPerParent": {
23091
+ const rel = this.hasMany(t).find((r) => r.child.name === op.child && r.column === op.column);
23092
+ if (!rel) throw new TableFnError(`${op.child ?? "?"}.${op.column ?? "?"} is not a foreign key onto ${table}.`);
23093
+ const k = requireKey(t);
23094
+ if (op.kind === "childrenOf") {
23095
+ const inner = this.#outer(rel.child, [], rel.child.columns.map((c) => c.name), [eq2(ref3("t", rel.column), param3(rel.column))]);
23096
+ return { ...base, name: `${camel(rel.child.name)}Of${cap(relWord(rel.column))}`, about: `The ${human(rel.child.name)} of one ${noun}, by its ${human(k.name)}.`, group: rel.word, rank: 5, mode: "read", query: inner, list: true, sorters: rel.child.columns.map((c) => c.name) };
23097
+ }
23098
+ const countName = `${rel.word}Count`;
23099
+ const query = {
23100
+ kind: "select",
23101
+ fields: [...t.columns.filter((c) => !this.#isForeign(t, c)).map((c) => ({ expr: ref3(table, c.name), as: c.name })), { expr: this.#countOf(t, rel, k.name), as: countName }],
23102
+ from: { kind: "type", type: table },
23103
+ order: [{ expr: { kind: "output", name: countName }, dir: "desc" }]
23104
+ };
23105
+ return { ...base, name: `${countName}Per${cap(camel(singular(table)))}`, about: `Every ${noun} with how many ${human(rel.child.name)} it has, the most first.`, group: rel.word, rank: 15, mode: "read", query, list: true, sorters: [countName, ...t.columns.map((c) => c.name)] };
23106
+ }
23107
+ case "derived": {
23108
+ const name = op.derived?.[0];
23109
+ if (name === void 0) throw new TableFnError("A derived fn names its derived field.");
23110
+ const d = this.#derivation(t, name);
23111
+ const k = requireKey(t);
23112
+ const label = t.columns.find((c) => c.type.kind === "text" && !t.primaryKey.includes(c.name) && !this.#isForeign(t, c));
23113
+ const columns = [k.name, ...label === void 0 ? [] : [label.name], d.field.name];
23114
+ const query = this.#outer(t, [d], columns, [maybe(k.name, eq2(ref3("t", k.name), param3(k.name)))]);
23115
+ return { ...base, name: d.field.name, about: `${d.field.about} Per ${noun}; give ${human(k.name)} for one.`, group: d.group, rank: d.rank, mode: "read", query, list: true, sorters: columns, optional: [k.name], derived: d.field };
23116
+ }
23117
+ }
23118
+ }
23119
+ /**
23120
+ * The row an insert writes: a param per column the database does not fill. A constant default becomes the arg's
23121
+ * default; a `now` default is `CASE WHEN :p IS NULL OR :p = now() THEN now() ELSE :p END` (the comparison types
23122
+ * the param); a column with an SQL default the database computes is required unless it may be empty.
23123
+ */
23124
+ #insertRow(t) {
23125
+ const row = {};
23126
+ const optional3 = [];
23127
+ const defaults = {};
23128
+ for (const c of t.columns) {
23129
+ if (c.generated) continue;
23130
+ const p = param3(c.name);
23131
+ if (c.default?.kind === "now") {
23132
+ const now = { kind: "function-call", function: "now", args: {} };
23133
+ row[c.name] = { kind: "case", branches: [{ when: { kind: "logical", op: "or", operands: [isNull2(p), eq2(p, now)] }, then: now }], else: p };
23134
+ optional3.push(c.name);
23135
+ continue;
23136
+ }
23137
+ row[c.name] = p;
23138
+ if (c.default?.kind === "value" && c.default.value !== null) defaults[c.name] = c.default.value;
23139
+ else if (c.nullable) optional3.push(c.name);
23140
+ }
23141
+ return { row, optional: optional3, defaults };
23142
+ }
23143
+ #derivation(t, name) {
23144
+ const d = this.derivations(t).find((x) => x.field.name === name);
23145
+ if (!d) throw new TableFnError(`${t.name} has no derived field ${name}.`);
23146
+ return d;
23147
+ }
23148
+ #isForeign(t, c) {
23149
+ return this.belongsTo(t).some((b) => b.column === c.name);
23150
+ }
23151
+ #parentAlias(t, column2) {
23152
+ return `${relWord(column2)}Of${cap(camel(t.name))}`;
23153
+ }
23154
+ #parentKey(t, column2) {
23155
+ const rel = this.belongsTo(t).find((b) => b.column === column2);
23156
+ if (!rel) throw new TableFnError(`${t.name}.${column2} is not a foreign key.`);
23157
+ return rel.key;
23158
+ }
23159
+ /** Columns `updateWhere` / `removeWhere` match on: every plain scalar (no json, no key columns of composite keys). */
23160
+ #matchable(t) {
23161
+ return t.columns.filter((c) => c.type.kind !== "json" && c.type.kind !== "bytes" && !this.#isForeign(t, c));
23162
+ }
23163
+ /** `RETURNING` every column, foreign keys as their stored value. */
23164
+ #returning(t, alias) {
23165
+ return t.columns.filter((c) => !this.#isForeign(t, c)).map((c) => ({ expr: ref3(alias, c.name), as: c.name }));
23166
+ }
23167
+ /** How many children a row of `t` (bound under its own name) has. */
23168
+ #countOf(t, rel, key) {
23169
+ const count3 = this.#hasManyFields(t, key, rel)[0];
23170
+ if (!count3) throw new TableFnError(`No count for ${rel.child.name}.`);
23171
+ return count3.build(new JoinSet(), t.name);
23172
+ }
23173
+ /**
23174
+ * A select over every row of the table with its derived fields computed (an
23175
+ * inner select, so windows see the whole table), then filtered from outside
23176
+ * under the alias `t`. Foreign keys are read through their join, so they come
23177
+ * out as plain key values.
23178
+ */
23179
+ #outer(t, derived, columns, where) {
23180
+ const joins = new JoinSet();
23181
+ const fields = t.columns.map((c) => {
23182
+ const rel = this.belongsTo(t).find((b) => b.column === c.name);
23183
+ return { expr: rel === void 0 ? ref3(t.name, c.name) : ref3(joins.parent(t.name, c.name), rel.key), as: c.name };
23184
+ });
23185
+ for (const d of derived) fields.push({ expr: d.build(joins, t.name), as: d.field.name });
23186
+ const inner = { kind: "select", fields, from: { kind: "type", type: t.name }, ...joins.joins.length > 0 ? { joins: joins.joins } : {} };
23187
+ const key = keyOf(t);
23188
+ return {
23189
+ kind: "select",
23190
+ fields: columns.map((name) => ({ expr: ref3("t", name), as: name })),
23191
+ from: { kind: "subquery", query: inner, as: "t" },
23192
+ ...where.length > 0 ? { where } : {},
23193
+ ...key !== void 0 && columns.includes(key) ? { order: [{ expr: ref3("t", key), dir: "asc" }] } : {}
23194
+ };
23195
+ }
23196
+ };
23197
+ function lower2(text) {
23198
+ return text.length === 0 ? text : `${text[0].toLowerCase()}${text.slice(1)}`;
23199
+ }
23200
+ function columnOf(t, name) {
23201
+ const c = t.columns.find((x) => x.name === name);
23202
+ if (!c) throw new TableFnError(`${t.name} has no column ${name}.`);
23203
+ return c;
23204
+ }
23205
+ function requireColumn(c, op) {
23206
+ if (!c) throw new TableFnError(`A ${op.kind} fn on ${op.table} names its column.`);
23207
+ return c;
23208
+ }
23209
+ function requireKey(t) {
23210
+ const key = keyOf(t);
23211
+ if (key === void 0) throw new TableFnError(`${t.name} has no single-column key.`);
23212
+ return columnOf(t, key);
23213
+ }
23214
+ function derivedFieldType(field, tables) {
23215
+ if (field.measure === "value" && field.column !== null) {
23216
+ const c = tables.find((t) => t.name === field.table)?.columns.find((x) => x.name === field.column);
23217
+ if (c) return scalarFieldType(c.type);
23218
+ }
23219
+ if (field.measure === "count" || field.measure === "rank") return { kind: "number", whole: true };
23220
+ return { kind: "number" };
23221
+ }
23222
+
21260
23223
  // src/util/infer-type.ts
21261
23224
  var ISO_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
21262
23225
  var ISO_TIMESTAMP2 = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
@@ -21609,9 +23572,9 @@ function unaggregateDef(def, engine) {
21609
23572
  };
21610
23573
  switch (def.kind) {
21611
23574
  case "aggregate": {
21612
- const agg2 = engine.registry.parseExpr(def);
21613
- if (!(agg2 instanceof AggregateExpr)) return def;
21614
- const un = agg2.unaggregate(engine);
23575
+ const agg3 = engine.registry.parseExpr(def);
23576
+ if (!(agg3 instanceof AggregateExpr)) return def;
23577
+ const un = agg3.unaggregate(engine);
21615
23578
  return un ? un.toJSON() : null;
21616
23579
  }
21617
23580
  case "window":
@@ -21938,7 +23901,7 @@ function drillDownInto(select, groupRow, engine) {
21938
23901
  }
21939
23902
 
21940
23903
  // src/llm/schemas.ts
21941
- import { z as z41 } from "zod";
23904
+ import { z as z43 } from "zod";
21942
23905
  var DEFAULT_MAX_QUERY_SCHEMA_TYPES = 5;
21943
23906
  function toRegistry(engineOrRegistry) {
21944
23907
  return "registry" in engineOrRegistry ? engineOrRegistry.registry : engineOrRegistry;
@@ -22016,8 +23979,8 @@ function relationOnSchema(types, depth, cache) {
22016
23979
  fieldMode: "one",
22017
23980
  eligible: relationFieldsOf,
22018
23981
  extras: {
22019
- kind: z41.literal("relation"),
22020
- as: z41.string().describe("Required alias the joined target binds under.")
23982
+ kind: z43.literal("relation"),
23983
+ as: z43.string().describe("Required alias the joined target binds under.")
22021
23984
  },
22022
23985
  aid: "JoinOn",
22023
23986
  describe: "Cross a relation field of a bound source (key synthesized from the relation)."
@@ -22047,37 +24010,37 @@ function buildSchemas(engineOrRegistry, options = {}) {
22047
24010
  functions: selected,
22048
24011
  includeDocs: options.includeDocs,
22049
24012
  cache,
22050
- Expr: z41.never(),
22051
- Query: z41.never()
24013
+ Expr: z43.never(),
24014
+ Query: z43.never()
22052
24015
  };
22053
- inner.Expr = z41.lazy(() => buildExprUnion(registry, inner, types, selected));
22054
- const typeRef = depth.typeNames === "enum" ? withAid(enumOf2(typeNames), "TypeName").describe("A registered Type name.") : z41.string().describe("A Type name.");
24016
+ inner.Expr = z43.lazy(() => buildExprUnion(registry, inner, types, selected));
24017
+ const typeRef = depth.typeNames === "enum" ? withAid(enumOf2(typeNames), "TypeName").describe("A registered Type name.") : z43.string().describe("A Type name.");
22055
24018
  const Expr9 = inner.Expr;
22056
- const Query2 = z41.lazy(() => QueryUnion);
24019
+ const Query2 = z43.lazy(() => QueryUnion);
22057
24020
  inner.Query = Query2;
22058
24021
  const sourceBranches = [
22059
- z41.object({ kind: z41.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
22060
- z41.object({
22061
- kind: z41.literal("aliased"),
24022
+ z43.object({ kind: z43.literal("type"), type: typeRef }).describe("A type source, bound under (and referenced by) its type name."),
24023
+ z43.object({
24024
+ kind: z43.literal("aliased"),
22062
24025
  type: typeRef,
22063
- as: z41.string().describe("Custom source name (self-join / collision break).")
24026
+ as: z43.string().describe("Custom source name (self-join / collision break).")
22064
24027
  }).describe("An explicitly-aliased type source (the discouraged escape hatch)."),
22065
- z41.object({
22066
- kind: z41.literal("subquery"),
24028
+ z43.object({
24029
+ kind: z43.literal("subquery"),
22067
24030
  query: Query2,
22068
- as: z41.string().describe("Required alias for the derived source.")
24031
+ as: z43.string().describe("Required alias for the derived source.")
22069
24032
  }).describe("A derived (subquery) source.")
22070
24033
  ];
22071
24034
  if (selected.tabular.length > 0) {
22072
- const fnName = depth.functions === "open" ? z41.string().describe("A registered tabular function name.") : withAid(enumOf2(selected.tabular.map((f) => f.name)), "FunctionName").describe(
24035
+ const fnName = depth.functions === "open" ? z43.string().describe("A registered tabular function name.") : withAid(enumOf2(selected.tabular.map((f) => f.name)), "FunctionName").describe(
22073
24036
  "A registered tabular function name."
22074
24037
  );
22075
24038
  sourceBranches.push(
22076
- z41.object({
22077
- kind: z41.literal("function"),
24039
+ z43.object({
24040
+ kind: z43.literal("function"),
22078
24041
  function: fnName,
22079
- args: z41.record(z41.string(), Expr9).describe("Arguments keyed by declared parameter name."),
22080
- as: z41.string().describe("Required alias the produced rows bind under.")
24042
+ args: z43.record(z43.string(), Expr9).describe("Arguments keyed by declared parameter name."),
24043
+ as: z43.string().describe("Required alias the produced rows bind under.")
22081
24044
  }).describe("A table-valued function source: FROM fn(args) AS alias.")
22082
24045
  );
22083
24046
  }
@@ -22095,22 +24058,22 @@ function buildSchemas(engineOrRegistry, options = {}) {
22095
24058
  { kinds: ["relation", ...sourceKinds] }
22096
24059
  ).describe("A join target: a relation crossing or a manually-joined source.");
22097
24060
  const Join = withAid(
22098
- z41.object({
24061
+ z43.object({
22099
24062
  on: JoinOn,
22100
24063
  and: Expr9.optional(),
22101
24064
  joinType: withAid(enumOf2(["inner", "left", "right", "full"]), "JoinType").optional()
22102
24065
  }),
22103
24066
  "Join"
22104
24067
  ).describe("A JOIN: a relation crossing (key synthesized) or a manual source-def join with `and` as its ON.");
22105
- const joinsField = hasRelations ? z41.array(Join).optional() : z41.array(z41.never()).optional();
22106
- const Order = z41.object({
24068
+ const joinsField = hasRelations ? z43.array(Join).optional() : z43.array(z43.never()).optional();
24069
+ const Order = z43.object({
22107
24070
  expr: Expr9,
22108
24071
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
22109
24072
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
22110
24073
  }).describe("An ORDER BY entry.");
22111
- const OutputRef = z41.object({ kind: z41.literal("output"), name: z41.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name).");
24074
+ const OutputRef = z43.object({ kind: z43.literal("output"), name: z43.string() }).describe("A reference to a SELECT output field by name (its `as`, or the natural derived name).");
22112
24075
  const GroupExpr = Expr9.or(OutputRef);
22113
- const SelectOrder = z41.object({
24076
+ const SelectOrder = z43.object({
22114
24077
  expr: GroupExpr,
22115
24078
  dir: withAid(enumOf2(["asc", "desc"]), "OrderDir"),
22116
24079
  nulls: withAid(enumOf2(["first", "last"]), "OrderNulls").optional()
@@ -22119,19 +24082,19 @@ function buildSchemas(engineOrRegistry, options = {}) {
22119
24082
  const SelectOrderEntry = SelectOrder.or(Sorter).describe(
22120
24083
  "A SELECT ORDER BY entry: a term, or a dynamic-sort `sorter` catalog (selection supplied at run time)."
22121
24084
  );
22122
- const SelectField = z41.object({ expr: Expr9, as: z41.string().optional() }).describe("A selected output field.");
22123
- const limitOffset = withAid(z41.number().or(cache.param()), "Limit", { id: cache.defId("Limit") });
24085
+ const SelectField = z43.object({ expr: Expr9, as: z43.string().optional() }).describe("A selected output field.");
24086
+ const limitOffset = withAid(z43.number().or(cache.param()), "Limit", { id: cache.defId("Limit") });
22124
24087
  const Select = withAid(
22125
- z41.object({
22126
- kind: z41.literal("select"),
22127
- distinct: z41.boolean().optional(),
22128
- fields: z41.array(SelectField),
24088
+ z43.object({
24089
+ kind: z43.literal("select"),
24090
+ distinct: z43.boolean().optional(),
24091
+ fields: z43.array(SelectField),
22129
24092
  from: Source,
22130
24093
  joins: joinsField,
22131
- where: z41.array(Expr9).optional(),
22132
- groupBy: z41.array(GroupExpr).optional(),
22133
- having: z41.array(GroupExpr).optional(),
22134
- order: z41.array(SelectOrderEntry).optional(),
24094
+ where: z43.array(Expr9).optional(),
24095
+ groupBy: z43.array(GroupExpr).optional(),
24096
+ having: z43.array(GroupExpr).optional(),
24097
+ order: z43.array(SelectOrderEntry).optional(),
22135
24098
  limit: limitOffset.optional(),
22136
24099
  offset: limitOffset.optional()
22137
24100
  // `includeTotal` is an EXECUTION-time option (engine.run / engine.toSQL),
@@ -22143,103 +24106,103 @@ function buildSchemas(engineOrRegistry, options = {}) {
22143
24106
  const updatableTypes = types.filter((t) => t.updatable);
22144
24107
  const deletableTypes = types.filter((t) => t.deletable);
22145
24108
  const fbOf = (typeName, field) => registry.backing(typeName)?.fields?.[field];
22146
- const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z41.string().describe("A Type name.");
22147
- const ExcludedExprSchema = z41.object({ kind: z41.literal("excluded"), field: z41.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
24109
+ const dmlTypeRef = (subset) => depth.typeNames === "enum" ? enumOf2(subset.map((t) => t.name)).describe("A permitted target Type name.") : z43.string().describe("A Type name.");
24110
+ const ExcludedExprSchema = z43.object({ kind: z43.literal("excluded"), field: z43.string() }).describe("The proposed row inside ON CONFLICT DO UPDATE (EXCLUDED.<field>).");
22148
24111
  const ConflictExpr = Expr9.or(ExcludedExprSchema);
22149
24112
  const onConflictSchema = (t) => {
22150
- const update = depth.writes !== "open" && t ? updateSetSchema(t, fbOf, depth.writes, ConflictExpr) : z41.record(z41.string(), ConflictExpr).describe("DO UPDATE SET assignments (field \u2192 value).");
22151
- return z41.object({
22152
- fields: z41.array(z41.string()),
22153
- doNothing: z41.boolean().optional(),
24113
+ const update = depth.writes !== "open" && t ? updateSetSchema(t, fbOf, depth.writes, ConflictExpr) : z43.record(z43.string(), ConflictExpr).describe("DO UPDATE SET assignments (field \u2192 value).");
24114
+ return z43.object({
24115
+ fields: z43.array(z43.string()),
24116
+ doNothing: z43.boolean().optional(),
22154
24117
  update: update.optional()
22155
24118
  });
22156
24119
  };
22157
24120
  const openInsert = () => withAid(
22158
- z41.object({
22159
- kind: z41.literal("insert"),
24121
+ z43.object({
24122
+ kind: z43.literal("insert"),
22160
24123
  into: dmlTypeRef(insertableTypes),
22161
- rows: z41.array(z41.record(z41.string(), Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
24124
+ rows: z43.array(z43.record(z43.string(), Expr9)).optional().describe("Rows to insert (each a field \u2192 value map)."),
22162
24125
  select: Query2.optional(),
22163
- returning: z41.array(SelectField).optional(),
24126
+ returning: z43.array(SelectField).optional(),
22164
24127
  onConflict: onConflictSchema().optional()
22165
24128
  }),
22166
24129
  "Query_insert"
22167
24130
  ).describe("An INSERT statement.");
22168
24131
  const namedInsert = (writes) => orFold(
22169
24132
  insertableTypes.map(
22170
- (t) => z41.object({
22171
- kind: z41.literal("insert"),
22172
- into: z41.literal(t.name),
22173
- rows: z41.array(insertRowSchema(t, fbOf, writes, Expr9)).optional(),
24133
+ (t) => z43.object({
24134
+ kind: z43.literal("insert"),
24135
+ into: z43.literal(t.name),
24136
+ rows: z43.array(insertRowSchema(t, fbOf, writes, Expr9)).optional(),
22174
24137
  select: Query2.optional(),
22175
- returning: z41.array(SelectField).optional(),
24138
+ returning: z43.array(SelectField).optional(),
22176
24139
  onConflict: onConflictSchema(t).optional()
22177
24140
  }).describe(`An INSERT into ${t.name}.`)
22178
24141
  )
22179
24142
  ).describe("An INSERT statement.");
22180
24143
  const Insert = depth.writes === "open" ? openInsert() : namedInsert(depth.writes);
22181
24144
  const openUpdate = () => withAid(
22182
- z41.object({
22183
- kind: z41.literal("update"),
24145
+ z43.object({
24146
+ kind: z43.literal("update"),
22184
24147
  type: dmlTypeRef(updatableTypes),
22185
- set: z41.record(z41.string(), Expr9).describe("Fields to set (field \u2192 value)."),
24148
+ set: z43.record(z43.string(), Expr9).describe("Fields to set (field \u2192 value)."),
22186
24149
  joins: joinsField,
22187
- where: z41.array(Expr9).optional(),
22188
- returning: z41.array(SelectField).optional()
24150
+ where: z43.array(Expr9).optional(),
24151
+ returning: z43.array(SelectField).optional()
22189
24152
  }),
22190
24153
  "Query_update"
22191
24154
  ).describe("An UPDATE statement.");
22192
24155
  const namedUpdate = (writes) => orFold(
22193
24156
  updatableTypes.map(
22194
- (t) => z41.object({
22195
- kind: z41.literal("update"),
22196
- type: z41.literal(t.name),
24157
+ (t) => z43.object({
24158
+ kind: z43.literal("update"),
24159
+ type: z43.literal(t.name),
22197
24160
  set: updateSetSchema(t, fbOf, writes, Expr9),
22198
24161
  joins: joinsField,
22199
- where: z41.array(Expr9).optional(),
22200
- returning: z41.array(SelectField).optional()
24162
+ where: z43.array(Expr9).optional(),
24163
+ returning: z43.array(SelectField).optional()
22201
24164
  }).describe(`An UPDATE of ${t.name}.`)
22202
24165
  )
22203
24166
  ).describe("An UPDATE statement.");
22204
24167
  const Update = depth.writes === "open" ? openUpdate() : namedUpdate(depth.writes);
22205
24168
  const Delete = withAid(
22206
- z41.object({
22207
- kind: z41.literal("delete"),
24169
+ z43.object({
24170
+ kind: z43.literal("delete"),
22208
24171
  from: dmlTypeRef(deletableTypes),
22209
24172
  joins: joinsField,
22210
- where: z41.array(Expr9).optional(),
22211
- returning: z41.array(SelectField).optional()
24173
+ where: z43.array(Expr9).optional(),
24174
+ returning: z43.array(SelectField).optional()
22212
24175
  }),
22213
24176
  "Query_delete"
22214
24177
  ).describe("A DELETE statement.");
22215
24178
  const SetOperation = withAid(
22216
- z41.object({
24179
+ z43.object({
22217
24180
  kind: withAid(enumOf2(["union", "intersect", "except"]), "SetOpKind"),
22218
24181
  left: Query2,
22219
24182
  right: Query2,
22220
- all: z41.boolean().optional(),
24183
+ all: z43.boolean().optional(),
22221
24184
  // SET-LEVEL ordering / pagination applied AFTER the set op; ORDER BY terms
22222
24185
  // reference OUTPUT COLUMN names (a set op has no table to qualify).
22223
- order: z41.array(Order).optional(),
24186
+ order: z43.array(Order).optional(),
22224
24187
  limit: limitOffset.optional(),
22225
24188
  offset: limitOffset.optional()
22226
24189
  }),
22227
24190
  "Query_set-operation"
22228
24191
  ).describe("A UNION / INTERSECT / EXCEPT set operation.");
22229
24192
  const CteEntry = orFold([
22230
- z41.object({ name: z41.string(), query: Query2 }).describe("A non-recursive CTE."),
22231
- z41.object({ name: z41.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
24193
+ z43.object({ name: z43.string(), query: Query2 }).describe("A non-recursive CTE."),
24194
+ z43.object({ name: z43.string(), base: Query2, recursive: Query2 }).describe("A recursive CTE: a base seed UNION-ed with a recursive arm.")
22232
24195
  ]);
22233
24196
  const CTE = withAid(
22234
- z41.object({
22235
- kind: z41.literal("cte"),
22236
- ctes: z41.array(CteEntry),
24197
+ z43.object({
24198
+ kind: z43.literal("cte"),
24199
+ ctes: z43.array(CteEntry),
22237
24200
  final: Query2
22238
24201
  }),
22239
24202
  "Query_cte"
22240
24203
  ).describe("A WITH (CTE) statement.");
22241
24204
  const ExprQuery2 = withAid(
22242
- z41.object({ kind: z41.literal("expr"), expr: Expr9 }),
24205
+ z43.object({ kind: z43.literal("expr"), expr: Expr9 }),
22243
24206
  "Query_expr"
22244
24207
  ).describe("A single-expression query.");
22245
24208
  const queryBranches = [Select];
@@ -22286,14 +24249,14 @@ function querySchema(engine, options = {}) {
22286
24249
  const types = options.types ?? registry.typeList();
22287
24250
  const max2 = options.max ?? DEFAULT_MAX_QUERY_SCHEMA_TYPES;
22288
24251
  if (shouldUseStringSchema(types, max2)) {
22289
- return z41.object({
22290
- query: z41.string().describe(
24252
+ return z43.object({
24253
+ query: z43.string().describe(
22291
24254
  "A detailed natural-language description of the query: which Types are involved, filter conditions, known record IDs, and the precise outcome desired. Do not emit a structured query \u2014 there are too many Types to enumerate."
22292
24255
  )
22293
24256
  });
22294
24257
  }
22295
24258
  const schemas = buildSchemas(registry, options);
22296
- return z41.object({
24259
+ return z43.object({
22297
24260
  query: schemas.Query.describe("The query to execute as a structured Query object.")
22298
24261
  });
22299
24262
  }
@@ -22365,9 +24328,9 @@ function depthInstructions(engine, options = {}) {
22365
24328
 
22366
24329
  // src/llm/describe-generate.ts
22367
24330
  function humanize(name) {
22368
- const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().split(/\s+/).filter((w) => w.length > 0).map((w) => w.charAt(0).toUpperCase() + w.slice(1));
22369
- if (words.length > 1 && words[words.length - 1] === "Id") words.pop();
22370
- return words.join(" ") || name;
24331
+ const words2 = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().split(/\s+/).filter((w) => w.length > 0).map((w) => w.charAt(0).toUpperCase() + w.slice(1));
24332
+ if (words2.length > 1 && words2[words2.length - 1] === "Id") words2.pop();
24333
+ return words2.join(" ") || name;
22371
24334
  }
22372
24335
  function boundSuffix(lo, hi, unit) {
22373
24336
  if (lo !== void 0 && hi !== void 0) return ` (${lo}\u2013${hi}${unit})`;
@@ -22816,6 +24779,7 @@ ${gatingNote}` : "",
22816
24779
  export {
22817
24780
  AID_REGISTRY,
22818
24781
  AggregateExpr,
24782
+ AnsiDdl,
22819
24783
  ArrayFieldType,
22820
24784
  ArrayOpExpr,
22821
24785
  BUILTIN_EXPRS,
@@ -22832,6 +24796,9 @@ export {
22832
24796
  CTEStatementQuery,
22833
24797
  CaseExpr,
22834
24798
  Code,
24799
+ ColumnDefault,
24800
+ ColumnSpec,
24801
+ ColumnType,
22835
24802
  ComparisonExpr,
22836
24803
  DEFAULT_MAX_CTE_ITERATIONS,
22837
24804
  DEFAULT_MAX_EXAMPLES,
@@ -22839,6 +24806,9 @@ export {
22839
24806
  DEFAULT_SAMPLES,
22840
24807
  DEFAULT_TEXT_CASING,
22841
24808
  DateFieldType,
24809
+ DdlAction,
24810
+ DdlError,
24811
+ DdlStep,
22842
24812
  DeleteQuery,
22843
24813
  Dialect,
22844
24814
  EQ_SELECTIVITY,
@@ -22851,6 +24821,7 @@ export {
22851
24821
  FieldType,
22852
24822
  FieldTypeRefinement,
22853
24823
  FiltersExpr,
24824
+ ForeignKeySpec,
22854
24825
  FunctionCallExpr,
22855
24826
  IN_SELECTIVITY,
22856
24827
  InExpr,
@@ -22869,6 +24840,7 @@ export {
22869
24840
  OutputRefExpr,
22870
24841
  ParamExpr,
22871
24842
  ParamSet,
24843
+ PostgresDdl,
22872
24844
  PostgresDialect,
22873
24845
  Problems,
22874
24846
  Query,
@@ -22896,17 +24868,27 @@ export {
22896
24868
  SetOperationQuery,
22897
24869
  SorterExpr,
22898
24870
  SqlContext,
24871
+ SqlDdl,
24872
+ SqlServerDdl,
24873
+ SqlServerDialect,
22899
24874
  SqlText,
24875
+ SqliteDdl,
24876
+ SqliteDialect,
22900
24877
  SubqueryExpr,
22901
24878
  TEXT_CASINGS,
22902
24879
  TEXT_SEARCH_ROW_PENALTY,
24880
+ TableFnError,
24881
+ TableFnSchema,
24882
+ TableSpec,
22903
24883
  TabularFunctionCallExpr,
22904
24884
  TextFieldType,
22905
24885
  TextScoreExpr,
22906
24886
  TextSearchExpr,
22907
24887
  TimestampFieldType,
22908
24888
  Type,
24889
+ UUID_PATTERN,
22909
24890
  UnaryExpr,
24891
+ UniqueSpec,
22910
24892
  UpdateQuery,
22911
24893
  Value,
22912
24894
  WINDOW_ORDER_ARG,
@@ -22942,14 +24924,17 @@ export {
22942
24924
  builtinDialects,
22943
24925
  bytesOfResolved,
22944
24926
  canAutoPaginate,
24927
+ canCompare,
22945
24928
  canonicalize,
22946
24929
  caseExpr,
22947
24930
  casingRank,
22948
24931
  checkFieldType,
22949
24932
  checkLatticeLaws,
22950
24933
  checkOperator,
24934
+ ckName,
22951
24935
  cloneRecord,
22952
24936
  code,
24937
+ columnTypeWidens,
22953
24938
  concat,
22954
24939
  contains,
22955
24940
  containsAll,
@@ -22964,13 +24949,14 @@ export {
22964
24949
  dateDiff,
22965
24950
  dateFormat,
22966
24951
  datePart,
22967
- dateTrunc,
24952
+ dateTrunc2 as dateTrunc,
22968
24953
  day,
22969
24954
  dayOfWeek,
22970
24955
  dayOfYear,
22971
24956
  defaultConditionOps,
22972
24957
  defaultConditionWithout,
22973
24958
  depthInstructions,
24959
+ derivedFieldType,
22974
24960
  describeDialects,
22975
24961
  describeEngine,
22976
24962
  describeExprs,
@@ -22999,8 +24985,10 @@ export {
22999
24985
  fieldMeta,
23000
24986
  fieldNameOf,
23001
24987
  fieldTypeDefSchema,
24988
+ fieldTypeToGin,
23002
24989
  filters,
23003
24990
  firstField,
24991
+ fkName,
23004
24992
  fn,
23005
24993
  foldsAtRuntime,
23006
24994
  foldsInSql,
@@ -23009,6 +24997,8 @@ export {
23009
24997
  generatedFieldLabel,
23010
24998
  generatedTypeDescription,
23011
24999
  generatedTypeLabel,
25000
+ ginToColumnType,
25001
+ ginTypeToTable,
23012
25002
  gt,
23013
25003
  gte,
23014
25004
  hour,
@@ -23063,10 +25053,15 @@ export {
23063
25053
  parseQueryRequest,
23064
25054
  parseQueryTool,
23065
25055
  parseVectorText,
25056
+ pkName,
23066
25057
  plain,
23067
25058
  pos,
25059
+ queryArgProblems,
25060
+ queryArgsType,
23068
25061
  querySchema,
25062
+ ratio,
23069
25063
  raw,
25064
+ readCommonType,
23070
25065
  recordKey,
23071
25066
  recordSignature,
23072
25067
  ref2 as ref,
@@ -23094,6 +25089,9 @@ export {
23094
25089
  runScalarFunction,
23095
25090
  runTabularFunction,
23096
25091
  runWindowFunction,
25092
+ sameColumnType,
25093
+ scalarFieldType,
25094
+ scalarType,
23097
25095
  scaleRows,
23098
25096
  scanTemplate,
23099
25097
  second,
@@ -23102,10 +25100,12 @@ export {
23102
25100
  semantic,
23103
25101
  shape_exports as shape,
23104
25102
  shouldUseStringSchema,
25103
+ signatureText,
23105
25104
  singleRow,
23106
25105
  sortEntries,
23107
25106
  sourcesOf,
23108
25107
  span,
25108
+ splitNative,
23109
25109
  stddev,
23110
25110
  strictestCasing,
23111
25111
  stringAgg,
@@ -23116,6 +25116,11 @@ export {
23116
25116
  sum,
23117
25117
  syntheticType,
23118
25118
  tableFn,
25119
+ tableFnQuery,
25120
+ tableFns,
25121
+ tableSchemaHash,
25122
+ tableToGinType,
25123
+ tableToQueryType,
23119
25124
  templateSlotNames,
23120
25125
  textScore,
23121
25126
  textSearch,
@@ -23126,6 +25131,7 @@ export {
23126
25131
  typeFromFields,
23127
25132
  typeMeta,
23128
25133
  typedValueSql,
25134
+ uqName,
23129
25135
  validateNamedCall,
23130
25136
  value,
23131
25137
  valueFieldType,
@@ -23135,5 +25141,6 @@ export {
23135
25141
  widenNullable,
23136
25142
  window2 as window,
23137
25143
  withAid,
25144
+ withArgDefaults,
23138
25145
  year
23139
25146
  };