symmetria 1.0.0 → 1.0.1

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/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # Symmetria
2
2
 
3
- A type-safe, SQL-first PostgreSQL query builder for Node.js and Bun. Declare
4
- schemas in TypeScript, compose immutable queries and infer the exact result
5
- shape, including relationships and nullable joins.
3
+ A type-safe, SQL-first PostgreSQL query builder for Node.js and Bun. The result
4
+ you describe in TypeScript becomes exactly one SQL statement, however deep the
5
+ nesting, typed to the field and as fast as hand-written SQL. Declare the schema
6
+ once; it drives queries, migrations, drift detection and `pull` for existing
7
+ databases.
6
8
 
7
9
  **Node.js 24.11+ or Bun 1.4.4+ · ESM · MIT**
8
10
 
@@ -386,6 +386,15 @@ markBuilder(jsonb, "jsonb<Value>() or jsonb(standardSchema)");
386
386
  markBuilder(oneOf, "oneOf(\"draft\", \"published\")");
387
387
  markBuilder(customType, "customType<Value>(\"sql_type\", { encode, decode })");
388
388
  //#endregion
389
+ //#region src/query/plan/freeze.ts
390
+ /**
391
+ * Plan records are built immutably by construction (spreads, never assignment).
392
+ * A real `Object.freeze` on every record costs about a third of query building,
393
+ * so it is applied only when SYMMETRIA_FREEZE=1 (the test suite runs with it)
394
+ * and is the identity otherwise.
395
+ */
396
+ const freeze = process.env.SYMMETRIA_FREEZE === "1" ? (value) => Object.freeze(value) : (value) => value;
397
+ //#endregion
389
398
  //#region src/query/plan/metadata.ts
