dsqlbase 0.2.0 → 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 +42 -0
  2. package/README.md +41 -60
  3. package/dist/client/clients/base.d.ts +20 -0
  4. package/dist/client/clients/base.d.ts.map +1 -0
  5. package/dist/client/clients/base.js +52 -0
  6. package/dist/client/clients/base.js.map +1 -0
  7. package/dist/client/clients/dsql.d.ts +24 -0
  8. package/dist/client/clients/dsql.d.ts.map +1 -0
  9. package/dist/client/clients/dsql.js +31 -0
  10. package/dist/client/clients/dsql.js.map +1 -0
  11. package/dist/client/clients/index.d.ts +6 -0
  12. package/dist/client/clients/index.d.ts.map +1 -0
  13. package/dist/client/clients/index.js +6 -0
  14. package/dist/client/clients/index.js.map +1 -0
  15. package/dist/client/clients/model.d.ts +169 -0
  16. package/dist/client/clients/model.d.ts.map +1 -0
  17. package/dist/client/{model/client.js → clients/model.js} +82 -53
  18. package/dist/client/clients/model.js.map +1 -0
  19. package/dist/client/clients/transaction.d.ts +9 -0
  20. package/dist/client/clients/transaction.d.ts.map +1 -0
  21. package/dist/client/{transaction/transaction-client.js → clients/transaction.js} +7 -7
  22. package/dist/client/clients/transaction.js.map +1 -0
  23. package/dist/client/clients/union.d.ts +39 -0
  24. package/dist/client/clients/union.d.ts.map +1 -0
  25. package/dist/client/clients/union.js +54 -0
  26. package/dist/client/clients/union.js.map +1 -0
  27. package/dist/client/create.d.ts +15 -18
  28. package/dist/client/create.d.ts.map +1 -1
  29. package/dist/client/create.js +10 -27
  30. package/dist/client/create.js.map +1 -1
  31. package/dist/client/index.d.ts +4 -8
  32. package/dist/client/index.d.ts.map +1 -1
  33. package/dist/client/index.js +3 -6
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/normalizers/base.d.ts +467 -0
  36. package/dist/client/normalizers/base.d.ts.map +1 -0
  37. package/dist/client/normalizers/base.js.map +1 -0
  38. package/dist/client/normalizers/context.d.ts +14 -0
  39. package/dist/client/normalizers/context.d.ts.map +1 -0
  40. package/dist/client/normalizers/context.js +16 -0
  41. package/dist/client/normalizers/context.js.map +1 -0
  42. package/dist/client/normalizers/index.d.ts +8 -0
  43. package/dist/client/normalizers/index.d.ts.map +1 -0
  44. package/dist/client/normalizers/index.js +8 -0
  45. package/dist/client/normalizers/index.js.map +1 -0
  46. package/dist/client/normalizers/pagination.d.ts +87 -0
  47. package/dist/client/normalizers/pagination.d.ts.map +1 -0
  48. package/dist/client/normalizers/pagination.js +245 -0
  49. package/dist/client/normalizers/pagination.js.map +1 -0
  50. package/dist/client/normalizers/request.d.ts +41 -0
  51. package/dist/client/normalizers/request.d.ts.map +1 -0
  52. package/dist/client/normalizers/request.js +346 -0
  53. package/dist/client/normalizers/request.js.map +1 -0
  54. package/dist/client/normalizers/rules.d.ts +132 -0
  55. package/dist/client/normalizers/rules.d.ts.map +1 -0
  56. package/dist/client/normalizers/rules.js +82 -0
  57. package/dist/client/normalizers/rules.js.map +1 -0
  58. package/dist/client/normalizers/utils.d.ts +6 -0
  59. package/dist/client/normalizers/utils.d.ts.map +1 -0
  60. package/dist/client/normalizers/utils.js +18 -0
  61. package/dist/client/normalizers/utils.js.map +1 -0
  62. package/dist/client/normalizers/where.d.ts +39 -0
  63. package/dist/client/normalizers/where.d.ts.map +1 -0
  64. package/dist/client/normalizers/where.js +230 -0
  65. package/dist/client/normalizers/where.js.map +1 -0
  66. package/dist/client/utils/occ-retry.d.ts.map +1 -0
  67. package/dist/client/utils/occ-retry.js.map +1 -0
  68. package/dist/index.d.ts +2 -3
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +2 -3
  71. package/dist/index.js.map +1 -1
  72. package/dist/schema/columns/guid.d.ts +21 -21
  73. package/dist/schema/columns/guid.d.ts.map +1 -1
  74. package/dist/schema/columns/guid.js +24 -25
  75. package/dist/schema/columns/guid.js.map +1 -1
  76. package/dist/schema/columns/numeric.d.ts +43 -2
  77. package/dist/schema/columns/numeric.d.ts.map +1 -1
  78. package/dist/schema/columns/numeric.js +42 -12
  79. package/dist/schema/columns/numeric.js.map +1 -1
  80. package/dist/schema/index.d.ts +1 -2
  81. package/dist/schema/index.d.ts.map +1 -1
  82. package/dist/schema/index.js +0 -2
  83. package/dist/schema/index.js.map +1 -1
  84. package/dist/schema/relations.d.ts +22 -13
  85. package/dist/schema/relations.d.ts.map +1 -1
  86. package/dist/schema/relations.js +9 -1
  87. package/dist/schema/relations.js.map +1 -1
  88. package/dist/schema/table.d.ts +2 -2
  89. package/dist/schema/table.d.ts.map +1 -1
  90. package/dist/schema/table.js.map +1 -1
  91. package/dist/schema/union.d.ts +13 -8
  92. package/dist/schema/union.d.ts.map +1 -1
  93. package/dist/schema/union.js +14 -9
  94. package/dist/schema/union.js.map +1 -1
  95. package/dist/schema/utils/global-id.d.ts +3 -3
  96. package/dist/schema/utils/global-id.js +3 -3
  97. package/dist/schema/utils/global-id.js.map +1 -1
  98. package/dist/schema/utils/guid-hooks.d.ts +49 -0
  99. package/dist/schema/utils/guid-hooks.d.ts.map +1 -0
  100. package/dist/schema/utils/guid-hooks.js +155 -0
  101. package/dist/schema/utils/guid-hooks.js.map +1 -0
  102. package/package.json +8 -6
  103. package/dist/client/database/base.d.ts +0 -99
  104. package/dist/client/database/base.d.ts.map +0 -1
  105. package/dist/client/database/base.js +0 -216
  106. package/dist/client/database/base.js.map +0 -1
  107. package/dist/client/database/client.d.ts +0 -26
  108. package/dist/client/database/client.d.ts.map +0 -1
  109. package/dist/client/database/client.js +0 -47
  110. package/dist/client/database/client.js.map +0 -1
  111. package/dist/client/database/index.d.ts +0 -65
  112. package/dist/client/database/index.d.ts.map +0 -1
  113. package/dist/client/database/index.js +0 -3
  114. package/dist/client/database/index.js.map +0 -1
  115. package/dist/client/model/base.d.ts +0 -747
  116. package/dist/client/model/base.d.ts.map +0 -1
  117. package/dist/client/model/base.js.map +0 -1
  118. package/dist/client/model/client.d.ts +0 -139
  119. package/dist/client/model/client.d.ts.map +0 -1
  120. package/dist/client/model/client.js.map +0 -1
  121. package/dist/client/model/filters.d.ts +0 -276
  122. package/dist/client/model/filters.d.ts.map +0 -1
  123. package/dist/client/model/filters.js +0 -470
  124. package/dist/client/model/filters.js.map +0 -1
  125. package/dist/client/model/normalizer.d.ts +0 -143
  126. package/dist/client/model/normalizer.d.ts.map +0 -1
  127. package/dist/client/model/normalizer.js +0 -641
  128. package/dist/client/model/normalizer.js.map +0 -1
  129. package/dist/client/nodes.d.ts +0 -62
  130. package/dist/client/nodes.d.ts.map +0 -1
  131. package/dist/client/nodes.js +0 -378
  132. package/dist/client/nodes.js.map +0 -1
  133. package/dist/client/pagination/cursor.d.ts +0 -40
  134. package/dist/client/pagination/cursor.d.ts.map +0 -1
  135. package/dist/client/pagination/cursor.js +0 -79
  136. package/dist/client/pagination/cursor.js.map +0 -1
  137. package/dist/client/pagination/page.d.ts +0 -23
  138. package/dist/client/pagination/page.d.ts.map +0 -1
  139. package/dist/client/pagination/page.js +0 -37
  140. package/dist/client/pagination/page.js.map +0 -1
  141. package/dist/client/transaction/index.d.ts +0 -2
  142. package/dist/client/transaction/index.d.ts.map +0 -1
  143. package/dist/client/transaction/index.js +0 -2
  144. package/dist/client/transaction/index.js.map +0 -1
  145. package/dist/client/transaction/occ-retry.d.ts.map +0 -1
  146. package/dist/client/transaction/occ-retry.js.map +0 -1
  147. package/dist/client/transaction/transaction-client.d.ts +0 -9
  148. package/dist/client/transaction/transaction-client.d.ts.map +0 -1
  149. package/dist/client/transaction/transaction-client.js.map +0 -1
  150. package/dist/client/union/client.d.ts +0 -55
  151. package/dist/client/union/client.d.ts.map +0 -1
  152. package/dist/client/union/client.js +0 -74
  153. package/dist/client/union/client.js.map +0 -1
  154. package/dist/schema/embedded.d.ts +0 -31
  155. package/dist/schema/embedded.d.ts.map +0 -1
  156. package/dist/schema/embedded.js +0 -33
  157. package/dist/schema/embedded.js.map +0 -1
  158. package/dist/schema/tenant.d.ts +0 -31
  159. package/dist/schema/tenant.d.ts.map +0 -1
  160. package/dist/schema/tenant.js +0 -33
  161. package/dist/schema/tenant.js.map +0 -1
  162. /package/dist/client/{model → normalizers}/base.js +0 -0
  163. /package/dist/client/{transaction → utils}/occ-retry.d.ts +0 -0
  164. /package/dist/client/{transaction → utils}/occ-retry.js +0 -0
