@dsqlbase/core 0.2.1 → 0.3.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.
Files changed (164) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/definition/base.d.ts +3 -30
  3. package/dist/definition/base.d.ts.map +1 -1
  4. package/dist/definition/base.js +3 -14
  5. package/dist/definition/base.js.map +1 -1
  6. package/dist/definition/column.d.ts +22 -14
  7. package/dist/definition/column.d.ts.map +1 -1
  8. package/dist/definition/column.js +11 -37
  9. package/dist/definition/column.js.map +1 -1
  10. package/dist/definition/constraint.d.ts +9 -9
  11. package/dist/definition/constraint.d.ts.map +1 -1
  12. package/dist/definition/constraint.js.map +1 -1
  13. package/dist/definition/domain.d.ts +2 -1
  14. package/dist/definition/domain.d.ts.map +1 -1
  15. package/dist/definition/domain.js +2 -1
  16. package/dist/definition/domain.js.map +1 -1
  17. package/dist/definition/index.d.ts +5 -6
  18. package/dist/definition/index.d.ts.map +1 -1
  19. package/dist/definition/index.js +3 -4
  20. package/dist/definition/index.js.map +1 -1
  21. package/dist/definition/indexes.d.ts +9 -20
  22. package/dist/definition/indexes.d.ts.map +1 -1
  23. package/dist/definition/indexes.js +3 -6
  24. package/dist/definition/indexes.js.map +1 -1
  25. package/dist/definition/namespace.d.ts +2 -2
  26. package/dist/definition/namespace.d.ts.map +1 -1
  27. package/dist/definition/namespace.js.map +1 -1
  28. package/dist/definition/policy.d.ts +35 -0
  29. package/dist/definition/policy.d.ts.map +1 -0
  30. package/dist/definition/policy.js +42 -0
  31. package/dist/definition/policy.js.map +1 -0
  32. package/dist/definition/relations.d.ts +28 -33
  33. package/dist/definition/relations.d.ts.map +1 -1
  34. package/dist/definition/relations.js +1 -4
  35. package/dist/definition/relations.js.map +1 -1
  36. package/dist/definition/table.d.ts +39 -32
  37. package/dist/definition/table.d.ts.map +1 -1
  38. package/dist/definition/table.js +57 -67
  39. package/dist/definition/table.js.map +1 -1
  40. package/dist/definition/union.d.ts +18 -61
  41. package/dist/definition/union.d.ts.map +1 -1
  42. package/dist/definition/union.js +8 -69
  43. package/dist/definition/union.js.map +1 -1
  44. package/dist/index.d.ts +5 -3
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +5 -3
  47. package/dist/index.js.map +1 -1
  48. package/dist/resolvers/codec.d.ts +16 -0
  49. package/dist/resolvers/codec.d.ts.map +1 -0
  50. package/dist/resolvers/codec.js +9 -0
  51. package/dist/resolvers/codec.js.map +1 -0
  52. package/dist/resolvers/hooks.d.ts +39 -0
  53. package/dist/resolvers/hooks.d.ts.map +1 -0
  54. package/dist/resolvers/hooks.js +2 -0
  55. package/dist/resolvers/hooks.js.map +1 -0
  56. package/dist/resolvers/index.d.ts +5 -0
  57. package/dist/resolvers/index.d.ts.map +1 -0
  58. package/dist/resolvers/index.js +2 -0
  59. package/dist/resolvers/index.js.map +1 -0
  60. package/dist/resolvers/policy.d.ts +31 -0
  61. package/dist/resolvers/policy.d.ts.map +1 -0
  62. package/dist/resolvers/policy.js +2 -0
  63. package/dist/resolvers/policy.js.map +1 -0
  64. package/dist/resolvers/validator.d.ts +14 -0
  65. package/dist/resolvers/validator.d.ts.map +1 -0
  66. package/dist/resolvers/validator.js +2 -0
  67. package/dist/resolvers/validator.js.map +1 -0
  68. package/dist/runtime/base.d.ts +7 -4
  69. package/dist/runtime/base.d.ts.map +1 -1
  70. package/dist/runtime/base.js.map +1 -1
  71. package/dist/runtime/build.d.ts +22 -0
  72. package/dist/runtime/build.d.ts.map +1 -0
  73. package/dist/runtime/build.js +184 -0
  74. package/dist/runtime/build.js.map +1 -0
  75. package/dist/runtime/column.d.ts +40 -23
  76. package/dist/runtime/column.d.ts.map +1 -1
  77. package/dist/runtime/column.js +120 -28
  78. package/dist/runtime/column.js.map +1 -1
  79. package/dist/runtime/context.d.ts +17 -26
  80. package/dist/runtime/context.d.ts.map +1 -1
  81. package/dist/runtime/context.js +4 -6
  82. package/dist/runtime/context.js.map +1 -1
  83. package/dist/runtime/errors.d.ts +31 -9
  84. package/dist/runtime/errors.d.ts.map +1 -1
  85. package/dist/runtime/errors.js +54 -11
  86. package/dist/runtime/errors.js.map +1 -1
  87. package/dist/runtime/executor.d.ts.map +1 -1
  88. package/dist/runtime/executor.js +10 -1
  89. package/dist/runtime/executor.js.map +1 -1
  90. package/dist/runtime/index.d.ts +10 -6
  91. package/dist/runtime/index.d.ts.map +1 -1
  92. package/dist/runtime/index.js +5 -3
  93. package/dist/runtime/index.js.map +1 -1
  94. package/dist/runtime/operation.d.ts +62 -83
  95. package/dist/runtime/operation.d.ts.map +1 -1
  96. package/dist/runtime/operation.js +194 -260
  97. package/dist/runtime/operation.js.map +1 -1
  98. package/dist/runtime/policy.d.ts +35 -0
  99. package/dist/runtime/policy.d.ts.map +1 -0
  100. package/dist/runtime/policy.js +72 -0
  101. package/dist/runtime/policy.js.map +1 -0
  102. package/dist/runtime/reference.d.ts +87 -0
  103. package/dist/runtime/reference.d.ts.map +1 -0
  104. package/dist/runtime/reference.js +68 -0
  105. package/dist/runtime/reference.js.map +1 -0
  106. package/dist/runtime/registry.d.ts +26 -95
  107. package/dist/runtime/registry.d.ts.map +1 -1
  108. package/dist/runtime/registry.js +29 -408
  109. package/dist/runtime/registry.js.map +1 -1
  110. package/dist/runtime/relation.d.ts +45 -0
  111. package/dist/runtime/relation.d.ts.map +1 -0
  112. package/dist/runtime/relation.js +2 -0
  113. package/dist/runtime/relation.js.map +1 -0
  114. package/dist/runtime/table.d.ts +31 -35
  115. package/dist/runtime/table.d.ts.map +1 -1
  116. package/dist/runtime/table.js +78 -47
  117. package/dist/runtime/table.js.map +1 -1
  118. package/dist/runtime/union.d.ts +11 -4
  119. package/dist/runtime/union.d.ts.map +1 -1
  120. package/dist/runtime/union.js +18 -7
  121. package/dist/runtime/union.js.map +1 -1
  122. package/dist/sql/index.d.ts +2 -2
  123. package/dist/sql/index.d.ts.map +1 -1
  124. package/dist/sql/index.js +1 -1
  125. package/dist/sql/index.js.map +1 -1
  126. package/dist/sql/nodes.d.ts +22 -0
  127. package/dist/sql/nodes.d.ts.map +1 -1
  128. package/dist/sql/nodes.js +21 -0
  129. package/dist/sql/nodes.js.map +1 -1
  130. package/dist/sql/tag.d.ts +3 -15
  131. package/dist/sql/tag.d.ts.map +1 -1
  132. package/dist/sql/tag.js +5 -71
  133. package/dist/sql/tag.js.map +1 -1
  134. package/dist/utils/index.d.ts +1 -1
  135. package/dist/utils/index.d.ts.map +1 -1
  136. package/dist/utils/index.js.map +1 -1
  137. package/dist/utils/types.d.ts +2 -14
  138. package/dist/utils/types.d.ts.map +1 -1
  139. package/dist/utils/types.js.map +1 -1
  140. package/dist/validation/index.d.ts +2 -0
  141. package/dist/validation/index.d.ts.map +1 -0
  142. package/dist/validation/index.js +2 -0
  143. package/dist/validation/index.js.map +1 -0
  144. package/dist/validation/references.d.ts +23 -0
  145. package/dist/validation/references.d.ts.map +1 -0
  146. package/dist/validation/references.js +240 -0
  147. package/dist/validation/references.js.map +1 -0
  148. package/dist/validation/validate.d.ts +40 -0
  149. package/dist/validation/validate.d.ts.map +1 -0
  150. package/dist/validation/validate.js +354 -0
  151. package/dist/validation/validate.js.map +1 -0
  152. package/package.json +13 -4
  153. package/dist/definition/embedded.d.ts +0 -131
  154. package/dist/definition/embedded.d.ts.map +0 -1
  155. package/dist/definition/embedded.js +0 -133
  156. package/dist/definition/embedded.js.map +0 -1
  157. package/dist/definition/tenant.d.ts +0 -50
  158. package/dist/definition/tenant.d.ts.map +0 -1
  159. package/dist/definition/tenant.js +0 -73
  160. package/dist/definition/tenant.js.map +0 -1
  161. package/dist/runtime/group.d.ts +0 -54
  162. package/dist/runtime/group.d.ts.map +0 -1
  163. package/dist/runtime/group.js +0 -96
  164. package/dist/runtime/group.js.map +0 -1
