@prisma-next/adapter-sqlite 0.12.0-dev.4 → 0.12.0-dev.41

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.
@@ -0,0 +1,764 @@
1
+ import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
2
+ import { RawExpr, isDdlNode } from "@prisma-next/sql-relational-core/ast";
3
+ import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-sqlite/sql-utils";
4
+ import { parseMarkerRowSafely, withMarkerReadErrorHandling } from "@prisma-next/errors/execution";
5
+ import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
6
+ import { buildControlTableBootstrapQueries, buildSignMarkerBootstrapQueries, datetime, integer, jsonText, sqliteTable, text } from "@prisma-next/target-sqlite/contract-free";
7
+ import { parseSqliteDefault } from "@prisma-next/target-sqlite/default-normalizer";
8
+ import { normalizeSqliteNativeType } from "@prisma-next/target-sqlite/native-type-normalizer";
9
+ import { blindCast } from "@prisma-next/utils/casts";
10
+ import { ifDefined } from "@prisma-next/utils/defined";
11
+ import { createAstCodecRegistry, deriveParamMetadata, encodeParamsWithMetadata } from "@prisma-next/sql-runtime";
12
+ import { SQLITE_DATETIME_CODEC_ID } from "@prisma-next/target-sqlite/codec-ids";
13
+ import { sqliteCodecRegistry } from "@prisma-next/target-sqlite/codecs";
14
+ //#region ../../../1-framework/3-tooling/migration/dist/exports/ledger-origin.mjs
15
+ function ledgerOriginFromStored(originCoreHash) {
16
+ if (originCoreHash === null || originCoreHash === "" || originCoreHash === "sha256:empty") return null;
17
+ return originCoreHash;
18
+ }
19
+ //#endregion
20
+ //#region src/core/ddl-renderer.ts
21
+ var SqliteDdlVisitorImpl = class {
22
+ createTable(node) {
23
+ return `CREATE TABLE ${node.ifNotExists ? "IF NOT EXISTS " : ""}${node.table} (\n ${node.columns.map((column) => renderColumn$1(column)).join(",\n ")}\n )`;
24
+ }
25
+ };
26
+ const defaultVisitor = {
27
+ literal(node) {
28
+ const { value } = node;
29
+ if (typeof value === "string") return `DEFAULT '${escapeLiteral(value)}'`;
30
+ if (typeof value === "number" || typeof value === "boolean") return `DEFAULT ${String(value)}`;
31
+ if (value === null) return "DEFAULT NULL";
32
+ return `DEFAULT '${JSON.stringify(value)}'`;
33
+ },
34
+ function(node) {
35
+ if (node.expression === "autoincrement()") return "";
36
+ return `DEFAULT (${node.expression})`;
37
+ }
38
+ };
39
+ function renderColumn$1(column) {
40
+ if (column.type.includes("AUTOINCREMENT")) return `${column.name} ${column.type}`;
41
+ const parts = [column.name, column.type];
42
+ if (column.notNull) parts.push("NOT NULL");
43
+ if (column.primaryKey) parts.push("PRIMARY KEY");
44
+ const defaultClause = column.default ? column.default.accept(defaultVisitor) : "";
45
+ if (defaultClause.length > 0) parts.push(defaultClause);
46
+ return parts.join(" ");
47
+ }
48
+ function renderLoweredDdl(ast) {
49
+ const sql = ast.accept(new SqliteDdlVisitorImpl());
50
+ return Object.freeze({
51
+ sql,
52
+ params: Object.freeze([])
53
+ });
54
+ }
55
+ //#endregion
56
+ //#region src/core/ledger-decode.ts
57
+ const DESIGNATOR_LESS_UTC_DATETIME = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?$/;
58
+ function coerceLedgerAppliedAt(value) {
59
+ if (value instanceof Date) return value;
60
+ if (DESIGNATOR_LESS_UTC_DATETIME.test(value)) return /* @__PURE__ */ new Date(`${value.replace(" ", "T")}Z`);
61
+ return new Date(value);
62
+ }
63
+ function operationCountFromStored(operations) {
64
+ if (Array.isArray(operations)) return operations.length;
65
+ if (typeof operations === "string") try {
66
+ const parsed = JSON.parse(operations);
67
+ return Array.isArray(parsed) ? parsed.length : 0;
68
+ } catch {
69
+ return 0;
70
+ }
71
+ return 0;
72
+ }
73
+ //#endregion
74
+ //#region src/core/marker-ledger.ts
75
+ const CONTROL_CODECS = createAstCodecRegistry(sqliteCodecRegistry);
76
+ const marker = sqliteTable("_prisma_marker", {
77
+ space: text(),
78
+ core_hash: text(),
79
+ profile_hash: text(),
80
+ contract_json: jsonText({ nullable: true }),
81
+ canonical_version: integer({ nullable: true }),
82
+ updated_at: datetime(),
83
+ app_tag: text({ nullable: true }),
84
+ meta: jsonText({ nullable: true }),
85
+ invariants: jsonText()
86
+ });
87
+ /**
88
+ * Writeable subset of `_prisma_ledger`. Omits the DB-generated `id`
89
+ * (`INTEGER PRIMARY KEY AUTOINCREMENT`) and `created_at` (default
90
+ * `strftime(...)`).
91
+ */
92
+ const ledger = sqliteTable("_prisma_ledger", {
93
+ space: text(),
94
+ migration_name: text(),
95
+ migration_hash: text(),
96
+ origin_core_hash: text({ nullable: true }),
97
+ destination_core_hash: text(),
98
+ operations: jsonText()
99
+ });
100
+ /**
101
+ * Read-side handle covering every column of `_prisma_ledger`, including
102
+ * the DB-generated `id` (for ORDER BY) and `created_at`.
103
+ */
104
+ const ledgerReadShape = sqliteTable("_prisma_ledger", {
105
+ id: integer(),
106
+ space: text(),
107
+ migration_name: text(),
108
+ migration_hash: text(),
109
+ origin_core_hash: text({ nullable: true }),
110
+ destination_core_hash: text(),
111
+ operations: jsonText(),
112
+ created_at: text()
113
+ });
114
+ const sqliteCatalog = sqliteTable("sqlite_master", {
115
+ type: text(),
116
+ name: text()
117
+ });
118
+ const NOW = new RawExpr({
119
+ parts: ["datetime('now')"],
120
+ returns: {
121
+ codecId: SQLITE_DATETIME_CODEC_ID,
122
+ nullable: false
123
+ }
124
+ });
125
+ function mergeInvariants(current, incoming) {
126
+ return [...new Set([...current, ...incoming])].sort();
127
+ }
128
+ async function execute(lower, driver, query) {
129
+ const lowered = lower(query);
130
+ const encoded = await encodeParamsWithMetadata(lowered.params.map((slot) => {
131
+ if (slot.kind === "literal") return slot.value;
132
+ throw new Error("SQLite control DML lowered to a bind parameter, which is unsupported");
133
+ }), deriveParamMetadata(query), {}, CONTROL_CODECS);
134
+ return (await driver.query(lowered.sql, encoded)).rows;
135
+ }
136
+ function decodeSqliteMarkerRow(row) {
137
+ if (typeof row !== "object" || row === null || !("invariants" in row)) return row;
138
+ const record = row;
139
+ if (typeof record.invariants !== "string") return row;
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(record.invariants);
143
+ } catch (err) {
144
+ const detail = err instanceof Error ? err.message : String(err);
145
+ throw new Error(`Invalid contract marker row: invariants is not valid JSON: ${detail}`);
146
+ }
147
+ return {
148
+ ...record,
149
+ invariants: parsed
150
+ };
151
+ }
152
+ //#endregion
153
+ //#region src/core/control-adapter.ts
154
+ const SQLITE_MARKER_TABLE = "_prisma_marker";
155
+ const SQLITE_LEDGER_TABLE = "_prisma_ledger";
156
+ var SqliteControlAdapter = class {
157
+ familyId = "sql";
158
+ targetId = "sqlite";
159
+ normalizeDefault = parseSqliteDefault;
160
+ normalizeNativeType = normalizeSqliteNativeType;
161
+ bootstrapControlTableQueries() {
162
+ return buildControlTableBootstrapQueries();
163
+ }
164
+ bootstrapSignMarkerQueries() {
165
+ return buildSignMarkerBootstrapQueries();
166
+ }
167
+ /**
168
+ * Lower a SQL query AST into a SQLite-flavored `{ sql, params }` payload.
169
+ *
170
+ * Delegates to the shared `renderLoweredSql` renderer so the control adapter
171
+ * emits byte-identical SQL to `SqliteAdapterImpl.lower()` for the same AST
172
+ * and contract. Used at migration plan/emit time (e.g. by `dataTransform`)
173
+ * without instantiating the runtime adapter.
174
+ */
175
+ lower(ast, context) {
176
+ if (isDdlNode(ast)) return renderLoweredDdl(ast);
177
+ return renderLoweredSql(ast, context.contract);
178
+ }
179
+ /**
180
+ * Reads the contract marker from `_prisma_marker`. Probes `sqlite_master`
181
+ * first so a fresh database (no marker table) returns `null` instead of a
182
+ * "no such table" error.
183
+ */
184
+ async readMarker(driver, space) {
185
+ const result = await this.readMarkerDiscriminated(driver, space);
186
+ return result.kind === "present" ? result.record : null;
187
+ }
188
+ async readMarkerDiscriminated(driver, space) {
189
+ return withMarkerReadErrorHandling(() => this.readMarkerResult(driver, space), {
190
+ space,
191
+ markerLocation: SQLITE_MARKER_TABLE
192
+ });
193
+ }
194
+ /**
195
+ * Reads every row from `_prisma_marker` and returns them keyed by
196
+ * `space`. Mirrors the existence probe in {@link readMarker}: a
197
+ * fresh database without the marker table returns an empty map.
198
+ */
199
+ async readAllMarkers(driver) {
200
+ return withMarkerReadErrorHandling(() => this.readAllMarkersResult(driver), {
201
+ space: APP_SPACE_ID,
202
+ markerLocation: SQLITE_MARKER_TABLE
203
+ });
204
+ }
205
+ async readAllMarkersResult(driver) {
206
+ const lower = (query) => this.lower(query, { contract: void 0 });
207
+ if ((await execute(lower, driver, sqliteCatalog.select(sqliteCatalog.name).where(sqliteCatalog.type.eq("table").and(sqliteCatalog.name.eq("_prisma_marker"))).build())).length === 0) return /* @__PURE__ */ new Map();
208
+ const rows = blindCast(await execute(lower, driver, marker.select(marker.space, marker.core_hash, marker.profile_hash, marker.contract_json, marker.canonical_version, marker.updated_at, marker.app_tag, marker.meta, marker.invariants).build()));
209
+ const out = /* @__PURE__ */ new Map();
210
+ for (const row of rows) out.set(row.space, parseMarkerRowSafely(row, (raw) => parseContractMarkerRow(decodeSqliteMarkerRow(raw)), {
211
+ space: row.space,
212
+ markerLocation: SQLITE_MARKER_TABLE
213
+ }));
214
+ return out;
215
+ }
216
+ /**
217
+ * Reads per-migration ledger rows from `_prisma_ledger` in apply order.
218
+ * Probes `sqlite_master` first so a fresh database without the ledger
219
+ * table returns `[]` instead of raising "no such table".
220
+ */
221
+ async readLedger(driver, space) {
222
+ return withMarkerReadErrorHandling(() => this.readLedgerResult(driver, space), {
223
+ space: space ?? "*",
224
+ markerLocation: SQLITE_LEDGER_TABLE
225
+ });
226
+ }
227
+ async readLedgerResult(driver, space) {
228
+ const lower = (query) => this.lower(query, { contract: void 0 });
229
+ if ((await execute(lower, driver, sqliteCatalog.select(sqliteCatalog.name).where(sqliteCatalog.type.eq("table").and(sqliteCatalog.name.eq("_prisma_ledger"))).build())).length === 0) return [];
230
+ const base = ledgerReadShape.select(ledgerReadShape.space, ledgerReadShape.migration_name, ledgerReadShape.migration_hash, ledgerReadShape.origin_core_hash, ledgerReadShape.destination_core_hash, ledgerReadShape.operations, ledgerReadShape.created_at);
231
+ return blindCast(await execute(lower, driver, (space !== void 0 ? base.where(ledgerReadShape.space.eq(space)) : base).orderBy(ledgerReadShape.id).build())).map((row) => ({
232
+ space: row.space,
233
+ migrationName: row.migration_name,
234
+ migrationHash: row.migration_hash,
235
+ from: ledgerOriginFromStored(row.origin_core_hash),
236
+ to: row.destination_core_hash,
237
+ appliedAt: coerceLedgerAppliedAt(row.created_at),
238
+ operationCount: operationCountFromStored(row.operations)
239
+ }));
240
+ }
241
+ /**
242
+ * Stamps the initial marker row for `space` via the shared contract-free DML
243
+ * builder, lowered through {@link lower} and executed on the driver. See the
244
+ * `SqlControlAdapter.initMarker` contract.
245
+ */
246
+ async insertMarker(driver, space, destination) {
247
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.insert({
248
+ space,
249
+ core_hash: destination.storageHash,
250
+ profile_hash: destination.profileHash,
251
+ contract_json: null,
252
+ canonical_version: null,
253
+ updated_at: NOW,
254
+ app_tag: null,
255
+ meta: {},
256
+ invariants: destination.invariants ?? []
257
+ }).build());
258
+ }
259
+ async initMarker(driver, space, destination) {
260
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.upsert({
261
+ space,
262
+ core_hash: destination.storageHash,
263
+ profile_hash: destination.profileHash,
264
+ contract_json: null,
265
+ canonical_version: null,
266
+ updated_at: NOW,
267
+ app_tag: null,
268
+ meta: {},
269
+ invariants: destination.invariants ?? []
270
+ }).onConflict(marker.space).doUpdate((excluded) => ({
271
+ core_hash: excluded.core_hash,
272
+ profile_hash: excluded.profile_hash,
273
+ contract_json: excluded.contract_json,
274
+ canonical_version: excluded.canonical_version,
275
+ updated_at: NOW,
276
+ app_tag: excluded.app_tag,
277
+ meta: excluded.meta,
278
+ invariants: excluded.invariants
279
+ })).build());
280
+ }
281
+ /**
282
+ * Compare-and-swap advance of the marker row for `space`. See the
283
+ * `SqlControlAdapter.updateMarker` contract.
284
+ */
285
+ async updateMarker(driver, space, expectedFrom, destination) {
286
+ const currentInvariants = destination.invariants === void 0 ? [] : (await this.readMarker(driver, space))?.invariants ?? [];
287
+ const mergedInvariants = destination.invariants === void 0 ? void 0 : mergeInvariants(currentInvariants, destination.invariants);
288
+ return (await execute((q) => this.lower(q, { contract: void 0 }), driver, marker.update().set({
289
+ core_hash: destination.storageHash,
290
+ profile_hash: destination.profileHash,
291
+ updated_at: NOW,
292
+ ...mergedInvariants !== void 0 ? { invariants: mergedInvariants } : {}
293
+ }).where(marker.space.eq(space).and(marker.core_hash.eq(expectedFrom))).returning(marker.space).build())).length > 0;
294
+ }
295
+ /**
296
+ * Appends a ledger entry for `space`. See the
297
+ * `SqlControlAdapter.writeLedgerEntry` contract.
298
+ */
299
+ async writeLedgerEntry(driver, space, entry) {
300
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, ledger.insert({
301
+ space,
302
+ migration_name: entry.migrationName,
303
+ migration_hash: entry.migrationHash,
304
+ origin_core_hash: entry.from,
305
+ destination_core_hash: entry.to,
306
+ operations: entry.operations
307
+ }).build());
308
+ }
309
+ async readMarkerResult(driver, space) {
310
+ const lower = (query) => this.lower(query, { contract: void 0 });
311
+ if ((await execute(lower, driver, sqliteCatalog.select(sqliteCatalog.name).where(sqliteCatalog.type.eq("table").and(sqliteCatalog.name.eq("_prisma_marker"))).build())).length === 0) return { kind: "no-table" };
312
+ const row = (await execute(lower, driver, marker.select(marker.core_hash, marker.profile_hash, marker.contract_json, marker.canonical_version, marker.updated_at, marker.app_tag, marker.meta, marker.invariants).where(marker.space.eq(space)).build()))[0];
313
+ if (!row) return { kind: "absent" };
314
+ return {
315
+ kind: "present",
316
+ record: parseContractMarkerRow(decodeSqliteMarkerRow(row))
317
+ };
318
+ }
319
+ async introspect(driver, _contract) {
320
+ const tablesResult = await driver.query(`SELECT name FROM sqlite_master
321
+ WHERE type = 'table'
322
+ AND name NOT LIKE 'sqlite_%'
323
+ AND name NOT IN ('_prisma_marker', '_prisma_ledger')
324
+ ORDER BY name`);
325
+ const tables = {};
326
+ for (const tableRow of tablesResult.rows) {
327
+ const tableName = tableRow.name;
328
+ const columnsResult = await driver.query(`PRAGMA table_info("${escapePragmaArg(tableName)}")`);
329
+ const fkResult = await driver.query(`PRAGMA foreign_key_list("${escapePragmaArg(tableName)}")`);
330
+ const indexListResult = await driver.query(`PRAGMA index_list("${escapePragmaArg(tableName)}")`);
331
+ const columns = {};
332
+ const pkColumns = [];
333
+ for (const col of columnsResult.rows) {
334
+ columns[col.name] = {
335
+ name: col.name,
336
+ nativeType: col.type.toLowerCase(),
337
+ nullable: col.notnull === 0 && col.pk === 0,
338
+ ...ifDefined("default", col.dflt_value ?? void 0)
339
+ };
340
+ if (col.pk > 0) pkColumns.push({
341
+ name: col.name,
342
+ pk: col.pk
343
+ });
344
+ }
345
+ pkColumns.sort((a, b) => a.pk - b.pk);
346
+ const primaryKey = pkColumns.length > 0 ? { columns: pkColumns.map((c) => c.name) } : void 0;
347
+ const fkMap = /* @__PURE__ */ new Map();
348
+ for (const fk of fkResult.rows) {
349
+ const existing = fkMap.get(fk.id);
350
+ if (existing) {
351
+ existing.columns.push(fk.from);
352
+ existing.referencedColumns.push(fk.to);
353
+ } else fkMap.set(fk.id, {
354
+ columns: [fk.from],
355
+ referencedTable: fk.table,
356
+ referencedColumns: [fk.to],
357
+ onDelete: fk.on_delete,
358
+ onUpdate: fk.on_update
359
+ });
360
+ }
361
+ const foreignKeys = Array.from(fkMap.values()).map((fk) => ({
362
+ columns: Object.freeze([...fk.columns]),
363
+ referencedTable: fk.referencedTable,
364
+ referencedColumns: Object.freeze([...fk.referencedColumns]),
365
+ ...ifDefined("onDelete", mapSqliteReferentialAction(fk.onDelete)),
366
+ ...ifDefined("onUpdate", mapSqliteReferentialAction(fk.onUpdate))
367
+ }));
368
+ const uniques = [];
369
+ const indexes = [];
370
+ for (const idx of indexListResult.rows) {
371
+ const idxColumns = (await driver.query(`PRAGMA index_info("${escapePragmaArg(idx.name)}")`)).rows.sort((a, b) => a.seqno - b.seqno).map((r) => r.name);
372
+ if (idx.origin === "u") uniques.push({
373
+ columns: Object.freeze([...idxColumns]),
374
+ name: idx.name
375
+ });
376
+ else if (idx.origin === "c") indexes.push({
377
+ columns: Object.freeze([...idxColumns]),
378
+ name: idx.name,
379
+ unique: idx.unique === 1
380
+ });
381
+ }
382
+ tables[tableName] = {
383
+ name: tableName,
384
+ columns,
385
+ ...ifDefined("primaryKey", primaryKey),
386
+ foreignKeys,
387
+ uniques,
388
+ indexes
389
+ };
390
+ }
391
+ return { tables };
392
+ }
393
+ };
394
+ function escapePragmaArg(name) {
395
+ return name.replace(/"/g, "\"\"");
396
+ }
397
+ const SQLITE_REFERENTIAL_ACTION_MAP = {
398
+ "NO ACTION": "noAction",
399
+ RESTRICT: "restrict",
400
+ CASCADE: "cascade",
401
+ "SET NULL": "setNull",
402
+ "SET DEFAULT": "setDefault"
403
+ };
404
+ function mapSqliteReferentialAction(rule) {
405
+ const mapped = SQLITE_REFERENTIAL_ACTION_MAP[rule.toUpperCase()];
406
+ if (mapped === void 0) throw new Error(`Unknown SQLite referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
407
+ if (mapped === "noAction") return void 0;
408
+ return mapped;
409
+ }
410
+ //#endregion
411
+ //#region src/core/adapter.ts
412
+ const defaultCapabilities = Object.freeze({ sql: {
413
+ orderBy: true,
414
+ limit: true,
415
+ lateral: false,
416
+ jsonAgg: true,
417
+ returning: true,
418
+ enums: false
419
+ } });
420
+ var SqliteAdapterImpl = class {
421
+ familyId = "sql";
422
+ targetId = "sqlite";
423
+ profile;
424
+ constructor(options) {
425
+ const controlAdapter = new SqliteControlAdapter();
426
+ this.profile = Object.freeze({
427
+ id: options?.profileId ?? "sqlite/default@1",
428
+ target: "sqlite",
429
+ capabilities: defaultCapabilities,
430
+ readMarker: (queryable) => controlAdapter.readMarkerDiscriminated({
431
+ familyId: "sql",
432
+ targetId: "sqlite",
433
+ query: async (sql, params) => {
434
+ return { rows: [...(await queryable.query(sql, params)).rows] };
435
+ },
436
+ close: async () => {}
437
+ }, APP_SPACE_ID)
438
+ });
439
+ }
440
+ lower(ast, context) {
441
+ if (isDdlNode(ast)) return renderLoweredDdl(ast);
442
+ return renderLoweredSql(ast, context.contract);
443
+ }
444
+ };
445
+ /** Codec-id lookup for bare-literal interpolations used by `fns.raw` on a sqlite client. Contributed as the descriptor's static `rawCodecInferer` slot. */
446
+ const sqliteRawCodecInferer = { inferCodec(value) {
447
+ switch (typeof value) {
448
+ case "number": return Number.isSafeInteger(value) && value % 1 === 0 ? "sqlite/integer@1" : "sqlite/real@1";
449
+ case "bigint": return "sqlite/bigint@1";
450
+ case "string": return "sqlite/text@1";
451
+ case "boolean": return "sqlite/integer@1";
452
+ case "object": if (value instanceof Uint8Array) return "sqlite/blob@1";
453
+ }
454
+ throw new Error("unsupported JS value type for raw-SQL interpolation: wrap this value in `param(...)` with an explicit codec");
455
+ } };
456
+ /**
457
+ * Lower a SQL query AST into a SQLite-flavored `{ sql, params }` payload.
458
+ *
459
+ * Shared between the runtime adapter (`SqliteAdapterImpl.lower`) and the control adapter (`SqliteControlAdapter.lower`) so both produce byte-identical SQL for the same AST and contract.
460
+ */
461
+ function renderLoweredSql(ast, contract) {
462
+ const collectedParamRefs = ast.collectParamRefs();
463
+ const params = [];
464
+ for (const ref of collectedParamRefs) params.push(ref.kind === "prepared-param-ref" ? {
465
+ kind: "bind",
466
+ name: ref.name
467
+ } : {
468
+ kind: "literal",
469
+ value: ref.value
470
+ });
471
+ let sql;
472
+ const node = ast;
473
+ switch (node.kind) {
474
+ case "select":
475
+ sql = renderSelect(node, contract);
476
+ break;
477
+ case "insert":
478
+ sql = renderInsert(node, contract);
479
+ break;
480
+ case "update":
481
+ sql = renderUpdate(node, contract);
482
+ break;
483
+ case "delete":
484
+ sql = renderDelete(node, contract);
485
+ break;
486
+ default: throw new Error(`Unsupported AST node kind: ${node.kind}`);
487
+ }
488
+ return Object.freeze({
489
+ sql,
490
+ params
491
+ });
492
+ }
493
+ function renderLimitOffset(keyword, value, contract) {
494
+ if (value === void 0) return "";
495
+ if (typeof value === "number") return `${keyword} ${value}`;
496
+ return `${keyword} ${renderExpr(value, contract)}`;
497
+ }
498
+ function renderSelect(ast, contract) {
499
+ return [
500
+ `SELECT ${ast.distinct ? "DISTINCT " : ""}${renderProjection(ast.projection, contract)}`,
501
+ `FROM ${renderSource(ast.from, contract)}`,
502
+ ast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract)).join(" ") : "",
503
+ ast.where ? `WHERE ${renderExpr(ast.where, contract)}` : "",
504
+ ast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract)).join(", ")}` : "",
505
+ ast.having ? `HAVING ${renderExpr(ast.having, contract)}` : "",
506
+ ast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`).join(", ")}` : "",
507
+ renderLimitOffset("LIMIT", ast.limit, contract),
508
+ renderLimitOffset("OFFSET", ast.offset, contract)
509
+ ].filter((part) => part.length > 0).join(" ").trim();
510
+ }
511
+ function renderProjection(projection, contract) {
512
+ return projection.map((item) => {
513
+ const alias = quoteIdentifier(item.alias);
514
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${alias}`;
515
+ return `${renderExpr(item.expr, contract)} AS ${alias}`;
516
+ }).join(", ");
517
+ }
518
+ function qualifyTableFromNamespaceCoordinate(table, contract) {
519
+ if (table.namespaceId === void 0) return quoteIdentifier(table.name);
520
+ const namespace = contract.storage.namespaces[table.namespaceId];
521
+ if (namespace === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not present on the contract`);
522
+ const qualifyTable = namespace.qualifyTable;
523
+ if (qualifyTable === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not materialised for SQL rendering on the contract`);
524
+ return qualifyTable.call(namespace, table.name);
525
+ }
526
+ function renderTableSource(source, contract) {
527
+ const qualified = qualifyTableFromNamespaceCoordinate(source, contract);
528
+ if (!source.alias) return qualified;
529
+ return `${qualified} AS ${quoteIdentifier(source.alias)}`;
530
+ }
531
+ function renderSource(source, contract) {
532
+ const node = source;
533
+ switch (node.kind) {
534
+ case "table-source": return renderTableSource(node, contract);
535
+ case "derived-table-source": return `(${renderSelect(node.query, contract)}) AS ${quoteIdentifier(node.alias)}`;
536
+ default: throw new Error(`Unsupported source node kind: ${node.kind}`);
537
+ }
538
+ }
539
+ function renderExpr(expr, contract) {
540
+ const node = expr;
541
+ switch (node.kind) {
542
+ case "column-ref": return renderColumn(node);
543
+ case "identifier-ref": return quoteIdentifier(node.name);
544
+ case "operation": return renderOperation(node, contract);
545
+ case "subquery": return renderSubqueryExpr(node, contract);
546
+ case "aggregate": return renderAggregateExpr(node, contract);
547
+ case "window-func": return renderWindowFuncExpr(node, contract);
548
+ case "json-object": return renderJsonObjectExpr(node, contract);
549
+ case "json-array-agg": return renderJsonArrayAggExpr(node, contract);
550
+ case "binary": return renderBinary(node, contract);
551
+ case "and":
552
+ if (node.exprs.length === 0) return "TRUE";
553
+ return `(${node.exprs.map((part) => renderExpr(part, contract)).join(" AND ")})`;
554
+ case "or":
555
+ if (node.exprs.length === 0) return "FALSE";
556
+ return `(${node.exprs.map((part) => renderExpr(part, contract)).join(" OR ")})`;
557
+ case "exists":
558
+ if (contract === void 0) throw new Error("EXISTS subquery rendering requires a Sqlite contract");
559
+ return `${node.notExists ? "NOT " : ""}EXISTS (${renderSelect(node.subquery, contract)})`;
560
+ case "null-check": return renderNullCheck(node, contract);
561
+ case "not": return `NOT (${renderExpr(node.expr, contract)})`;
562
+ case "param-ref":
563
+ case "prepared-param-ref": return "?";
564
+ case "literal": return renderLiteral(node);
565
+ case "list": return renderListLiteral(node);
566
+ case "raw-expr": return renderRawExpr(node, contract);
567
+ default: throw new Error(`Unsupported expression node kind: ${node.kind}`);
568
+ }
569
+ }
570
+ function renderRawExpr(node, contract) {
571
+ return node.parts.map((part) => typeof part === "string" ? part : renderExpr(part, contract)).join("");
572
+ }
573
+ function renderColumn(ref) {
574
+ if (ref.table === "excluded") return `excluded.${quoteIdentifier(ref.column)}`;
575
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
576
+ }
577
+ function renderLiteral(expr) {
578
+ if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
579
+ if (typeof expr.value === "number" || typeof expr.value === "boolean") return String(expr.value);
580
+ if (typeof expr.value === "bigint") return String(expr.value);
581
+ if (expr.value === null || expr.value === void 0) return "NULL";
582
+ if (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;
583
+ const json = JSON.stringify(expr.value);
584
+ if (json === void 0) return "NULL";
585
+ return `'${escapeLiteral(json)}'`;
586
+ }
587
+ function renderOperation(expr, contract) {
588
+ const self = renderExpr(expr.self, contract);
589
+ const args = expr.args.map((arg) => renderExpr(arg, contract));
590
+ let result = expr.lowering.template;
591
+ result = result.replace(/\{\{self\}\}/g, self);
592
+ for (let i = 0; i < args.length; i++) result = result.replace(new RegExp(`\\{\\{arg${i}\\}\\}`, "g"), args[i] ?? "");
593
+ return result;
594
+ }
595
+ function renderSubqueryExpr(expr, contract) {
596
+ if (expr.query.projection.length !== 1) throw new Error("Subquery expressions must project exactly one column");
597
+ if (contract === void 0) throw new Error("Subquery expression rendering requires a Sqlite contract");
598
+ return `(${renderSelect(expr.query, contract)})`;
599
+ }
600
+ function renderNullCheck(expr, contract) {
601
+ const rendered = renderExpr(expr.expr, contract);
602
+ const renderedExpr = expr.expr.kind === "operation" || expr.expr.kind === "subquery" ? `(${rendered})` : rendered;
603
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
604
+ }
605
+ function renderBinary(expr, contract) {
606
+ if (expr.right.kind === "list" && expr.right.values.length === 0) {
607
+ if (expr.op === "in") return "FALSE";
608
+ if (expr.op === "notIn") return "TRUE";
609
+ }
610
+ const leftExpr = expr.left;
611
+ const left = renderExpr(leftExpr, contract);
612
+ const leftRendered = leftExpr.kind === "operation" || leftExpr.kind === "subquery" ? `(${left})` : left;
613
+ const rightNode = expr.right;
614
+ let right;
615
+ switch (rightNode.kind) {
616
+ case "list":
617
+ right = renderListLiteral(rightNode);
618
+ break;
619
+ case "literal":
620
+ right = renderLiteral(rightNode);
621
+ break;
622
+ case "column-ref":
623
+ right = renderColumn(rightNode);
624
+ break;
625
+ case "param-ref":
626
+ case "prepared-param-ref":
627
+ right = "?";
628
+ break;
629
+ default:
630
+ right = renderExpr(rightNode, contract);
631
+ break;
632
+ }
633
+ return `${leftRendered} ${{
634
+ eq: "=",
635
+ neq: "!=",
636
+ gt: ">",
637
+ lt: "<",
638
+ gte: ">=",
639
+ lte: "<=",
640
+ like: "LIKE",
641
+ in: "IN",
642
+ notIn: "NOT IN"
643
+ }[expr.op]} ${right}`;
644
+ }
645
+ function renderListLiteral(expr) {
646
+ if (expr.values.length === 0) return "(NULL)";
647
+ return `(${expr.values.map((v) => {
648
+ if (v.kind === "param-ref" || v.kind === "prepared-param-ref") return "?";
649
+ if (v.kind === "literal") return renderLiteral(v);
650
+ return renderExpr(v);
651
+ }).join(", ")})`;
652
+ }
653
+ function renderAggregateExpr(expr, contract) {
654
+ const fn = expr.fn.toUpperCase();
655
+ if (!expr.expr) return `${fn}(*)`;
656
+ return `${fn}(${renderExpr(expr.expr, contract)})`;
657
+ }
658
+ function renderWindowFuncExpr(expr, contract) {
659
+ return `${expr.fn.toUpperCase()}(${expr.args.map((arg) => renderExpr(arg, contract)).join(", ")}) OVER (${[expr.partitionBy && expr.partitionBy.length > 0 ? `PARTITION BY ${expr.partitionBy.map((e) => renderExpr(e, contract)).join(", ")}` : "", expr.orderBy && expr.orderBy.length > 0 ? `ORDER BY ${renderOrderByItems(expr.orderBy, contract)}` : ""].filter((part) => part.length > 0).join(" ")})`;
660
+ }
661
+ function renderJsonObjectExpr(expr, contract) {
662
+ return `json_object(${expr.entries.flatMap((entry) => {
663
+ const key = `'${escapeLiteral(entry.key)}'`;
664
+ if (entry.value.kind === "literal") return [key, renderLiteral(entry.value)];
665
+ return [key, renderExpr(entry.value, contract)];
666
+ }).join(", ")})`;
667
+ }
668
+ function renderOrderByItems(items, contract) {
669
+ return items.map((item) => `${renderExpr(item.expr, contract)} ${item.dir.toUpperCase()}`).join(", ");
670
+ }
671
+ function renderJsonArrayAggExpr(expr, contract) {
672
+ const aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract)}` : "";
673
+ const aggregated = `json_group_array(${renderExpr(expr.expr, contract)}${aggregateOrderBy})`;
674
+ if (expr.onEmpty === "emptyArray") return `coalesce(${aggregated}, '[]')`;
675
+ return aggregated;
676
+ }
677
+ function renderJoin(join, contract) {
678
+ if (contract === void 0) throw new Error("JOIN rendering requires a Sqlite contract");
679
+ return `${join.joinType.toUpperCase()} JOIN ${renderSource(join.source, contract)} ON ${renderJoinOn(join.on, contract)}`;
680
+ }
681
+ function renderJoinOn(on, contract) {
682
+ if (on.kind === "eq-col-join-on") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;
683
+ return renderExpr(on, contract);
684
+ }
685
+ function renderInsertValue(value) {
686
+ switch (value.kind) {
687
+ case "param-ref":
688
+ case "prepared-param-ref": return "?";
689
+ case "column-ref": return renderColumn(value);
690
+ case "raw-expr": return renderExpr(value);
691
+ case "default-value": throw new Error("SQLite does not support DEFAULT as a value in INSERT ... VALUES");
692
+ default: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);
693
+ }
694
+ }
695
+ function renderInsert(ast, contract) {
696
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
697
+ const rows = ast.rows;
698
+ if (rows.length === 0) throw new Error("INSERT requires at least one row");
699
+ const firstRow = rows[0];
700
+ const columnOrder = Object.keys(firstRow);
701
+ let insertClause;
702
+ if (columnOrder.length === 0) insertClause = `INSERT INTO ${table} DEFAULT VALUES`;
703
+ else {
704
+ const columns = columnOrder.map((column) => quoteIdentifier(column));
705
+ const values = rows.map((row) => {
706
+ return `(${columnOrder.map((column) => {
707
+ const value = row[column];
708
+ if (value === void 0) throw new Error(`Missing value for column "${column}" in INSERT row`);
709
+ return renderInsertValue(value);
710
+ }).join(", ")})`;
711
+ }).join(", ");
712
+ insertClause = `INSERT INTO ${table} (${columns.join(", ")}) VALUES ${values}`;
713
+ }
714
+ let onConflictClause = "";
715
+ if (ast.onConflict) {
716
+ const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));
717
+ if (conflictColumns.length === 0) throw new Error("INSERT onConflict requires at least one conflict column");
718
+ const action = ast.onConflict.action;
719
+ switch (action.kind) {
720
+ case "do-nothing":
721
+ onConflictClause = ` ON CONFLICT (${conflictColumns.join(", ")}) DO NOTHING`;
722
+ break;
723
+ case "do-update-set": {
724
+ const updates = Object.entries(action.set).map(([colName, value]) => {
725
+ return `${quoteIdentifier(colName)} = ${renderExpr(value, contract)}`;
726
+ });
727
+ onConflictClause = ` ON CONFLICT (${conflictColumns.join(", ")}) DO UPDATE SET ${updates.join(", ")}`;
728
+ break;
729
+ }
730
+ default: throw new Error(`Unsupported onConflict action: ${action.kind}`);
731
+ }
732
+ }
733
+ const returningClause = renderReturning(ast.returning);
734
+ return `${insertClause}${onConflictClause}${returningClause}`;
735
+ }
736
+ function renderUpdate(ast, contract) {
737
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
738
+ const setClauses = Object.entries(ast.set).map(([col, val]) => {
739
+ return `${quoteIdentifier(col)} = ${renderExpr(val, contract)}`;
740
+ });
741
+ const whereClause = ast.where ? ` WHERE ${renderExpr(ast.where, contract)}` : "";
742
+ const returningClause = renderReturning(ast.returning);
743
+ return `UPDATE ${table} SET ${setClauses.join(", ")}${whereClause}${returningClause}`;
744
+ }
745
+ function renderDelete(ast, contract) {
746
+ return `DELETE FROM ${qualifyTableFromNamespaceCoordinate(ast.table, contract)}${ast.where ? ` WHERE ${renderExpr(ast.where)}` : ""}${renderReturning(ast.returning)}`;
747
+ }
748
+ function renderReturning(returning) {
749
+ if (!returning?.length) return "";
750
+ return ` RETURNING ${returning.map((item) => {
751
+ if (item.expr.kind === "column-ref") {
752
+ const rendered = `${quoteIdentifier(item.expr.table)}.${quoteIdentifier(item.expr.column)}`;
753
+ return item.expr.column === item.alias ? rendered : `${rendered} AS ${quoteIdentifier(item.alias)}`;
754
+ }
755
+ return `${renderExpr(item.expr)} AS ${quoteIdentifier(item.alias)}`;
756
+ }).join(", ")}`;
757
+ }
758
+ function createSqliteAdapter(options) {
759
+ return Object.freeze(new SqliteAdapterImpl(options));
760
+ }
761
+ //#endregion
762
+ export { sqliteRawCodecInferer as n, SqliteControlAdapter as r, createSqliteAdapter as t };
763
+
764
+ //# sourceMappingURL=adapter-CwTpH1kL.mjs.map