@@ -0,0 +1,49 @@
1
+ import { AnyColumn, ColumnHooks, ComputedDiscriminator } from "@dsqlbase/core";
2
+ /** What a `guid()` column's values name: one node, the same for every row. */
3
+ export type GuidBinding = {
4
+ /** The node this column's values name. */
5
+ readonly key: string;
6
+ /** The field the target node's primary key is addressed by (`id`, `membershipId`, …). */
7
+ readonly keyField: string;
8
+ };
9
+ /**
10
+ * What a `guid()` column whose node is named per row names: a key pointing at a union's member
11
+ * — the `from` of a belongs-to a union, or the foreign key of a relation whose source is one.
12
+ * The discriminator names each row's member alias, which is the node key.
13
+ */
14
+ export type DynamicGuidBinding = {
15
+ /**
16
+ * What names each row's member: a stored column, or a discriminator core computes when the
17
+ * query runs, when the relation declares none. Either is read from the row by its `name`.
18
+ */
19
+ readonly discriminator: AnyColumn | ComputedDiscriminator;
20
+ /**
21
+ * The stored discriminator's field name, as `create` / `update` data names it; `undefined`
22
+ * for a computed one, which there is nothing to write to.
23
+ */
24
+ readonly discriminatorField: string | undefined;
25
+ /** Member alias → the field its key is addressed by in a payload (`id`, …). */
26
+ readonly members: Readonly<Record<string, string>>;
27
+ };
28
+ /**
29
+ * The hooks every `guid()` column carries: a read wraps the raw uuid as a global id, a write or
30
+ * a filter unwraps one. What an id names comes from the column's references, read when the hook
31
+ * first runs — they are linked and frozen by then — and kept per built column.
32
+ *
33
+ * One object for every guid column, which is what lets `validateSchema` require both sides of a
34
+ * relation pair to carry it, and refuse a guid column referencing two targets.
35
+ */
36
+ export declare const guidHooks: ColumnHooks<string>;
37
+ /** The binding of a `guid()` column; `undefined` for a column that names one node per row, or is no guid. */
38
+ export declare function getGuidBinding(column: AnyColumn): GuidBinding | undefined;
39
+ /** The binding of a `guid()` column that names its node per row; `undefined` otherwise. */
40
+ export declare function getDynamicGuidBinding(column: AnyColumn): DynamicGuidBinding | undefined;
41
+ /**
42
+ * The member a wrapped id names, checked against the union: its key must be a member, and its
43
+ * payload must carry that member's key field. `undefined` for a value that is not a global id.
44
+ */
45
+ export declare function decodeMemberId(value: unknown, members: Readonly<Record<string, string>>): {
46
+ key: string;
47
+ value: string;
48
+ } | undefined;
49
+ //# sourceMappingURL=guid-hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guid-hooks.d.ts","sourceRoot":"","sources":["../../../src/schema/utils/guid-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAET,WAAW,EACX,qBAAqB,EAEtB,MAAM,gBAAgB,CAAC;AAGxB,8EAA8E;AAC9E,MAAM,MAAM,WAAW,GAAG;IACxB,0CAA0C;IAC1C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAErB,yFAAyF;IACzF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,SAAS,GAAG,qBAAqB,CAAC;IAE1D;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IAEhD,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,SAAS,EAAE,WAAW,CAAC,MAAM,CAiDzC,CAAC;AAEF,6GAA6G;AAC7G,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,GAAG,WAAW,GAAG,SAAS,CAOzE;AAED,2FAA2F;AAC3F,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,GAAG,kBAAkB,GAAG,SAAS,CAOvF;AAkED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACxC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CA4B5C"}
@@ -0,0 +1,155 @@
1
+ import { ComputedDiscriminator, } from "@dsqlbase/core";
2
+ import { GlobalIdError, decodeGlobalId, encodeGlobalId, isGlobalId } from "./global-id.js";
3
+ /**
4
+ * The hooks every `guid()` column carries: a read wraps the raw uuid as a global id, a write or
5
+ * a filter unwraps one. What an id names comes from the column's references, read when the hook
6
+ * first runs — they are linked and frozen by then — and kept per built column.
7
+ *
8
+ * One object for every guid column, which is what lets `validateSchema` require both sides of a
9
+ * relation pair to carry it, and refuse a guid column referencing two targets.
10
+ */
11
+ export const guidHooks = {
12
+ filter(value, { column }) {
13
+ if (!isGlobalId(value)) {
14
+ return value;
15
+ }
16
+ const { pk } = decodeGlobalId(value);
17
+ if (!Object.hasOwn(pk, column.fieldName)) {
18
+ throw new Error(`Global id for "${column.fieldName}" carries ${Object.keys(pk).join(", ")} rather than its key "${column.fieldName}".`);
19
+ }
20
+ return pk[column.fieldName];
21
+ },
22
+ read(value, { column, row }) {
23
+ const binding = bindingOf(column);
24
+ if ("key" in binding) {
25
+ return encodeGlobalId(binding.key, { [binding.keyField]: value });
26
+ }
27
+ // A NULL discriminator, or one naming no member, reads the id raw.
28
+ const member = row?.[binding.discriminator.name];
29
+ return typeof member === "string" && Object.hasOwn(binding.members, member)
30
+ ? encodeGlobalId(member, { [binding.members[member]]: value })
31
+ : value;
32
+ },
33
+ write(value, { column }) {
34
+ const binding = bindingOf(column);
35
+ return "key" in binding
36
+ ? unwrap(value, binding.key, binding.keyField)
37
+ : (decodeMemberId(value, binding.members)?.value ?? value);
38
+ },
39
+ writeDeps(value) {
40
+ if (!isGlobalId(value)) {
41
+ return null;
42
+ }
43
+ const { key } = decodeGlobalId(value);
44
+ return key;
45
+ },
46
+ };
47
+ /** The binding of a `guid()` column; `undefined` for a column that names one node per row, or is no guid. */
48
+ export function getGuidBinding(column) {
49
+ if (column.hooks !== guidHooks) {
50
+ return undefined;
51
+ }
52
+ const binding = bindingOf(column);
53
+ return "key" in binding ? binding : undefined;
54
+ }
55
+ /** The binding of a `guid()` column that names its node per row; `undefined` otherwise. */
56
+ export function getDynamicGuidBinding(column) {
57
+ if (column.hooks !== guidHooks) {
58
+ return undefined;
59
+ }
60
+ const binding = bindingOf(column);
61
+ return "discriminator" in binding ? binding : undefined;
62
+ }
63
+ /**
64
+ * Bindings per built column. A built column belongs to one registry, so a binding — which
65
+ * depends on the alias a table is exported under — never leaks into another client over the
66
+ * same schema.
67
+ */
68
+ const BINDINGS = new WeakMap();
69
+ function bindingOf(column) {
70
+ let binding = BINDINGS.get(column);
71
+ if (!binding) {
72
+ binding = resolveBinding(column);
73
+ BINDINGS.set(column, binding);
74
+ }
75
+ return binding;
76
+ }
77
+ /**
78
+ * What a guid column's ids name, from where its references end:
79
+ *
80
+ * - no reference: its own table and field — a primary key, or a column no relation points
81
+ * through;
82
+ * - a chain of table references: the column it ends at — `articles.authorId` reads as an
83
+ * authors id through `articles.author`;
84
+ * - a union reference: the member its row's discriminator names.
85
+ *
86
+ * `validateSchema` has refused every other shape — two targets, a ring, a member reached
87
+ * through no unique key — so the first end found is the only one.
88
+ */
89
+ function resolveBinding(column) {
90
+ const { ends } = column.resolveReferences();
91
+ const end = ends.find((candidate) => candidate.kind === "union") ?? ends[0];
92
+ if (!end || (end.kind === "table" && end.column === column)) {
93
+ return { key: column.table.alias, keyField: fieldOf(column.table, column) };
94
+ }
95
+ if (end.kind === "table") {
96
+ return { key: end.column.table.alias, keyField: fieldOf(end.column.table, end.column) };
97
+ }
98
+ const { discriminator, members } = end.reference;
99
+ return {
100
+ discriminator,
101
+ discriminatorField: discriminator instanceof ComputedDiscriminator
102
+ ? undefined
103
+ : fieldOf(discriminator.table, discriminator),
104
+ members: Object.fromEntries(Object.entries(members).map(([member, target]) => [member, fieldOf(target.table, target)])),
105
+ };
106
+ }
107
+ /** The field a built column is declared under on its table. */
108
+ function fieldOf(table, column) {
109
+ const entry = table.getColumnEntries().find(([, candidate]) => candidate === column);
110
+ return entry?.[0] ?? column.name;
111
+ }
112
+ /**
113
+ * The member a wrapped id names, checked against the union: its key must be a member, and its
114
+ * payload must carry that member's key field. `undefined` for a value that is not a global id.
115
+ */
116
+ export function decodeMemberId(value, members) {
117
+ if (!isGlobalId(value)) {
118
+ return undefined;
119
+ }
120
+ const { key, pk } = decodeGlobalId(value);
121
+ const keyField = members[key];
122
+ if (keyField === undefined) {
123
+ throw new GlobalIdError("key_mismatch", `Global id for "${key}" cannot be stored here: this column holds ids for ` +
124
+ `${Object.keys(members)
125
+ .map((member) => `"${member}"`)
126
+ .join(", ")}.`);
127
+ }
128
+ if (!Object.hasOwn(pk, keyField)) {
129
+ throw new GlobalIdError("key_mismatch", `Global id for "${key}" carries ${Object.keys(pk)
130
+ .map((field) => `"${field}"`)
131
+ .join(", ")} rather than its key "${keyField}".`);
132
+ }
133
+ return { key, value: pk[keyField] };
134
+ }
135
+ /**
136
+ * Reads a written or filtered value back down to what the column stores.
137
+ *
138
+ * Lenient by design: a raw uuid is accepted, because ids reach an application from places
139
+ * that never went through the ORM. A *wrapped* id, though, is checked — that is the whole
140
+ * point of carrying the table in the value. `decodeGlobalId` catches the wrong table; the
141
+ * field check below catches a payload that names the right table but the wrong key.
142
+ */
143
+ function unwrap(value, alias, fieldName) {
144
+ if (!isGlobalId(value)) {
145
+ return value;
146
+ }
147
+ const { pk } = decodeGlobalId(value, alias);
148
+ if (!Object.hasOwn(pk, fieldName)) {
149
+ throw new GlobalIdError("key_mismatch", `Global id for "${alias}" carries ${Object.keys(pk)
150
+ .map((field) => `"${field}"`)
151
+ .join(", ")} rather than its key "${fieldName}".`);
152
+ }
153
+ return pk[fieldName];
154
+ }
155
+ //# sourceMappingURL=guid-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guid-hooks.js","sourceRoot":"","sources":["../../../src/schema/utils/guid-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,qBAAqB,GAEtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAiC3F;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,SAAS,GAAwB;IAC5C,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE;QACtB,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YACvB,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,EAAE,EAAE,EAAE,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;QAErC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,KAAK,CACb,kBAAkB,MAAM,CAAC,SAAS,aAAa,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CACjE,IAAI,CACL,yBAAyB,MAAM,CAAC,SAAS,IAAI,CAC/C,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC9B,CAAC;IACD,IAAI,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE;QACzB,MAAM,OAAO,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;QAElC,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;YACrB,OAAO,cAAc,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,mEAAmE;QACnE,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAA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;IACJ,CAAC;IAED,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import {\n AnyColumn,\n AnyTable,\n ColumnHooks,\n ComputedDiscriminator,\n ReferenceEnd,\n} from \"@dsqlbase/core\";\nimport { GlobalIdError, decodeGlobalId, encodeGlobalId, isGlobalId } from \"./global-id.js\";\n\n/** What a `guid()` column's values name: one node, the same for every row. */\nexport type GuidBinding = {\n /** The node this column's values name. */\n readonly key: string;\n\n /** The field the target node's primary key is addressed by (`id`, `membershipId`, …). */\n readonly keyField: string;\n};\n\n/**\n * What a `guid()` column whose node is named per row names: a key pointing at a union's member\n * — the `from` of a belongs-to a union, or the foreign key of a relation whose source is one.\n * The discriminator names each row's member alias, which is the node key.\n */\nexport type DynamicGuidBinding = {\n /**\n * What names each row's member: a stored column, or a discriminator core computes when the\n * query runs, when the relation declares none. Either is read from the row by its `name`.\n */\n readonly discriminator: AnyColumn | ComputedDiscriminator;\n\n /**\n * The stored discriminator's field name, as `create` / `update` data names it; `undefined`\n * for a computed one, which there is nothing to write to.\n */\n readonly discriminatorField: string | undefined;\n\n /** Member alias → the field its key is addressed by in a payload (`id`, …). */\n readonly members: Readonly<Record<string, string>>;\n};\n\n/**\n * The hooks every `guid()` column carries: a read wraps the raw uuid as a global id, a write or\n * a filter unwraps one. What an id names comes from the column's references, read when the hook\n * first runs — they are linked and frozen by then — and kept per built column.\n *\n * One object for every guid column, which is what lets `validateSchema` require both sides of a\n * relation pair to carry it, and refuse a guid column referencing two targets.\n */\nexport const guidHooks: ColumnHooks<string> = {\n filter(value, { column }) {\n if (!isGlobalId(value)) {\n return value;\n }\n\n const { pk } = decodeGlobalId(value);\n\n if (!Object.hasOwn(pk, column.fieldName)) {\n throw new Error(\n `Global id for \"${column.fieldName}\" carries ${Object.keys(pk).join(\n \", \"\n )} rather than its key \"${column.fieldName}\".`\n );\n }\n\n return pk[column.fieldName];\n },\n read(value, { column, row }) {\n const binding = bindingOf(column);\n\n if (\"key\" in binding) {\n return encodeGlobalId(binding.key, { [binding.keyField]: value });\n }\n\n // A NULL discriminator, or one naming no member, reads the id raw.\n const member = row?.[binding.discriminator.name];\n\n return typeof member === \"string\" && Object.hasOwn(binding.members, member)\n ? encodeGlobalId(member, { [binding.members[member]]: value })\n : value;\n },\n\n write(value, { column }) {\n const binding = bindingOf(column);\n\n return \"key\" in binding\n ? unwrap(value, binding.key, binding.keyField)\n : (decodeMemberId(value, binding.members)?.value ?? value);\n },\n\n writeDeps(value) {\n if (!isGlobalId(value)) {\n return null;\n }\n\n const { key } = decodeGlobalId(value);\n return key;\n },\n};\n\n/** The binding of a `guid()` column; `undefined` for a column that names one node per row, or is no guid. */\nexport function getGuidBinding(column: AnyColumn): GuidBinding | undefined {\n if (column.hooks !== guidHooks) {\n return undefined;\n }\n\n const binding = bindingOf(column);\n return \"key\" in binding ? binding : undefined;\n}\n\n/** The binding of a `guid()` column that names its node per row; `undefined` otherwise. */\nexport function getDynamicGuidBinding(column: AnyColumn): DynamicGuidBinding | undefined {\n if (column.hooks !== guidHooks) {\n return undefined;\n }\n\n const binding = bindingOf(column);\n return \"discriminator\" in binding ? binding : undefined;\n}\n\n/**\n * Bindings per built column. A built column belongs to one registry, so a binding — which\n * depends on the alias a table is exported under — never leaks into another client over the\n * same schema.\n */\nconst BINDINGS = new WeakMap<AnyColumn, GuidBinding | DynamicGuidBinding>();\n\nfunction bindingOf(column: AnyColumn): GuidBinding | DynamicGuidBinding {\n let binding = BINDINGS.get(column);\n\n if (!binding) {\n binding = resolveBinding(column);\n BINDINGS.set(column, binding);\n }\n\n return binding;\n}\n\n/**\n * What a guid column's ids name, from where its references end:\n *\n * - no reference: its own table and field — a primary key, or a column no relation points\n * through;\n * - a chain of table references: the column it ends at — `articles.authorId` reads as an\n * authors id through `articles.author`;\n * - a union reference: the member its row's discriminator names.\n *\n * `validateSchema` has refused every other shape — two targets, a ring, a member reached\n * through no unique key — so the first end found is the only one.\n */\nfunction resolveBinding(column: AnyColumn): GuidBinding | DynamicGuidBinding {\n const { ends } = column.resolveReferences();\n const end: ReferenceEnd | undefined =\n ends.find((candidate) => candidate.kind === \"union\") ?? ends[0];\n\n if (!end || (end.kind === \"table\" && end.column === column)) {\n return { key: column.table.alias, keyField: fieldOf(column.table, column) };\n }\n\n if (end.kind === \"table\") {\n return { key: end.column.table.alias, keyField: fieldOf(end.column.table, end.column) };\n }\n\n const { discriminator, members } = end.reference;\n\n return {\n discriminator,\n discriminatorField:\n discriminator instanceof ComputedDiscriminator\n ? undefined\n : fieldOf(discriminator.table, discriminator),\n members: Object.fromEntries(\n Object.entries(members).map(([member, target]) => [member, fieldOf(target.table, target)])\n ),\n };\n}\n\n/** The field a built column is declared under on its table. */\nfunction fieldOf(table: AnyTable, column: AnyColumn): string {\n const entry = table.getColumnEntries().find(([, candidate]) => candidate === column);\n\n return entry?.[0] ?? column.name;\n}\n\n/**\n * The member a wrapped id names, checked against the union: its key must be a member, and its\n * payload must carry that member's key field. `undefined` for a value that is not a global id.\n */\nexport function decodeMemberId(\n value: unknown,\n members: Readonly<Record<string, string>>\n): { key: string; value: string } | undefined {\n if (!isGlobalId(value)) {\n return undefined;\n }\n\n const { key, pk } = decodeGlobalId(value);\n const keyField = members[key];\n\n if (keyField === undefined) {\n throw new GlobalIdError(\n \"key_mismatch\",\n `Global id for \"${key}\" cannot be stored here: this column holds ids for ` +\n `${Object.keys(members)\n .map((member) => `\"${member}\"`)\n .join(\", \")}.`\n );\n }\n\n if (!Object.hasOwn(pk, keyField)) {\n throw new GlobalIdError(\n \"key_mismatch\",\n `Global id for \"${key}\" carries ${Object.keys(pk)\n .map((field) => `\"${field}\"`)\n .join(\", \")} rather than its key \"${keyField}\".`\n );\n }\n\n return { key, value: pk[keyField] };\n}\n\n/**\n * Reads a written or filtered value back down to what the column stores.\n *\n * Lenient by design: a raw uuid is accepted, because ids reach an application from places\n * that never went through the ORM. A *wrapped* id, though, is checked — that is the whole\n * point of carrying the table in the value. `decodeGlobalId` catches the wrong table; the\n * field check below catches a payload that names the right table but the wrong key.\n */\nfunction unwrap(value: string, alias: string, fieldName: string): string {\n if (!isGlobalId(value)) {\n return value;\n }\n\n const { pk } = decodeGlobalId(value, alias);\n\n if (!Object.hasOwn(pk, fieldName)) {\n throw new GlobalIdError(\n \"key_mismatch\",\n `Global id for \"${alias}\" carries ${Object.keys(pk)\n .map((field) => `\"${field}\"`)\n .join(\", \")} rather than its key \"${fieldName}\".`\n );\n }\n\n return pk[fieldName];\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsqlbase",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Query client and schema definition for distributed SQL databases",
5
5
  "sideEffects": false,
