symmetria 1.0.2 → 1.1.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/README.md +7 -0
- package/dist/{assembly-BN0T778g.js → assembly-C4GbrzmO.js} +240 -99
- package/dist/assembly-C4GbrzmO.js.map +1 -0
- package/dist/bun.d.ts +3 -3
- package/dist/{compile-a0a4N4Pm.js → compile-B3TD9LbS.js} +2 -2
- package/dist/{compile-a0a4N4Pm.js.map → compile-B3TD9LbS.js.map} +1 -1
- package/dist/driver.d.ts +3 -3
- package/dist/driver.js +1 -1
- package/dist/index-wLTEGtyg.d.ts +29 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +74 -10
- package/dist/index.js.map +1 -1
- package/dist/{inspection-DRyWuGMg.js → inspection-DZf70oHB.js} +3 -3
- package/dist/{inspection-DRyWuGMg.js.map → inspection-DZf70oHB.js.map} +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +1 -1
- package/dist/{pg-BzycsnK9.js → pg-D4y92gPt.js} +8 -1
- package/dist/pg-D4y92gPt.js.map +1 -0
- package/dist/{pg-B7PQlBHz.d.ts → pg-DS7w6m9g.d.ts} +3 -3
- package/dist/pg.d.ts +3 -3
- package/dist/pg.js +1 -1
- package/dist/{pool-UBdmZPmu.d.ts → pool-C9sl2iHw.d.ts} +2 -2
- package/dist/{profiling-CRd3epfk.d.ts → profiling-CrinWe63.d.ts} +2 -2
- package/dist/{types-BNSyrEFw.d.ts → types-BB8ndsIR.d.ts} +121 -29
- package/dist/vector.d.ts +1 -1
- package/dist/vector.js +1 -1
- package/package.json +1 -1
- package/dist/assembly-BN0T778g.js.map +0 -1
- package/dist/index-DNCu4XEk.d.ts +0 -10
- package/dist/pg-BzycsnK9.js.map +0 -1
package/README.md
CHANGED
|
@@ -288,6 +288,13 @@ UPDATE or DELETE without `where()` is refused unless `.all()` confirms it.
|
|
|
288
288
|
`smallint`, `real`, `doublePrecision`, `date`, `time`, `interval`, `bytea` and
|
|
289
289
|
`inet` as first-class builders.
|
|
290
290
|
- Conditional upserts: `doUpdate(values, { where: (current, incoming) => … })`.
|
|
291
|
+
- Any SQL names: `casing: "preserve"` for camelCase databases such as Prisma's,
|
|
292
|
+
`.named()` on tables and columns, `.onUpdate.cascade` foreign keys and
|
|
293
|
+
`timestamp(3)` columns read as UTC dates.
|
|
294
|
+
- Exact arithmetic: `plus`, `minus`, `multiply` and `divide` follow PostgreSQL's
|
|
295
|
+
promotion, so `quantity.multiply(price)` is a `Decimal`.
|
|
296
|
+
- `databaseError(error)` describes unique, foreign-key, not-null and check
|
|
297
|
+
violations the same way on both drivers; `one()` errors carry a code.
|
|
291
298
|
- Arrays, full-text search with stored `tsvector` columns, weighted documents,
|
|
292
299
|
ranking and headlines, pgvector embeddings with distance operators and HNSW
|
|
293
300
|
indexes (`symmetria/vector`), typed JSON paths and Standard Schema JSON
|
|
@@ -80,6 +80,8 @@ const arrayCodec = (elementType, element) => ({
|
|
|
80
80
|
parameterCast: `${elementType}[]`,
|
|
81
81
|
...element ? { element } : {}
|
|
82
82
|
});
|
|
83
|
+
/** A timestamp without zone as PostgreSQL prints it in text and JSON. */
|
|
84
|
+
const LOCAL_TIMESTAMP = /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d(:\d\d(\.\d+)?)?$/;
|
|
83
85
|
const codecFor = (sqlType) => {
|
|
84
86
|
if (sqlType.endsWith("[]")) {
|
|
85
87
|
const elementType = sqlType.slice(0, -2);
|
|
@@ -99,11 +101,13 @@ const codecFor = (sqlType) => {
|
|
|
99
101
|
decode: (value) => value,
|
|
100
102
|
parameterCast: sqlType
|
|
101
103
|
};
|
|
102
|
-
|
|
103
|
-
|
|
104
|
+
const zoned = /^timestamptz(\(\d\))?$/.test(sqlType);
|
|
105
|
+
if (zoned || /^timestamp(\(\d\))?$/.test(sqlType)) return {
|
|
106
|
+
encode: zoned ? (value) => value : (value) => value instanceof Date ? value.toISOString() : value,
|
|
104
107
|
decode: (value) => {
|
|
105
108
|
if (value instanceof Date) return value;
|
|
106
|
-
const
|
|
109
|
+
const text = String(value);
|
|
110
|
+
const date = new Date(!zoned && LOCAL_TIMESTAMP.test(text) ? `${text.replace(" ", "T")}Z` : text);
|
|
107
111
|
if (Number.isNaN(date.getTime())) throw new Error(`symmetria: cannot represent ${sqlType} value ${JSON.stringify(typeof value === "number" ? String(value) : value)} as a Date; read it with sql.of(text)\`…\` instead`);
|
|
108
112
|
return date;
|
|
109
113
|
}
|
|
@@ -200,10 +204,21 @@ const makeColumn = (definition, extras = {}, codec, call) => {
|
|
|
200
204
|
sqlType: `${definition.sqlType}[]`,
|
|
201
205
|
notNull: definition.notNull,
|
|
202
206
|
unique: false,
|
|
203
|
-
primaryKey: false
|
|
207
|
+
primaryKey: false,
|
|
208
|
+
...definition.sqlName !== void 0 ? { sqlName: definition.sqlName } : {}
|
|
204
209
|
}, {}, arrayCodec(definition.sqlType, codec ?? codecFor(definition.sqlType)));
|
|
205
210
|
});
|
|
206
211
|
for (const [name, transform] of Object.entries(extras)) defineGetter(column, name, () => chain(transform(definition)));
|
|
212
|
+
Object.defineProperty(column, "named", {
|
|
213
|
+
value: (sqlName) => {
|
|
214
|
+
if (typeof sqlName !== "string" || !sqlName) throw new Error("symmetria: named() expects the column's SQL name");
|
|
215
|
+
return chain({
|
|
216
|
+
...definition,
|
|
217
|
+
sqlName
|
|
218
|
+
});
|
|
219
|
+
},
|
|
220
|
+
enumerable: false
|
|
221
|
+
});
|
|
207
222
|
Object.defineProperty(column, "default", {
|
|
208
223
|
value: (value) => {
|
|
209
224
|
const isSql = typeof value === "object" && value !== null && value.kind === "sql";
|
|
@@ -284,13 +299,30 @@ const interval = base("interval");
|
|
|
284
299
|
const bytea = base("bytea");
|
|
285
300
|
/** IPv4 or IPv6 address as text, such as `10.0.0.1` or `::1/128`. */
|
|
286
301
|
const inet = base("inet");
|
|
287
|
-
const
|
|
302
|
+
const nowDefault = { now: (definition) => ({
|
|
288
303
|
...definition,
|
|
289
304
|
default: {
|
|
290
305
|
kind: "sql",
|
|
291
306
|
sql: "now()"
|
|
292
307
|
}
|
|
293
|
-
}) }
|
|
308
|
+
}) };
|
|
309
|
+
/** A timestamp builder usable bare (`timestamptz`) or with fractional-second precision (`timestamptz(3)`). */
|
|
310
|
+
const timestampBuilder = (sqlType) => makeColumn({
|
|
311
|
+
sqlType,
|
|
312
|
+
notNull: true,
|
|
313
|
+
unique: false,
|
|
314
|
+
primaryKey: false
|
|
315
|
+
}, nowDefault, void 0, (precision) => {
|
|
316
|
+
if (precision !== void 0 && (!Number.isInteger(precision) || precision < 0 || precision > 6)) throw new Error(`symmetria: ${sqlType} precision must be an integer between 0 and 6`);
|
|
317
|
+
return base(precision === void 0 ? sqlType : `${sqlType}(${precision})`, nowDefault);
|
|
318
|
+
});
|
|
319
|
+
const timestamptz = timestampBuilder("timestamptz");
|
|
320
|
+
/**
|
|
321
|
+
* `timestamp without time zone`, read and written as UTC `Date` values: the
|
|
322
|
+
* convention of Prisma, Drizzle and Rails, and what Bun.SQL already does.
|
|
323
|
+
* `timestamp(3)` sets millisecond precision, as Prisma declares it.
|
|
324
|
+
*/
|
|
325
|
+
const timestamp = timestampBuilder("timestamp");
|
|
294
326
|
const varchar = makeColumn({
|
|
295
327
|
sqlType: "varchar",
|
|
296
328
|
notNull: true,
|
|
@@ -794,15 +826,60 @@ const membership = (description, values, negated) => {
|
|
|
794
826
|
negated
|
|
795
827
|
});
|
|
796
828
|
};
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
829
|
+
/** How PostgreSQL types an arithmetic operand, from its SQL type or codec. */
|
|
830
|
+
const numericClass = (expression) => {
|
|
831
|
+
const sqlType = expressionSqlType(expression);
|
|
832
|
+
if (expression.codec === numericCodec || sqlType.startsWith("numeric")) return "decimal";
|
|
833
|
+
if (expression.codec === bigintCodec || sqlType === "bigint") return "bigint";
|
|
834
|
+
return /^(real|double precision)$/.test(sqlType) ? "float" : "integer";
|
|
835
|
+
};
|
|
836
|
+
const castNode = (node, sqlType) => freeze({
|
|
837
|
+
kind: "raw",
|
|
838
|
+
parts: freeze([
|
|
839
|
+
"(",
|
|
840
|
+
node,
|
|
841
|
+
`)::${sqlType}`
|
|
842
|
+
]),
|
|
843
|
+
sqlType
|
|
844
|
+
});
|
|
845
|
+
const decimalCodec = freeze({
|
|
846
|
+
...numericCodec,
|
|
847
|
+
sqlType: "numeric"
|
|
805
848
|
});
|
|
849
|
+
/**
|
|
850
|
+
* `left <operator> right` with PostgreSQL's numeric promotion made explicit: a
|
|
851
|
+
* decimal operand turns the other side into numeric, a bigint operand keeps
|
|
852
|
+
* bigint, and a fractional JavaScript number is sent as double precision, so
|
|
853
|
+
* `quantity.multiply("19.99")` and `quantity.multiply(1.5)` neither truncate
|
|
854
|
+
* nor fail to parse as integers.
|
|
855
|
+
*/
|
|
856
|
+
const arithmetic = (description, operator, value) => {
|
|
857
|
+
if (value === void 0 || value === null) throw new Error("symmetria: arithmetic needs a value; use coalesce() for NULL operands");
|
|
858
|
+
const left = numericClass(description);
|
|
859
|
+
const operand = typeof value === "object" && COLUMN_EXPRESSION in value ? readColumn(value) : void 0;
|
|
860
|
+
const right = operand ? numericClass(operand) : typeof value === "string" ? "decimal" : typeof value === "bigint" ? "bigint" : typeof value === "number" && !Number.isInteger(value) ? "float" : left === "bigint" || left === "decimal" ? left : "integer";
|
|
861
|
+
if (!operand && typeof value !== "number" && typeof value !== "bigint" && typeof value !== "string") throw new Error("symmetria: arithmetic operands are numbers, bigints, decimal strings or numeric columns");
|
|
862
|
+
const result = left === "decimal" || right === "decimal" ? "decimal" : left === "float" || right === "float" ? "float" : left === "bigint" || right === "bigint" ? "bigint" : "integer";
|
|
863
|
+
const leftNode = result === "decimal" && left !== "decimal" ? castNode(description.node, "numeric") : description.node;
|
|
864
|
+
const rightNode = operand ? result === "decimal" && right !== "decimal" ? castNode(operand.node, "numeric") : operand.node : freeze({
|
|
865
|
+
kind: "parameter",
|
|
866
|
+
value: cloneParameter(right === "bigint" ? bigintCodec.encode(value) : typeof value === "number" && result === "decimal" ? String(value) : value),
|
|
867
|
+
...right === "decimal" || result === "decimal" ? { cast: "numeric" } : right === "float" ? { cast: "double precision" } : right === "bigint" && left !== "bigint" ? { cast: "bigint" } : {}
|
|
868
|
+
});
|
|
869
|
+
const sqlType = result === "decimal" ? "numeric" : result === "float" ? "double precision" : result === "bigint" ? "bigint" : "integer";
|
|
870
|
+
const codec = result === "decimal" ? decimalCodec : result === "bigint" ? bigintCodec : result === "float" ? codecFor("double precision") : left === "integer" && right === "integer" ? description.codec : void 0;
|
|
871
|
+
return createExpression({
|
|
872
|
+
outputName: description.outputName,
|
|
873
|
+
node: freeze({
|
|
874
|
+
kind: "binary",
|
|
875
|
+
left: leftNode,
|
|
876
|
+
operator,
|
|
877
|
+
right: rightNode,
|
|
878
|
+
sqlType
|
|
879
|
+
}),
|
|
880
|
+
...codec ? { codec } : {}
|
|
881
|
+
});
|
|
882
|
+
};
|
|
806
883
|
/** Callable equality whose string properties are enum-member predicates. */
|
|
807
884
|
const equality = (description, negated) => new Proxy((value) => value === null ? predicate({
|
|
808
885
|
kind: "nullCheck",
|
|
@@ -1006,16 +1083,20 @@ var ColumnHandle = class {
|
|
|
1006
1083
|
multiply(value) {
|
|
1007
1084
|
return arithmetic(this[COLUMN_EXPRESSION], "*", value);
|
|
1008
1085
|
}
|
|
1086
|
+
divide(value) {
|
|
1087
|
+
return arithmetic(this[COLUMN_EXPRESSION], "/", value);
|
|
1088
|
+
}
|
|
1009
1089
|
};
|
|
1010
1090
|
const createExpression = (description) => freeze(new ColumnHandle(description));
|
|
1011
|
-
|
|
1012
|
-
|
|
1091
|
+
/** Falsy entries are skipped; anything else must be a predicate. */
|
|
1092
|
+
const presentPredicates = (conditions) => freeze(conditions.filter((condition) => !!condition).map((condition) => readPredicate(condition)));
|
|
1093
|
+
/** AND of the given predicates; falsy entries (`undefined`, `null`, `false`, `""`, `0`) are skipped. Empty is TRUE. */
|
|
1013
1094
|
const and = (...conditions) => predicate({
|
|
1014
1095
|
kind: "group",
|
|
1015
1096
|
operator: "AND",
|
|
1016
1097
|
predicates: presentPredicates(conditions)
|
|
1017
1098
|
});
|
|
1018
|
-
/** OR of the given predicates;
|
|
1099
|
+
/** OR of the given predicates; falsy entries are skipped like in and(). Empty is FALSE. */
|
|
1019
1100
|
const or = (...conditions) => predicate({
|
|
1020
1101
|
kind: "group",
|
|
1021
1102
|
operator: "OR",
|
|
@@ -1530,7 +1611,7 @@ const presentSelection = Object.freeze([{
|
|
|
1530
1611
|
* - a Column → scalar column
|
|
1531
1612
|
* - a keyed schema link → FK + relation, including cyclic references
|
|
1532
1613
|
* - another table → FK + relation (`author: users`)
|
|
1533
|
-
* - table.nullable
|
|
1614
|
+
* - table.nullable, .unique, .onDelete.<action>, .onUpdate.<action> → FK with flags
|
|
1534
1615
|
* - a thunk `() => users` → lazy FK (cross-file cycles)
|
|
1535
1616
|
* - `self` (with the same chain as tables, e.g. `self.nullable.inverse("children")`) → self-reference
|
|
1536
1617
|
*/
|
|
@@ -1555,6 +1636,10 @@ const referenceChain = (target, flags) => {
|
|
|
1555
1636
|
get: () => onDeleteChain(target, flags),
|
|
1556
1637
|
enumerable: false
|
|
1557
1638
|
});
|
|
1639
|
+
Object.defineProperty(reference, "onUpdate", {
|
|
1640
|
+
get: () => onUpdateChain(target, flags),
|
|
1641
|
+
enumerable: false
|
|
1642
|
+
});
|
|
1558
1643
|
Object.defineProperty(reference, "inverse", { value: (name) => referenceChain(target, {
|
|
1559
1644
|
...flags,
|
|
1560
1645
|
inverse: name
|
|
@@ -1588,6 +1673,18 @@ const onDeleteChain = (target, flags) => {
|
|
|
1588
1673
|
});
|
|
1589
1674
|
} });
|
|
1590
1675
|
};
|
|
1676
|
+
const ON_UPDATE_ACTIONS = /* @__PURE__ */ new Map([
|
|
1677
|
+
["cascade", "cascade"],
|
|
1678
|
+
["restrict", "restrict"],
|
|
1679
|
+
["noAction", "no action"]
|
|
1680
|
+
]);
|
|
1681
|
+
const onUpdateChain = (target, flags) => new Proxy({}, { get: (_target, key) => {
|
|
1682
|
+
const action = typeof key === "string" ? ON_UPDATE_ACTIONS.get(key) : void 0;
|
|
1683
|
+
return action ? referenceChain(target, {
|
|
1684
|
+
...flags,
|
|
1685
|
+
onUpdate: action
|
|
1686
|
+
}) : void 0;
|
|
1687
|
+
} });
|
|
1591
1688
|
/**
|
|
1592
1689
|
* A binding over a table that is not assembled yet: references appear as
|
|
1593
1690
|
* `${name}Id` columns. primaryKey() and relations() discovery run their
|
|
@@ -1616,39 +1713,42 @@ const REFERENCE_MODIFIERS = /* @__PURE__ */ new Set([
|
|
|
1616
1713
|
"unique",
|
|
1617
1714
|
"index",
|
|
1618
1715
|
"onDelete",
|
|
1716
|
+
"onUpdate",
|
|
1619
1717
|
"inverse",
|
|
1620
1718
|
"by",
|
|
1621
1719
|
"column"
|
|
1622
1720
|
]);
|
|
1623
|
-
const createTable = (
|
|
1721
|
+
const createTable = (init) => {
|
|
1624
1722
|
const state = {
|
|
1625
|
-
columns: Object.freeze({ ...columns }),
|
|
1626
|
-
indexCallbacks: Object.freeze([...indexCallbacks]),
|
|
1627
|
-
checkCallbacks: Object.freeze([...checkCallbacks]),
|
|
1628
|
-
computedCallbacks: Object.freeze([...computedCallbacks]),
|
|
1629
|
-
relationCallbacks: Object.freeze([...relationCallbacks]),
|
|
1630
|
-
junction,
|
|
1631
|
-
...primaryKey ? { primaryKey: Object.freeze([...primaryKey]) } : {}
|
|
1723
|
+
columns: Object.freeze({ ...init.columns }),
|
|
1724
|
+
indexCallbacks: Object.freeze([...init.indexCallbacks]),
|
|
1725
|
+
checkCallbacks: Object.freeze([...init.checkCallbacks]),
|
|
1726
|
+
computedCallbacks: Object.freeze([...init.computedCallbacks]),
|
|
1727
|
+
relationCallbacks: Object.freeze([...init.relationCallbacks]),
|
|
1728
|
+
junction: init.junction,
|
|
1729
|
+
...init.primaryKey ? { primaryKey: Object.freeze([...init.primaryKey]) } : {},
|
|
1730
|
+
...init.named !== void 0 ? { named: init.named } : {}
|
|
1632
1731
|
};
|
|
1633
|
-
|
|
1732
|
+
const target = { [TABLE]: state };
|
|
1733
|
+
const next = (changes) => createTable({
|
|
1734
|
+
...state,
|
|
1735
|
+
...changes
|
|
1736
|
+
});
|
|
1737
|
+
const callbackMethod = (name, add) => (callback) => {
|
|
1738
|
+
if (typeof callback !== "function") throw new Error(`symmetria: ${name}() expects a callback`);
|
|
1739
|
+
return next(add(callback));
|
|
1740
|
+
};
|
|
1741
|
+
return new Proxy(target, {
|
|
1634
1742
|
get: (proxyTarget, key) => {
|
|
1635
1743
|
if (key === TABLE) return state;
|
|
1636
1744
|
if (typeof key !== "string") return Reflect.get(proxyTarget, key);
|
|
1637
|
-
if (key === "indexes") return (callback) => {
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
};
|
|
1641
|
-
if (key === "
|
|
1642
|
-
if (typeof
|
|
1643
|
-
return
|
|
1644
|
-
};
|
|
1645
|
-
if (key === "computed") return (callback) => {
|
|
1646
|
-
if (typeof callback !== "function") throw new Error("symmetria: computed() expects a callback");
|
|
1647
|
-
return createTable(state.columns, state.indexCallbacks, state.checkCallbacks, state.primaryKey, [...state.computedCallbacks, callback], state.junction, state.relationCallbacks);
|
|
1648
|
-
};
|
|
1649
|
-
if (key === "relations") return (callback) => {
|
|
1650
|
-
if (typeof callback !== "function") throw new Error("symmetria: relations() expects a callback");
|
|
1651
|
-
return createTable(state.columns, state.indexCallbacks, state.checkCallbacks, state.primaryKey, state.computedCallbacks, state.junction, [...state.relationCallbacks, callback]);
|
|
1745
|
+
if (key === "indexes") return callbackMethod("indexes", (callback) => ({ indexCallbacks: [...state.indexCallbacks, callback] }));
|
|
1746
|
+
if (key === "checks") return callbackMethod("checks", (callback) => ({ checkCallbacks: [...state.checkCallbacks, callback] }));
|
|
1747
|
+
if (key === "computed") return callbackMethod("computed", (callback) => ({ computedCallbacks: [...state.computedCallbacks, callback] }));
|
|
1748
|
+
if (key === "relations") return callbackMethod("relations", (callback) => ({ relationCallbacks: [...state.relationCallbacks, callback] }));
|
|
1749
|
+
if (key === "named") return (sqlName) => {
|
|
1750
|
+
if (typeof sqlName !== "string" || !sqlName) throw new Error("symmetria: named() expects the table's SQL name");
|
|
1751
|
+
return next({ named: sqlName });
|
|
1652
1752
|
};
|
|
1653
1753
|
if (key === "primaryKey") return (callback) => {
|
|
1654
1754
|
if (state.junction) throw new Error("symmetria: junction tables use both foreign keys as the primary key");
|
|
@@ -1662,10 +1762,11 @@ const createTable = (columns, indexCallbacks, checkCallbacks = [], primaryKey, c
|
|
|
1662
1762
|
return expression.node.description.column.name;
|
|
1663
1763
|
});
|
|
1664
1764
|
if (new Set(names).size !== names.length) throw new Error("symmetria: duplicate primary-key column");
|
|
1665
|
-
return
|
|
1765
|
+
return next({ primaryKey: names });
|
|
1666
1766
|
};
|
|
1667
1767
|
if (REFERENCE_MODIFIERS.has(key)) {
|
|
1668
1768
|
if (key === "onDelete") return onDeleteChain(state, {});
|
|
1769
|
+
if (key === "onUpdate") return onUpdateChain(state, {});
|
|
1669
1770
|
if (key === "inverse") return (name) => referenceChain(state, { inverse: name });
|
|
1670
1771
|
if (key === "by") return (name) => referenceChain(state, { by: name });
|
|
1671
1772
|
if (key === "column") return (sqlName) => referenceChain(state, { column: sqlName });
|
|
@@ -1678,12 +1779,19 @@ const createTable = (columns, indexCallbacks, checkCallbacks = [], primaryKey, c
|
|
|
1678
1779
|
};
|
|
1679
1780
|
},
|
|
1680
1781
|
has: (proxyTarget, key) => {
|
|
1681
|
-
return key === TABLE || key === "indexes" || key === "checks" || key === "primaryKey" || key === "computed" || key === "relations" || typeof key === "string" && key in state.columns || Reflect.has(proxyTarget, key);
|
|
1782
|
+
return key === TABLE || key === "indexes" || key === "checks" || key === "primaryKey" || key === "computed" || key === "relations" || key === "named" || typeof key === "string" && key in state.columns || Reflect.has(proxyTarget, key);
|
|
1682
1783
|
}
|
|
1683
1784
|
});
|
|
1684
1785
|
};
|
|
1685
1786
|
/** Names come from schema keys; index callbacks run after all references are resolved. */
|
|
1686
|
-
const table = (columns) => createTable(
|
|
1787
|
+
const table = (columns) => createTable({
|
|
1788
|
+
columns,
|
|
1789
|
+
indexCallbacks: [],
|
|
1790
|
+
checkCallbacks: [],
|
|
1791
|
+
computedCallbacks: [],
|
|
1792
|
+
relationCallbacks: [],
|
|
1793
|
+
junction: false
|
|
1794
|
+
});
|
|
1687
1795
|
/**
|
|
1688
1796
|
* Explicit many-to-many link table: exactly two references form a composite primary
|
|
1689
1797
|
* key and both sides receive through relations. Extra data columns are allowed.
|
|
@@ -1692,7 +1800,14 @@ const junction = (columns) => {
|
|
|
1692
1800
|
const entries = Object.entries(columns);
|
|
1693
1801
|
if (entries.filter(([, value]) => !isColumn(value)).length !== 2) throw new Error("symmetria: junction() requires exactly two table references");
|
|
1694
1802
|
if (entries.some(([name, value]) => name === "id" || isColumn(value) && value.definition.primaryKey)) throw new Error("symmetria: junction tables use both foreign keys as the primary key; remove id and primaryKey columns");
|
|
1695
|
-
return createTable(
|
|
1803
|
+
return createTable({
|
|
1804
|
+
columns,
|
|
1805
|
+
indexCallbacks: [],
|
|
1806
|
+
checkCallbacks: [],
|
|
1807
|
+
computedCallbacks: [],
|
|
1808
|
+
relationCallbacks: [],
|
|
1809
|
+
junction: true
|
|
1810
|
+
});
|
|
1696
1811
|
};
|
|
1697
1812
|
/** Self-reference marker: `parent: self.nullable.onDelete.cascade.inverse("children")`. */
|
|
1698
1813
|
const self = referenceChain("self", {});
|
|
@@ -1855,7 +1970,7 @@ const applyIndexes = (snapshot, codecs, callback, tableName) => {
|
|
|
1855
1970
|
for (const [name, definition] of Object.entries(definitions)) {
|
|
1856
1971
|
if (!definition || !(INDEX_DEFINITION in definition)) throw new Error(`symmetria: "${name}" is not an index definition`);
|
|
1857
1972
|
quoteIdentifier(name);
|
|
1858
|
-
const sqlName = tableName === void 0 ?
|
|
1973
|
+
const sqlName = tableName === void 0 ? sqlKey(name, snapshot.casing) : `${bindings[tableName].table.sqlName}_${sqlKey(name, snapshot.casing)}_idx`;
|
|
1859
1974
|
quoteIdentifier(sqlName);
|
|
1860
1975
|
if (names.has(sqlName)) throw new Error(`symmetria: duplicate SQL index name "${sqlName}"`);
|
|
1861
1976
|
names.add(sqlName);
|
|
@@ -1954,7 +2069,7 @@ const applyChecks = (snapshot, codecs, tableName, callback) => {
|
|
|
1954
2069
|
const names = new Set((table.checks ?? []).map((check) => check.sqlName));
|
|
1955
2070
|
for (const [name, condition] of Object.entries(callback(createScope({ [tableName]: binding })[tableName]))) {
|
|
1956
2071
|
quoteIdentifier(name);
|
|
1957
|
-
const sqlName = `${table.sqlName}_${
|
|
2072
|
+
const sqlName = `${table.sqlName}_${sqlKey(name, snapshot.casing)}_check`;
|
|
1958
2073
|
quoteIdentifier(sqlName);
|
|
1959
2074
|
if (names.has(sqlName)) throw new Error(`symmetria: duplicate check constraint "${sqlName}"`);
|
|
1960
2075
|
names.add(sqlName);
|
|
@@ -1980,11 +2095,13 @@ const applyChecks = (snapshot, codecs, tableName, callback) => {
|
|
|
1980
2095
|
* only when explicitly named. Public schema() translates .inverse() modifiers
|
|
1981
2096
|
* into overrides before assembly.
|
|
1982
2097
|
*/
|
|
2098
|
+
/** The SQL name a key produces under a casing. */
|
|
2099
|
+
const sqlKey = (key, casing) => casing === "preserve" ? key : snakeCase(key);
|
|
1983
2100
|
const snakeCase = (name) => {
|
|
1984
2101
|
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1985
2102
|
};
|
|
1986
2103
|
/** The column a reference points at: its `by()` column (unique or the key) or the target's primary key. */
|
|
1987
|
-
const referencedColumn = (table, reference) => {
|
|
2104
|
+
const referencedColumn = (table, reference, casing) => {
|
|
1988
2105
|
const { by } = reference.flags;
|
|
1989
2106
|
if (by === void 0) {
|
|
1990
2107
|
if (!reference.target.primaryKey) throw new Error(`symmetria: "${table.key}.${reference.key}" references "${reference.target.key}", which has no primary key`);
|
|
@@ -1995,18 +2112,23 @@ const referencedColumn = (table, reference) => {
|
|
|
1995
2112
|
if (!scalar.definition.unique && !(reference.target.keys.length === 1 && reference.target.keys[0] === by)) throw new Error(`symmetria: "${table.key}.${reference.key}" references "${reference.target.key}.${by}", which must be a unique column or the primary key`);
|
|
1996
2113
|
return {
|
|
1997
2114
|
key: scalar.key,
|
|
1998
|
-
sqlName:
|
|
2115
|
+
sqlName: scalar.definition.sqlName ?? sqlKey(scalar.key, casing),
|
|
1999
2116
|
definition: scalar.definition
|
|
2000
2117
|
};
|
|
2001
2118
|
};
|
|
2002
|
-
const assembleSchema = (tables, overrides = {}, conditions = {}) => {
|
|
2119
|
+
const assembleSchema = (tables, overrides = {}, conditions = {}, casing = "snake_case") => {
|
|
2120
|
+
const nameOf = (key, named) => {
|
|
2121
|
+
const sqlName = named ?? sqlKey(key, casing);
|
|
2122
|
+
quoteIdentifier(sqlName);
|
|
2123
|
+
return sqlName;
|
|
2124
|
+
};
|
|
2003
2125
|
const analyzedTables = [];
|
|
2004
2126
|
const tablesByState = /* @__PURE__ */ new Map();
|
|
2005
2127
|
for (const [key, handle] of Object.entries(tables)) {
|
|
2006
2128
|
const state = tableState(handle);
|
|
2007
2129
|
if (state.key !== void 0) throw new Error(`symmetria: table "${state.key}" is already part of a schema (passed as "${key}")`);
|
|
2008
2130
|
state.key = key;
|
|
2009
|
-
state.sqlName =
|
|
2131
|
+
state.sqlName = nameOf(key, state.named);
|
|
2010
2132
|
const analyzedTable = {
|
|
2011
2133
|
key,
|
|
2012
2134
|
state,
|
|
@@ -2018,6 +2140,13 @@ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
|
|
|
2018
2140
|
analyzedTables.push(analyzedTable);
|
|
2019
2141
|
tablesByState.set(state, analyzedTable);
|
|
2020
2142
|
}
|
|
2143
|
+
const tableSqlNames = /* @__PURE__ */ new Map();
|
|
2144
|
+
for (const analyzedTable of analyzedTables) {
|
|
2145
|
+
const sqlName = analyzedTable.state.sqlName;
|
|
2146
|
+
const previous = tableSqlNames.get(sqlName);
|
|
2147
|
+
if (previous !== void 0) throw new Error(`symmetria: tables "${previous}" and "${analyzedTable.key}" both map to SQL name "${sqlName}"; rename one or set it with .named()`);
|
|
2148
|
+
tableSqlNames.set(sqlName, analyzedTable.key);
|
|
2149
|
+
}
|
|
2021
2150
|
for (const analyzedTable of analyzedTables) {
|
|
2022
2151
|
for (const [key, value] of Object.entries(analyzedTable.state.columns)) if (isColumn(value)) analyzedTable.scalars.push({
|
|
2023
2152
|
key,
|
|
@@ -2074,7 +2203,7 @@ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
|
|
|
2074
2203
|
const primaryKeyColumn = keys.length === 1 ? analyzedTable.scalars.find((column) => column.key === keys[0]) : void 0;
|
|
2075
2204
|
if (primaryKeyColumn) analyzedTable.primaryKey = {
|
|
2076
2205
|
key: primaryKeyColumn.key,
|
|
2077
|
-
sqlName:
|
|
2206
|
+
sqlName: nameOf(primaryKeyColumn.key, primaryKeyColumn.definition.sqlName),
|
|
2078
2207
|
definition: primaryKeyColumn.definition
|
|
2079
2208
|
};
|
|
2080
2209
|
}
|
|
@@ -2192,51 +2321,63 @@ const assembleSchema = (tables, overrides = {}, conditions = {}) => {
|
|
|
2192
2321
|
}
|
|
2193
2322
|
}
|
|
2194
2323
|
}
|
|
2195
|
-
const snapshot = {
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
const
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
notNull: reference.flags.nullable !== true,
|
|
2216
|
-
unique: reference.flags.unique === true,
|
|
2217
|
-
primaryKey: analyzedTable.keys.includes(`${reference.key}Id`),
|
|
2218
|
-
references: {
|
|
2219
|
-
table: reference.target.state.sqlName,
|
|
2220
|
-
column: targetColumn.sqlName,
|
|
2221
|
-
onDelete: reference.flags.onDelete ?? "restrict"
|
|
2324
|
+
const snapshot = {
|
|
2325
|
+
tables: [...analyzedTables.map((analyzedTable) => {
|
|
2326
|
+
const columns = analyzedTable.scalars.map((column) => ({
|
|
2327
|
+
name: column.key,
|
|
2328
|
+
sqlName: nameOf(column.key, column.definition.sqlName),
|
|
2329
|
+
sqlType: column.definition.sqlType,
|
|
2330
|
+
notNull: column.definition.notNull,
|
|
2331
|
+
unique: column.definition.unique,
|
|
2332
|
+
primaryKey: column.definition.primaryKey,
|
|
2333
|
+
...column.definition.default !== void 0 ? { default: column.definition.default } : {},
|
|
2334
|
+
...column.definition.enumerationValues !== void 0 ? { enumerationValues: column.definition.enumerationValues } : {}
|
|
2335
|
+
}));
|
|
2336
|
+
for (const reference of analyzedTable.references) {
|
|
2337
|
+
const targetColumn = referencedColumn(analyzedTable, reference, casing);
|
|
2338
|
+
reference.targetColumn = targetColumn;
|
|
2339
|
+
const sqlName = reference.flags.column ?? (casing === "preserve" ? `${reference.key}Id` : `${snakeCase(reference.key)}_id`);
|
|
2340
|
+
try {
|
|
2341
|
+
quoteIdentifier(sqlName);
|
|
2342
|
+
} catch (error) {
|
|
2343
|
+
throw new Error(`symmetria: "${analyzedTable.key}.${reference.key}" column name "${sqlName}" is not a valid SQL identifier: ${error.message.replace(/^symmetria: /, "")}`);
|
|
2222
2344
|
}
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2345
|
+
columns.push({
|
|
2346
|
+
name: `${reference.key}Id`,
|
|
2347
|
+
sqlName,
|
|
2348
|
+
sqlType: targetColumn.definition.sqlType,
|
|
2349
|
+
notNull: reference.flags.nullable !== true,
|
|
2350
|
+
unique: reference.flags.unique === true,
|
|
2351
|
+
primaryKey: analyzedTable.keys.includes(`${reference.key}Id`),
|
|
2352
|
+
references: {
|
|
2353
|
+
table: reference.target.state.sqlName,
|
|
2354
|
+
column: targetColumn.sqlName,
|
|
2355
|
+
onDelete: reference.flags.onDelete ?? "restrict",
|
|
2356
|
+
...reference.flags.onUpdate && reference.flags.onUpdate !== "no action" ? { onUpdate: reference.flags.onUpdate } : {}
|
|
2357
|
+
}
|
|
2358
|
+
});
|
|
2359
|
+
}
|
|
2360
|
+
const positions = new Map(Object.keys(analyzedTable.state.columns).map((key, position) => [key, position]));
|
|
2361
|
+
const referenceKeys = new Map(analyzedTable.references.map((reference) => [`${reference.key}Id`, reference.key]));
|
|
2362
|
+
const positionOf = (column) => positions.get(column.name) ?? positions.get(referenceKeys.get(column.name) ?? "") ?? Number.MAX_SAFE_INTEGER;
|
|
2363
|
+
columns.sort((left, right) => positionOf(left) - positionOf(right));
|
|
2364
|
+
const sqlNames = /* @__PURE__ */ new Set();
|
|
2365
|
+
for (const column of columns) {
|
|
2366
|
+
if (sqlNames.has(column.sqlName)) throw new Error(`symmetria: "${analyzedTable.key}" declares two columns named "${column.sqlName}"`);
|
|
2367
|
+
sqlNames.add(column.sqlName);
|
|
2368
|
+
}
|
|
2369
|
+
const tableRelations = relations.get(analyzedTable.key).map(({ origin: _origin, ...relation }) => relation);
|
|
2370
|
+
return {
|
|
2371
|
+
name: analyzedTable.key,
|
|
2372
|
+
sqlName: analyzedTable.state.sqlName,
|
|
2373
|
+
junction: analyzedTable.isJunction,
|
|
2374
|
+
columns,
|
|
2375
|
+
relations: tableRelations,
|
|
2376
|
+
...analyzedTable.state.primaryKey ? { primaryKey: analyzedTable.state.primaryKey.map((name) => columns.find((column) => column.name === name)?.sqlName ?? nameOf(name)) } : {}
|
|
2377
|
+
};
|
|
2378
|
+
})].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0),
|
|
2379
|
+
...casing === "preserve" ? { casing: "preserve" } : {}
|
|
2380
|
+
};
|
|
2240
2381
|
for (const analyzedTable of analyzedTables) {
|
|
2241
2382
|
const indexedColumns = [...analyzedTable.scalars.filter((column) => column.definition.index && !column.definition.unique && !(column.definition.primaryKey && analyzedTable.primaryKey)).map((column) => ({
|
|
2242
2383
|
column: column.key,
|
|
@@ -2259,6 +2400,6 @@ const resolveTarget = (tablesByState, state, source) => {
|
|
|
2259
2400
|
return found;
|
|
2260
2401
|
};
|
|
2261
2402
|
//#endregion
|
|
2262
|
-
export {
|
|
2403
|
+
export { coalesce as $, booleanCodec as $t, presentSelection as A, builderExample as At, quoteIdentifier as B, numeric as Bt, countValue as C, jsonRowCodec as Ct, initialPlan as D, COLUMN_CODEC as Dt, evaluateContext as E, COLUMN_BUILDER as Et, validateNode as F, inet as Ft, sqlString as G, time as Gt, searchHeadlineSql as H, real as Ht, validatePredicate as I, int as It, computedFields as J, tsvector as Jt, tsquerySql as K, timestamp as Kt, aliasSql as L, interval as Lt, readSelection as M, customType as Mt, resultRows as N, date as Nt, limitedPlan as O, bigint as Ot, shapeFrame as P, doublePrecision as Pt, average as Q, bigintCodec as Qt, createCompilation as R, isColumn as Rt, bindingScope as S, when as St, emptyBindings as T, freeze as Tt, searchRankSql as U, smallint as Ut, renderContext as V, oneOf as Vt, searchVectorSql as W, text as Wt, NAMED_PARAMETER as X, uuid as Xt, COLUMN_EXPRESSION as Y, typedColumn as Yt, and as Z, varchar as Zt, self as _, rowNumber as _t, INDEX_METHODS as a, numericCodec as an, lead as at, EMPTY as b, sum as bt, createIndexesSQL as c, not as ct, operatorClass as d, over as dt, cloneParameter as en, count as et, TABLE as f, predicate as ft, junction as g, readPredicate as gt, isTable as h, readColumn as ht, applyChecks as i, encodeValue as in, lag as it, readOrdering as j, bytea as jt, lockPlan as k, bool as kt, index as l, notExists as lt, isReferenceInput as m, rank as mt, snakeCase as n, codecMap as nn, denseRank as nt, applyIndexes as o, maximum as ot, draftBinding as p, presentPredicates as pt, tsvectorSql as q, timestamptz as qt, sqlKey as r, createRowDecoder as rn, exists as rt, createIndexQuery as s, minimum as st, assembleSchema as t, codecFor as tn, createExpression as tt, indexClausesSQL as u, or as ut, table as v, searchDocument as vt, createScope as w, expressionSqlType as wt, QUERY_STATE as x, valueNode as xt, tableState as y, sql as yt, parameter as z, jsonb as zt };
|
|
2263
2404
|
|
|
2264
|
-
//# sourceMappingURL=assembly-
|
|
2405
|
+
//# sourceMappingURL=assembly-C4GbrzmO.js.map
|