@@ -0,0 +1,184 @@
1
+ import { Relation, TableDefinition, UnionDefinition, } from "../definition/index.js";
2
+ import { collectRelations, findColumnAlias, memberToColumns, } from "../validation/index.js";
3
+ import { ComputedDiscriminator } from "./reference.js";
4
+ import { Table } from "./table.js";
5
+ import { Union } from "./union.js";
6
+ /**
7
+ * Builds the runtime objects of a schema `validateSchema` accepted: tables, unions, relations
8
+ * resolved to runtime columns, and the references those relations set on their foreign keys.
9
+ *
10
+ * It checks nothing; given a schema that was not validated, it may build nonsense or throw on
11
+ * a missing column. Nothing it uses while building outlives the call.
12
+ */
13
+ export function buildSchema(schema) {
14
+ const tables = new Map();
15
+ const tableOf = new Map();
16
+ for (const [alias, node] of Object.entries(schema)) {
17
+ if (node instanceof TableDefinition) {
18
+ const table = new Table(node, alias);
19
+ tables.set(node.name, table);
20
+ tables.set(alias, table);
21
+ tableOf.set(node, table);
22
+ }
23
+ }
24
+ const unions = new Map();
25
+ const unionOf = new Map();
26
+ for (const [alias, node] of Object.entries(schema)) {
27
+ if (node instanceof UnionDefinition) {
28
+ const members = Object.fromEntries(Object.entries(node.members).map(([key, member]) => [
29
+ key,
30
+ tableOf.get(member),
31
+ ]));
32
+ const union = new Union(node, members, alias);
33
+ unions.set(alias, union);
34
+ unionOf.set(node, union);
35
+ }
36
+ }
37
+ const computed = computedDiscriminators();
38
+ const all = [];
39
+ const relations = new Map();
40
+ for (const entry of collectRelations(schema)) {
41
+ const relation = buildRelation(entry, tableOf, unionOf, computed);
42
+ const byField = relations.get(relation.source) ?? {};
43
+ byField[relation.field] = relation;
44
+ relations.set(relation.source, byField);
45
+ all.push(relation);
46
+ }
47
+ linkReferences(all, computed);
48
+ const unique = new Set(tables.values());
49
+ for (const table of unique) {
50
+ for (const [, column] of table.getColumnEntries()) {
51
+ column._freezeReferences();
52
+ }
53
+ }
54
+ for (const [table, byField] of relations) {
55
+ relations.set(table, Object.freeze(byField));
56
+ }
57
+ return { tables, unions, relations };
58
+ }
59
+ /** The runtime column a definition column is declared as on `table`. */
60
+ function columnOf(table, definition, column) {
61
+ return table.getColumn(findColumnAlias(definition, column));
62
+ }
63
+ /**
64
+ * Makes computed discriminators, one per union and key columns: a belongs-to a union and a
65
+ * has-many from it over the same key are one reference, so they must share one.
66
+ */
67
+ function computedDiscriminators() {
68
+ const made = [];
69
+ return (union, keys, members) => {
70
+ const known = made.find((candidate) => candidate.union === union &&
71
+ candidate.keys.length === keys.length &&
72
+ candidate.keys.every((key, index) => key === keys[index]) &&
73
+ union.memberAliases.every((alias) => candidate.members[alias].every((column, index) => column === members[alias][index])));
74
+ if (known) {
75
+ return known;
76
+ }
77
+ const discriminator = new ComputedDiscriminator(union, keys, members);
78
+ made.push(discriminator);
79
+ return discriminator;
80
+ };
81
+ }
82
+ function buildRelation(entry, tableOf, unionOf, computed) {
83
+ const { field, relation } = entry;
84
+ const source = tableOf.get(entry.source);
85
+ const declaredOn = entry.union ? unionOf.get(entry.union) : source;
86
+ const from = relation.from.map((column) => columnOf(source, entry.source, column));
87
+ const base = { field, type: relation.type, source, declaredOn, from };
88
+ if (!(relation.target instanceof UnionDefinition)) {
89
+ const definition = relation.target;
90
+ const target = tableOf.get(definition);
91
+ return {
92
+ ...base,
93
+ kind: "table",
94
+ target,
95
+ to: relation.to.map((column) => columnOf(target, definition, column)),
96
+ };
97
+ }
98
+ const definition = relation.target;
99
+ const union = unionOf.get(definition);
100
+ const lists = memberToColumns(field, union.alias, definition, relation.to);
101
+ const members = Object.fromEntries(Object.entries(lists).map(([alias, columns]) => [
102
+ alias,
103
+ columns.map((column) => columnOf(union.getMember(alias), definition.members[alias], column)),
104
+ ]));
105
+ let discriminator;
106
+ if (relation.type === Relation.BELONGS_TO) {
107
+ // Without a stored discriminator, the member is the first one holding the key.
108
+ discriminator = relation.discriminator
109
+ ? columnOf(source, entry.source, relation.discriminator)
110
+ : computed(union, from, members);
111
+ }
112
+ return { ...base, kind: "union", target: union, members, discriminator };
113
+ }
114
+ /**
115
+ * Sets every reference the relations imply, on the foreign key, as in SQL:
116
+ *
117
+ * - a belongs-to: on each `from` column, pointing at the paired `to` — or, to a union, at the
118
+ * member its discriminator names;
119
+ * - a has-many / has-one: on each `to` column — every member's, to a union — pointing at `from`;
120
+ * - a has-many / has-one declared on a union: one union reference on each `to` column, since it
121
+ * holds a key of whichever member its row points at. Linked last, so a belongs-to back over
122
+ * the same key — with its stored discriminator — is found and shared.
123
+ */
124
+ function linkReferences(relations, computed) {
125
+ const fromUnions = new Map();
126
+ for (const relation of relations) {
127
+ const via = relation;
128
+ const belongsTo = relation.type === Relation.BELONGS_TO;
129
+ if (relation.kind === "union") {
130
+ for (const [index, from] of relation.from.entries()) {
131
+ if (belongsTo) {
132
+ from._addReference({
133
+ kind: "union",
134
+ union: relation.target,
135
+ members: Object.fromEntries(Object.entries(relation.members).map(([alias, columns]) => [alias, columns[index]])),
136
+ discriminator: relation.discriminator,
137
+ via,
138
+ });
139
+ continue;
140
+ }
141
+ for (const to of Object.values(relation.members)) {
142
+ to[index]._addReference({ kind: "table", column: from, via });
143
+ }
144
+ }
145
+ continue;
146
+ }
147
+ if (!belongsTo && relation.declaredOn instanceof Union) {
148
+ const byField = fromUnions.get(relation.declaredOn) ?? new Map();
149
+ byField.set(relation.field, [...(byField.get(relation.field) ?? []), relation]);
150
+ fromUnions.set(relation.declaredOn, byField);
151
+ continue;
152
+ }
153
+ for (const [index, from] of relation.from.entries()) {
154
+ const to = relation.to[index];
155
+ if (belongsTo) {
156
+ from._addReference({ kind: "table", column: to, via });
157
+ }
158
+ else {
159
+ to._addReference({ kind: "table", column: from, via });
160
+ }
161
+ }
162
+ }
163
+ for (const [union, byField] of fromUnions) {
164
+ for (const copies of byField.values()) {
165
+ const [first] = copies;
166
+ const keys = first.to;
167
+ const pairs = Object.fromEntries(copies.map((copy) => [copy.source.alias, copy.from]));
168
+ const back = keys[0].references.find((reference) => reference.kind === "union" &&
169
+ reference.union === union &&
170
+ union.memberAliases.every((alias) => reference.members[alias] === pairs[alias][0]));
171
+ const discriminator = back?.kind === "union" ? back.discriminator : computed(union, keys, pairs);
172
+ for (const [index, key] of keys.entries()) {
173
+ key._addReference({
174
+ kind: "union",
175
+ union,
176
+ members: Object.fromEntries(Object.entries(pairs).map(([alias, columns]) => [alias, columns[index]])),
177
+ discriminator,
178
+ via: first,
179
+ });
180
+ }
181
+ }
182
+ }
183
+ }
184
+ //# sourceMappingURL=build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/runtime/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,QAAQ,EACR,eAAe,EACf,eAAe,GAChB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAY,KAAK,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAY,KAAK,EAAE,MAAM,YAAY,CAAC;AAY7C;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,MAAwB;IAClD,MAAM,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAgC,CAAC;IAExD,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACnD,IAAI,IAAI,YAAY,eAAe,EAAE,CAAC;YACpC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAErC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAC7B,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAgC,CAAC;IAExD,KAAK,MAAM,CAAC,KAAK,E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E,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACvF,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAClC,CAAC,SAAS,EAAE,EAAE,CACZ,SAAS,CAAC,IAAI,KAAK,OAAO;gBAC1B,SAAS,CAAC,KAAK,KAAK,KAAK;gBACzB,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CACrF,CAAC;YACF,MAAM,aAAa,GACjB,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;YAE7E,KAAK,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;gBAC1C,GAAG,CAAC,aAAa,CAAC;oBAChB,IAAI,EAAE,OAAO;oBACb,KAAK;oBACL,OAAO,EAAE,MAAM,CAAC,WAAW,CACzB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CACzE;oBACD,aAAa;oBACb,GAAG,EAAE,KAAK;iBACX,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n AnyColumnDefinition,\n AnyTableDefinition,\n AnyUnionDefinition,\n DefinitionSchema,\n Relation,\n TableDefinition,\n UnionDefinition,\n} from \"../definition/index.js\";\nimport {\n SourcedRelation,\n collectRelations,\n findColumnAlias,\n memberToColumns,\n} from \"../validation/index.js\";\nimport { AnyColumn } from \"./column.js\";\nimport { ComputedDiscriminator } from \"./reference.js\";\nimport { RuntimeRelation, TableRelation } from \"./relation.js\";\nimport { AnyTable, Table } from \"./table.js\";\nimport { AnyUnion, Union } from \"./union.js\";\n\n/** A schema's runtime objects, as `SchemaRegistry` holds them. */\nexport type BuiltSchema = {\n /** Every table, under both its schema alias and its database name. */\n readonly tables: Map<string, AnyTable>;\n /** Every union, by schema alias. */\n readonly unions: Map<string, AnyUnion>;\n /** Every table's relations, by field. A table with none has no entry. */\n readonly relations: Map<AnyTable, Readonly<Record<string, RuntimeRelation>>>;\n};\n\n/**\n * Builds the runtime objects of a schema `validateSchema` accepted: tables, unions, relations\n * resolved to runtime columns, and the references those relations set on their foreign keys.\n *\n * It checks nothing; given a schema that was not validated, it may build nonsense or throw on\n * a missing column. Nothing it uses while building outlives the call.\n */\nexport function buildSchema(schema: DefinitionSchema): BuiltSchema {\n const tables = new Map<string, AnyTable>();\n const tableOf = new Map<AnyTableDefinition, AnyTable>();\n\n for (const [alias, node] of Object.entries(schema)) {\n if (node instanceof TableDefinition) {\n const table = new Table(node, alias);\n\n tables.set(node.name, table);\n tables.set(alias, table);\n tableOf.set(node, table);\n }\n }\n\n const unions = new Map<string, AnyUnion>();\n const unionOf = new Map<AnyUnionDefinition, AnyUnion>();\n\n for (const [alias, node] of Object.entries(schema)) {\n if (node instanceof UnionDefinition) {\n const members = Object.fromEntries(\n Object.entries<AnyTableDefinition>(node.members).map(([key, member]) => [\n key,\n tableOf.get(member) as AnyTable,\n ])\n );\n const union = new Union(node, members, alias);\n\n unions.set(alias, union);\n unionOf.set(node, union);\n }\n }\n\n const computed = computedDiscriminators();\n const all: RuntimeRelation[] = [];\n const relations = new Map<AnyTable, Record<string, RuntimeRelation>>();\n\n for (const entry of collectRelations(schema)) {\n const relation = buildRelation(entry, tableOf, unionOf, computed);\n const byField = relations.get(relation.source) ?? {};\n\n byField[relation.field] = relation;\n relations.set(relation.source, byField);\n all.push(relation);\n }\n\n linkReferences(all, computed);\n\n const unique = new Set(tables.values());\n\n for (const table of unique) {\n for (const [, column] of table.getColumnEntries()) {\n column._freezeReferences();\n }\n }\n\n for (const [table, byField] of relations) {\n relations.set(table, Object.freeze(byField));\n }\n\n return { tables, unions, relations };\n}\n\n/** The runtime column a definition column is declared as on `table`. */\nfunction columnOf(\n table: AnyTable,\n definition: AnyTableDefinition,\n column: AnyColumnDefinition\n): AnyColumn {\n return table.getColumn(findColumnAlias(definition, column) as string) as AnyColumn;\n}\n\ntype ComputedDiscriminators = (\n union: AnyUnion,\n keys: readonly AnyColumn[],\n members: Readonly<Record<string, readonly AnyColumn[]>>\n) => ComputedDiscriminator;\n\n/**\n * Makes computed discriminators, one per union and key columns: a belongs-to a union and a\n * has-many from it over the same key are one reference, so they must share one.\n */\nfunction computedDiscriminators(): ComputedDiscriminators {\n const made: ComputedDiscriminator[] = [];\n\n return (union, keys, members) => {\n const known = made.find(\n (candidate) =>\n candidate.union === union &&\n candidate.keys.length === keys.length &&\n candidate.keys.every((key, index) => key === keys[index]) &&\n union.memberAliases.every((alias) =>\n candidate.members[alias].every((column, index) => column === members[alias][index])\n )\n );\n\n if (known) {\n return known;\n }\n\n const discriminator = new ComputedDiscriminator(union, keys, members);\n made.push(discriminator);\n\n return discriminator;\n };\n}\n\nfunction buildRelation(\n entry: SourcedRelation,\n tableOf: ReadonlyMap<AnyTableDefinition, AnyTable>,\n unionOf: ReadonlyMap<AnyUnionDefinition, AnyUnion>,\n computed: ComputedDiscriminators\n): RuntimeRelation {\n const { field, relation } = entry;\n const source = tableOf.get(entry.source) as AnyTable;\n const declaredOn = entry.union ? (unionOf.get(entry.union) as AnyUnion) : source;\n const from = relation.from.map((column) => columnOf(source, entry.source, column));\n const base = { field, type: relation.type, source, declaredOn, from };\n\n if (!(relation.target instanceof UnionDefinition)) {\n const definition = relation.target;\n const target = tableOf.get(definition) as AnyTable;\n\n return {\n ...base,\n kind: \"table\",\n target,\n to: (relation.to as AnyColumnDefinition[]).map((column) =>\n columnOf(target, definition, column)\n ),\n };\n }\n\n const definition = relation.target;\n const union = unionOf.get(definition) as AnyUnion;\n const lists = memberToColumns(field, union.alias, definition, relation.to);\n const members = Object.fromEntries(\n Object.entries(lists).map(([alias, columns]) => [\n alias,\n columns.map((column) =>\n columnOf(union.getMember(alias), definition.members[alias] as AnyTableDefinition, column)\n ),\n ])\n );\n\n let discriminator: AnyColumn | ComputedDiscriminator | undefined;\n\n if (relation.type === Relation.BELONGS_TO) {\n // Without a stored discriminator, the member is the first one holding the key.\n discriminator = relation.discriminator\n ? columnOf(source, entry.source, relation.discriminator)\n : computed(union, from, members);\n }\n\n return { ...base, kind: \"union\", target: union, members, discriminator };\n}\n\n/**\n * Sets every reference the relations imply, on the foreign key, as in SQL:\n *\n * - a belongs-to: on each `from` column, pointing at the paired `to` — or, to a union, at the\n * member its discriminator names;\n * - a has-many / has-one: on each `to` column — every member's, to a union — pointing at `from`;\n * - a has-many / has-one declared on a union: one union reference on each `to` column, since it\n * holds a key of whichever member its row points at. Linked last, so a belongs-to back over\n * the same key — with its stored discriminator — is found and shared.\n */\nfunction linkReferences(relations: readonly RuntimeRelation[], computed: ComputedDiscriminators) {\n const fromUnions = new Map<AnyUnion, Map<string, TableRelation[]>>();\n\n for (const relation of relations) {\n const via = relation;\n const belongsTo = relation.type === Relation.BELONGS_TO;\n\n if (relation.kind === \"union\") {\n for (const [index, from] of relation.from.entries()) {\n if (belongsTo) {\n from._addReference({\n kind: \"union\",\n union: relation.target,\n members: Object.fromEntries(\n Object.entries(relation.members).map(([alias, columns]) => [alias, columns[index]])\n ),\n discriminator: relation.discriminator as AnyColumn | ComputedDiscriminator,\n via,\n });\n continue;\n }\n\n for (const to of Object.values(relation.members)) {\n to[index]._addReference({ kind: \"table\", column: from, via });\n }\n }\n\n continue;\n }\n\n if (!belongsTo && relation.declaredOn instanceof Union) {\n const byField = fromUnions.get(relation.declaredOn) ?? new Map<string, TableRelation[]>();\n byField.set(relation.field, [...(byField.get(relation.field) ?? []), relation]);\n fromUnions.set(relation.declaredOn, byField);\n continue;\n }\n\n for (const [index, from] of relation.from.entries()) {\n const to = relation.to[index];\n\n if (belongsTo) {\n from._addReference({ kind: \"table\", column: to, via });\n } else {\n to._addReference({ kind: \"table\", column: from, via });\n }\n }\n }\n\n for (const [union, byField] of fromUnions) {\n for (const copies of byField.values()) {\n const [first] = copies;\n const keys = first.to;\n const pairs = Object.fromEntries(copies.map((copy) => [copy.source.alias, copy.from]));\n const back = keys[0].references.find(\n (reference) =>\n reference.kind === \"union\" &&\n reference.union === union &&\n union.memberAliases.every((alias) => reference.members[alias] === pairs[alias][0])\n );\n const discriminator =\n back?.kind === \"union\" ? back.discriminator : computed(union, keys, pairs);\n\n for (const [index, key] of keys.entries()) {\n key._addReference({\n kind: \"union\",\n union,\n members: Object.fromEntries(\n Object.entries(pairs).map(([alias, columns]) => [alias, columns[index]])\n ),\n discriminator,\n via: first,\n });\n }\n }\n }\n}\n"]}
@@ -2,19 +2,15 @@ import { TypedObject } from "../utils/index.js";
2
2
  import { ColumnConfig, ColumnDefinition, ColumnRuntimeType } from "../definition/index.js";