6
6
  "type": "module",
@@ -61,18 +61,20 @@
61
61
  }
62
62
  },
63
63
  "scripts": {
64
- "prebuild": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('tsconfig.tsbuildinfo',{force:true})\"",
65
- "build": "tsc -b",
64
+ "prebuild": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})\"",
65
+ "build": "tsc -p tsconfig.build.json",
66
+ "dev": "tsc -p tsconfig.build.json --watch",
66
67
  "test": "vitest run",
68
+ "typecheck": "tsc -p tsconfig.json",
67
69
  "lint": "eslint src --ext .ts",
68
70
  "prepack": "node -e \"require('fs').copyFileSync('../../LICENSE','LICENSE')\""
69
71
  },
70
72
  "dependencies": {
71
- "@dsqlbase/core": "^0.2.0"
73
+ "@dsqlbase/core": "^0.3.0"
72
74
  },
73
75
  "peerDependencies": {
74
- "@electric-sql/pglite": "^0.4.5",
75
- "pg": "^8.20.0"
76
+ "@electric-sql/pglite": ">=0.4.6",
77
+ "pg": ">=8.20.0"
76
78
  },
77
79
  "peerDependenciesMeta": {
78
80
  "pg": {
@@ -1,99 +0,0 @@
1
- import { AnyTable, DefinitionSchema, ExecutableQuery, ExecutionContext, Schema, SQLQuery, SQLStatement } from "@dsqlbase/core";
2
- import { ModelClient } from "../model/client.js";
3
- import { GlobalIdListResultOf, GlobalIdOptionsOf, GlobalIdResultOf } from "../model/base.js";
4
- export declare abstract class BaseClient<T extends DefinitionSchema> {
5
- protected readonly _ctx: ExecutionContext<T>;
6
- /** One model per table, keyed by schema alias. Populated by {@link attachModels}. */
7
- protected readonly _models: Map<string, ModelClient<AnyTable, T>>;
8
- constructor(ctx: ExecutionContext<T>);
9
- /**
10
- * Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,
11
- * so a scoped client does not carry it. The types remove it; this is the runtime half, for
12
- * callers reaching it through a widened type.
13
- */
14
- private _assertUnscoped;
15
- /**
16
- * Resolves a global id to the node it names, and to how the caller wants it read.
17
- *
18
- * Every failure is raised here, before a query is built: an id that does not decode, one
19
- * naming a table that is not a node, one whose payload is not that node's key, and one the
20
- * caller's `on` map excluded.
21
- */
22
- private _resolveNode;
23
- /**
24
- * A `where` over a field named at runtime.
25
- *
26
- * `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the
27
- * compiler cannot match to a column. The node registry resolved it against the real table
28
- * when the client was built, which is the check this cast stands on.
29
- */
30
- private _byKey;
31
- /**
32
- * The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A
33
- * row that fails the member filter is a miss, exactly as if the id named nothing.
34
- */
35
- private _lookupWhere;
36
- private _model;
37
- /**
38
- * Reads the single row a global id names, or `null` when it no longer exists.
39
- *
40
- * The lookup runs through the table's own model client rather than issuing SQL of its own,
41
- * so every seam a `findOne` passes applies to it — the tenant predicate above all. A node
42
- * lookup that bypassed it would be a cross-tenant read; going through the model makes that
43
- * structurally impossible rather than something to remember.
44
- *
45
- * The row is tagged with `$$key`, the alias it came from, which is what narrows the union.
46
- * `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow
47
- * on a nested discriminant.
48
- *
49
- * @example
50
- * ```ts
51
- * const record = await dsql.$findByGlobalId({
52
- * id,
53
- * on: { users: { select: { id: true, name: true } }, workspaces: true },
54
- * });
55
- *
56
- * if (record?.$$key === "users") record.name;
57
- * ```
58
- *
59
- * @throws GlobalIdError when the id does not decode, names a table that is not a node,
60
- * carries a payload that is not that node's key, or names a member `on` set to `false`.
61
- */
62
- $findByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {
63
- id: string;
64
- on?: TOn;
65
- }): Promise<GlobalIdResultOf<Schema<T>, TOn>>;
66
- /** Tags a resolved row with the alias it came from, so a caller can narrow the union. */
67
- private _tag;
68
- /**
69
- * Reads many global ids at once: one query per table rather than one per id, with the
70
- * results handed back **in the order the ids were given** and `null` wherever a row no
71
- * longer exists — the shape a batch resolver wants.
72
- *
73
- * Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids
74
- * from different tables fan out to different queries.
75
- *
76
- * The node's key field is always projected, even when `select` leaves it out: matching a
77
- * row back to the id that asked for it is what the key is for.
78
- *
79
- * @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`
80
- * in the result; a malformed id is a caller bug and is not silently dropped.
81
- */
82
- $listByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {
83
- ids: readonly string[];
84
- on?: TOn;
85
- }): Promise<(GlobalIdListResultOf<Schema<T>, TOn> | null)[]>;
86
- $query<T = unknown>(sql: SQLQuery): ExecutableQuery<T[]>;
87
- $execute<T = unknown>(query: SQLStatement): Promise<T[]>;
88
- }
89
- /**
90
- * Attaches one {@link ModelClient} per table to a client, keyed by the table's schema
91
- * alias, as a non-writable enumerable property. Shared by `createClient` and the
92
- * transaction client so a derived client is built exactly one way.
93
- *
94
- * Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once
95
- * under its alias — `getTables()` holds every table under both its alias and its database
96
- * name, which would attach two models for an aliased table.
97
- */
98
- export declare function attachModels<T extends DefinitionSchema>(client: BaseClient<T>, ctx: ExecutionContext<T>): void;
99
- //# sourceMappingURL=base.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":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AAG,EAAE,SAAS,MAAM,EAAE,CAAC;QACvB,EAAE,CAAC,EAAE,GAAG,CAAC;KACV,GAAG,OAAO,CAAC,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;IAwC5D,MAAM,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,QAAQ;IAgB3B,QAAQ,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC;CAa/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,gBAAgB,EACrD,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,EACrB,GAAG,EAAE,gBAAgB,CAAC,CAAC,CAAC,GACvB,IAAI,CAsBN"}
@@ -1,216 +0,0 @@
1
- import { ExecutableQuery, TenancyError, } from "@dsqlbase/core";
2
- import { ModelClient } from "../model/client.js";
3
- import { UnionClient } from "../union/client.js";
4
- import { GlobalIdError, decodeGlobalId } from "../../schema/utils/global-id.js";
5
- import { getNodes } from "../nodes.js";
6
- export class BaseClient {
7
- _ctx;
8
- /** One model per table, keyed by schema alias. Populated by {@link attachModels}. */
9
- _models = new Map();
10
- constructor(ctx) {
11
- this._ctx = ctx;
12
- }
13
- /**
14
- * Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,
15
- * so a scoped client does not carry it. The types remove it; this is the runtime half, for
16
- * callers reaching it through a widened type.
17
- */
18
- _assertUnscoped(method) {
19
- if (this._ctx.identity) {
20
- throw new TenancyError(`${method} is not available on an identity-scoped client: raw SQL is not tenant-safe. ` +
21
- `Use it on the base client, where that is plain to read.`);
22
- }
23
- }
24
- /**
25
- * Resolves a global id to the node it names, and to how the caller wants it read.
26
- *
27
- * Every failure is raised here, before a query is built: an id that does not decode, one
28
- * naming a table that is not a node, one whose payload is not that node's key, and one the
29
- * caller's `on` map excluded.
30
- */
31
- _resolveNode(id, on) {
32
- const { key, pk } = decodeGlobalId(id);
33
- const node = getNodes(this._ctx.schema).get(key);
34
- if (!node) {
35
- throw new GlobalIdError("unknown_node", `"${key}" is not a node in this schema.`);
36
- }
37
- const fields = Object.keys(pk);
38
- if (fields.length !== 1 || fields[0] !== node.keyField) {
39
- throw new GlobalIdError("key_mismatch", `Global id for "${key}" carries ${fields.map((field) => `"${field}"`).join(", ")} ` +
40
- `rather than its key "${node.keyField}".`);
41
- }
42
- const option = on?.[node.alias];
43
- if (option === false) {
44
- throw new GlobalIdError("unknown_node", `"${node.alias}" was excluded from this lookup by its \`on\` map.`);
45
- }
46
- const { select, where, join } = (option && typeof option === "object" ? option : {});
47
- return { node, value: pk[node.keyField], args: { select, where, join } };
48
- }
49
- /**
50
- * A `where` over a field named at runtime.
51
- *
52
- * `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the
53
- * compiler cannot match to a column. The node registry resolved it against the real table
54
- * when the client was built, which is the check this cast stands on.
55
- */
56
- _byKey(field, condition) {
57
- return { [field]: condition };
58
- }
59
- /**
60
- * The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A
61
- * row that fails the member filter is a miss, exactly as if the id named nothing.
62
- */
63
- _lookupWhere(field, condition, where) {
64
- const key = this._byKey(field, condition);
65
- return where ? { and: [key, where] } : key;
66
- }
67
- _model(alias) {
68
- const model = this._models.get(alias);
69
- if (!model) {
70
- throw new Error(`No model is attached for "${alias}".`);
71
- }
72
- return model;
73
- }
74
- /**
75
- * Reads the single row a global id names, or `null` when it no longer exists.
76
- *
77
- * The lookup runs through the table's own model client rather than issuing SQL of its own,
78
- * so every seam a `findOne` passes applies to it — the tenant predicate above all. A node
79
- * lookup that bypassed it would be a cross-tenant read; going through the model makes that
80
- * structurally impossible rather than something to remember.
81
- *
82
- * The row is tagged with `$$key`, the alias it came from, which is what narrows the union.
83
- * `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow
84
- * on a nested discriminant.
85
- *
86
- * @example
87
- * ```ts
88
- * const record = await dsql.$findByGlobalId({
89
- * id,
90
- * on: { users: { select: { id: true, name: true } }, workspaces: true },
91
- * });
92
- *
93
- * if (record?.$$key === "users") record.name;
94
- * ```
95
- *
96
- * @throws GlobalIdError when the id does not decode, names a table that is not a node,
97
- * carries a payload that is not that node's key, or names a member `on` set to `false`.
98
- */
99
- async $findByGlobalId(args) {
100
- const { node, value, args: nodeArgs } = this._resolveNode(args.id, args.on);
101
- const { select, where, join } = nodeArgs;
102
- const row = (await this._model(node.alias).findOne({
103
- where: this._lookupWhere(node.keyField, { eq: value }, where),
104
- ...(select ? { select } : {}),
105
- ...(join ? { join } : {}),
106
- }));
107
- return (row ? this._tag(row, node) : null);
108
- }
109
- /** Tags a resolved row with the alias it came from, so a caller can narrow the union. */
110
- _tag(row, node) {
111
- return { ...row, $$key: node.alias };
112
- }
113
- /**
114
- * Reads many global ids at once: one query per table rather than one per id, with the
115
- * results handed back **in the order the ids were given** and `null` wherever a row no
116
- * longer exists — the shape a batch resolver wants.
117
- *
118
- * Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids
119
- * from different tables fan out to different queries.
120
- *
121
- * The node's key field is always projected, even when `select` leaves it out: matching a
122
- * row back to the id that asked for it is what the key is for.
123
- *
124
- * @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`
125
- * in the result; a malformed id is a caller bug and is not silently dropped.
126
- */
127
- async $listByGlobalId(args) {
128
- const resolved = args.ids.map((id) => this._resolveNode(id, args.on));
129
- const groups = new Map();
130
- for (const { node, value, args: nodeArgs } of resolved) {
131
- const group = groups.get(node.alias) ?? { node, values: new Set(), args: nodeArgs };
132
- group.values.add(value);
133
- groups.set(node.alias, group);
134
- }
135
- // One query per table, all of them in flight together. Rows are matched back by node and
136
- // canonical key, not by id text: the database finds a row for any spelling of its uuid.
137
- const rows = new Map();
138
- const keyOf = (alias, value) => `${alias}\u0000${canonicalUuid(value)}`;
139
- await Promise.all([...groups.values()].map(async ({ node, values, args: { select, where, join } }) => {
140
- const found = (await this._model(node.alias).findMany({
141
- where: this._lookupWhere(node.keyField, { in: [...values] }, where),
142
- // The key is always projected: it is the only thing that can put a row back
143
- // against the id that asked for it.
144
- ...(select ? { select: { ...select, [node.keyField]: true } } : {}),
145
- ...(join ? { join } : {}),
146
- }));
147
- for (const row of found) {
148
- // The key column reads back wrapped as a global id; its payload is the stored uuid.
149
- const { pk } = decodeGlobalId(String(row[node.keyField]));
150
- rows.set(keyOf(node.alias, pk[node.keyField] ?? ""), this._tag(row, node));
151
- }
152
- }));
153
- return resolved.map(({ node, value }) => (rows.get(keyOf(node.alias, value)) ?? null));
154
- }
155
- $query(sql) {
156
- this._assertUnscoped("$query");
157
- return new ExecutableQuery({
158
- mode: "many",
159
- name: "anonymous_query",
160
- type: "select",
161
- args: {},
162
- query: sql.toQuery(),
163
- resolve: (result) => result,
164
- }, this._ctx.session);
165
- }
166
- async $execute(query) {
167
- this._assertUnscoped("$execute");
168
- // A `sql` template here is an object with no `text`: the session would run nothing.
169
- if (typeof query?.text !== "string") {
170
- throw new TypeError("$execute takes a rendered statement ({ text, params }); pass a sql`…` template to " +
171
- "$query, or call .toQuery() on it.");
172
- }
173
- return this._ctx.session.execute(query);
174
- }
175
- }
176
- /**
177
- * Attaches one {@link ModelClient} per table to a client, keyed by the table's schema
178
- * alias, as a non-writable enumerable property. Shared by `createClient` and the
179
- * transaction client so a derived client is built exactly one way.
180
- *
181
- * Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once
182
- * under its alias — `getTables()` holds every table under both its alias and its database
183
- * name, which would attach two models for an aliased table.
184
- */
185
- export function attachModels(client, ctx) {
186
- for (const [alias, table] of ctx.schema.getTableEntries()) {
187
- const model = new ModelClient(ctx, table);
188
- client["_models"].set(alias, model);
189
- Object.defineProperty(client, alias, {
190
- value: model,
191
- writable: false,
192
- enumerable: true,
193
- });
194
- }
195
- // Unions are read under their own alias, next to the tables; the registry already refused a
196
- // union named like a table, so the two cannot collide.
197
- for (const [alias, union] of ctx.schema.getUnions()) {
198
- Object.defineProperty(client, alias, {
199
- value: new UnionClient(ctx, union),
200
- writable: false,
201
- enumerable: true,
202
- });
203
- }
204
- }
205
- /**
206
- * A uuid as PostgreSQL prints it — lower case, hyphenated 8-4-4-4-12 — from any spelling its
207
- * input accepts (upper case, braces, hyphens anywhere or none). Anything that is not 32 hex
208
- * digits is returned as given: the database refuses it.
209
- */
210
- function canonicalUuid(value) {
211
- const hex = value.replace(/[{}-]/g, "").toLowerCase();
212
- if (!/^[0-9a-f]{32}$/.test(hex))
213
- return value;
214
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
215
- }
216
- //# sourceMappingURL=base.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/database/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,eAAe,EAKf,YAAY,GACb,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAQjD,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAa,QAAQ,EAAE,MAAM,aAAa,CAAC;AASlD,MAAM,OAAgB,UAAU;IACX,IAAI,CAAsB;IAE7C,qFAAqF;IAClE,OAAO,GAAG,IAAI,GAAG,EAAoC,CAAC;IAEzE,YAAY,GAAwB;QAClC,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IAClB,CAAC;IAED;;;;OAIG;IACK,eAAe,CAAC,MAAc;QACpC,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvB,MAAM,IAAI,YAAY,CACpB,GAAG,MAAM,8EAA8E;gBACrF,yDAAyD,CAC5D,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACK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Error,\n} from \"@dsqlbase/core\";\nimport { AnyUnionMembers } from \"@dsqlbase/core/definition\";\nimport { ModelClient } from \"../model/client.js\";\nimport { UnionClient } from \"../union/client.js\";\nimport {\n GlobalIdListResultOf,\n GlobalIdOptionsOf,\n GlobalIdResultOf,\n JoinExpressionOf,\n} from \"../model/base.js\";\nimport { WhereExpressionOf } from \"../model/filters.js\";\nimport { GlobalIdError, decodeGlobalId } from \"../../schema/utils/global-id.js\";\nimport { NodeTable, getNodes } from \"../nodes.js\";\n\n/** The member arguments an `on` entry carries into a global-id lookup. */\ntype NodeArgs = {\n select?: Record<string, boolean>;\n where?: WhereExpressionOf<AnyTable>;\n join?: JoinExpressionOf<AnyTable, AnySchema>;\n};\n\nexport abstract class BaseClient<T extends DefinitionSchema> {\n protected readonly _ctx: ExecutionContext<T>;\n\n /** One model per table, keyed by schema alias. Populated by {@link attachModels}. */\n protected readonly _models = new Map<string, ModelClient<AnyTable, T>>();\n\n constructor(ctx: ExecutionContext<T>) {\n this._ctx = ctx;\n }\n\n /**\n * Raw SQL bypasses every seam the operations factory applies, the tenant predicate included,\n * so a scoped client does not carry it. The types remove it; this is the runtime half, for\n * callers reaching it through a widened type.\n */\n private _assertUnscoped(method: string): void {\n if (this._ctx.identity) {\n throw new TenancyError(\n `${method} is not available on an identity-scoped client: raw SQL is not tenant-safe. ` +\n `Use it on the base client, where that is plain to read.`\n );\n }\n }\n\n /**\n * Resolves a global id to the node it names, and to how the caller wants it read.\n *\n * Every failure is raised here, before a query is built: an id that does not decode, one\n * naming a table that is not a node, one whose payload is not that node's key, and one the\n * caller's `on` map excluded.\n */\n private _resolveNode(\n id: string,\n on?: Record<string, unknown>\n ): { node: NodeTable; value: string; args: NodeArgs } {\n const { key, pk } = decodeGlobalId(id);\n const node = getNodes(this._ctx.schema).get(key);\n\n if (!node) {\n throw new GlobalIdError(\"unknown_node\", `\"${key}\" is not a node in this schema.`);\n }\n\n const fields = Object.keys(pk);\n\n if (fields.length !== 1 || fields[0] !== node.keyField) {\n throw new GlobalIdError(\n \"key_mismatch\",\n `Global id for \"${key}\" carries ${fields.map((field) => `\"${field}\"`).join(\", \")} ` +\n `rather than its key \"${node.keyField}\".`\n );\n }\n\n const option = on?.[node.alias];\n\n if (option === false) {\n throw new GlobalIdError(\n \"unknown_node\",\n `\"${node.alias}\" was excluded from this lookup by its \\`on\\` map.`\n );\n }\n\n const { select, where, join } = (\n option && typeof option === \"object\" ? option : {}\n ) as NodeArgs;\n\n return { node, value: pk[node.keyField], args: { select, where, join } };\n }\n\n /**\n * A `where` over a field named at runtime.\n *\n * `_models` is keyed by alias and typed over `AnyTable`, so the key field is a `string` the\n * compiler cannot match to a column. The node registry resolved it against the real table\n * when the client was built, which is the check this cast stands on.\n */\n private _byKey(field: string, condition: object): WhereExpressionOf<AnyTable> {\n return { [field]: condition } as WhereExpressionOf<AnyTable>;\n }\n\n /**\n * The lookup's own key filter, AND-ed with the member's `on.<alias>.where` when it has one. A\n * row that fails the member filter is a miss, exactly as if the id named nothing.\n */\n private _lookupWhere(\n field: string,\n condition: object,\n where: WhereExpressionOf<AnyTable> | undefined\n ): WhereExpressionOf<AnyTable> {\n const key = this._byKey(field, condition);\n\n return where ? ({ and: [key, where] } as WhereExpressionOf<AnyTable>) : key;\n }\n\n private _model(alias: string): ModelClient<AnyTable, T> {\n const model = this._models.get(alias);\n\n if (!model) {\n throw new Error(`No model is attached for \"${alias}\".`);\n }\n\n return model;\n }\n\n /**\n * Reads the single row a global id names, or `null` when it no longer exists.\n *\n * The lookup runs through the table's own model client rather than issuing SQL of its own,\n * so every seam a `findOne` passes applies to it — the tenant predicate above all. A node\n * lookup that bypassed it would be a cross-tenant read; going through the model makes that\n * structurally impossible rather than something to remember.\n *\n * The row is tagged with `$$key`, the alias it came from, which is what narrows the union.\n * `$$meta.key` carries the same value but cannot be used for it: TypeScript does not narrow\n * on a nested discriminant.\n *\n * @example\n * ```ts\n * const record = await dsql.$findByGlobalId({\n * id,\n * on: { users: { select: { id: true, name: true } }, workspaces: true },\n * });\n *\n * if (record?.$$key === \"users\") record.name;\n * ```\n *\n * @throws GlobalIdError when the id does not decode, names a table that is not a node,\n * carries a payload that is not that node's key, or names a member `on` set to `false`.\n */\n async $findByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {\n id: string;\n on?: TOn;\n }): Promise<GlobalIdResultOf<Schema<T>, TOn>> {\n const { node, value, args: nodeArgs } = this._resolveNode(args.id, args.on);\n const { select, where, join } = nodeArgs;\n\n const row = (await this._model(node.alias).findOne({\n where: this._lookupWhere(node.keyField, { eq: value }, where),\n ...(select ? { select } : {}),\n ...(join ? { join } : {}),\n })) as Record<string, unknown> | null;\n\n return (row ? this._tag(row, node) : null) as GlobalIdResultOf<Schema<T>, TOn>;\n }\n\n /** Tags a resolved row with the alias it came from, so a caller can narrow the union. */\n private _tag(row: Record<string, unknown>, node: NodeTable): Record<string, unknown> {\n return { ...row, $$key: node.alias };\n }\n\n /**\n * Reads many global ids at once: one query per table rather than one per id, with the\n * results handed back **in the order the ids were given** and `null` wherever a row no\n * longer exists — the shape a batch resolver wants.\n *\n * Unlike {@link $findByGlobalId} this cannot be a single `ExecutableQuery`, because ids\n * from different tables fan out to different queries.\n *\n * The node's key field is always projected, even when `select` leaves it out: matching a\n * row back to the id that asked for it is what the key is for.\n *\n * @throws GlobalIdError on the first id that does not resolve. A missing *row* is a `null`\n * in the result; a malformed id is a caller bug and is not silently dropped.\n */\n async $listByGlobalId<TOn extends GlobalIdOptionsOf<Schema<T>> | undefined = undefined>(args: {\n ids: readonly string[];\n on?: TOn;\n }): Promise<(GlobalIdListResultOf<Schema<T>, TOn> | null)[]> {\n const resolved = args.ids.map((id) => this._resolveNode(id, args.on));\n const groups = new Map<string, { node: NodeTable; values: Set<string>; args: NodeArgs }>();\n\n for (const { node, value, args: nodeArgs } of resolved) {\n const group = groups.get(node.alias) ?? { node, values: new Set<string>(), args: nodeArgs };\n\n group.values.add(value);\n groups.set(node.alias, group);\n }\n\n // One query per table, all of them in flight together. Rows are matched back by node and\n // canonical key, not by id text: the database finds a row for any spelling of its uuid.\n const rows = new Map<string, Record<string, unknown>>();\n const keyOf = (alias: string, value: string) => `${alias}\\u0000${canonicalUuid(value)}`;\n\n await Promise.all(\n [...groups.values()].map(async ({ node, values, args: { select, where, join } }) => {\n const found = (await this._model(node.alias).findMany({\n where: this._lookupWhere(node.keyField, { in: [...values] }, where),\n // The key is always projected: it is the only thing that can put a row back\n // against the id that asked for it.\n ...(select ? { select: { ...select, [node.keyField]: true } } : {}),\n ...(join ? { join } : {}),\n })) as unknown as Record<string, unknown>[];\n\n for (const row of found) {\n // The key column reads back wrapped as a global id; its payload is the stored uuid.\n const { pk } = decodeGlobalId(String(row[node.keyField]));\n rows.set(keyOf(node.alias, pk[node.keyField] ?? \"\"), this._tag(row, node));\n }\n })\n );\n\n return resolved.map(\n ({ node, value }) =>\n (rows.get(keyOf(node.alias, value)) ?? null) as GlobalIdListResultOf<Schema<T>, TOn> | null\n );\n }\n\n $query<T = unknown>(sql: SQLQuery) {\n this._assertUnscoped(\"$query\");\n\n return new ExecutableQuery<T[]>(\n {\n mode: \"many\",\n name: \"anonymous_query\",\n type: \"select\",\n args: {},\n query: sql.toQuery(),\n resolve: (result) => result,\n },\n this._ctx.session\n );\n }\n\n async $execute<T = unknown>(query: SQLStatement): Promise<T[]> {\n this._assertUnscoped(\"$execute\");\n\n // A `sql` template here is an object with no `text`: the session would run nothing.\n if (typeof (query as Partial<SQLStatement> | null)?.text !== \"string\") {\n throw new TypeError(\n \"$execute takes a rendered statement ({ text, params }); pass a sql`…` template to \" +\n \"$query, or call .toQuery() on it.\"\n );\n }\n\n return this._ctx.session.execute<T>(query);\n }\n}\n\n/**\n * Attaches one {@link ModelClient} per table to a client, keyed by the table's schema\n * alias, as a non-writable enumerable property. Shared by `createClient` and the\n * transaction client so a derived client is built exactly one way.\n *\n * Tables are taken from `SchemaRegistry.getTableEntries()`, which yields each table once\n * under its alias — `getTables()` holds every table under both its alias and its database\n * name, which would attach two models for an aliased table.\n */\nexport function attachModels<T extends DefinitionSchema>(\n client: BaseClient<T>,\n ctx: ExecutionContext<T>\n): void {\n for (const [alias, table] of ctx.schema.getTableEntries()) {\n const model = new ModelClient<AnyTable, T>(ctx, table);\n\n client[\"_models\"].set(alias, model);\n\n Object.defineProperty(client, alias, {\n value: model,\n writable: false,\n enumerable: true,\n });\n }\n\n // Unions are read under their own alias, next to the tables; the registry already refused a\n // union named like a table, so the two cannot collide.\n for (const [alias, union] of ctx.schema.getUnions()) {\n Object.defineProperty(client, alias, {\n value: new UnionClient<AnyUnionMembers, T>(ctx, union),\n writable: false,\n enumerable: true,\n });\n }\n}\n\n/**\n * A uuid as PostgreSQL prints it — lower case, hyphenated 8-4-4-4-12 — from any spelling its\n * input accepts (upper case, braces, hyphens anywhere or none). Anything that is not 32 hex\n * digits is returned as given: the database refuses it.\n */\nfunction canonicalUuid(value: string): string {\n const hex = value.replace(/[{}-]/g, \"\").toLowerCase();\n if (!/^[0-9a-f]{32}$/.test(hex)) return value;\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n"]}