qubu 0.5.1 → 0.6.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 (41) hide show
  1. package/dist/codegen.mjs +1 -1
  2. package/dist/column-Da37jYSD.mjs +309 -0
  3. package/dist/column-r1Y4ivwt.mjs +327 -0
  4. package/dist/constraints-YGyNPQ_z.mjs +208 -0
  5. package/dist/core.mjs +3 -3
  6. package/dist/index-B2rZf3-2.d.mts +32 -0
  7. package/dist/index.mjs +9 -7
  8. package/dist/introspection.mjs +1 -1
  9. package/dist/{on-conflict-jPsl9l0K.mjs → on-conflict-DZQ85f1t.mjs} +3 -2
  10. package/dist/postgres.mjs +3 -3
  11. package/dist/registry-BRcUuazJ.mjs +256 -0
  12. package/dist/{relational-x3BDVX9e.mjs → relational-CxnLCqZQ.mjs} +2 -2
  13. package/dist/schema.mjs +6 -4
  14. package/dist/{sqlite-CsIUtZ2Q.mjs → serialize-BN07IK0v.mjs} +3 -317
  15. package/dist/serialize-CEIIlWhC.d.mts +66 -0
  16. package/dist/snapshot/mysql.d.mts +17 -0
  17. package/dist/snapshot/mysql.mjs +356 -0
  18. package/dist/snapshot/postgres.d.mts +17 -0
  19. package/dist/snapshot/postgres.mjs +237 -0
  20. package/dist/snapshot/sqlite.d.mts +25 -0
  21. package/dist/snapshot/sqlite.mjs +321 -0
  22. package/dist/{snapshot-BSraiLtH.mjs → snapshot-Xam8-q0j.mjs} +1 -1
  23. package/dist/snapshot.d.mts +3 -2
  24. package/dist/snapshot.mjs +2 -583
  25. package/dist/{source-C4Vmu5bb.mjs → source-SqrKWjFJ.mjs} +2 -1
  26. package/dist/sqlite.mjs +2 -2
  27. package/dist/{table-DLQ7YWth.mjs → table-BwflqeAj.mjs} +3 -2
  28. package/dist/{types-CTENnDh9.mjs → types-BIJsj2fJ.mjs} +3 -2
  29. package/dist/{value-BEEj_Ayd.mjs → value-D14I_XgL.mjs} +1 -1
  30. package/docs/migrations/index.md +7 -7
  31. package/docs/reference/mysql-snapshot.md +5 -5
  32. package/docs/reference/postgres-snapshot.md +7 -7
  33. package/docs/reference/sqlite-snapshot.md +5 -5
  34. package/docs/reference/supported-surface.md +3 -0
  35. package/docs/schema/code-generation.md +2 -2
  36. package/docs/schema/ddl-emission.md +1 -1
  37. package/docs/schema/snapshots.md +12 -0
  38. package/package.json +13 -1
  39. package/dist/column-DmazTL67.mjs +0 -633
  40. package/dist/index-C-480HmV.d.mts +0 -146
  41. package/dist/registry-BGqa05et.mjs +0 -461
package/dist/codegen.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { l as decodeSchemaSnapshot } from "./canonical-DMvR9yBe.mjs";
2
- import { t as mapCatalogToSnapshot } from "./snapshot-BSraiLtH.mjs";
2
+ import { t as mapCatalogToSnapshot } from "./snapshot-Xam8-q0j.mjs";
3
3
  //#region src/codegen/source.ts