3
3
  import { SQLContext, SQLNode, SQLParam, SQLStatement } from "../sql/index.js";
4
4
  import { AnyTable } from "./table.js";
5
+ import { ColumnReference, ComputedDiscriminator, ResolvedReferences } from "./reference.js";
5
6
  export type AnyColumn = Column<any, any, any>;
6
- /** See {@link Column.rowDecoder}. */
7
- export type ColumnRowDecoder = {
8
- /** Columns of the same table the decode reads; projected alongside this one. */
9
- readonly dependsOn: AnyColumn[];
10
- /** The value from the column's raw value and the raw row it was read from, keyed by column name. */
11
- decode(raw: unknown, row: Record<string, unknown>): unknown;
12
- };
13
7
  export declare class Column<TName extends string, TConfig extends ColumnConfig, TTable extends AnyTable> implements SQLNode, TypedObject<TConfig> {
14
8
  readonly __type: TConfig;
15
9
  readonly codec: ColumnDefinition<TName, TConfig>["_codec"];
16
10
  /** Checks writes before they are encoded and reads after they are decoded; never filters. */
17
11
  readonly validator: ColumnDefinition<TName, TConfig>["_validator"];
12
+ /** Transforms around the codec that read this column or the row; see `ColumnHooks`. */
13
+ readonly hooks: ColumnDefinition<TName, TConfig>["_hooks"];
18
14
  readonly onCreate: ColumnDefinition<TName, TConfig>["_onCreate"];
19
15
  readonly onUpdate: ColumnDefinition<TName, TConfig>["_onUpdate"];
20
16
  readonly table: TTable;
@@ -34,27 +30,48 @@ export declare class Column<TName extends string, TConfig extends ColumnConfig,
34
30
  readonly primaryKey: TConfig["primaryKey"];
35
31
  readonly unique: TConfig["unique"];
36
32
  readonly readOnly: TConfig["readOnly"];
37
- readonly tenantKey: TConfig["tenantKey"];
38
- constructor(table: TTable, definition: ColumnDefinition<TName, TConfig>);
33
+ readonly fieldName: string;
34
+ constructor(table: TTable, definition: ColumnDefinition<TName, TConfig>, fieldName: string);
35
+ private _references;
36
+ private _referencesFrozen;
39
37
  /**
40
- * A decode that needs more than the column's own value — sibling columns of the same row.
38
+ * What this column points at, one entry per relation that makes it a foreign key. Set by the
39
+ * `SchemaRegistry` while it builds relations, for every column type; empty for a column no
40
+ * relation references through. A column may point at more than one target — a plain key can
41
+ * be a foreign key of two tables — and what that means is left to the reader.
42
+ */
43
+ get references(): readonly ColumnReference[];
44
+ /**
45
+ * What gives this column's value its meaning, read from the same row: the discriminator of
46
+ * each union reference — a sibling column, or a {@link ComputedDiscriminator}. Projected alongside the column whenever it is
47
+ * selected.
48
+ */
49
+ get dependsOn(): readonly (AnyColumn | ComputedDiscriminator)[];
50
+ /**
51
+ * Follows this column's references to where each chain ends. A table reference continues
52
+ * through the column it points at; a union reference is an end of its own, since its member
53
+ * is only known per row — given the `row`, it resolves to the member column its discriminator
54
+ * names, or to nothing when the discriminator is null or names no member.
41
55
  *
42
- * Unset by default; a client sets it on the built column when it is created, as it does a
43
- * bound codec, for a value whose meaning depends on another column (a polymorphic reference
44
- * whose target is named by a discriminator). When set, `dependsOn` is projected whenever this
45
- * column is selected, and the value is read through {@link Column.resolveRow} instead of
46
- * {@link Column.resolve}. Core applies no meaning to it.
56
+ * Never throws: two ends can be legitimate for a plain key, so it is the caller who decides
57
+ * whether they are a conflict. `validateSchema` refuses a ring, so a built schema has none;
58
+ * one is still reported rather than looped on.
59
+ */
60
+ resolveReferences(row?: Record<string, unknown>): ResolvedReferences;
61
+ /**
62
+ * A value as read: decoded by the codec, passed through the `read` hook with the `row` it came
63
+ * from, then checked by the validator. `row` is the raw row, keyed by column name — the root
64
+ * row, a joined level or a union branch — and carries {@link Column.dependsOn}.
47
65
  */
48
- readonly rowDecoder?: ColumnRowDecoder;
49
- /** Reads this column's value from a whole row, through {@link Column.rowDecoder} if set. */
50
- resolveRow(row: Record<string, unknown>): TConfig["valueType"];
51
- resolve(value: TConfig["rawType"]): TConfig["valueType"];
52
- private _validateRead;
53
- /** A write's value as sent: validated, if the column has a validator, then encoded. */
66
+ resolve(value: TConfig["rawType"], row?: Readonly<Record<string, unknown>>): TConfig["valueType"];
67
+ /** A filter's value as sent: through the `write` hook, then encoded. Never validated. */
68
+ private readonly _encodeParam;
69
+ /** A write's value as sent: validated, if the column has a validator, then as a filter's. */
54
70
  private readonly _encodeInput;
55
71
  /**
56
- * Wraps a value as a parameter encoded by this column's codec. It is not validated: a filter
57
- * value is compared with stored values, not stored, and may be a fragment of one.
72
+ * Wraps a value as a parameter for this column: through its `write` hook, then encoded by its
73
+ * codec. It is not validated: a filter value is compared with stored values, not stored, and
74
+ * may be a fragment of one.
58
75
  *
59
76
  * This is the filter counterpart to {@link Column.getInsertValue} and
60
77
  * {@link Column.getUpdateValue}: a `date`, `bigint` or `interval` column only matches if
@@ -1 +1 @@
1
- {"version":3,"file":"column.d.ts","sourceRoot":"","sources":["../../src/runtime/column.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAE,UAAU,EAAE,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AC7F,OAAO,CAAC,QAAQ,CAAC,YAAY,CAC6C;IAE1E;;;;;;;;;;;;;OAaG;IACI,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,GAAG,OAAO;IAQrD,cAAc,CACnB,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,GAgB/D,OAAO;IAGzB,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,GAAG,SAAS,GAgB5E,OAAO;IAGzB,KAAK,CAAC,GAAG,EAAE,UAAU,GAAG,YAAY;CAMrC"}
@@ -1,8 +1,11 @@
1
1
  import { SQLParam, isSQLNode, sql } from "../sql/index.js";
2
+ import { isSameReference, } from "./reference.js";
2
3
  export class Column {
3
4
  codec;
4
5
  /** Checks writes before they are encoded and reads after they are decoded; never filters. */
5
6
  validator;
7
+ /** Transforms around the codec that read this column or the row; see `ColumnHooks`. */
8
+ hooks;
6
9
  onCreate;
7
10
  onUpdate;
8
11
  table;
@@ -22,8 +25,8 @@ export class Column {
22
25
  primaryKey;
23
26
  unique;
24
27
  readOnly;
25
- tenantKey;
26
- constructor(table, definition) {
28
+ fieldName;
29
+ constructor(table, definition, fieldName) {
27
30
  this.table = table;
28
31
  this.name = definition.name;
29
32
  this.dataType = definition["_dataType"];
@@ -34,47 +37,136 @@ export class Column {
34
37
  this.primaryKey = definition["_primaryKey"];
35
38
  this.unique = definition["_unique"];
36
39
  this.readOnly = definition["_readOnly"];
37
- this.tenantKey = definition["_tenantKey"];
40
+ this.fieldName = fieldName;
38
41
  this.codec = definition["_codec"];
39
42
  this.validator = definition["_validator"];
43
+ this.hooks = definition["_hooks"];
40
44
  this.onCreate = definition["_onCreate"];
41
45
  this.onUpdate = definition["_onUpdate"];
42
46
  }
47
+ _references = [];
48
+ _referencesFrozen = false;
43
49
  /**
44
- * A decode that needs more than the column's own value — sibling columns of the same row.
45
- *
46
- * Unset by default; a client sets it on the built column when it is created, as it does a
47
- * bound codec, for a value whose meaning depends on another column (a polymorphic reference
48
- * whose target is named by a discriminator). When set, `dependsOn` is projected whenever this
49
- * column is selected, and the value is read through {@link Column.resolveRow} instead of
50
- * {@link Column.resolve}. Core applies no meaning to it.
50
+ * What this column points at, one entry per relation that makes it a foreign key. Set by the
51
+ * `SchemaRegistry` while it builds relations, for every column type; empty for a column no
52
+ * relation references through. A column may point at more than one target — a plain key can
53
+ * be a foreign key of two tables — and what that means is left to the reader.
54
+ */
55
+ get references() {
56
+ return this._references;
57
+ }
58
+ /**
59
+ * What gives this column's value its meaning, read from the same row: the discriminator of
60
+ * each union reference — a sibling column, or a {@link ComputedDiscriminator}. Projected alongside the column whenever it is
61
+ * selected.
62
+ */
63
+ get dependsOn() {
64
+ const dependencies = [];
65
+ for (const reference of this._references) {
66
+ if (reference.kind === "union" && !dependencies.includes(reference.discriminator)) {
67
+ dependencies.push(reference.discriminator);
68
+ }
69
+ }
70
+ return dependencies;
71
+ }
72
+ /**
73
+ * @internal Called by `SchemaRegistry` while it builds relations. A reference already held is
74
+ * skipped, not refused: both sides of one relation declare the same reference. So is a
75
+ * column referencing itself.
51
76
  */
52
- rowDecoder;
53
- /** Reads this column's value from a whole row, through {@link Column.rowDecoder} if set. */
54
- resolveRow(row) {
55
- const raw = row[this.name];
56
- if (!this.rowDecoder || raw === null || raw === undefined) {
57
- return this.resolve(raw);
77
+ _addReference(reference) {
78
+ if (this._referencesFrozen) {
79
+ throw new Error(`Column "${this.table.name}"."${this.name}" is already built; its references are fixed.`);
58
80
  }
59
- return this._validateRead(this.rowDecoder.decode(raw, row));
81
+ // A pair of a column with itself says nothing about where it points.
82
+ if (reference.kind === "table" && reference.column === this) {
83
+ return;
84
+ }
85
+ if (this._references.some((existing) => isSameReference(existing, reference))) {
86
+ return;
87
+ }
88
+ this._references = [...this._references, reference];
89
+ }
90
+ /** @internal Called by `SchemaRegistry` once every relation is built. */
91
+ _freezeReferences() {
92
+ this._referencesFrozen = true;
93
+ Object.freeze(this._references);
60
94
  }
61
- resolve(value) {
95
+ /**
96
+ * Follows this column's references to where each chain ends. A table reference continues
97
+ * through the column it points at; a union reference is an end of its own, since its member
98
+ * is only known per row — given the `row`, it resolves to the member column its discriminator
99
+ * names, or to nothing when the discriminator is null or names no member.
100
+ *
101
+ * Never throws: two ends can be legitimate for a plain key, so it is the caller who decides
102
+ * whether they are a conflict. `validateSchema` refuses a ring, so a built schema has none;
103
+ * one is still reported rather than looped on.
104
+ */
105
+ resolveReferences(row) {
106
+ const ends = [];
107
+ let ring;
108
+ const addEnd = (end) => {
109
+ const known = ends.some((existing) => existing.kind === "table" && end.kind === "table"
110
+ ? existing.column === end.column
111
+ : existing.kind === "union" &&
112
+ end.kind === "union" &&
113
+ isSameReference(existing.reference, end.reference));
114
+ if (!known) {
115
+ ends.push(end);
116
+ }
117
+ };
118
+ const walk = (column, path) => {
119
+ if (path.includes(column)) {
120
+ ring ??= [...path.slice(path.indexOf(column)), column];
121
+ return;
122
+ }
123
+ if (column.references.length === 0) {
124
+ addEnd({ kind: "table", column });
125
+ return;
126
+ }
127
+ for (const reference of column.references) {
128
+ if (reference.kind === "table") {
129
+ walk(reference.column, [...path, column]);
130
+ continue;
131
+ }
132
+ if (!row) {
133
+ addEnd({ kind: "union", reference });
134
+ continue;
135
+ }
136
+ // Only the column the row was read from has its discriminator in the row.
137
+ const key = column === this ? row[reference.discriminator.name] : undefined;
138
+ if (typeof key === "string" && Object.hasOwn(reference.members, key)) {
139
+ walk(reference.members[key], [...path, column]);
140
+ }
141
+ }
142
+ };
143
+ walk(this, []);
144
+ return ring ? { ends, ring } : { ends };
145
+ }
146
+ /**
147
+ * A value as read: decoded by the codec, passed through the `read` hook with the `row` it came
148
+ * from, then checked by the validator. `row` is the raw row, keyed by column name — the root
149
+ * row, a joined level or a union branch — and carries {@link Column.dependsOn}.
150
+ */
151
+ resolve(value, row = {}) {
62
152
  if (value === null || value === undefined) {
63
153
  if (this.notNull) {
64
154
  throw new Error(`Column ${this.name} cannot be null`);
65
155
  }
66
156
  return null;
67
157
  }
68
- return this._validateRead(this.codec.decode(value));
69
- }
70
- _validateRead(value) {
71
- return this.validator ? this.validator.read(value) : value;
158
+ const decoded = this.codec.decode(value);
159
+ const read = this.hooks?.read ? this.hooks.read(decoded, { column: this, row }) : decoded;
160
+ return this.validator ? this.validator.read(read) : read;
72
161
  }
73
- /** A write's value as sent: validated, if the column has a validator, then encoded. */
74
- _encodeInput = (input) => this.codec.encode(this.validator ? this.validator.write(input) : input);
162
+ /** A filter's value as sent: through the `write` hook, then encoded. Never validated. */
163
+ _encodeParam = (value) => this.codec.encode(this.hooks?.write ? this.hooks.write(value, { column: this }) : value);
164
+ /** A write's value as sent: validated, if the column has a validator, then as a filter's. */
165
+ _encodeInput = (input) => this._encodeParam(this.validator ? this.validator.write(input) : input);
75
166
  /**
76
- * Wraps a value as a parameter encoded by this column's codec. It is not validated: a filter
77
- * value is compared with stored values, not stored, and may be a fragment of one.
167
+ * Wraps a value as a parameter for this column: through its `write` hook, then encoded by its
168
+ * codec. It is not validated: a filter value is compared with stored values, not stored, and
169
+ * may be a fragment of one.
78
170
  *
79
171
  * This is the filter counterpart to {@link Column.getInsertValue} and
80
172
  * {@link Column.getUpdateValue}: a `date`, `bigint` or `interval` column only matches if
@@ -89,7 +181,7 @@ export class Column {
89
181
  if (isSQLNode(value)) {
90
182
  return value;
91
183
  }
92
- return new SQLParam(value, this.codec.encode);
184
+ return new SQLParam(value, this._encodeParam);
93
185
  }
94
186
  getInsertValue(value) {
95
187
  let param = value ?? undefined;
@@ -107,7 +199,7 @@ export class Column {
107
199
  getUpdateValue(value) {
108
200
  let param = value;
109
201
  if (param === undefined) {
110
- param = this.onUpdate?.() ?? undefined;
202
+ param = this.onUpdate?.(sql.identifier(this.name)) ?? undefined;
111
203
  }
112
204
  if (param instanceof SQLParam) {
113
205
  param = new SQLParam(param["_value"], this._encodeInput);
@@ -1 +1 @@
1
- {"version":3,"file":"column.js","sourceRoot":"","sources":["../../src/runtime/column.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,QAAQ,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAc9F,MAAM,OAAO,MAAM;IAKR,KAAK,CAA6C;IAC3D,6FAA6F;IACpF,SAAS,CAAiD;IAC1D,QAAQ,CAAgD;IACxD,QAAQ,CAAgD;IAExD,KAAK,CAAS;IACd,IAAI,CAAQ;IACrB,mEAAmE;IAC1D,QAAQ,CAAS;IAC1B,uFAAuF;IAC9E,WAAW,CAAoB;IACxC;;;;;OAKG;IACM,UAAU,CAAU;IACpB,OAAO,CAAqB;IAC5B,UAAU,CAAwB;IAClC,MAAM,CAAoB;IAC1B,QAAQ,CAAsB;IAC9B,SAAS,CAAuB;IAEzC,YAAY,KAAa,EAAE,UAA4C;QACrE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC;QAC5B,IAAI,CAAC,QAAQ,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;QACxC,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;QAC9C,IAAI,CAAC,UAAU;YACb,IAAI,CAAC,WAAW,KAAK,QAAQ,IAAI,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC3F,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,CAAC,QAAQ,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;QACxC,IAAI,CAAC,SAAS,GAAG,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,YAAY,QAAQ,EAAE,CAAC;YAC9B,KAAK,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAC3D,CAAC;QAED,yFAAyF;QACzF,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7C,KAAK,GAAG,IAAI,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACjD,CAAC;QAED,OAAO,KAAgB,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,GAAe;QACnB,oFAAoF;QACpF,mFAAmF;QACnF,uDAAuD;QACvD,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjF,CAAC;CACF","sourcesContent":["import { TypedObject } from \"../utils/index.js\";\nimport { ColumnConfig, ColumnDefinition, ColumnRuntimeType } from \"../definition/index.js\";\nimport { SQLContext, SQLNode, SQLParam, SQLStatement, isSQLNode, sql } from \"../sql/index.js\";\nimport { AnyTable } from \"./table.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyColumn = Column<any, any, any>;\n\n/** See {@link Column.rowDecoder}. */\nexport type ColumnRowDecoder = {\n /** Columns of the same table the decode reads; projected alongside this one. */\n readonly dependsOn: AnyColumn[];\n /** The value from the column's raw value and the raw row it was read from, keyed by column name. */\n decode(raw: unknown, row: Record<string, unknown>): unknown;\n};\n\nexport class Column<TName extends string, TConfig extends ColumnConfig, TTable extends AnyTable>\n implements SQLNode, TypedObject<TConfig>\n{\n declare readonly __type: TConfig;\n\n readonly codec: ColumnDefinition<TName, TConfig>[\"_codec\"];\n /** Checks writes before they are encoded and reads after they are decoded; never filters. */\n readonly validator: ColumnDefinition<TName, TConfig>[\"_validator\"];\n readonly onCreate: ColumnDefinition<TName, TConfig>[\"_onCreate\"];\n readonly onUpdate: ColumnDefinition<TName, TConfig>[\"_onUpdate\"];\n\n readonly table: TTable;\n readonly name: TName;\n /** The database type, or the domain's name for a domain column. */\n readonly dataType: string;\n /** The kind of value the column holds, for querying; see {@link ColumnRuntimeType}. */\n readonly runtimeType: ColumnRuntimeType;\n /**\n * Whether a JSON projection (a joined row, a union row) must carry this column as text. The\n * driver hands a root read of `bigint` and `numeric` to the codec as the database's exact\n * text; `row_to_json` would emit a JSON number, already rounded to a double before the codec\n * sees it. Cast, the codec gets the same string either way.\n */\n readonly textInJson: boolean;\n readonly notNull: TConfig[\"notNull\"];\n readonly primaryKey: TConfig[\"primaryKey\"];\n readonly unique: TConfig[\"unique\"];\n readonly readOnly: TConfig[\"readOnly\"];\n readonly tenantKey: TConfig[\"tenantKey\"];\n\n constructor(table: TTable, definition: ColumnDefinition<TName, TConfig>) {\n this.table = table;\n this.name = definition.name;\n this.dataType = definition[\"_dataType\"];\n this.runtimeType = definition[\"_runtimeType\"];\n this.textInJson =\n this.runtimeType === \"bigint\" || /^(bigint|int8|numeric|decimal)\\b/i.test(this.dataType);\n this.notNull = definition[\"_notNull\"];\n this.primaryKey = definition[\"_primaryKey\"];\n this.unique = definition[\"_unique\"];\n this.readOnly = definition[\"_readOnly\"];\n this.tenantKey = definition[\"_tenantKey\"];\n\n this.codec = definition[\"_codec\"];\n this.validator = definition[\"_validator\"];\n this.onCreate = definition[\"_onCreate\"];\n this.onUpdate = definition[\"_onUpdate\"];\n }\n\n /**\n * A decode that needs more than the column's own value — sibling columns of the same row.\n *\n * Unset by default; a client sets it on the built column when it is created, as it does a\n * bound codec, for a value whose meaning depends on another column (a polymorphic reference\n * whose target is named by a discriminator). When set, `dependsOn` is projected whenever this\n * column is selected, and the value is read through {@link Column.resolveRow} instead of\n * {@link Column.resolve}. Core applies no meaning to it.\n */\n readonly rowDecoder?: ColumnRowDecoder;\n\n /** Reads this column's value from a whole row, through {@link Column.rowDecoder} if set. */\n public resolveRow(row: Record<string, unknown>): TConfig[\"valueType\"] {\n const raw = row[this.name];\n\n if (!this.rowDecoder || raw === null || raw === undefined) {\n return this.resolve(raw as TConfig[\"rawType\"]);\n }\n\n return this._validateRead(this.rowDecoder.decode(raw, row) as TConfig[\"valueType\"]);\n }\n\n public resolve(value: TConfig[\"rawType\"]): TConfig[\"valueType\"] {\n if (value === null || value === undefined) {\n if (this.notNull) {\n throw new Error(`Column ${this.name} cannot be null`);\n }\n\n return null;\n }\n\n return this._validateRead(this.codec.decode(value));\n }\n\n private _validateRead(value: TConfig[\"valueType\"]): TConfig[\"valueType\"] {\n return this.validator ? this.validator.read(value) : value;\n }\n\n /** A write's value as sent: validated, if the column has a validator, then encoded. */\n private readonly _encodeInput = (input: TConfig[\"inputType\"]): TConfig[\"rawType\"] =>\n this.codec.encode(this.validator ? this.validator.write(input) : input);\n\n /**\n * Wraps a value as a parameter encoded by this column's codec. It is not validated: a filter\n * value is compared with stored values, not stored, and may be a fragment of one.\n *\n * This is the filter counterpart to {@link Column.getInsertValue} and\n * {@link Column.getUpdateValue}: a `date`, `bigint` or `interval` column only matches if\n * the value on the wire is written the same way it was stored. A value that is already an\n * `SQLNode` — another column, a sub-expression — is passed through untouched, since it is\n * SQL rather than a value to encode.\n *\n * Also the way to filter by a codec column in raw `$query`:\n * ``sql`${users.columns.createdAt} > ${users.columns.createdAt.param(cutoff)}` ``\n */\n public param(value: TConfig[\"valueType\"] | SQLNode): SQLNode {\n if (isSQLNode(value)) {\n return value;\n }\n\n return new SQLParam(value, this.codec.encode);\n }\n\n public getInsertValue(\n value: TConfig[\"inputType\"] | SQLParam<TConfig[\"inputType\"]> | null | undefined\n ) {\n let param = value ?? undefined;\n\n if (param === undefined) {\n param = this.onCreate?.() ?? sql.raw(\"DEFAULT\");\n }\n\n if (param instanceof SQLParam) {\n param = new SQLParam(param[\"_value\"], this._encodeInput);\n }\n\n if (!isSQLNode(param)) {\n param = new SQLParam(param, this._encodeInput);\n }\n\n return param as SQLNode;\n }\n\n getUpdateValue(value: TConfig[\"inputType\"] | SQLParam<TConfig[\"inputType\"]> | null | undefined) {\n let param = value;\n\n if (param === undefined) {\n param = this.onUpdate?.() ?? undefined;\n }\n\n if (param instanceof SQLParam) {\n param = new SQLParam(param[\"_value\"], this._encodeInput);\n }\n\n // `param`, not `value`: an `$onUpdate` result is a value to validate and encode as well.\n if (param !== undefined && !isSQLNode(param)) {\n param = new SQLParam(param, this._encodeInput);\n }\n\n return param as SQLNode;\n }\n\n toSQL(ctx: SQLContext): SQLStatement {\n // The table decides how it is named here: an alias when one is bound for it in this\n // scope, otherwise its plain name. Outside a select tree nothing is bound, so this\n // renders `\"table\".\"column\"` exactly as it always has.\n return sql.join([this.table.ref(), sql.identifier(this.name)], \".\").toSQL(ctx);\n }\n}\n"]}
1
+ {"version":3,"file":"column.js","sourceRoot":"","sources":["../../src/runtime/column.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,QAAQ,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE9F,OAAO,EAKL,eAAe,GAChB,MAAM,gBAAgB,CAAC;AAKxB,MAAM,OAAO,MAAM;IAKR,KAAK,CAA6C;IAC3D,6FAA6F;IACpF,SAAS,CAAiD;IACnE,uFAAuF;IAC9E,KAAK,CAA6C;IAClD,QAAQ,CAAgD;IACxD,QAAQ,CAAgD;IAExD,KAAK,CAAS;IACd,IAAI,CAAQ;IACrB,mEAAmE;IAC1D,QAAQ,CAAS;IAC1B,uFAAuF;IAC9E,WAAW,CAAoB;IACxC;;;;;OAKG;IACM,UAAU,CAAU;IACpB,OAAO,CAAqB;IAC5B,UAAU,CAAwB;IAClC,MAAM,CAAoB;IAC1B,QAAQ,CAAsB;IAC9B,SAAS,CAAS;IAE3B,YAAY,KAAa,EAAE,UAA4C,EAAE,SAAiB;QACxF,IAAI,CAAC,KAAK,GAAG,KA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AAC;IAC1B,CAAC;IAED,cAAc,CAAC,KAA+E;QAC5F,IAAI,KAAK,GAAG,KAAK,CAAC;QAElB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,SAAS,CAAC;QAClE,CAAC;QAED,IAAI,KAAK,YAAY,QAAQ,EAAE,CAAC;YAC9B,KAAK,GAAG,IAAI,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAC3D,CAAC;QAED,yFAAyF;QACzF,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7C,KAAK,GAAG,IAAI,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACjD,CAAC;QAED,OAAO,KAAgB,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,GAAe;QACnB,oFAAoF;QACpF,mFAAmF;QACnF,uDAAuD;QACvD,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjF,CAAC;CACF","sourcesContent":["import { TypedObject } from \"../utils/index.js\";\nimport { ColumnConfig, ColumnDefinition, ColumnRuntimeType } from \"../definition/index.js\";\nimport { SQLContext, SQLNode, SQLParam, SQLStatement, isSQLNode, sql } from \"../sql/index.js\";\nimport { AnyTable } from \"./table.js\";\nimport {\n ColumnReference,\n ComputedDiscriminator,\n ReferenceEnd,\n ResolvedReferences,\n isSameReference,\n} from \"./reference.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyColumn = Column<any, any, any>;\n\nexport class Column<TName extends string, TConfig extends ColumnConfig, TTable extends AnyTable>\n implements SQLNode, TypedObject<TConfig>\n{\n declare readonly __type: TConfig;\n\n readonly codec: ColumnDefinition<TName, TConfig>[\"_codec\"];\n /** Checks writes before they are encoded and reads after they are decoded; never filters. */\n readonly validator: ColumnDefinition<TName, TConfig>[\"_validator\"];\n /** Transforms around the codec that read this column or the row; see `ColumnHooks`. */\n readonly hooks: ColumnDefinition<TName, TConfig>[\"_hooks\"];\n readonly onCreate: ColumnDefinition<TName, TConfig>[\"_onCreate\"];\n readonly onUpdate: ColumnDefinition<TName, TConfig>[\"_onUpdate\"];\n\n readonly table: TTable;\n readonly name: TName;\n /** The database type, or the domain's name for a domain column. */\n readonly dataType: string;\n /** The kind of value the column holds, for querying; see {@link ColumnRuntimeType}. */\n readonly runtimeType: ColumnRuntimeType;\n /**\n * Whether a JSON projection (a joined row, a union row) must carry this column as text. The\n * driver hands a root read of `bigint` and `numeric` to the codec as the database's exact\n * text; `row_to_json` would emit a JSON number, already rounded to a double before the codec\n * sees it. Cast, the codec gets the same string either way.\n */\n readonly textInJson: boolean;\n readonly notNull: TConfig[\"notNull\"];\n readonly primaryKey: TConfig[\"primaryKey\"];\n readonly unique: TConfig[\"unique\"];\n readonly readOnly: TConfig[\"readOnly\"];\n readonly fieldName: string;\n\n constructor(table: TTable, definition: ColumnDefinition<TName, TConfig>, fieldName: string) {\n this.table = table;\n this.name = definition.name;\n this.dataType = definition[\"_dataType\"];\n this.runtimeType = definition[\"_runtimeType\"];\n this.textInJson =\n this.runtimeType === \"bigint\" || /^(bigint|int8|numeric|decimal)\\b/i.test(this.dataType);\n this.notNull = definition[\"_notNull\"];\n this.primaryKey = definition[\"_primaryKey\"];\n this.unique = definition[\"_unique\"];\n this.readOnly = definition[\"_readOnly\"];\n this.fieldName = fieldName;\n\n this.codec = definition[\"_codec\"];\n this.validator = definition[\"_validator\"];\n this.hooks = definition[\"_hooks\"];\n this.onCreate = definition[\"_onCreate\"];\n this.onUpdate = definition[\"_onUpdate\"];\n }\n\n private _references: ColumnReference[] = [];\n private _referencesFrozen = false;\n\n /**\n * What this column points at, one entry per relation that makes it a foreign key. Set by the\n * `SchemaRegistry` while it builds relations, for every column type; empty for a column no\n * relation references through. A column may point at more than one target — a plain key can\n * be a foreign key of two tables — and what that means is left to the reader.\n */\n public get references(): readonly ColumnReference[] {\n return this._references;\n }\n\n /**\n * What gives this column's value its meaning, read from the same row: the discriminator of\n * each union reference — a sibling column, or a {@link ComputedDiscriminator}. Projected alongside the column whenever it is\n * selected.\n */\n public get dependsOn(): readonly (AnyColumn | ComputedDiscriminator)[] {\n const dependencies: (AnyColumn | ComputedDiscriminator)[] = [];\n\n for (const reference of this._references) {\n if (reference.kind === \"union\" && !dependencies.includes(reference.discriminator)) {\n dependencies.push(reference.discriminator);\n }\n }\n\n return dependencies;\n }\n\n /**\n * @internal Called by `SchemaRegistry` while it builds relations. A reference already held is\n * skipped, not refused: both sides of one relation declare the same reference. So is a\n * column referencing itself.\n */\n public _addReference(reference: ColumnReference): void {\n if (this._referencesFrozen) {\n throw new Error(\n `Column \"${this.table.name}\".\"${this.name}\" is already built; its references are fixed.`\n );\n }\n\n // A pair of a column with itself says nothing about where it points.\n if (reference.kind === \"table\" && reference.column === this) {\n return;\n }\n\n if (this._references.some((existing) => isSameReference(existing, reference))) {\n return;\n }\n\n this._references = [...this._references, reference];\n }\n\n /** @internal Called by `SchemaRegistry` once every relation is built. */\n public _freezeReferences(): void {\n this._referencesFrozen = true;\n Object.freeze(this._references);\n }\n\n /**\n * Follows this column's references to where each chain ends. A table reference continues\n * through the column it points at; a union reference is an end of its own, since its member\n * is only known per row — given the `row`, it resolves to the member column its discriminator\n * names, or to nothing when the discriminator is null or names no member.\n *\n * Never throws: two ends can be legitimate for a plain key, so it is the caller who decides\n * whether they are a conflict. `validateSchema` refuses a ring, so a built schema has none;\n * one is still reported rather than looped on.\n */\n public resolveReferences(row?: Record<string, unknown>): ResolvedReferences {\n const ends: ReferenceEnd[] = [];\n let ring: AnyColumn[] | undefined;\n\n const addEnd = (end: ReferenceEnd) => {\n const known = ends.some((existing) =>\n existing.kind === \"table\" && end.kind === \"table\"\n ? existing.column === end.column\n : existing.kind === \"union\" &&\n end.kind === \"union\" &&\n isSameReference(existing.reference, end.reference)\n );\n\n if (!known) {\n ends.push(end);\n }\n };\n\n const walk = (column: AnyColumn, path: AnyColumn[]) => {\n if (path.includes(column)) {\n ring ??= [...path.slice(path.indexOf(column)), column];\n return;\n }\n\n if (column.references.length === 0) {\n addEnd({ kind: \"table\", column });\n return;\n }\n\n for (const reference of column.references) {\n if (reference.kind === \"table\") {\n walk(reference.column, [...path, column]);\n continue;\n }\n\n if (!row) {\n addEnd({ kind: \"union\", reference });\n continue;\n }\n\n // Only the column the row was read from has its discriminator in the row.\n const key = column === this ? row[reference.discriminator.name] : undefined;\n\n if (typeof key === \"string\" && Object.hasOwn(reference.members, key)) {\n walk(reference.members[key], [...path, column]);\n }\n }\n };\n\n walk(this, []);\n\n return ring ? { ends, ring } : { ends };\n }\n\n /**\n * A value as read: decoded by the codec, passed through the `read` hook with the `row` it came\n * from, then checked by the validator. `row` is the raw row, keyed by column name — the root\n * row, a joined level or a union branch — and carries {@link Column.dependsOn}.\n */\n public resolve(\n value: TConfig[\"rawType\"],\n row: Readonly<Record<string, unknown>> = {}\n ): TConfig[\"valueType\"] {\n if (value === null || value === undefined) {\n if (this.notNull) {\n throw new Error(`Column ${this.name} cannot be null`);\n }\n\n return null;\n }\n\n const decoded = this.codec.decode(value);\n const read = this.hooks?.read ? this.hooks.read(decoded, { column: this, row }) : decoded;\n\n return this.validator ? this.validator.read(read) : read;\n }\n\n /** A filter's value as sent: through the `write` hook, then encoded. Never validated. */\n private readonly _encodeParam = (value: TConfig[\"valueType\"]): TConfig[\"rawType\"] =>\n this.codec.encode(this.hooks?.write ? this.hooks.write(value, { column: this }) : value);\n\n /** A write's value as sent: validated, if the column has a validator, then as a filter's. */\n private readonly _encodeInput = (input: TConfig[\"inputType\"]): TConfig[\"rawType\"] =>\n this._encodeParam(this.validator ? this.validator.write(input) : input);\n\n /**\n * Wraps a value as a parameter for this column: through its `write` hook, then encoded by its\n * codec. It is not validated: a filter value is compared with stored values, not stored, and\n * may be a fragment of one.\n *\n * This is the filter counterpart to {@link Column.getInsertValue} and\n * {@link Column.getUpdateValue}: a `date`, `bigint` or `interval` column only matches if\n * the value on the wire is written the same way it was stored. A value that is already an\n * `SQLNode` — another column, a sub-expression — is passed through untouched, since it is\n * SQL rather than a value to encode.\n *\n * Also the way to filter by a codec column in raw `$query`:\n * ``sql`${users.columns.createdAt} > ${users.columns.createdAt.param(cutoff)}` ``\n */\n public param(value: TConfig[\"valueType\"] | SQLNode): SQLNode {\n if (isSQLNode(value)) {\n return value;\n }\n\n return new SQLParam(value, this._encodeParam);\n }\n\n public getInsertValue(\n value: TConfig[\"inputType\"] | SQLParam<TConfig[\"inputType\"]> | null | undefined\n ) {\n let param = value ?? undefined;\n\n if (param === undefined) {\n param = this.onCreate?.() ?? sql.raw(\"DEFAULT\");\n }\n\n if (param instanceof SQLParam) {\n param = new SQLParam(param[\"_value\"], this._encodeInput);\n }\n\n if (!isSQLNode(param)) {\n param = new SQLParam(param, this._encodeInput);\n }\n\n return param as SQLNode;\n }\n\n getUpdateValue(value: TConfig[\"inputType\"] | SQLParam<TConfig[\"inputType\"]> | null | undefined) {\n let param = value;\n\n if (param === undefined) {\n param = this.onUpdate?.(sql.identifier(this.name)) ?? undefined;\n }\n\n if (param instanceof SQLParam) {\n param = new SQLParam(param[\"_value\"], this._encodeInput);\n }\n\n // `param`, not `value`: an `$onUpdate` result is a value to validate and encode as well.\n if (param !== undefined && !isSQLNode(param)) {\n param = new SQLParam(param, this._encodeInput);\n }\n\n return param as SQLNode;\n }\n\n toSQL(ctx: SQLContext): SQLStatement {\n // The table decides how it is named here: an alias when one is bound for it in this\n // scope, otherwise its plain name. Outside a select tree nothing is bound, so this\n // renders `\"table\".\"column\"` exactly as it always has.\n return sql.join([this.table.ref(), sql.identifier(this.name)], \".\").toSQL(ctx);\n }\n}\n"]}