390
399
  const expressionSqlType = (expression) => {
391
400
  const node = expression.node;
@@ -454,14 +463,16 @@ const encodeJsonField = (value, codec) => {
454
463
  /** Composite parameters use the same encoded field values as SQL JSON projections. */
455
464
  const jsonRowCodec = (selection, many = false) => {
456
465
  let rowDecoder;
457
- const decodeRow = (row) => (rowDecoder ??= createRowDecoder(selection))(row);
458
- return Object.freeze({
466
+ return freeze({
459
467
  parameterCast: "jsonb",
460
468
  encode: (value) => {
461
469
  const encodeRow = (row) => Object.fromEntries(selection.map((expression) => [expression.outputName, encodeJsonField(row[expression.outputName], expression.codec)]));
462
470
  return JSON.stringify(many ? value.map(encodeRow) : encodeRow(value));
463
471
  },
464
- decode: (value) => many ? value.map(decodeRow) : decodeRow(value)
472
+ decode: (value) => {
473
+ const decode = rowDecoder ??= createRowDecoder(selection);
474
+ return many ? value.map(decode) : decode(value);
475
+ }
465
476
  });
466
477
  };
467
478
  //#endregion
@@ -519,10 +530,10 @@ const jsonPathDescription = (description, path) => {
519
530
  const codec = scalarType ? target?.codec : jsonValueCodec(target);
520
531
  current = {
521
532
  outputName: description.outputName,
522
- node: Object.freeze({
533
+ node: freeze({
523
534
  kind: "jsonPath",
524
535
  value: current.node,
525
- path: Object.freeze([key]),
536
+ path: freeze([key]),
526
537
  ...target ? { target } : {},
527
538
  ...scalarType ? { scalarType } : {}
528
539
  }),
@@ -555,26 +566,26 @@ const over = (expression, options = {}) => {
555
566
  const names = Object.keys(value);
556
567
  const offset = "preceding" in value ? value.preceding : value.following;
557
568
  if (names.length !== 1 || !["preceding", "following"].includes(names[0]) || !Number.isSafeInteger(offset) || offset < 0) throw new Error("symmetria: window frame offsets must be nonnegative safe integers");
558
- return Object.freeze({ ...value });
569
+ return freeze({ ...value });
559
570
  };
560
571
  const rows = options.rows?.map(boundary);
561
572
  if (rows && (rows.length !== 2 || rows[0] === "unbounded following" || rows[1] === "unbounded preceding")) throw new Error("symmetria: invalid window frame bounds");
562
573
  return createExpression({
563
574
  ...description,
564
575
  outputName: expression[COLUMN_EXPRESSION].outputName,
565
- node: Object.freeze({
576
+ node: freeze({
566
577
  kind: "window",
567
578
  expression: description.node,
568
- partitionBy: Object.freeze((options.partitionBy ?? []).map((column) => readColumn(column).node)),
569
- orderBy: Object.freeze(ordering.map((entry) => {
579
+ partitionBy: freeze((options.partitionBy ?? []).map((column) => readColumn(column).node)),
580
+ orderBy: freeze(ordering.map((entry) => {
570
581
  if (!entry || !(ORDERING_EXPRESSION in entry)) throw new Error("symmetria: window orderBy requires ordering expressions");
571
582
  return entry[ORDERING_EXPRESSION];
572
583
  })),
573
- ...rows ? { rows: Object.freeze(rows) } : {}
584
+ ...rows ? { rows: freeze(rows) } : {}
574
585
  })
575
586
  });
576
587
  };
577
- const windowFunction = (expression) => Object.freeze(Object.assign(Object.create(expression), { over: (options) => over(expression, options) }));
588
+ const windowFunction = (expression) => freeze(Object.assign(Object.create(expression), { over: (options) => over(expression, options) }));
578
589
  const rowNumber = () => windowFunction(createExpression({
579
590
  node: {
580
591
  kind: "raw",
@@ -616,7 +627,8 @@ const relativeWindow = (name, expression, offset, fallback) => {
616
627
  };
617
628
  const lag = (expression, offset = 1, fallback) => relativeWindow("lag", expression, offset, fallback);
618
629
  const lead = (expression, offset = 1, fallback) => relativeWindow("lead", expression, offset, fallback);
619
- const predicate = (description) => Object.freeze({ [PREDICATE_EXPRESSION]: Object.freeze(description) });
630
+ const predicate = (description) => freeze({ [PREDICATE_EXPRESSION]: freeze(description) });
631
+ const isPredicate = (value) => typeof value === "object" && value !== null && PREDICATE_EXPRESSION in value;
620
632
  const readPredicate = (value) => {
621
633
  if (!value || typeof value !== "object" || !(PREDICATE_EXPRESSION in value)) throw new Error("symmetria: expected a SQL predicate, such as column.is(value)");
622
634
  return value[PREDICATE_EXPRESSION];
@@ -628,13 +640,13 @@ const readColumn = (value) => {
628
640
  const valueNode = (value, codec) => {
629
641
  if (value && typeof value === "object" && COLUMN_EXPRESSION in value) {
630
642
  const node = value[COLUMN_EXPRESSION].node;
631
- return node.kind === "placeholder" && codec ? Object.freeze({
643
+ return node.kind === "placeholder" && codec ? freeze({
632
644
  ...node,
633
645
  codec
634
646
  }) : node;
635
647
  }
636
648
  if (value === void 0) throw new Error("symmetria: undefined is not a SQL value");
637
- return Object.freeze({
649
+ return freeze({
638
650
  kind: "parameter",
639
651
  value: cloneParameter(encodeValue(value, codec)),
640
652
  ...codec?.parameterCast ? { cast: codec.parameterCast } : {},
@@ -648,7 +660,7 @@ const readQuery = (query) => {
648
660
  var OrderingHandle = class {
649
661
  [ORDERING_EXPRESSION];
650
662
  constructor(description) {
651
- this[ORDERING_EXPRESSION] = Object.freeze(description);
663
+ this[ORDERING_EXPRESSION] = freeze(description);
652
664
  }
653
665
  get nullsFirst() {
654
666
  return ordering({
@@ -663,7 +675,7 @@ var OrderingHandle = class {
663
675
  });
664
676
  }
665
677
  };
666
- const ordering = (description) => Object.freeze(new OrderingHandle(description));
678
+ const ordering = (description) => freeze(new OrderingHandle(description));
667
679
  const searchLanguage = (language = "simple") => {
668
680
  if (!/^[a-z][a-z0-9_]*$/.test(language)) throw new Error("symmetria: search language must be a PostgreSQL text search configuration name");
669
681
  return language;
@@ -683,7 +695,7 @@ const rankOptions = (options) => {
683
695
  if (weights !== void 0 && (!Array.isArray(weights) || weights.length !== 4 || weights.some((weight) => typeof weight !== "number" || !Number.isFinite(weight) || weight < 0))) throw new Error("symmetria: search weights must be four non-negative numbers in PostgreSQL's order (D, C, B, A)");
684
696
  if (normalization !== void 0 && (!Number.isSafeInteger(normalization) || normalization < 0 || normalization > 63)) throw new Error("symmetria: search normalization must be an integer between 0 and 63");
685
697
  return {
686
- ...weights ? { weights: Object.freeze([...weights]) } : {},
698
+ ...weights ? { weights: freeze([...weights]) } : {},
687
699
  ...normalization === void 0 ? {} : { normalization },
688
700
  ...coverDensity ? { coverDensity: true } : {}
689
701
  };
@@ -707,7 +719,7 @@ const headlineOptions = (options) => {
707
719
  if (!(expected === "string" ? typeof value === "string" && !value.includes("\0") : expected === "integer" ? Number.isSafeInteger(value) && value >= 0 : typeof value === "boolean")) throw new Error(`symmetria: headline option "${key}" must be a ${expected === "integer" ? "non-negative integer" : expected}`);
708
720
  result[key] = value;
709
721
  }
710
- return Object.freeze(result);
722
+ return freeze(result);
711
723
  };
712
724
  const matchExpression = (description, branches) => {
713
725
  const source = expressionSource(description).node;
@@ -734,9 +746,9 @@ const matchExpression = (description, branches) => {
734
746
  if (expression && expressionSqlType(expression) !== "derived" && expressionSqlType(expression) !== sqlType) throw new Error("symmetria: match() branches require the same SQL type");
735
747
  if (!expression && result !== null && (!selectedDescription && typeof result !== typeof literal || result === void 0)) throw new Error("symmetria: match() branches require compatible scalar values");
736
748
  const node = valueNode(result, parameterCodec);
737
- return Object.freeze({
749
+ return freeze({
738
750
  when: valueNode(name, description.codec),
739
- then: node.kind === "parameter" && sqlType !== "derived" && sqlType !== "enum" ? Object.freeze({
751
+ then: node.kind === "parameter" && sqlType !== "derived" && sqlType !== "enum" ? freeze({
740
752
  ...node,
741
753
  cast: sqlType
742
754
  }) : node
@@ -745,10 +757,10 @@ const matchExpression = (description, branches) => {
745
757
  return createExpression({
746
758
  outputName: description.outputName,
747
759
  ...codec ? { codec } : {},
748
- node: Object.freeze({
760
+ node: freeze({
749
761
  kind: "case",
750
762
  value: description.node,
751
- branches: Object.freeze(values),
763
+ branches: freeze(values),
752
764
  sqlType
753
765
  })
754
766
  });
@@ -778,13 +790,13 @@ const membership = (description, values, negated) => {
778
790
  return predicate({
779
791
  kind: "membership",
780
792
  value: description.node,
781
- values: Object.freeze(values.map((value) => valueNode(value, description.codec))),
793
+ values: freeze(values.map((value) => valueNode(value, description.codec))),
782
794
  negated
783
795
  });
784
796
  };
785
797
  const arithmetic = (description, operator, value) => createExpression({
786
798
  ...description,
787
- node: Object.freeze({
799
+ node: freeze({
788
800
  kind: "binary",
789
801
  left: description.node,
790
802
  operator,
@@ -806,7 +818,7 @@ var ColumnHandle = class {
806
818
  [COLUMN_EXPRESSION];
807
819
  [HANDLE_MEMO];
808
820
  constructor(description) {
809
- this[COLUMN_EXPRESSION] = Object.freeze(description);
821
+ this[COLUMN_EXPRESSION] = freeze(description);
810
822
  this[HANDLE_MEMO] = {};
811
823
  }
812
824
  get is() {
@@ -867,7 +879,7 @@ var ColumnHandle = class {
867
879
  const description = this[COLUMN_EXPRESSION];
868
880
  return createExpression({
869
881
  outputName: description.outputName,
870
- node: Object.freeze({
882
+ node: freeze({
871
883
  kind: "arrayLength",
872
884
  value: description.node,
873
885
  ...!expressionSqlType(description).endsWith("[]") ? { json: true } : {}
@@ -891,7 +903,7 @@ var ColumnHandle = class {
891
903
  searchRank(query, options = {}) {
892
904
  return createExpression({
893
905
  outputName: "searchRank",
894
- node: Object.freeze({
906
+ node: freeze({
895
907
  kind: "searchRank",
896
908
  value: this[COLUMN_EXPRESSION].node,
897
909
  query: valueNode(query),
@@ -906,7 +918,7 @@ var ColumnHandle = class {
906
918
  if (expressionSqlType(description) === "tsvector") throw new Error("symmetria: searchHeadline() highlights text; call it on the text column, not on a tsvector");
907
919
  return createExpression({
908
920
  outputName: "searchHeadline",
909
- node: Object.freeze({
921
+ node: freeze({
910
922
  kind: "searchHeadline",
911
923
  value: description.node,
912
924
  query: valueNode(query),
@@ -921,7 +933,7 @@ var ColumnHandle = class {
921
933
  if (!/^vector(\(|$)/.test(expressionSqlType(description))) throw new Error("symmetria: distance operators require a vector column or expression");
922
934
  return createExpression({
923
935
  outputName: name,
924
- node: Object.freeze({
936
+ node: freeze({
925
937
  kind: "binary",
926
938
  left: description.node,
927
939
  operator,
@@ -995,8 +1007,8 @@ var ColumnHandle = class {
995
1007
  return arithmetic(this[COLUMN_EXPRESSION], "*", value);
996
1008
  }
997
1009
  };
998
- const createExpression = (description) => Object.freeze(new ColumnHandle(description));
999
- const presentPredicates = (conditions) => Object.freeze(conditions.filter((condition) => condition !== void 0 && condition !== null && condition !== false).map(readPredicate));
1010
+ const createExpression = (description) => freeze(new ColumnHandle(description));
1011
+ const presentPredicates = (conditions) => freeze(conditions.filter((condition) => condition !== void 0 && condition !== null && condition !== false).map(readPredicate));
1000
1012
  /** AND of the given predicates; `undefined`, `null` and `false` are skipped. Empty is TRUE. */
1001
1013
  const and = (...conditions) => predicate({
1002
1014
  kind: "group",
@@ -1025,7 +1037,7 @@ const notExists = (query) => predicate({
1025
1037
  negated: true
1026
1038
  });
1027
1039
  const count = (expression) => createExpression({
1028
- node: Object.freeze({
1040
+ node: freeze({
1029
1041
  kind: "aggregate",
1030
1042
  name: "COUNT",
1031
1043
  ...expression ? { value: readColumn(expression).node } : {}
@@ -1034,7 +1046,7 @@ const count = (expression) => createExpression({
1034
1046
  codec: countCodec
1035
1047
  });
1036
1048
  const sum = (expression) => createExpression({
1037
- node: Object.freeze({
1049
+ node: freeze({
1038
1050
  kind: "aggregate",
1039
1051
  name: "SUM",
1040
1052
  value: readColumn(expression).node,
@@ -1044,7 +1056,7 @@ const sum = (expression) => createExpression({
1044
1056
  codec: numericCodec
1045
1057
  });
1046
1058
  const average = (expression) => createExpression({
1047
- node: Object.freeze({
1059
+ node: freeze({
1048
1060
  kind: "aggregate",
1049
1061
  name: "AVG",
1050
1062
  value: readColumn(expression).node,
@@ -1057,7 +1069,7 @@ const minimum = (expression) => {
1057
1069
  const description = readColumn(expression);
1058
1070
  return createExpression({
1059
1071
  ...description,
1060
- node: Object.freeze({
1072
+ node: freeze({
1061
1073
  kind: "aggregate",
1062
1074
  name: "MIN",
1063
1075
  value: description.node
@@ -1069,7 +1081,7 @@ const maximum = (expression) => {
1069
1081
  const description = readColumn(expression);
1070
1082
  return createExpression({
1071
1083
  ...description,
1072
- node: Object.freeze({
1084
+ node: freeze({
1073
1085
  kind: "aggregate",
1074
1086
  name: "MAX",
1075
1087
  value: description.node
@@ -1081,9 +1093,9 @@ const coalesce = (expression, fallback) => {
1081
1093
  const description = readColumn(expression);
1082
1094
  return createExpression({
1083
1095
  ...description,
1084
- node: Object.freeze({
1096
+ node: freeze({
1085
1097
  kind: "coalesce",
1086
- values: Object.freeze([description.node, valueNode(fallback, description.codec)])
1098
+ values: freeze([description.node, valueNode(fallback, description.codec)])
1087
1099
  }),
1088
1100
  outputName: "coalesce"
1089
1101
  });
@@ -1103,7 +1115,7 @@ const SEARCH_WEIGHTS = /* @__PURE__ */ new Set([
1103
1115
  const searchDocument = (parts, options = {}) => {
1104
1116
  const collected = [];
1105
1117
  const add = (part, weight) => {
1106
- for (const entry of Array.isArray(part) ? part : [part]) collected.push(Object.freeze({
1118
+ for (const entry of Array.isArray(part) ? part : [part]) collected.push(freeze({
1107
1119
  value: readColumn(entry).node,
1108
1120
  ...weight ? { weight } : {}
1109
1121
  }));
@@ -1117,9 +1129,9 @@ const searchDocument = (parts, options = {}) => {
1117
1129
  if (!collected.length) throw new Error("symmetria: searchDocument() requires at least one text expression");
1118
1130
  return createExpression({
1119
1131
  outputName: "searchDocument",
1120
- node: Object.freeze({
1132
+ node: freeze({
1121
1133
  kind: "tsvector",
1122
- parts: Object.freeze(collected),
1134
+ parts: freeze(collected),
1123
1135
  language: searchLanguage(options.language)
1124
1136
  })
1125
1137
  });
@@ -1146,10 +1158,10 @@ const sqlTemplate = (strings, values, codec, sqlType) => {
1146
1158
  parts.push(text);
1147
1159
  if (index < values.length) parts.push(valueNode(values[index]));
1148
1160
  });
1149
- return Object.freeze(new SqlHandle({
1150
- node: Object.freeze({
1161
+ return freeze(new SqlHandle({
1162
+ node: freeze({
1151
1163
  kind: "raw",
1152
- parts: Object.freeze(parts),
1164
+ parts: freeze(parts),
1153
1165
  ...sqlType ? { sqlType } : {}
1154
1166
  }),
1155
1167
  outputName: "expression",
@@ -1228,8 +1240,15 @@ const createCompilation = (plan, renderer, placeholder, selectSql) => ({
1228
1240
  aggregateReferences: void 0,
1229
1241
  selectSql
1230
1242
  });
1243
+ const quotedIdentifiers = /* @__PURE__ */ new Map();
1231
1244
  const quoteIdentifier = (identifier) => {
1232
- if (identifier.length <= 63 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) return `"${identifier}"`;
1245
+ const cached = quotedIdentifiers.get(identifier);
1246
+ if (cached !== void 0) return cached;
1247
+ if (identifier.length <= 63 && /^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
1248
+ const quoted = `"${identifier}"`;
1249
+ if (quotedIdentifiers.size < 4096) quotedIdentifiers.set(identifier, quoted);
1250
+ return quoted;
1251
+ }
1233
1252
  if (!identifier.length || identifier.includes("\0")) throw new Error("symmetria: SQL identifiers must be nonempty and cannot contain null bytes");
1234
1253
  if (Buffer.byteLength(identifier) > 63) throw new Error(`symmetria: PostgreSQL identifiers cannot exceed 63 bytes: "${identifier}" has ${Buffer.byteLength(identifier)}; shorten the table, column or index name`);
1235
1254
  return `"${identifier.replaceAll("\"", "\"\"")}"`;
@@ -1264,7 +1283,7 @@ const limitedPlan = (state, limit) => {
1264
1283
  derived = [];
1265
1284
  limitedPlans.set(state, derived);
1266
1285
  }
1267
- return derived[limit] ??= Object.freeze({
1286
+ return derived[limit] ??= freeze({
1268
1287
  ...state,
1269
1288
  limit: typeof state.limit === "number" ? Math.min(state.limit, limit) : limit
1270
1289
  });
@@ -1283,34 +1302,34 @@ const bindingScope = (binding, bindings) => {
1283
1302
  let expression;
1284
1303
  return [column.name, {
1285
1304
  enumerable: true,
1286
- get: () => expression ??= createExpression({
1287
- node: Object.freeze({
1305
+ get: () => expression ??= Object.freeze(createExpression({
1306
+ node: freeze({
1288
1307
  kind: "column",
1289
- description: Object.freeze({
1308
+ description: freeze({
1290
1309
  binding,
1291
1310
  column
1292
1311
  })
1293
1312
  }),
1294
1313
  outputName: column.name,
1295
1314
  ...binding.codecs[column.name] ? { codec: binding.codecs[column.name] } : {}
1296
- })
1315
+ }))
1297
1316
  }];
1298
1317
  })));
1299
- for (const callback of computedFields.get(binding.table) ?? []) for (const [name, selected] of Object.entries(callback(Object.freeze({ ...columns })))) {
1318
+ for (const callback of computedFields.get(binding.table) ?? []) for (const [name, selected] of Object.entries(callback(freeze({ ...columns })))) {
1300
1319
  quoteIdentifier(name);
1301
1320
  if (Object.hasOwn(columns, name)) throw new Error(`symmetria: duplicate computed field "${name}"`);
1302
1321
  const description = readColumn(selected);
1303
1322
  validateNode(description.node, bindings);
1304
- columns[name] = createExpression({
1323
+ columns[name] = Object.freeze(createExpression({
1305
1324
  ...description,
1306
1325
  outputName: name
1307
- });
1326
+ }));
1308
1327
  }
1309
1328
  const result = Object.freeze(columns);
1310
1329
  bindingColumns.set(binding, result);
1311
1330
  return result;
1312
1331
  };
1313
- const createScope = (bindings) => Object.freeze(Object.fromEntries(Object.entries(bindings).map(([aliasName, binding]) => [aliasName, bindingScope(binding, bindings)])));
1332
+ const createScope = (bindings) => freeze(Object.fromEntries(Object.entries(bindings).map(([aliasName, binding]) => [aliasName, bindingScope(binding, bindings)])));
1314
1333
  /** Every column inside a predicate must belong to the given bindings (subqueries are checked when built). */
1315
1334
  const validatePredicate = (description, bindings) => {
1316
1335
  switch (description.kind) {
@@ -1379,16 +1398,17 @@ const readSelection = (expressions, bindings) => {
1379
1398
  if (expressions && typeof expressions === "object" && !Array.isArray(expressions)) {
1380
1399
  const entries = Object.entries(expressions);
1381
1400
  if (!entries.length) throw new Error("symmetria: a projection requires at least one field");
1382
- return Object.freeze(entries.map(([name, selected]) => {
1401
+ return freeze(entries.map(([name, selected]) => {
1383
1402
  quoteIdentifier(name);
1384
1403
  if (!selected || typeof selected !== "object" && typeof selected !== "function") throw new Error("symmetria: selected fields must be SQL expressions, objects or selected queries");
1404
+ if (isPredicate(selected)) throw new Error(`symmetria: "${name}" is a predicate, not a value; select a boolean with sql<boolean>\`…\` or use it in where`);
1385
1405
  if (QUERY_PLAN in selected) {
1386
1406
  const query = selected[QUERY_PLAN];
1387
1407
  if (!query.selection.length) throw new Error("symmetria: nested queries require selected fields");
1388
1408
  if (Object.values(query.bindings).some((binding) => containsBinding(bindings, binding))) throw new Error("symmetria: nested queries require a distinct source occurrence");
1389
- return Object.freeze({
1409
+ return freeze({
1390
1410
  outputName: name,
1391
- node: Object.freeze({
1411
+ node: freeze({
1392
1412
  kind: "jsonRows",
1393
1413
  query,
1394
1414
  many: true
@@ -1399,15 +1419,15 @@ const readSelection = (expressions, bindings) => {
1399
1419
  if (COLUMN_EXPRESSION in selected) {
1400
1420
  const description = readColumn(selected);
1401
1421
  validateNode(description.node, bindings);
1402
- return description.outputName === name && Object.isFrozen(description) ? description : Object.freeze({
1422
+ return description.outputName === name && Object.isFrozen(description) ? description : freeze({
1403
1423
  ...description,
1404
1424
  outputName: name
1405
1425
  });
1406
1426
  }
1407
1427
  const selection = readSelection(selected, bindings);
1408
- return Object.freeze({
1428
+ return freeze({
1409
1429
  outputName: name,
1410
- node: Object.freeze({
1430
+ node: freeze({
1411
1431
  kind: "jsonObject",
1412
1432
  selection
1413
1433
  }),
@@ -1417,7 +1437,7 @@ const readSelection = (expressions, bindings) => {
1417
1437
  }
1418
1438
  if (!Array.isArray(expressions) || !expressions.length) throw new Error("symmetria: a projection requires at least one field");
1419
1439
  const names = /* @__PURE__ */ new Set();
1420
- return Object.freeze(expressions.map((expression) => {
1440
+ return freeze(expressions.map((expression) => {
1421
1441
  const description = readColumn(expression);
1422
1442
  quoteIdentifier(description.outputName);
1423
1443
  validateNode(description.node, bindings);
@@ -1430,7 +1450,7 @@ const countValue = (name, count) => {
1430
1450
  if (typeof count !== "number") {
1431
1451
  const node = readColumn(count).node;
1432
1452
  if (node.kind !== "placeholder") throw new Error(`symmetria: ${name} requires a number or prepared parameter`);
1433
- return Object.freeze({
1453
+ return freeze({
1434
1454
  ...node,
1435
1455
  count: true
1436
1456
  });
@@ -1441,10 +1461,10 @@ const countValue = (name, count) => {
1441
1461
  const EMPTY = Object.freeze([]);
1442
1462
  const noBindings = Object.freeze({});
1443
1463
  const emptyBindings = () => noBindings;
1444
- const initialPlan = (root) => Object.freeze({
1464
+ const initialPlan = (root) => freeze({
1445
1465
  kind: "select",
1446
1466
  root,
1447
- bindings: Object.freeze({ [root.alias]: root }),
1467
+ bindings: freeze({ [root.alias]: root }),
1448
1468
  joins: EMPTY,
1449
1469
  selection: EMPTY,
1450
1470
  predicates: EMPTY,
@@ -1472,12 +1492,12 @@ const lockPlan = (state, mode, options = {}) => {
1472
1492
  ].includes(name)) || options.noWait !== void 0 && typeof options.noWait !== "boolean" || options.skipLocked !== void 0 && typeof options.skipLocked !== "boolean") throw new Error("symmetria: invalid row lock options");
1473
1493
  if (options.noWait && options.skipLocked) throw new Error("symmetria: choose either NOWAIT or SKIP LOCKED");
1474
1494
  if (options.of !== void 0 && (!Array.isArray(options.of) || !options.of.length || options.of.some((alias) => typeof alias !== "string" || !Object.hasOwn(state.bindings, alias)))) throw new Error("symmetria: row locks require existing query aliases");
1475
- return Object.freeze({
1495
+ return freeze({
1476
1496
  ...state,
1477
- locking: Object.freeze({
1497
+ locking: freeze({
1478
1498
  ...options,
1479
1499
  mode,
1480
- ...options.of ? { of: Object.freeze([...options.of]) } : {}
1500
+ ...options.of ? { of: freeze([...options.of]) } : {}
1481
1501
  })
1482
1502
  });
1483
1503
  };
@@ -2060,8 +2080,13 @@ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
2060
2080
  }
2061
2081
  const relations = new Map(analyzedTables.map((analyzedTable) => [analyzedTable.key, []]));
2062
2082
  const namedRelations = /* @__PURE__ */ new Set();
2083
+ const columnNames = new Map(analyzedTables.map((analyzedTable) => [analyzedTable.key, /* @__PURE__ */ new Set([...analyzedTable.scalars.map((column) => column.key), ...analyzedTable.references.map((reference) => `${reference.key}Id`)])]));
2063
2084
  const addRelation = (tableKey, relation) => {
2064
2085
  const list = relations.get(tableKey);
2086
+ if (columnNames.get(tableKey)?.has(relation.name)) {
2087
+ if (relation.origin.startsWith("reverse of ") || relation.origin.startsWith("M:N through ")) return;
2088
+ throw new Error(`symmetria: relation "${tableKey}.${relation.name}" (${relation.origin}) clashes with a column of the same name; rename the column or name the relation with .inverse()`);
2089
+ }
2065
2090
  const clash = list.find((existingRelation) => existingRelation.name === relation.name);
2066
2091
  if (clash) {
2067
2092
  const advice = clash.kind === "condition" || relation.kind === "condition" ? "Rename the condition relation in relations()." : `Name it explicitly in schema overrides: schema({...}, { ${tableKey}: { <name>: <table>.<foreignKeyColumn> } })`;
@@ -2213,11 +2238,17 @@ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
2213
2238
  };
2214
2239
  })].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0) };
2215
2240
  for (const analyzedTable of analyzedTables) {
2216
- const indexedColumns = [...analyzedTable.scalars.filter((column) => column.definition.index && !column.definition.unique && !(column.definition.primaryKey && analyzedTable.primaryKey)).map((column) => column.key), ...analyzedTable.references.filter((reference, position) => reference.flags.index && !reference.flags.unique && !(analyzedTable.state.primaryKey?.length === 1 && analyzedTable.state.primaryKey[0] === `${reference.key}Id`) && !(analyzedTable.isJunction && position === 0)).map((reference) => `${reference.key}Id`)];
2241
+ const indexedColumns = [...analyzedTable.scalars.filter((column) => column.definition.index && !column.definition.unique && !(column.definition.primaryKey && analyzedTable.primaryKey)).map((column) => ({
2242
+ column: column.key,
2243
+ key: column.key
2244
+ })), ...analyzedTable.references.filter((reference, position) => reference.flags.index && !reference.flags.unique && !(analyzedTable.state.primaryKey?.length === 1 && analyzedTable.state.primaryKey[0] === `${reference.key}Id`) && !(analyzedTable.isJunction && position === 0)).map((reference) => ({
2245
+ column: `${reference.key}Id`,
2246
+ key: reference.flags.column ?? `${reference.key}Id`
2247
+ }))];
2217
2248
  if (!analyzedTable.state.indexCallbacks.length && !analyzedTable.state.checkCallbacks.length && !indexedColumns.length) continue;
2218
2249
  const codecs = Object.fromEntries([...analyzedTable.scalars.map((column) => [column.key, analyzedTable.state.columns[column.key]]), ...analyzedTable.references.map((reference) => [`${reference.key}Id`, reference.target.state.columns[reference.targetColumn.key]])].flatMap(([name, column]) => isColumn(column) && column[COLUMN_CODEC] ? [[name, column[COLUMN_CODEC]]] : []));
2219
2250
  for (const callback of analyzedTable.state.indexCallbacks) applyIndexes(snapshot, { [analyzedTable.key]: codecs }, (scope) => callback(scope[analyzedTable.key]), analyzedTable.key);
2220
- if (indexedColumns.length) applyIndexes(snapshot, { [analyzedTable.key]: codecs }, (scope) => Object.fromEntries(indexedColumns.map((name) => [name, index(scope[analyzedTable.key][name])])), analyzedTable.key);
2251
+ if (indexedColumns.length) applyIndexes(snapshot, { [analyzedTable.key]: codecs }, (scope) => Object.fromEntries(indexedColumns.map(({ column, key }) => [key, index(scope[analyzedTable.key][column])])), analyzedTable.key);
2221
2252
  for (const callback of analyzedTable.state.checkCallbacks) applyChecks(snapshot, { [analyzedTable.key]: codecs }, analyzedTable.key, callback);
2222
2253
  }
2223
2254
  return snapshot;
@@ -2228,6 +2259,6 @@ const resolveTarget = (tablesByState, state, source) => {
2228
2259
  return found;
2229
2260
  };
2230
2261
  //#endregion
2231
- export { count as $, createRowDecoder as $t, readOrdering as A, date as At, renderContext as B, smallint as Bt, createScope as C, COLUMN_BUILDER as Ct, limitedPlan as D, builderExample as Dt, initialPlan as E, bool as Et, validatePredicate as F, isColumn as Ft, tsquerySql as G, typedColumn as Gt, searchRankSql as H, time as Ht, aliasSql as I, jsonb as It, COLUMN_EXPRESSION as J, bigintCodec as Jt, tsvectorSql as K, uuid as Kt, createCompilation as L, numeric as Lt, resultRows as M, inet as Mt, shapeFrame as N, int as Nt, lockPlan as O, bytea as Ot, validateNode as P, interval as Pt, coalesce as Q, codecMap as Qt, parameter as R, oneOf as Rt, countValue as S, expressionSqlType as St, evaluateContext as T, bigint as Tt, searchVectorSql as U, timestamptz as Ut, searchHeadlineSql as V, text as Vt, sqlString as W, tsvector as Wt, and as X, cloneParameter as Xt, NAMED_PARAMETER as Y, booleanCodec as Yt, average as Z, codecFor as Zt, table as _, sql as _t, applyIndexes as a, maximum as at, QUERY_STATE as b, when as bt, index as c, notExists as ct, TABLE as d, predicate as dt, encodeValue as en, createExpression as et, draftBinding as f, rank as ft, self as g, searchDocument as gt, junction as h, rowNumber as ht, INDEX_METHODS as i, lead as it, readSelection as j, doublePrecision as jt, presentSelection as k, customType as kt, indexClausesSQL as l, or as lt, isTable as m, readPredicate as mt, snakeCase as n, exists as nt, createIndexQuery as o, minimum as ot, isReferenceInput as p, readColumn as pt, computedFields as q, varchar as qt, applyChecks as r, lag as rt, createIndexesSQL as s, not as st, assembleSchema as t, numericCodec as tn, denseRank as tt, operatorClass as u, over as ut, tableState as v, sum as vt, emptyBindings as w, COLUMN_CODEC as wt, bindingScope as x, jsonRowCodec as xt, EMPTY as y, valueNode as yt, quoteIdentifier as z, real as zt };
2262
+ export { count as $, codecMap as $t, readOrdering as A, customType as At, renderContext as B, real as Bt, createScope as C, freeze as Ct, limitedPlan as D, bool as Dt, initialPlan as E, bigint as Et, validatePredicate as F, interval as Ft, tsquerySql as G, tsvector as Gt, searchRankSql as H, text as Ht, aliasSql as I, isColumn as It, COLUMN_EXPRESSION as J, varchar as Jt, tsvectorSql as K, typedColumn as Kt, createCompilation as L, jsonb as Lt, resultRows as M, doublePrecision as Mt, shapeFrame as N, inet as Nt, lockPlan as O, builderExample as Ot, validateNode as P, int as Pt, coalesce as Q, codecFor as Qt, parameter as R, numeric as Rt, countValue as S, expressionSqlType as St, evaluateContext as T, COLUMN_CODEC as Tt, searchVectorSql as U, time as Ut, searchHeadlineSql as V, smallint as Vt, sqlString as W, timestamptz as Wt, and as X, booleanCodec as Xt, NAMED_PARAMETER as Y, bigintCodec as Yt, average as Z, cloneParameter as Zt, table as _, sql as _t, applyIndexes as a, maximum as at, QUERY_STATE as b, when as bt, index as c, notExists as ct, TABLE as d, predicate as dt, createRowDecoder as en, createExpression as et, draftBinding as f, rank as ft, self as g, searchDocument as gt, junction as h, rowNumber as ht, INDEX_METHODS as i, lead as it, readSelection as j, date as jt, presentSelection as k, bytea as kt, indexClausesSQL as l, or as lt, isTable as m, readPredicate as mt, snakeCase as n, numericCodec as nn, exists as nt, createIndexQuery as o, minimum as ot, isReferenceInput as p, readColumn as pt, computedFields as q, uuid as qt, applyChecks as r, lag as rt, createIndexesSQL as s, not as st, assembleSchema as t, encodeValue as tn, denseRank as tt, operatorClass as u, over as ut, tableState as v, sum as vt, emptyBindings as w, COLUMN_BUILDER as wt, bindingScope as x, jsonRowCodec as xt, EMPTY as y, valueNode as yt, quoteIdentifier as z, oneOf as zt };
2232
2263
 
2233
- //# sourceMappingURL=assembly-B-tpaqlp.js.map
2264
+ //# sourceMappingURL=assembly-BN0T778g.js.map