4
4
  const header = `/* Generated by Qubu. Do not edit this machine-owned file. */
5
5
  import * as _qubu from 'qubu'
@@ -0,0 +1,309 @@
1
+ import { P as resultValue, _ as isSchemaExpression, l as freezeSchemaMetadata } from "./column-r1Y4ivwt.mjs";
2
+ //#region src/schema/column-behavior.ts
3
+ /** A column behavior error with a stable code and optional property path. */
4
+ var ColumnBehaviorError = class extends TypeError {
5
+ code;
6
+ path;
7
+ constructor(code, message, path) {
8
+ super(message);
9
+ this.name = "ColumnBehaviorError";
10
+ this.code = code;
11
+ this.path = path;
12
+ }
13
+ };
14
+ /** Build a canonical literal node from a supported JavaScript scalar. */
15
+ function canonicalLiteral(value) {
16
+ if (value === null) return Object.freeze({ kind: "null" });
17
+ if (typeof value === "boolean") return Object.freeze({
18
+ kind: "boolean",
19
+ value
20
+ });
21
+ if (typeof value === "string") return Object.freeze({
22
+ kind: "string",
23
+ value
24
+ });
25
+ if (typeof value === "bigint") return Object.freeze({
26
+ kind: "bigint",
27
+ value: String(value)
28
+ });
29
+ if (!Number.isFinite(value)) throw new ColumnBehaviorError("invalid-default", "Default literal numbers must be finite", "default.value");
30
+ return Object.freeze({
31
+ kind: "number",
32
+ value: Object.is(value, -0) ? "0" : String(value)
33
+ });
34
+ }
35
+ function literalDefault(value) {
36
+ return Object.freeze({
37
+ kind: "literal",
38
+ value: canonicalLiteral(value)
39
+ });
40
+ }
41
+ /** Normalize a public default input into its canonical snapshot descriptor. */
42
+ function normalizeDefault(value) {
43
+ if (isSchemaExpression(value)) return Object.freeze({
44
+ kind: "expression",
45
+ expression: value
46
+ });
47
+ if (isExternalDefaultDescriptor(value)) return externalDefault();
48
+ return literalDefault(value);
49
+ }
50
+ /** Mark a legacy or externally managed database default explicitly. */
51
+ function externalDefault() {
52
+ return Object.freeze({ kind: "external" });
53
+ }
54
+ /** Create an immutable generated-column descriptor. */
55
+ function generatedColumn(expression, mode) {
56
+ assertSchemaExpression(expression, "generatedColumn.expression", "invalid-generated-column");
57
+ const resolvedMode = typeof mode === "string" ? mode : mode?.mode ?? "stored";
58
+ if (resolvedMode !== "stored" && resolvedMode !== "virtual") throw new ColumnBehaviorError("invalid-generated-column", `Generated-column mode must be "stored" or "virtual", received "${String(resolvedMode)}"`, "generatedColumn.mode");
59
+ return Object.freeze({
60
+ kind: "expression",
61
+ expression,
62
+ mode: resolvedMode
63
+ });
64
+ }
65
+ /** Mark a legacy or externally managed generated column explicitly. */
66
+ function externalGeneratedColumn() {
67
+ return Object.freeze({ kind: "external" });
68
+ }
69
+ /** Describe a database identity column without inventing a generated SQL expression. */
70
+ function identityColumn(generation, options) {
71
+ const resolvedGeneration = generation ?? "by-default";
72
+ if (resolvedGeneration !== "always" && resolvedGeneration !== "by-default") throw new ColumnBehaviorError("invalid-identity", `Identity generation must be "always" or "by-default", received "${String(resolvedGeneration)}"`, "identity.generation");
73
+ return Object.freeze({
74
+ kind: "identity",
75
+ generation: resolvedGeneration,
76
+ ...options?.dialect === void 0 ? {} : { dialect: freezeSchemaMetadata(options.dialect) }
77
+ });
78
+ }
79
+ /** Normalize complete and legacy column behavior into immutable metadata. */
80
+ function resolveColumnBehavior(options) {
81
+ const hasDefaultFlag = options.hasDefault === true;
82
+ const defaultFn = options.defaultFn;
83
+ const generatedFlag = options.generated === true;
84
+ const defaultDescriptor = options.default === void 0 ? void 0 : normalizeDefault(options.default);
85
+ const generatedDescriptor = options.generatedColumn;
86
+ const identityDescriptor = options.identity;
87
+ const onUpdateExpression = options.onUpdate;
88
+ if (defaultFn !== void 0 && typeof defaultFn !== "function") throw new ColumnBehaviorError("invalid-runtime-default", "Column defaultFn must be a function", "defaultFn");
89
+ if (defaultFn !== void 0 && (generatedFlag || generatedDescriptor !== void 0 || identityDescriptor !== void 0)) throw new ColumnBehaviorError("runtime-default-generated-conflict", "A runtime default cannot be combined with generated-column or identity metadata", "defaultFn");
90
+ if (onUpdateExpression !== void 0 && !isSchemaExpression(onUpdateExpression)) throw new ColumnBehaviorError("invalid-on-update", "Column onUpdate metadata must carry the deterministic schema-expression brand", "onUpdate");
91
+ if (defaultDescriptor !== void 0) {
92
+ assertDefaultDescriptor(defaultDescriptor);
93
+ if (options.hasDefault === false) throw new ColumnBehaviorError("default-flag-conflict", "A complete default descriptor cannot be combined with hasDefault: false", "hasDefault");
94
+ if (generatedDescriptor !== void 0 || identityDescriptor !== void 0) throw new ColumnBehaviorError("default-generated-conflict", "A column cannot declare a complete default together with generated-column or identity metadata", "default");
95
+ if (generatedFlag) throw new ColumnBehaviorError("default-generated-conflict", "A complete default descriptor cannot be combined with generated: true", "default");
96
+ }
97
+ if (generatedDescriptor !== void 0) {
98
+ assertGeneratedColumnDescriptor(generatedDescriptor);
99
+ if (options.generated === false) throw new ColumnBehaviorError("generated-flag-conflict", "A complete generated-column descriptor cannot be combined with generated: false", "generated");
100
+ if (identityDescriptor !== void 0) throw new ColumnBehaviorError("identity-generated-conflict", "A column cannot declare both generated-column and identity metadata", "generatedColumn");
101
+ if (hasDefaultFlag) throw new ColumnBehaviorError("default-generated-conflict", "A complete generated-column descriptor cannot be combined with hasDefault: true", "generatedColumn");
102
+ }
103
+ if (identityDescriptor !== void 0) {
104
+ assertIdentityDescriptor(identityDescriptor);
105
+ if (options.generated === false) throw new ColumnBehaviorError("generated-flag-conflict", "Identity metadata cannot be combined with generated: false", "generated");
106
+ if (hasDefaultFlag) throw new ColumnBehaviorError("identity-generated-conflict", "Identity metadata cannot be combined with hasDefault: true", "identity");
107
+ }
108
+ const normalizedDefault = defaultDescriptor === void 0 ? void 0 : freezeDefaultDescriptor(defaultDescriptor);
109
+ const normalizedGenerated = generatedDescriptor === void 0 ? void 0 : freezeGeneratedColumnDescriptor(generatedDescriptor);
110
+ const normalizedIdentity = identityDescriptor === void 0 ? void 0 : freezeIdentityDescriptor(identityDescriptor);
111
+ return Object.freeze({
112
+ hasDefault: hasDefaultFlag || normalizedDefault !== void 0,
113
+ hasRuntimeDefault: defaultFn !== void 0,
114
+ generated: generatedFlag || normalizedGenerated !== void 0 || normalizedIdentity !== void 0,
115
+ default: normalizedDefault ?? (hasDefaultFlag ? externalDefault() : void 0),
116
+ defaultFn,
117
+ generatedColumn: normalizedGenerated ?? (generatedFlag && normalizedIdentity === void 0 ? externalGeneratedColumn() : void 0),
118
+ identity: normalizedIdentity,
119
+ onUpdate: onUpdateExpression
120
+ });
121
+ }
122
+ function freezeDefaultDescriptor(value) {
123
+ if (value.kind === "external") return externalDefault();
124
+ if (value.kind === "expression") return Object.freeze({
125
+ kind: "expression",
126
+ expression: value.expression
127
+ });
128
+ return Object.freeze({
129
+ kind: "literal",
130
+ value: Object.freeze({ ...value.value })
131
+ });
132
+ }
133
+ function isExternalDefaultDescriptor(value) {
134
+ return typeof value === "object" && value !== null && value.kind === "external";
135
+ }
136
+ function freezeGeneratedColumnDescriptor(value) {
137
+ if (value.kind === "external") return externalGeneratedColumn();
138
+ return Object.freeze({
139
+ kind: "expression",
140
+ expression: value.expression,
141
+ mode: value.mode
142
+ });
143
+ }
144
+ function freezeIdentityDescriptor(value) {
145
+ return Object.freeze({
146
+ kind: "identity",
147
+ generation: value.generation,
148
+ ...value.dialect === void 0 ? {} : { dialect: freezeSchemaMetadata(value.dialect) }
149
+ });
150
+ }
151
+ function assertSchemaExpression(expression, path, code = "invalid-default") {
152
+ if (!isSchemaExpression(expression)) throw new ColumnBehaviorError(code, "Schema behavior expressions must carry the deterministic schema-expression brand", path);
153
+ }
154
+ function assertDefaultDescriptor(value) {
155
+ if (!value || typeof value !== "object") throw new ColumnBehaviorError("invalid-default", "Column default metadata must be an object", "default");
156
+ if (value.kind === "external") return;
157
+ if (value.kind === "expression") {
158
+ assertSchemaExpression(value.expression, "default.expression");
159
+ return;
160
+ }
161
+ if (value.kind === "literal") {
162
+ assertCanonicalLiteral(value.value);
163
+ return;
164
+ }
165
+ throw new ColumnBehaviorError("invalid-default", "Unknown column default descriptor kind", "default.kind");
166
+ }
167
+ function assertGeneratedColumnDescriptor(value) {
168
+ if (!value || typeof value !== "object") throw new ColumnBehaviorError("invalid-generated-column", "Generated-column metadata must be an object", "generatedColumn");
169
+ if (value.kind === "external") return;
170
+ if (value.kind === "expression") {
171
+ assertSchemaExpression(value.expression, "generatedColumn.expression", "invalid-generated-column");
172
+ if (value.mode !== "stored" && value.mode !== "virtual") throw new ColumnBehaviorError("invalid-generated-column", "Generated-column mode must be \"stored\" or \"virtual\"", "generatedColumn.mode");
173
+ return;
174
+ }
175
+ throw new ColumnBehaviorError("invalid-generated-column", "Unknown generated-column descriptor kind", "generatedColumn.kind");
176
+ }
177
+ function assertIdentityDescriptor(value) {
178
+ if (!value || typeof value !== "object" || value.kind !== "identity" || value.generation !== "always" && value.generation !== "by-default") throw new ColumnBehaviorError("invalid-identity", "Identity metadata must use generation \"always\" or \"by-default\"", "identity.generation");
179
+ if (value.dialect !== void 0) {
180
+ if (typeof value.dialect !== "object" || value.dialect === null || typeof value.dialect.dialect !== "string" || value.dialect.dialect.length === 0) throw new ColumnBehaviorError("invalid-identity", "Identity dialect metadata must contain a non-empty dialect tag", "identity.dialect");
181
+ }
182
+ }
183
+ function assertCanonicalLiteral(value) {
184
+ if (!value || typeof value !== "object") throw new ColumnBehaviorError("invalid-default", "Literal defaults must contain a canonical literal node", "default.value");
185
+ switch (value.kind) {
186
+ case "null": return;
187
+ case "boolean":
188
+ if (typeof value.value === "boolean") return;
189
+ break;
190
+ case "string":
191
+ if (typeof value.value === "string") return;
192
+ break;
193
+ case "number":
194
+ if (typeof value.value === "string" && value.value.length > 0) return;
195
+ break;
196
+ case "bigint": if (/^-?(0|[1-9][0-9]*)$/.test(value.value)) return;
197
+ }
198
+ throw new ColumnBehaviorError("invalid-default", "Literal defaults must contain a valid canonical literal node", "default.value");
199
+ }
200
+ //#endregion
201
+ //#region src/schema/column.ts
202
+ /** Create an immutable portable physical storage descriptor. */
203
+ function portableStorage(type) {
204
+ return Object.freeze({
205
+ kind: "portable",
206
+ type
207
+ });
208
+ }
209
+ function nativeStorage(dialectOrOptions, type) {
210
+ const dialect = typeof dialectOrOptions === "string" ? dialectOrOptions : dialectOrOptions.dialect;
211
+ const declaration = typeof dialectOrOptions === "string" ? type : "type" in dialectOrOptions ? dialectOrOptions.type : dialectOrOptions.declaration;
212
+ return Object.freeze({
213
+ kind: "native",
214
+ dialect,
215
+ type: declaration
216
+ });
217
+ }
218
+ function narrowColumnType() {
219
+ return this;
220
+ }
221
+ function withPortableCast(definition, type) {
222
+ return Object.freeze({
223
+ ...definition,
224
+ castTarget: Object.freeze({
225
+ kind: "portable-cast",
226
+ type
227
+ })
228
+ });
229
+ }
230
+ function withPortableStorage(definition, type) {
231
+ return Object.freeze({
232
+ ...definition,
233
+ storage: portableStorage(type)
234
+ });
235
+ }
236
+ function column(options) {
237
+ return Object.freeze({
238
+ definitionKind: "column",
239
+ nullable: options?.nullable === true,
240
+ ...resolveColumnBehavior(options ?? {}),
241
+ sqlName: options?.sqlName,
242
+ storage: options?.storage ? Object.freeze({ ...options.storage }) : void 0,
243
+ ...options?.decode === void 0 && options?.codec === void 0 ? {} : { resultDecoder: options?.decode ?? options?.codec?.fromDriver },
244
+ ...options?.codec === void 0 ? {} : {
245
+ parameterEncoder: options.codec.toDriver,
246
+ columnCodec: Object.freeze({ ...options.codec })
247
+ },
248
+ $type: narrowColumnType,
249
+ castTarget: options?.castType ? Object.freeze({
250
+ kind: "named-cast",
251
+ typeName: options.castType
252
+ }) : void 0
253
+ });
254
+ }
255
+ /** Resolve the runtime result metadata carried by a column definition. */
256
+ function columnResultValue(definition) {
257
+ const storage = definition.storage;
258
+ const type = storage?.kind === "portable" && (storage.type === "boolean" || storage.type === "date" || storage.type === "timestamp" || storage.type === "json") ? storage.type : void 0;
259
+ return resultValue(type, definition.resultDecoder);
260
+ }
261
+ /** Apply a live column codec while preserving SQL NULL unchanged. */
262
+ function encodeColumnParameter(definition, value) {
263
+ return value === null || definition.parameterEncoder === void 0 ? value : definition.parameterEncoder(value);
264
+ }
265
+ function nativeColumn(storageOrDialect, typeOrOptions, maybeOptions) {
266
+ const storage = typeof storageOrDialect === "string" ? nativeStorage(storageOrDialect, typeOrOptions) : storageOrDialect;
267
+ return column({
268
+ ...typeof storageOrDialect === "string" ? maybeOptions : typeOrOptions,
269
+ storage
270
+ });
271
+ }
272
+ function nullable(definition) {
273
+ return Object.freeze({
274
+ ...definition,
275
+ nullable: true
276
+ });
277
+ }
278
+ function integer(options) {
279
+ return withPortableStorage(withPortableCast(column(options), "integer"), "integer");
280
+ }
281
+ function numeric(options) {
282
+ return withPortableStorage(withPortableCast(column(options), "decimal"), "numeric");
283
+ }
284
+ function text(options) {
285
+ return withPortableStorage(withPortableCast(column(options), "text"), "text");
286
+ }
287
+ function boolean(options) {
288
+ return withPortableStorage(withPortableCast(column(options), "boolean"), "boolean");
289
+ }
290
+ function date(options) {
291
+ return withPortableStorage(withPortableCast(column(options), "date"), "date");
292
+ }
293
+ function timestamp(options) {
294
+ return withPortableStorage(withPortableCast(column(options), "timestamp"), "timestamp");
295
+ }
296
+ function uuid(options) {
297
+ return withPortableStorage(withPortableCast(column(options), "uuid"), "uuid");
298
+ }
299
+ function json(options) {
300
+ return withPortableStorage(withPortableCast(column(options), "json"), "json");
301
+ }
302
+ function bigint(options) {
303
+ return withPortableStorage(withPortableCast(column(options), "bigint"), "bigint");
304
+ }
305
+ function binary(options) {
306
+ return withPortableStorage(withPortableCast(column(options), "binary"), "binary");
307
+ }
308
+ //#endregion
309
+ export { identityColumn as C, generatedColumn as S, uuid as _, columnResultValue as a, externalDefault as b, integer as c, nativeStorage as d, nullable as f, timestamp as g, text as h, column as i, json as l, portableStorage as m, binary as n, date as o, numeric as p, boolean as r, encodeColumnParameter as s, bigint as t, nativeColumn as u, ColumnBehaviorError as v, resolveColumnBehavior as w, externalGeneratedColumn as x, canonicalLiteral as y };
@@ -0,0 +1,327 @@
1
+ import { a as assertDialectCapability } from "./json-Db7XRD91.mjs";
2
+ //#region src/result.ts
3
+ const resultValueMetadata = Symbol("qubu.result-value-metadata");
4
+ function resultValue(type, decoder) {
5
+ return type === void 0 && decoder === void 0 ? void 0 : Object.freeze({
6
+ ...type === void 0 ? {} : { type },
7
+ ...decoder === void 0 ? {} : { decoder }
8
+ });
9
+ }
10
+ function resultValueOf(value) {
11
+ if (typeof value !== "object" || value === null) return;
12
+ return value[resultValueMetadata];
13
+ }
14
+ function attachResultValue(value, metadata) {
15
+ if (metadata === void 0) return value;
16
+ return Object.freeze({
17
+ ...value,
18
+ [resultValueMetadata]: metadata
19
+ });
20
+ }
21
+ function createResultShape(fields) {
22
+ return Object.freeze({ fields: Object.freeze(fields.map((field) => Object.freeze({ ...field }))) });
23
+ }
24
+ function resultShapeValue(shape, name) {
25
+ const field = shape.fields.find((candidate) => candidate.name === name);
26
+ return field === void 0 ? void 0 : resultValue(field.type, field.decoder);
27
+ }
28
+ /** Decode SQLite/MySQL-style boolean values while accepting native booleans. */
29
+ const booleanResultDecoder = (value) => {
30
+ if (typeof value === "boolean") return value;
31
+ if (value === 0 || value === 0n) return false;
32
+ if (value === 1 || value === 1n) return true;
33
+ throw new TypeError("Expected a boolean or numeric 0/1 result");
34
+ };
35
+ /** Decode a SQL DATE string as a JavaScript Date at UTC midnight. */
36
+ const dateResultDecoder = (value) => {
37
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;
38
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) throw new TypeError("Expected a valid Date or YYYY-MM-DD result");
39
+ const decoded = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
40
+ if (Number.isNaN(decoded.getTime()) || decoded.toISOString().slice(0, 10) !== value) throw new TypeError("Expected a valid calendar date result");
41
+ return decoded;
42
+ };
43
+ /** Decode a SQL/ISO timestamp string while accepting driver-created Dates. */
44
+ const timestampResultDecoder = (value) => {
45
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;
46
+ if (typeof value !== "string") throw new TypeError("Expected a valid Date or timestamp string result");
47
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
48
+ const decoded = new Date(/(?:Z|[+-]\d{2}:?\d{2})$/u.test(normalized) ? normalized : `${normalized}Z`);
49
+ if (Number.isNaN(decoded.getTime())) throw new TypeError("Expected a valid timestamp result");
50
+ return decoded;
51
+ };
52
+ /** Decode a serialized JSON result. Use only when the adapter returns JSON text. */
53
+ const jsonTextResultDecoder = (value) => {
54
+ if (typeof value !== "string") return value;
55
+ return JSON.parse(value);
56
+ };
57
+ /** Error raised when a projected driver value cannot be decoded. */
58
+ var ResultDecodingError = class extends TypeError {
59
+ name = "ResultDecodingError";
60
+ field;
61
+ rowIndex;
62
+ resultType;
63
+ constructor(field, rowIndex, resultType) {
64
+ super(`Could not decode result field "${field}" in row ${rowIndex}${resultType === void 0 ? "" : ` as ${resultType}`}`);
65
+ this.field = field;
66
+ this.rowIndex = rowIndex;
67
+ this.resultType = resultType;
68
+ }
69
+ };
70
+ function decodeResultRow(row, shape, decoders, dialect, rowIndex) {
71
+ let decoded;
72
+ for (const field of shape.fields) {
73
+ const decoder = field.decoder ?? (field.type ? decoders?.[field.type] : void 0);
74
+ if (decoder === void 0 || row[field.name] === null) continue;
75
+ try {
76
+ decoded ??= { ...row };
77
+ decoded[field.name] = decoder(row[field.name], {
78
+ dialect,
79
+ field: field.name,
80
+ rowIndex
81
+ });
82
+ } catch {
83
+ throw new ResultDecodingError(field.name, rowIndex, field.type);
84
+ }
85
+ }
86
+ return decoded ?? row;
87
+ }
88
+ //#endregion
89
+ //#region src/core/fragment.ts
90
+ function fragment(render) {
91
+ return Object.freeze({ render });
92
+ }
93
+ function sequence(parts, separator = " ") {
94
+ return fragment((context) => {
95
+ let first = true;
96
+ for (const part of parts) {
97
+ if (!first) context.append(separator);
98
+ context.render(part);
99
+ first = false;
100
+ }
101
+ });
102
+ }
103
+ function parenthesize(part) {
104
+ return fragment((context) => {
105
+ context.append("(");
106
+ context.render(part);
107
+ context.append(")");
108
+ });
109
+ }
110
+ function isFragment(value) {
111
+ return typeof value === "object" && value !== null && "render" in value && typeof value.render === "function";
112
+ }
113
+ //#endregion
114
+ //#region src/expressions/types.ts
115
+ /** Runtime/type-level proof that an expression is safe to use in schema SQL. */
116
+ const schemaExpressionBrand = Symbol("qubu.schema-expression");
117
+ /** Add a concrete dialect requirement without dropping expression metadata. */
118
+ function withDialectCapability(expression, capability) {
119
+ const wrapped = makeExpression(expression.expressionKind, (context) => {
120
+ assertDialectCapability(context.dialect, capability);
121
+ context.render(expression);
122
+ }, expression.expressionCategory, resultValueOf(expression));
123
+ return isSchemaExpression(expression) ? markSchemaExpression(wrapped) : wrapped;
124
+ }
125
+ function makeExpression(expressionKind, render, expressionCategory, result) {
126
+ return attachResultValue(Object.freeze({
127
+ expressionKind,
128
+ ...expressionCategory ? { expressionCategory } : {},
129
+ ...fragment(render)
130
+ }), result);
131
+ }
132
+ /** Mark a query-only expression category without changing its SQL renderer. */
133
+ function markExpressionCategory(expression, category) {
134
+ return Object.freeze({
135
+ ...expression,
136
+ expressionCategory: category
137
+ });
138
+ }
139
+ /**
140
+ * Mark a built-in or explicitly audited renderer as schema-deterministic. Prefer
141
+ * {@link defineSchemaExpression} for application extensions because it supplies a restricted schema
142
+ * rendering context.
143
+ */
144
+ function makeSchemaExpression(expressionKind, render, result) {
145
+ const expression = makeExpression(expressionKind, render, void 0, result);
146
+ return Object.freeze({
147
+ ...expression,
148
+ [schemaExpressionBrand]: true
149
+ });
150
+ }
151
+ /** Add the schema-determinism brand to an explicitly audited expression. */
152
+ function markSchemaExpression(expression) {
153
+ if (isSchemaExpression(expression)) return expression;
154
+ return Object.freeze({
155
+ ...expression,
156
+ [schemaExpressionBrand]: true
157
+ });
158
+ }
159
+ /** Test the runtime brand used by schema rendering and validation. */
160
+ function isSchemaExpression(value) {
161
+ return typeof value === "object" && value !== null && schemaExpressionBrand in value && value[schemaExpressionBrand] === true;
162
+ }
163
+ function isExpression(value) {
164
+ return typeof value === "object" && value !== null && "expressionKind" in value && "render" in value && typeof value.render === "function";
165
+ }
166
+ //#endregion
167
+ //#region src/core/naming.ts
168
+ /** Convert an application-facing field name to a SQL-facing identifier. */
169
+ function snakeCaseIdentifier(name) {
170
+ return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
171
+ }
172
+ function resolveSqlNames(fields) {
173
+ const sqlNames = {};
174
+ const fieldsBySqlName = /* @__PURE__ */ new Map();
175
+ for (const field of fields) {
176
+ const sqlName = field.sqlName ?? snakeCaseIdentifier(field.fieldName);
177
+ if (sqlName.length === 0) throw new Error(`SQL name for field "${field.fieldName}" cannot be empty`);
178
+ const existingField = fieldsBySqlName.get(sqlName);
179
+ if (existingField) throw new Error(`Fields "${existingField}" and "${field.fieldName}" both resolve to SQL name "${sqlName}"`);
180
+ fieldsBySqlName.set(sqlName, field.fieldName);
181
+ sqlNames[field.fieldName] = sqlName;
182
+ }
183
+ return Object.freeze(sqlNames);
184
+ }
185
+ //#endregion
186
+ //#region src/schema/metadata.ts
187
+ /** Error raised when relational metadata cannot be represented safely. */
188
+ var SchemaMetadataValidationError = class extends TypeError {
189
+ name = "SchemaMetadataValidationError";
190
+ diagnostics;
191
+ issues;
192
+ constructor(diagnostics) {
193
+ const frozenDiagnostics = Object.freeze(diagnostics.map((diagnostic) => Object.freeze({
194
+ ...diagnostic,
195
+ path: Object.freeze([...diagnostic.path]),
196
+ relatedPaths: diagnostic.relatedPaths ? Object.freeze(diagnostic.relatedPaths.map((path) => Object.freeze([...path]))) : void 0
197
+ })));
198
+ super(frozenDiagnostics.map((diagnostic) => diagnostic.message).join("\n"));
199
+ this.diagnostics = frozenDiagnostics;
200
+ this.issues = frozenDiagnostics;
201
+ }
202
+ };
203
+ /** Generate the version-one physical name for a relational object ID. */
204
+ function generatedSchemaObjectName(id) {
205
+ return snakeCaseIdentifier(id);
206
+ }
207
+ /** Deep-freeze plain metadata values without introducing executable nodes. */
208
+ function freezeSchemaMetadata(value) {
209
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => freezeSchemaMetadata(item)));
210
+ if (typeof value !== "object" || value === null) return value;
211
+ const frozen = Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, freezeSchemaMetadata(nested)]));
212
+ return Object.freeze(frozen);
213
+ }
214
+ /** Check the portable identifier subset used for generated metadata names. */
215
+ function isValidSchemaObjectName(name) {
216
+ return name.length > 0 && name === name.trim() && !/[.\\/\u0000-\u001f\u007f"']/u.test(name);
217
+ }
218
+ /**
219
+ * Attach a record key and resolved physical name without changing the enumerable shape of legacy
220
+ * constraint/index values. The properties are still ordinary read-only runtime metadata and are
221
+ * available to snapshot traversals.
222
+ */
223
+ function materializeSchemaObjectIdentity(value, id, physicalName) {
224
+ const materialized = { ...value };
225
+ Object.defineProperties(materialized, {
226
+ id: {
227
+ configurable: false,
228
+ enumerable: false,
229
+ value: id,
230
+ writable: false
231
+ },
232
+ physicalName: {
233
+ configurable: false,
234
+ enumerable: false,
235
+ value: physicalName ?? generatedSchemaObjectName(id),
236
+ writable: false
237
+ }
238
+ });
239
+ return Object.freeze(materialized);
240
+ }
241
+ /**
242
+ * Resolve and validate names for one metadata record. The caller decides whether constraint and
243
+ * index names share a database namespace.
244
+ */
245
+ function materializeSchemaObjectRecord(record, kind) {
246
+ const diagnostics = [];
247
+ const names = /* @__PURE__ */ new Map();
248
+ const result = {};
249
+ for (const [id, value] of Object.entries(record)) {
250
+ const physicalName = value.physicalName ?? generatedSchemaObjectName(id);
251
+ const path = [kind === "constraint" ? "constraints" : "indexes", id];
252
+ if (!isValidSchemaObjectName(physicalName)) diagnostics.push({
253
+ code: "invalid-physical-name",
254
+ message: `The ${kind} "${id}" has invalid physical name "${physicalName}"`,
255
+ path: [...path, "physicalName"]
256
+ });
257
+ const previousId = names.get(physicalName);
258
+ if (previousId !== void 0) diagnostics.push({
259
+ code: "duplicate-physical-name",
260
+ message: `The ${kind}s "${previousId}" and "${id}" both use physical name "${physicalName}"`,
261
+ path: [...path, "physicalName"],
262
+ relatedPaths: [[
263
+ kind === "constraint" ? "constraints" : "indexes",
264
+ previousId,
265
+ "physicalName"
266
+ ]]
267
+ });
268
+ else names.set(physicalName, id);
269
+ result[id] = materializeSchemaObjectIdentity(value, id, physicalName);
270
+ }
271
+ if (diagnostics.length > 0) throw new SchemaMetadataValidationError(diagnostics);
272
+ return Object.freeze(result);
273
+ }
274
+ /** Return a diagnostic when a dialect extension is used by another adapter. */
275
+ function dialectMismatchDiagnostic(extension, dialect, path) {
276
+ if (extension.dialect === dialect) return;
277
+ return {
278
+ code: "dialect-mismatch",
279
+ message: `Dialect extension belongs to "${extension.dialect}" but the active schema dialect is "${dialect}"`,
280
+ path,
281
+ dialect
282
+ };
283
+ }
284
+ /** Throw a structured error for one or more dialect capability findings. */
285
+ function assertSchemaDialectSupport(diagnostics) {
286
+ if (diagnostics.length > 0) throw new SchemaMetadataValidationError(diagnostics);
287
+ }
288
+ //#endregion
289
+ //#region src/core/primitives/identifier.ts
290
+ function identifier(name) {
291
+ return fragment((context) => context.append(context.dialect.quoteIdentifier(name)));
292
+ }
293
+ function qualifiedIdentifier(...parts) {
294
+ return fragment((context) => {
295
+ parts.forEach((part, index) => {
296
+ if (index > 0) context.append(".");
297
+ context.append(context.dialect.quoteIdentifier(part));
298
+ });
299
+ });
300
+ }
301
+ //#endregion
302
+ //#region src/expressions/column.ts
303
+ function createColumnReference(columnName, sourceReference, fieldName, result) {
304
+ const expression = makeSchemaExpression("column", (context) => {
305
+ if (context.renderColumnReference) {
306
+ context.renderColumnReference(columnName);
307
+ return;
308
+ }
309
+ context.render(sourceReference);
310
+ context.append(".");
311
+ context.render(identifier(columnName));
312
+ }, result);
313
+ return Object.freeze({
314
+ ...expression,
315
+ fieldName,
316
+ columnName
317
+ });
318
+ }
319
+ function isColumnReference(value) {
320
+ return typeof value === "object" && value !== null && "expressionKind" in value && value.expressionKind === "column";
321
+ }
322
+ /** Turn an expression into a fragment that renders it without changing it. */
323
+ function expressionFragment(expression) {
324
+ return fragment((context) => context.render(expression));
325
+ }
326
+ //#endregion
327
+ export { dateResultDecoder as A, fragment as C, ResultDecodingError as D, sequence as E, resultValueOf as F, timestampResultDecoder as I, jsonTextResultDecoder as M, resultShapeValue as N, booleanResultDecoder as O, resultValue as P, withDialectCapability as S, parenthesize as T, isSchemaExpression as _, qualifiedIdentifier as a, markExpressionCategory as b, dialectMismatchDiagnostic as c, isValidSchemaObjectName as d, materializeSchemaObjectIdentity as f, isExpression as g, snakeCaseIdentifier as h, identifier as i, decodeResultRow as j, createResultShape as k, freezeSchemaMetadata as l, resolveSqlNames as m, expressionFragment as n, SchemaMetadataValidationError as o, materializeSchemaObjectRecord as p, isColumnReference as r, assertSchemaDialectSupport as s, createColumnReference as t, generatedSchemaObjectName as u, makeExpression as v, isFragment as w, markSchemaExpression as x, makeSchemaExpression as y };