@prisma-next/adapter-postgres 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,1364 @@
1
+ import { APP_SPACE_ID, extractCodecLookup } from "@prisma-next/framework-components/control";
2
+ import { LiteralExpr, RawExpr, collectOrderedParamRefs, isDdlNode } from "@prisma-next/sql-relational-core/ast";
3
+ import { postgresCodecRegistry } from "@prisma-next/target-postgres/codecs";
4
+ import { parseMarkerRowSafely, rethrowMarkerReadError, withMarkerReadErrorHandling } from "@prisma-next/errors/execution";
5
+ import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
6
+ import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
7
+ import { postgresColumnsCompatible } from "@prisma-next/target-postgres/column-type-compatibility";
8
+ import { PostgresTableSource, buildControlTableBootstrapQueries, buildSignMarkerBootstrapQueries, int4, int8, jsonb, pgTable, text, textArray, timestamptz } from "@prisma-next/target-postgres/contract-free";
9
+ import { parsePostgresDefault } from "@prisma-next/target-postgres/default-normalizer";
10
+ import { createResolveExistingEnumValues, enumStorageCompoundKey, readExistingEnumValues, readPostgresSchemaIrAnnotations } from "@prisma-next/target-postgres/enum-planning";
11
+ import { normalizeSchemaNativeType } from "@prisma-next/target-postgres/native-type-normalizer";
12
+ import { blindCast } from "@prisma-next/utils/casts";
13
+ import { ifDefined } from "@prisma-next/utils/defined";
14
+ import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
15
+ import { PG_ENUM_CODEC_ID, PG_TIMESTAMPTZ_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
16
+ import { createAstCodecRegistry, deriveParamMetadata, encodeParamsWithMetadata } from "@prisma-next/sql-runtime";
17
+ import { runtimeError } from "@prisma-next/framework-components/runtime";
18
+ //#region src/core/codec-lookup.ts
19
+ /**
20
+ * Build a {@link CodecLookup} populated with the Postgres-builtin codec definitions only.
21
+ *
22
+ * This is the default lookup used by `createPostgresAdapter()` and `new PostgresControlAdapter()` when called without a stack-derived lookup (e.g. from tests, or one-off scripts that don't compose a full stack).
23
+ *
24
+ * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`) are intentionally NOT included here: a bare adapter cannot see extensions. Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` / `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader, extension-inclusive lookup at construction time.
25
+ */
26
+ function createPostgresBuiltinCodecLookup() {
27
+ return extractCodecLookup([{
28
+ id: "postgres-builtin-codecs",
29
+ types: { codecTypes: { codecDescriptors: Array.from(postgresCodecRegistry.values()) } }
30
+ }]);
31
+ }
32
+ //#endregion
33
+ //#region ../../../1-framework/3-tooling/migration/dist/exports/ledger-origin.mjs
34
+ function ledgerOriginFromStored(originCoreHash) {
35
+ if (originCoreHash === null || originCoreHash === "" || originCoreHash === "sha256:empty") return null;
36
+ return originCoreHash;
37
+ }
38
+ //#endregion
39
+ //#region src/core/ddl-renderer.ts
40
+ var PostgresDdlVisitorImpl = class {
41
+ createTable(node) {
42
+ return `create table ${node.ifNotExists ? "if not exists " : ""}${node.schema ? `${node.schema}.${node.table}` : node.table} (\n ${node.columns.map((column) => renderColumn$1(column)).join(",\n ")}\n )`;
43
+ }
44
+ createSchema(node) {
45
+ return `create schema ${node.ifNotExists ? "if not exists " : ""}${node.schema}`;
46
+ }
47
+ };
48
+ const defaultVisitor = {
49
+ literal(node) {
50
+ const { value } = node;
51
+ if (typeof value === "string") return `default '${escapeLiteral(value)}'`;
52
+ if (typeof value === "number" || typeof value === "boolean") return `default ${String(value)}`;
53
+ if (value === null) return "default null";
54
+ return `default '${JSON.stringify(value)}'`;
55
+ },
56
+ function(node) {
57
+ if (node.expression === "autoincrement()") return "";
58
+ if (node.expression === "now()") return "default now()";
59
+ return `default (${node.expression})`;
60
+ }
61
+ };
62
+ function renderColumn$1(column) {
63
+ const parts = [column.name, column.type];
64
+ if (column.notNull) parts.push("not null");
65
+ if (column.primaryKey) parts.push("primary key");
66
+ const defaultClause = column.default ? column.default.accept(defaultVisitor) : "";
67
+ if (defaultClause.length > 0) parts.push(defaultClause);
68
+ return parts.join(" ");
69
+ }
70
+ function renderLoweredDdl(ast) {
71
+ const sql = ast.accept(new PostgresDdlVisitorImpl());
72
+ return Object.freeze({
73
+ sql,
74
+ params: Object.freeze([])
75
+ });
76
+ }
77
+ //#endregion
78
+ //#region src/core/enum-control-hooks.ts
79
+ const ENUM_INTROSPECT_QUERY = `
80
+ SELECT
81
+ n.nspname AS schema_name,
82
+ t.typname AS type_name,
83
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
84
+ FROM pg_type t
85
+ JOIN pg_namespace n ON t.typnamespace = n.oid
86
+ JOIN pg_enum e ON t.oid = e.enumtypid
87
+ WHERE n.nspname = $1
88
+ GROUP BY n.nspname, t.typname
89
+ ORDER BY n.nspname, t.typname
90
+ `;
91
+ function isStringArray(value) {
92
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
93
+ }
94
+ /**
95
+ * Parses a PostgreSQL array value into a JavaScript string array.
96
+ *
97
+ * The `pg` library returns `array_agg` results either as a JS array
98
+ * (when type parsers are configured) or as a string in PostgreSQL array
99
+ * literal format (`{value1,value2,...}`). Handles PG's quoting rules:
100
+ * - Elements containing commas, quotes, backslashes, or whitespace are
101
+ * double-quoted.
102
+ * - Inside quoted elements, `\"` represents `"` and `\\` represents `\`.
103
+ *
104
+ * Returns `null` when the input cannot be parsed as a PG array.
105
+ */
106
+ function parsePostgresArray(value) {
107
+ if (isStringArray(value)) return value;
108
+ if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
109
+ const inner = value.slice(1, -1);
110
+ if (inner === "") return [];
111
+ return parseArrayElements(inner);
112
+ }
113
+ return null;
114
+ }
115
+ function parseArrayElements(input) {
116
+ const result = [];
117
+ let i = 0;
118
+ while (i < input.length) {
119
+ if (input[i] === ",") {
120
+ i++;
121
+ continue;
122
+ }
123
+ if (input[i] === "\"") {
124
+ i++;
125
+ let element = "";
126
+ while (i < input.length && input[i] !== "\"") {
127
+ if (input[i] === "\\" && i + 1 < input.length) {
128
+ i++;
129
+ element += input[i];
130
+ } else element += input[i];
131
+ i++;
132
+ }
133
+ i++;
134
+ result.push(element);
135
+ } else {
136
+ const nextComma = input.indexOf(",", i);
137
+ if (nextComma === -1) {
138
+ result.push(input.slice(i).trim());
139
+ i = input.length;
140
+ } else {
141
+ result.push(input.slice(i, nextComma).trim());
142
+ i = nextComma;
143
+ }
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * Reads enum types from the live Postgres schema and returns them in
150
+ * the codec-typed annotation shape consumed by `control-adapter.ts`
151
+ * (which writes them under `schema.annotations.pg.storageTypes`).
152
+ */
153
+ async function introspectPostgresEnumTypes(options) {
154
+ const namespace = options.schemaName ?? "public";
155
+ const result = await options.driver.query(ENUM_INTROSPECT_QUERY, [namespace]);
156
+ const types = {};
157
+ for (const row of result.rows) {
158
+ const values = parsePostgresArray(row.values);
159
+ if (!values) throw new Error(`Failed to parse enum values for type "${row.type_name}": unexpected format: ${JSON.stringify(row.values)}`);
160
+ types[row.type_name] = {
161
+ codecId: PG_ENUM_CODEC_ID,
162
+ nativeType: row.type_name,
163
+ typeParams: { values }
164
+ };
165
+ }
166
+ return types;
167
+ }
168
+ //#endregion
169
+ //#region src/core/marker-ledger.ts
170
+ const CONTROL_CODECS = createAstCodecRegistry(postgresCodecRegistry);
171
+ const marker = pgTable({
172
+ name: "marker",
173
+ schema: "prisma_contract"
174
+ }, {
175
+ space: text(),
176
+ core_hash: text(),
177
+ profile_hash: text(),
178
+ contract_json: jsonb({ nullable: true }),
179
+ canonical_version: int4({ nullable: true }),
180
+ updated_at: timestamptz(),
181
+ app_tag: text({ nullable: true }),
182
+ meta: jsonb({ nullable: true }),
183
+ invariants: textArray()
184
+ });
185
+ /**
186
+ * Writeable subset of the `prisma_contract.ledger` table. Omits the
187
+ * DB-generated `id` (bigserial) and `created_at` (default `now()`) so the
188
+ * insert path doesn't have to pass them.
189
+ */
190
+ const ledger = pgTable({
191
+ name: "ledger",
192
+ schema: "prisma_contract"
193
+ }, {
194
+ space: text(),
195
+ migration_name: text(),
196
+ migration_hash: text(),
197
+ origin_core_hash: text({ nullable: true }),
198
+ destination_core_hash: text(),
199
+ operations: jsonb()
200
+ });
201
+ /**
202
+ * Read-side handle covering every column of `prisma_contract.ledger`,
203
+ * including the DB-generated `id` (for ORDER BY) and `created_at`.
204
+ */
205
+ const ledgerReadShape = pgTable({
206
+ name: "ledger",
207
+ schema: "prisma_contract"
208
+ }, {
209
+ id: int8(),
210
+ space: text(),
211
+ migration_name: text(),
212
+ migration_hash: text(),
213
+ origin_core_hash: text({ nullable: true }),
214
+ destination_core_hash: text(),
215
+ operations: jsonb(),
216
+ created_at: timestamptz()
217
+ });
218
+ const infoSchemaTables = pgTable({
219
+ name: "tables",
220
+ schema: "information_schema"
221
+ }, {
222
+ table_schema: text(),
223
+ table_name: text()
224
+ });
225
+ const NOW = new RawExpr({
226
+ parts: ["now()"],
227
+ returns: {
228
+ codecId: PG_TIMESTAMPTZ_CODEC_ID,
229
+ nullable: false
230
+ }
231
+ });
232
+ function mergeInvariants(current, incoming) {
233
+ return [...new Set([...current, ...incoming])].sort();
234
+ }
235
+ async function execute(lower, driver, query) {
236
+ const lowered = lower(query);
237
+ const encoded = await encodeParamsWithMetadata(lowered.params.map((slot) => {
238
+ if (slot.kind === "literal") return slot.value;
239
+ throw new Error("Postgres control DML lowered to a bind parameter, which is unsupported");
240
+ }), deriveParamMetadata(query), {}, CONTROL_CODECS);
241
+ return (await driver.query(lowered.sql, encoded)).rows;
242
+ }
243
+ //#endregion
244
+ //#region src/core/sql-renderer.ts
245
+ /**
246
+ * Postgres native types whose unknown-OID parameter inference is reliable in arbitrary expression positions. Parameters bound to a codec whose `meta.db.sql.postgres.nativeType` falls in this set are emitted as plain `$N`; everything else (including `json`, `jsonb`, extension types like `vector`, and unknown user types) is emitted as `$N::<nativeType>` so the planner picks an unambiguous overload.
247
+ *
248
+ * `json` / `jsonb` are intentionally excluded despite being Postgres builtins: their operator overloads make context inference unreliable in expression positions (e.g. `$1 -> 'key'` is ambiguous between the two).
249
+ *
250
+ * Spellings match the on-disk `meta.db.sql.postgres.nativeType` values in `@prisma-next/target-postgres`'s codec definitions, not the `udt_name` abbreviations that ADR 205 used as illustrative shorthand. The lookup-based cast policy compares against these strings directly.
251
+ */
252
+ const POSTGRES_INFERRABLE_NATIVE_TYPES = new Set([
253
+ "integer",
254
+ "smallint",
255
+ "bigint",
256
+ "real",
257
+ "double precision",
258
+ "numeric",
259
+ "boolean",
260
+ "text",
261
+ "character",
262
+ "character varying",
263
+ "timestamp",
264
+ "timestamp without time zone",
265
+ "timestamp with time zone",
266
+ "time",
267
+ "timetz",
268
+ "interval",
269
+ "bit",
270
+ "bit varying"
271
+ ]);
272
+ function renderTypedParam(index, codecId, codecLookup) {
273
+ if (codecId === void 0) return `$${index}`;
274
+ const meta = codecLookup.metaFor(codecId);
275
+ if (!(codecLookup.get(codecId) !== void 0 || meta !== void 0 || codecLookup.targetTypesFor(codecId) !== void 0)) throw new Error(`Postgres lowering: ParamRef carries codecId "${codecId}" but the assembled codec lookup has no entry for it. This usually indicates a missing extension pack in the runtime stack — register the pack that contributes this codec (e.g. \`extensionPacks: [pgvectorRuntime]\`), or use the codec directly from \`@prisma-next/target-postgres/codecs\` if it's a builtin.`);
276
+ const dbRecord = meta?.db;
277
+ const sqlBlock = isRecord(dbRecord) ? dbRecord["sql"] : void 0;
278
+ const dialectBlock = isRecord(sqlBlock) ? sqlBlock["postgres"] : void 0;
279
+ const nativeType = isRecord(dialectBlock) ? dialectBlock["nativeType"] : void 0;
280
+ if (typeof nativeType === "string" && !POSTGRES_INFERRABLE_NATIVE_TYPES.has(nativeType)) return `$${index}::${nativeType}`;
281
+ return `$${index}`;
282
+ }
283
+ function isRecord(value) {
284
+ return typeof value === "object" && value !== null;
285
+ }
286
+ /**
287
+ * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.
288
+ *
289
+ * Shared between the runtime (`PostgresAdapterImpl.lower`) and control (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time paths produce byte-identical output for the same AST.
290
+ */
291
+ function renderLoweredSql(ast, contract, codecLookup) {
292
+ const orderedRefs = collectOrderedParamRefs(ast);
293
+ const indexMap = /* @__PURE__ */ new Map();
294
+ const params = orderedRefs.map((ref, i) => {
295
+ indexMap.set(ref, i + 1);
296
+ return ref.kind === "prepared-param-ref" ? {
297
+ kind: "bind",
298
+ name: ref.name
299
+ } : {
300
+ kind: "literal",
301
+ value: ref.value
302
+ };
303
+ });
304
+ const pim = {
305
+ indexMap,
306
+ codecLookup
307
+ };
308
+ const node = ast;
309
+ let sql;
310
+ switch (node.kind) {
311
+ case "select":
312
+ sql = renderSelect(node, contract, pim);
313
+ break;
314
+ case "insert":
315
+ sql = renderInsert(node, contract, pim);
316
+ break;
317
+ case "update":
318
+ sql = renderUpdate(node, contract, pim);
319
+ break;
320
+ case "delete":
321
+ sql = renderDelete(node, contract, pim);
322
+ break;
323
+ case "raw-sql":
324
+ sql = renderRawSql(node, contract, pim);
325
+ break;
326
+ // v8 ignore next 4
327
+ default: throw new Error(`Unsupported AST node kind: ${node.kind}`);
328
+ }
329
+ return Object.freeze({
330
+ sql,
331
+ params: Object.freeze(params)
332
+ });
333
+ }
334
+ function renderLimitOffset(keyword, value, contract, pim) {
335
+ if (value === void 0) return "";
336
+ if (typeof value === "number") return `${keyword} ${value}`;
337
+ return `${keyword} ${renderExpr(value, contract, pim)}`;
338
+ }
339
+ function renderSelect(ast, contract, pim) {
340
+ return [
341
+ `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(ast.projection, contract, pim)}`,
342
+ `FROM ${renderSource(ast.from, contract, pim)}`,
343
+ ast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(" ") : "",
344
+ ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : "",
345
+ ast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(", ")}` : "",
346
+ ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : "",
347
+ ast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => {
348
+ return `${renderExpr(order.expr, contract, pim)} ${order.dir.toUpperCase()}`;
349
+ }).join(", ")}` : "",
350
+ renderLimitOffset("LIMIT", ast.limit, contract, pim),
351
+ renderLimitOffset("OFFSET", ast.offset, contract, pim)
352
+ ].filter((part) => part.length > 0).join(" ").trim();
353
+ }
354
+ function renderProjection(projection, contract, pim) {
355
+ return projection.map((item) => {
356
+ const alias = quoteIdentifier(item.alias);
357
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${alias}`;
358
+ return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;
359
+ }).join(", ");
360
+ }
361
+ function renderReturning(items, contract, pim) {
362
+ return items.map((item) => {
363
+ if (item.expr.kind === "column-ref") {
364
+ const rendered = renderColumn(item.expr);
365
+ return item.expr.column === item.alias ? rendered : `${rendered} AS ${quoteIdentifier(item.alias)}`;
366
+ }
367
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${quoteIdentifier(item.alias)}`;
368
+ return `${renderExpr(item.expr, contract, pim)} AS ${quoteIdentifier(item.alias)}`;
369
+ }).join(", ");
370
+ }
371
+ function renderDistinctPrefix(distinct, distinctOn, contract, pim) {
372
+ if (distinctOn && distinctOn.length > 0) return `DISTINCT ON (${distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(", ")}) `;
373
+ if (distinct) return "DISTINCT ";
374
+ return "";
375
+ }
376
+ function qualifyTableFromNamespaceCoordinate(table, contract) {
377
+ if (table instanceof PostgresTableSource && table.schema !== void 0) return `${quoteIdentifier(table.schema)}.${quoteIdentifier(table.name)}`;
378
+ if (table.namespaceId === void 0) return quoteIdentifier(table.name);
379
+ const namespace = contract.storage.namespaces[table.namespaceId];
380
+ if (namespace === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not present as a Postgres schema on the contract`);
381
+ const qualifyTable = namespace.qualifyTable;
382
+ if (qualifyTable === void 0) throw new Error(`Table "${table.name}" references namespace "${table.namespaceId}" which is not materialised as a Postgres schema on the contract`);
383
+ return qualifyTable.call(namespace, table.name);
384
+ }
385
+ function renderTableSource(source, contract) {
386
+ const qualified = qualifyTableFromNamespaceCoordinate(source, contract);
387
+ if (!source.alias) return qualified;
388
+ return `${qualified} AS ${quoteIdentifier(source.alias)}`;
389
+ }
390
+ function renderSource(source, contract, pim) {
391
+ const node = source;
392
+ switch (node.kind) {
393
+ case "table-source": return renderTableSource(node, contract);
394
+ case "derived-table-source": return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;
395
+ // v8 ignore next 4
396
+ default: throw new Error(`Unsupported source node kind: ${node.kind}`);
397
+ }
398
+ }
399
+ function assertScalarSubquery(query) {
400
+ if (query.projection.length !== 1) throw new Error("Subquery expressions must project exactly one column");
401
+ }
402
+ function renderSubqueryExpr(expr, contract, pim) {
403
+ assertScalarSubquery(expr.query);
404
+ return `(${renderSelect(expr.query, contract, pim)})`;
405
+ }
406
+ function renderWhere(expr, contract, pim) {
407
+ return renderExpr(expr, contract, pim);
408
+ }
409
+ function renderNullCheck(expr, contract, pim) {
410
+ const rendered = renderExpr(expr.expr, contract, pim);
411
+ const renderedExpr = isAtomicExpressionKind(expr.expr.kind) ? rendered : `(${rendered})`;
412
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
413
+ }
414
+ /**
415
+ * Atomic expression kinds whose rendered SQL is already self-delimited (a column reference, parameter, literal, function call, aggregate, etc.) and therefore does not need surrounding parentheses when used as the left operand of a postfix predicate like `IS NULL` or `IS NOT NULL`, or as either operand of a binary infix operator.
416
+ *
417
+ * Anything not in this set is treated as composite (binary, AND/OR/NOT, EXISTS, nested IS NULL, subqueries, operation templates) and gets wrapped to preserve grouping.
418
+ */
419
+ function isAtomicExpressionKind(kind) {
420
+ switch (kind) {
421
+ case "column-ref":
422
+ case "identifier-ref":
423
+ case "param-ref":
424
+ case "prepared-param-ref":
425
+ case "literal":
426
+ case "aggregate":
427
+ case "window-func":
428
+ case "json-object":
429
+ case "json-array-agg":
430
+ case "list": return true;
431
+ case "subquery":
432
+ case "operation":
433
+ case "binary":
434
+ case "and":
435
+ case "or":
436
+ case "exists":
437
+ case "null-check":
438
+ case "not":
439
+ case "raw-expr": return false;
440
+ }
441
+ }
442
+ function renderBinary(expr, contract, pim) {
443
+ if (expr.right.kind === "list" && expr.right.values.length === 0) {
444
+ if (expr.op === "in") return "FALSE";
445
+ if (expr.op === "notIn") return "TRUE";
446
+ }
447
+ const leftExpr = expr.left;
448
+ const left = renderExpr(leftExpr, contract, pim);
449
+ const leftRendered = leftExpr.kind === "operation" || leftExpr.kind === "subquery" ? `(${left})` : left;
450
+ const rightNode = expr.right;
451
+ let right;
452
+ switch (rightNode.kind) {
453
+ case "list":
454
+ right = renderListLiteral(rightNode, contract, pim);
455
+ break;
456
+ case "literal":
457
+ right = renderLiteral(rightNode);
458
+ break;
459
+ case "column-ref":
460
+ right = renderColumn(rightNode);
461
+ break;
462
+ case "param-ref":
463
+ case "prepared-param-ref":
464
+ right = renderParamRef(rightNode, pim);
465
+ break;
466
+ default:
467
+ right = renderExpr(rightNode, contract, pim);
468
+ break;
469
+ }
470
+ return `${leftRendered} ${{
471
+ eq: "=",
472
+ neq: "!=",
473
+ gt: ">",
474
+ lt: "<",
475
+ gte: ">=",
476
+ lte: "<=",
477
+ like: "LIKE",
478
+ in: "IN",
479
+ notIn: "NOT IN"
480
+ }[expr.op]} ${right}`;
481
+ }
482
+ function renderListLiteral(expr, contract, pim) {
483
+ if (expr.values.length === 0) return "(NULL)";
484
+ return `(${expr.values.map((v) => {
485
+ if (v.kind === "param-ref" || v.kind === "prepared-param-ref") return renderParamRef(v, pim);
486
+ if (v.kind === "literal") return renderLiteral(v);
487
+ return renderExpr(v, contract, pim);
488
+ }).join(", ")})`;
489
+ }
490
+ function renderColumn(ref) {
491
+ if (ref.table === "excluded") return `excluded.${quoteIdentifier(ref.column)}`;
492
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
493
+ }
494
+ function renderAggregateExpr(expr, contract, pim) {
495
+ const fn = expr.fn.toUpperCase();
496
+ if (!expr.expr) return `${fn}(*)`;
497
+ return `${fn}(${renderExpr(expr.expr, contract, pim)})`;
498
+ }
499
+ function renderWindowFuncExpr(expr, contract, pim) {
500
+ return `${expr.fn.toUpperCase()}(${expr.args.map((arg) => renderExpr(arg, contract, pim)).join(", ")}) OVER (${[expr.partitionBy && expr.partitionBy.length > 0 ? `PARTITION BY ${expr.partitionBy.map((e) => renderExpr(e, contract, pim)).join(", ")}` : "", expr.orderBy && expr.orderBy.length > 0 ? `ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : ""].filter((part) => part.length > 0).join(" ")})`;
501
+ }
502
+ function renderJsonObjectExpr(expr, contract, pim) {
503
+ return `json_build_object(${expr.entries.flatMap((entry) => {
504
+ const key = `'${escapeLiteral(entry.key)}'`;
505
+ if (entry.value.kind === "literal") return [key, renderLiteral(entry.value)];
506
+ return [key, renderExpr(entry.value, contract, pim)];
507
+ }).join(", ")})`;
508
+ }
509
+ function renderOrderByItems(items, contract, pim) {
510
+ return items.map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`).join(", ");
511
+ }
512
+ function renderJsonArrayAggExpr(expr, contract, pim) {
513
+ const aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : "";
514
+ const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;
515
+ if (expr.onEmpty === "emptyArray") return `coalesce(${aggregated}, json_build_array())`;
516
+ return aggregated;
517
+ }
518
+ function renderExpr(expr, contract, pim) {
519
+ const node = expr;
520
+ switch (node.kind) {
521
+ case "column-ref": return renderColumn(node);
522
+ case "identifier-ref": return quoteIdentifier(node.name);
523
+ case "operation": return renderOperation(node, contract, pim);
524
+ case "subquery": return renderSubqueryExpr(node, contract, pim);
525
+ case "aggregate": return renderAggregateExpr(node, contract, pim);
526
+ case "window-func": return renderWindowFuncExpr(node, contract, pim);
527
+ case "json-object": return renderJsonObjectExpr(node, contract, pim);
528
+ case "json-array-agg": return renderJsonArrayAggExpr(node, contract, pim);
529
+ case "binary": return renderBinary(node, contract, pim);
530
+ case "and":
531
+ if (node.exprs.length === 0) return "TRUE";
532
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" AND ")})`;
533
+ case "or":
534
+ if (node.exprs.length === 0) return "FALSE";
535
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" OR ")})`;
536
+ case "exists": return `${node.notExists ? "NOT " : ""}EXISTS (${renderSelect(node.subquery, contract, pim)})`;
537
+ case "null-check": return renderNullCheck(node, contract, pim);
538
+ case "not": return `NOT (${renderExpr(node.expr, contract, pim)})`;
539
+ case "param-ref":
540
+ case "prepared-param-ref": return renderParamRef(node, pim);
541
+ case "literal": return renderLiteral(node);
542
+ case "list": return renderListLiteral(node, contract, pim);
543
+ case "raw-expr": return renderRawExpr(node, contract, pim);
544
+ // v8 ignore next 4
545
+ default: throw new Error(`Unsupported expression node kind: ${node.kind}`);
546
+ }
547
+ }
548
+ function renderParamRef(ref, pim) {
549
+ const index = pim.indexMap.get(ref);
550
+ if (index === void 0) throw new Error("ParamRef not found in index map");
551
+ if (ref.kind === "prepared-param-ref") return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
552
+ if (ref.codec === void 0) throw runtimeError("RUNTIME.PARAM_REF_MISSING_CODEC", "Postgres renderer: ParamRef reached lowering without a bound CodecRef. Every column-bound ParamRef must carry a codec under the AST-bound codec contract. This usually indicates a builder path that constructed a ParamRef without threading the column codec.", {
553
+ paramIndex: index,
554
+ ...ifDefined("name", ref.name)
555
+ });
556
+ return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
557
+ }
558
+ function renderLiteral(expr) {
559
+ if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
560
+ if (typeof expr.value === "number" || typeof expr.value === "boolean") return String(expr.value);
561
+ if (typeof expr.value === "bigint") return String(expr.value);
562
+ if (expr.value === null) return "NULL";
563
+ if (expr.value === void 0) return "NULL";
564
+ if (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;
565
+ if (Array.isArray(expr.value)) return `ARRAY[${expr.value.map((v) => renderLiteral(new LiteralExpr(v))).join(", ")}]`;
566
+ const json = JSON.stringify(expr.value);
567
+ if (json === void 0) return "NULL";
568
+ return `'${escapeLiteral(json)}'`;
569
+ }
570
+ function renderOperation(expr, contract, pim) {
571
+ const self = renderExpr(expr.self, contract, pim);
572
+ const args = expr.args.map((arg) => {
573
+ return renderExpr(arg, contract, pim);
574
+ });
575
+ return expr.lowering.template.replace(/\{\{self\}\}|\{\{arg(\d+)\}\}/g, (token, argIndex) => {
576
+ if (token === "{{self}}") return self;
577
+ const arg = args[Number(argIndex)];
578
+ if (arg === void 0) throw new Error(`Operation lowering template for "${expr.method}" referenced missing argument {{arg${argIndex}}}; template has ${args.length} arg(s)`);
579
+ return arg;
580
+ });
581
+ }
582
+ function renderJoin(join, contract, pim) {
583
+ return `${join.joinType.toUpperCase()} JOIN ${join.lateral ? "LATERAL " : ""}${renderSource(join.source, contract, pim)} ON ${renderJoinOn(join.on, contract, pim)}`;
584
+ }
585
+ function renderJoinOn(on, contract, pim) {
586
+ if (on.kind === "eq-col-join-on") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;
587
+ return renderWhere(on, contract, pim);
588
+ }
589
+ function getInsertColumnOrder(rows, contract, tableRef) {
590
+ const tableName = tableRef.name;
591
+ const orderedColumns = [];
592
+ const seenColumns = /* @__PURE__ */ new Set();
593
+ for (const row of rows) for (const column of Object.keys(row)) {
594
+ if (seenColumns.has(column)) continue;
595
+ seenColumns.add(column);
596
+ orderedColumns.push(column);
597
+ }
598
+ if (orderedColumns.length > 0) return orderedColumns;
599
+ let table;
600
+ if (tableRef.namespaceId !== void 0) table = contract.storage.namespaces[tableRef.namespaceId]?.entries.table[tableName];
601
+ if (table === void 0) for (const ns of Object.values(contract.storage.namespaces)) {
602
+ const found = ns.entries.table[tableName];
603
+ if (found !== void 0) {
604
+ table = found;
605
+ break;
606
+ }
607
+ }
608
+ if (!table) throw new Error(`INSERT target table not found in contract storage: ${tableName}`);
609
+ return Object.keys(table.columns);
610
+ }
611
+ function renderInsertValue(value, contract, pim) {
612
+ if (!value || value.kind === "default-value") return "DEFAULT";
613
+ switch (value.kind) {
614
+ case "param-ref":
615
+ case "prepared-param-ref": return renderParamRef(value, pim);
616
+ case "column-ref": return renderColumn(value);
617
+ case "raw-expr": return renderExpr(value, contract, pim);
618
+ // v8 ignore next 4
619
+ default: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);
620
+ }
621
+ }
622
+ function renderInsert(ast, contract, pim) {
623
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
624
+ const rows = ast.rows;
625
+ if (rows.length === 0) throw new Error("INSERT requires at least one row");
626
+ const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);
627
+ return `${(() => {
628
+ if (!hasExplicitValues) {
629
+ if (rows.length === 1) return `INSERT INTO ${table} DEFAULT VALUES`;
630
+ const defaultColumns = getInsertColumnOrder(rows, contract, ast.table);
631
+ if (defaultColumns.length === 0) return `INSERT INTO ${table} VALUES ${rows.map(() => "()").join(", ")}`;
632
+ const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));
633
+ const defaultRow = `(${defaultColumns.map(() => "DEFAULT").join(", ")})`;
634
+ return `INSERT INTO ${table} (${quotedColumns.join(", ")}) VALUES ${rows.map(() => defaultRow).join(", ")}`;
635
+ }
636
+ const columnOrder = getInsertColumnOrder(rows, contract, ast.table);
637
+ const columns = columnOrder.map((column) => quoteIdentifier(column));
638
+ const values = rows.map((row) => {
639
+ return `(${columnOrder.map((column) => renderInsertValue(row[column], contract, pim)).join(", ")})`;
640
+ }).join(", ");
641
+ return `INSERT INTO ${table} (${columns.join(", ")}) VALUES ${values}`;
642
+ })()}${ast.onConflict ? (() => {
643
+ const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));
644
+ if (conflictColumns.length === 0) throw new Error("INSERT onConflict requires at least one conflict column");
645
+ const action = ast.onConflict.action;
646
+ switch (action.kind) {
647
+ case "do-nothing": return ` ON CONFLICT (${conflictColumns.join(", ")}) DO NOTHING`;
648
+ case "do-update-set": {
649
+ const updateEntries = Object.entries(action.set);
650
+ if (updateEntries.length === 0) throw new Error("INSERT onConflict do-update-set requires at least one assignment");
651
+ const updates = updateEntries.map(([colName, value]) => {
652
+ return `${quoteIdentifier(colName)} = ${renderExpr(value, contract, pim)}`;
653
+ });
654
+ return ` ON CONFLICT (${conflictColumns.join(", ")}) DO UPDATE SET ${updates.join(", ")}`;
655
+ }
656
+ // v8 ignore next 4
657
+ default: throw new Error(`Unsupported onConflict action: ${action.kind}`);
658
+ }
659
+ })() : ""}${ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : ""}`;
660
+ }
661
+ function renderUpdate(ast, contract, pim) {
662
+ const table = qualifyTableFromNamespaceCoordinate(ast.table, contract);
663
+ const setEntries = Object.entries(ast.set);
664
+ if (setEntries.length === 0) throw new Error("UPDATE requires at least one SET assignment");
665
+ const setClauses = setEntries.map(([col, val]) => {
666
+ return `${quoteIdentifier(col)} = ${renderExpr(val, contract, pim)}`;
667
+ });
668
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : "";
669
+ const returningClause = ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : "";
670
+ return `UPDATE ${table} SET ${setClauses.join(", ")}${whereClause}${returningClause}`;
671
+ }
672
+ function renderDelete(ast, contract, pim) {
673
+ return `DELETE FROM ${qualifyTableFromNamespaceCoordinate(ast.table, contract)}${ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : ""}${ast.returning?.length ? ` RETURNING ${renderReturning(ast.returning, contract, pim)}` : ""}`;
674
+ }
675
+ function renderRawSql(ast, contract, pim) {
676
+ const out = [];
677
+ for (let i = 0; i < ast.fragments.length; i++) {
678
+ out.push(ast.fragments[i] ?? "");
679
+ if (i < ast.args.length) {
680
+ const arg = ast.args[i];
681
+ if (arg !== void 0) out.push(renderExpr(arg, contract, pim));
682
+ }
683
+ }
684
+ return out.join("");
685
+ }
686
+ function renderRawExpr(node, contract, pim) {
687
+ return node.parts.map((part) => typeof part === "string" ? part : renderExpr(part, contract, pim)).join("");
688
+ }
689
+ //#endregion
690
+ //#region src/core/control-adapter.ts
691
+ const POSTGRES_MARKER_TABLE = "prisma_contract.marker";
692
+ const POSTGRES_LEDGER_TABLE = "prisma_contract.ledger";
693
+ /**
694
+ * Postgres control plane adapter for control-plane operations like introspection.
695
+ * Provides target-specific implementations for control-plane domain actions.
696
+ */
697
+ var PostgresControlAdapter = class {
698
+ familyId = "sql";
699
+ targetId = "postgres";
700
+ codecLookup;
701
+ /**
702
+ * @param codecLookup - Codec lookup used by the SQL renderer to resolve
703
+ * per-codec metadata at lower-time. Defaults to a Postgres-builtins-only
704
+ * lookup when omitted. Stack-aware callers
705
+ * (`SqlControlAdapterDescriptor.create(stack)`) supply
706
+ * `stack.codecLookup` so extension codecs are visible to the renderer.
707
+ */
708
+ constructor(codecLookup) {
709
+ this.codecLookup = codecLookup ?? createPostgresBuiltinCodecLookup();
710
+ }
711
+ /**
712
+ * Target-specific normalizer for raw Postgres default expressions.
713
+ * Used by schema verification to normalize raw defaults before comparison.
714
+ */
715
+ normalizeDefault = parsePostgresDefault;
716
+ /**
717
+ * Target-specific normalizer for Postgres schema native type names.
718
+ * Used by schema verification to normalize introspected type names
719
+ * before comparison with contract native types.
720
+ */
721
+ normalizeNativeType = normalizeSchemaNativeType;
722
+ /**
723
+ * Target-supplied compatible-shape relation used under the `external`
724
+ * control policy. Threading the same relation the migration planner/runner
725
+ * use keeps runtime verify and migration verify in agreement.
726
+ */
727
+ columnsCompatible = postgresColumnsCompatible;
728
+ /**
729
+ * Bridges native `PostgresEnumStorageEntry` IR walks against the Postgres
730
+ * introspection shape (`schema.annotations.pg.storageTypes`). Lets
731
+ * the family-level schema verifier walk enum types without reaching
732
+ * into target-specific annotation layouts itself.
733
+ */
734
+ resolveExistingEnumValues = (schema, enumType, namespaceId) => {
735
+ return readExistingEnumValues(schema, namespaceId === UNBOUND_NAMESPACE_ID ? readPostgresSchemaIrAnnotations(schema).schema ?? "public" : namespaceId, enumType.nativeType);
736
+ };
737
+ resolveExistingEnumValuesForContract = (contract) => createResolveExistingEnumValues(contract.storage);
738
+ bootstrapControlTableQueries() {
739
+ return buildControlTableBootstrapQueries();
740
+ }
741
+ bootstrapSignMarkerQueries() {
742
+ return buildSignMarkerBootstrapQueries();
743
+ }
744
+ /**
745
+ * Lower a SQL query AST into a Postgres-flavored `{ sql, params }` payload.
746
+ *
747
+ * Delegates to the shared `renderLoweredSql` renderer so the control adapter
748
+ * emits byte-identical SQL to `PostgresAdapterImpl.lower()` for the same AST
749
+ * and contract. Used at migration plan/emit time (e.g. by `dataTransform`)
750
+ * without instantiating the runtime adapter.
751
+ */
752
+ lower(ast, context) {
753
+ if (isDdlNode(ast)) return renderLoweredDdl(ast);
754
+ return renderLoweredSql(ast, context.contract, this.codecLookup);
755
+ }
756
+ /**
757
+ * Reads the contract marker from `prisma_contract.marker`. Probes
758
+ * `information_schema.tables` first so a fresh database (where the
759
+ * `prisma_contract` schema doesn't yet exist) returns `null` instead of a
760
+ * "relation does not exist" error — some Postgres wire-protocol clients
761
+ * (e.g. PGlite's TCP proxy) don't fully recover from extended-protocol
762
+ * parse errors, so we probe before reading.
763
+ */
764
+ async readMarker(driver, space) {
765
+ const result = await this.readMarkerDiscriminated(driver, space);
766
+ return result.kind === "present" ? result.record : null;
767
+ }
768
+ async readMarkerDiscriminated(driver, space) {
769
+ return withMarkerReadErrorHandling(() => this.readMarkerResult(driver, space), {
770
+ space,
771
+ markerLocation: POSTGRES_MARKER_TABLE
772
+ });
773
+ }
774
+ /**
775
+ * Reads every row from `prisma_contract.marker` and returns them keyed
776
+ * by `space`. Mirrors the existence probe in {@link readMarker}: a
777
+ * fresh database without the `prisma_contract` schema returns an empty
778
+ * map rather than raising "relation does not exist".
779
+ */
780
+ async readAllMarkers(driver) {
781
+ return withMarkerReadErrorHandling(() => this.readAllMarkersResult(driver), {
782
+ space: APP_SPACE_ID,
783
+ markerLocation: POSTGRES_MARKER_TABLE
784
+ });
785
+ }
786
+ async readAllMarkersResult(driver) {
787
+ const lower = (query) => this.lower(query, { contract: void 0 });
788
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("marker"))).build())).length === 0) return /* @__PURE__ */ new Map();
789
+ await this.assertMarkerTableHasSpaceColumn(driver, APP_SPACE_ID);
790
+ 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()));
791
+ const out = /* @__PURE__ */ new Map();
792
+ for (const row of rows) out.set(row.space, parseMarkerRowSafely(row, parseContractMarkerRow, {
793
+ space: row.space,
794
+ markerLocation: POSTGRES_MARKER_TABLE
795
+ }));
796
+ return out;
797
+ }
798
+ /**
799
+ * Reads per-migration ledger rows from `prisma_contract.ledger` in apply
800
+ * order. Probes `information_schema.tables` first so a fresh database
801
+ * without the ledger table returns `[]` instead of raising "relation does
802
+ * not exist".
803
+ */
804
+ async readLedger(driver, space) {
805
+ return withMarkerReadErrorHandling(() => this.readLedgerResult(driver, space), {
806
+ space: space ?? "*",
807
+ markerLocation: POSTGRES_LEDGER_TABLE
808
+ });
809
+ }
810
+ async readLedgerResult(driver, space) {
811
+ const lower = (query) => this.lower(query, { contract: void 0 });
812
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("ledger"))).build())).length === 0) return [];
813
+ 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);
814
+ return blindCast(await execute(lower, driver, (space !== void 0 ? base.where(ledgerReadShape.space.eq(space)) : base).orderBy(ledgerReadShape.id).build())).map((row) => {
815
+ const appliedAt = row.created_at instanceof Date ? row.created_at : new Date(row.created_at);
816
+ return {
817
+ space: row.space,
818
+ migrationName: row.migration_name,
819
+ migrationHash: row.migration_hash,
820
+ from: ledgerOriginFromStored(row.origin_core_hash),
821
+ to: row.destination_core_hash,
822
+ appliedAt,
823
+ operationCount: Array.isArray(row.operations) ? row.operations.length : 0
824
+ };
825
+ });
826
+ }
827
+ /**
828
+ * Stamps the initial marker row for `space` via the shared contract-free DML
829
+ * builder, lowered through {@link lower} and executed on the driver. See the
830
+ * `SqlControlAdapter.initMarker` contract.
831
+ */
832
+ async insertMarker(driver, space, destination) {
833
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.insert({
834
+ space,
835
+ core_hash: destination.storageHash,
836
+ profile_hash: destination.profileHash,
837
+ contract_json: null,
838
+ canonical_version: null,
839
+ updated_at: NOW,
840
+ app_tag: null,
841
+ meta: {},
842
+ invariants: destination.invariants ?? []
843
+ }).build());
844
+ }
845
+ async initMarker(driver, space, destination) {
846
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, marker.upsert({
847
+ space,
848
+ core_hash: destination.storageHash,
849
+ profile_hash: destination.profileHash,
850
+ contract_json: null,
851
+ canonical_version: null,
852
+ updated_at: NOW,
853
+ app_tag: null,
854
+ meta: {},
855
+ invariants: destination.invariants ?? []
856
+ }).onConflict(marker.space).doUpdate((excluded) => ({
857
+ core_hash: excluded.core_hash,
858
+ profile_hash: excluded.profile_hash,
859
+ contract_json: excluded.contract_json,
860
+ canonical_version: excluded.canonical_version,
861
+ updated_at: NOW,
862
+ app_tag: excluded.app_tag,
863
+ meta: excluded.meta,
864
+ invariants: excluded.invariants
865
+ })).build());
866
+ }
867
+ /**
868
+ * Compare-and-swap advance of the marker row for `space`. See the
869
+ * `SqlControlAdapter.updateMarker` contract.
870
+ */
871
+ async updateMarker(driver, space, expectedFrom, destination) {
872
+ const currentInvariants = destination.invariants === void 0 ? [] : (await this.readMarker(driver, space))?.invariants ?? [];
873
+ const mergedInvariants = destination.invariants === void 0 ? void 0 : mergeInvariants(currentInvariants, destination.invariants);
874
+ return (await execute((q) => this.lower(q, { contract: void 0 }), driver, marker.update().set({
875
+ core_hash: destination.storageHash,
876
+ profile_hash: destination.profileHash,
877
+ updated_at: NOW,
878
+ ...mergedInvariants !== void 0 ? { invariants: mergedInvariants } : {}
879
+ }).where(marker.space.eq(space).and(marker.core_hash.eq(expectedFrom))).returning(marker.space).build())).length > 0;
880
+ }
881
+ /**
882
+ * Appends a ledger entry for `space`. See the
883
+ * `SqlControlAdapter.writeLedgerEntry` contract.
884
+ */
885
+ async writeLedgerEntry(driver, space, entry) {
886
+ await execute((query) => this.lower(query, { contract: void 0 }), driver, ledger.insert({
887
+ space,
888
+ migration_name: entry.migrationName,
889
+ migration_hash: entry.migrationHash,
890
+ origin_core_hash: entry.from,
891
+ destination_core_hash: entry.to,
892
+ operations: entry.operations
893
+ }).build());
894
+ }
895
+ async assertMarkerTableHasSpaceColumn(driver, space) {
896
+ const rows = (await driver.query(`select column_name
897
+ from information_schema.columns
898
+ where table_schema = 'prisma_contract'
899
+ and table_name = 'marker'`)).rows;
900
+ if (rows.length === 0) return;
901
+ if (!rows.every((row) => typeof row.column_name === "string")) return;
902
+ if (rows.some((row) => row.column_name === "space")) return;
903
+ rethrowMarkerReadError(/* @__PURE__ */ new Error("column \"space\" does not exist"), {
904
+ space,
905
+ markerLocation: POSTGRES_MARKER_TABLE
906
+ });
907
+ }
908
+ async readMarkerResult(driver, space) {
909
+ const lower = (query) => this.lower(query, { contract: void 0 });
910
+ if ((await execute(lower, driver, infoSchemaTables.select(infoSchemaTables.table_schema).where(infoSchemaTables.table_schema.eq("prisma_contract").and(infoSchemaTables.table_name.eq("marker"))).build())).length === 0) return { kind: "no-table" };
911
+ await this.assertMarkerTableHasSpaceColumn(driver, space);
912
+ 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];
913
+ if (!row) return { kind: "absent" };
914
+ return {
915
+ kind: "present",
916
+ record: parseContractMarkerRow(row)
917
+ };
918
+ }
919
+ /**
920
+ * Introspects a Postgres database schema and returns a raw SqlSchemaIR.
921
+ *
922
+ * This is a pure schema discovery operation that queries the Postgres catalog
923
+ * and returns the schema structure without type mapping or contract enrichment.
924
+ * Type mapping and enrichment are handled separately by enrichment helpers.
925
+ *
926
+ * When `contract` is provided and its storage declares more than one
927
+ * namespace (or any explicit bound namespace), the adapter walks every
928
+ * declared namespace and merges the per-schema introspection results
929
+ * into a single `SqlSchemaIR`. `UNBOUND_NAMESPACE_ID` resolves to the
930
+ * connection's `current_schema()` so late-bound tables follow the
931
+ * runtime `search_path`. When no contract is passed, the adapter falls
932
+ * back to introspecting the single `schema` argument (defaulting to
933
+ * `'public'`).
934
+ *
935
+ * Uses batched queries to minimize database round trips (6 queries per
936
+ * schema walked).
937
+ *
938
+ * @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries
939
+ * @param contract - Optional contract for contract-guided introspection (multi-namespace walk, filtering)
940
+ * @param schema - Schema name to introspect when no contract is provided (defaults to 'public')
941
+ * @returns Promise resolving to SqlSchemaIR representing the live database schema
942
+ */
943
+ async introspect(driver, contract, schema = "public") {
944
+ const declaredNamespaces = extractContractNamespaceIds(contract);
945
+ const ir = declaredNamespaces.length > 0 ? await this.introspectNamespaces(driver, declaredNamespaces) : await this.introspectSchema(driver, schema);
946
+ const existingSchemas = await this.listExistingSchemas(driver);
947
+ const annotations = ir.annotations ?? {};
948
+ const pg = annotations.pg ?? {};
949
+ return {
950
+ ...ir,
951
+ annotations: {
952
+ ...annotations,
953
+ pg: {
954
+ ...pg,
955
+ existingSchemas
956
+ }
957
+ }
958
+ };
959
+ }
960
+ /**
961
+ * Lists every non-system schema present in the connected database.
962
+ * The introspection consumer (`verifyPostgresNamespacePresence`)
963
+ * treats the result as the authoritative ground truth — declared
964
+ * namespaces whose `ddlSchemaName` is missing from this list become
965
+ * `missing_schema` issues, and the planner emits the matching
966
+ * `CREATE SCHEMA` before table DDL.
967
+ */
968
+ async listExistingSchemas(driver) {
969
+ return (await driver.query(`SELECT nspname
970
+ FROM pg_catalog.pg_namespace
971
+ WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
972
+ AND nspname NOT LIKE 'pg_temp_%'
973
+ AND nspname NOT LIKE 'pg_toast_temp_%'
974
+ ORDER BY nspname`)).rows.map((row) => row.nspname);
975
+ }
976
+ /**
977
+ * Walks every declared namespace, resolving `UNBOUND_NAMESPACE_ID` to
978
+ * the connection's `current_schema()`, and merges the per-schema results
979
+ * into a single `SqlSchemaIR`. The merged `tables` map is flat (keyed by
980
+ * table name) so callers that look up by `tableName` see every contract
981
+ * table regardless of which namespace it lives in.
982
+ */
983
+ async introspectNamespaces(driver, namespaceIds) {
984
+ const resolvedSchemas = await Promise.all(namespaceIds.map(async (id) => {
985
+ if (id === UNBOUND_NAMESPACE_ID) {
986
+ const { rows } = await driver.query("SELECT current_schema() AS current_schema");
987
+ return rows[0]?.current_schema ?? "public";
988
+ }
989
+ return id;
990
+ }));
991
+ const uniqueSchemas = Array.from(new Set(resolvedSchemas));
992
+ const perSchema = await Promise.all(uniqueSchemas.map((s) => this.introspectSchema(driver, s)));
993
+ const mergedTables = {};
994
+ for (const ir of perSchema) for (const [tableName, table] of Object.entries(ir.tables)) mergedTables[tableName] = table;
995
+ const mergedStorageTypes = {};
996
+ for (let i = 0; i < perSchema.length; i++) {
997
+ const ir = perSchema[i];
998
+ const pg = blindCast(ir?.annotations?.["pg"])?.storageTypes;
999
+ if (!pg) continue;
1000
+ for (const [key, value] of Object.entries(pg)) mergedStorageTypes[key] = value;
1001
+ }
1002
+ const firstAnnotations = perSchema[0]?.annotations;
1003
+ const firstPg = blindCast(firstAnnotations?.["pg"]) ?? {};
1004
+ return {
1005
+ tables: mergedTables,
1006
+ ...ifDefined("annotations", {
1007
+ ...firstAnnotations,
1008
+ pg: {
1009
+ ...firstPg,
1010
+ ...ifDefined("storageTypes", Object.keys(mergedStorageTypes).length > 0 ? mergedStorageTypes : void 0)
1011
+ }
1012
+ })
1013
+ };
1014
+ }
1015
+ /**
1016
+ * Introspects a single Postgres schema and returns a raw SqlSchemaIR
1017
+ * containing only the tables in that schema. Used by `introspect` as
1018
+ * the per-namespace walk.
1019
+ */
1020
+ async introspectSchema(driver, schema) {
1021
+ const [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult] = await Promise.all([
1022
+ driver.query(`SELECT table_name
1023
+ FROM information_schema.tables
1024
+ WHERE table_schema = $1
1025
+ AND table_type = 'BASE TABLE'
1026
+ ORDER BY table_name`, [schema]),
1027
+ driver.query(`SELECT
1028
+ c.table_name,
1029
+ column_name,
1030
+ data_type,
1031
+ udt_name,
1032
+ is_nullable,
1033
+ character_maximum_length,
1034
+ numeric_precision,
1035
+ numeric_scale,
1036
+ column_default,
1037
+ format_type(a.atttypid, a.atttypmod) AS formatted_type
1038
+ FROM information_schema.columns c
1039
+ JOIN pg_catalog.pg_class cl
1040
+ ON cl.relname = c.table_name
1041
+ JOIN pg_catalog.pg_namespace ns
1042
+ ON ns.nspname = c.table_schema
1043
+ AND ns.oid = cl.relnamespace
1044
+ JOIN pg_catalog.pg_attribute a
1045
+ ON a.attrelid = cl.oid
1046
+ AND a.attname = c.column_name
1047
+ AND a.attnum > 0
1048
+ AND NOT a.attisdropped
1049
+ WHERE c.table_schema = $1
1050
+ ORDER BY c.table_name, c.ordinal_position`, [schema]),
1051
+ driver.query(`SELECT
1052
+ tc.table_name,
1053
+ tc.constraint_name,
1054
+ kcu.column_name,
1055
+ kcu.ordinal_position
1056
+ FROM information_schema.table_constraints tc
1057
+ JOIN information_schema.key_column_usage kcu
1058
+ ON tc.constraint_name = kcu.constraint_name
1059
+ AND tc.table_schema = kcu.table_schema
1060
+ AND tc.table_name = kcu.table_name
1061
+ WHERE tc.table_schema = $1
1062
+ AND tc.constraint_type = 'PRIMARY KEY'
1063
+ ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),
1064
+ driver.query(`SELECT
1065
+ tc.table_name,
1066
+ tc.constraint_name,
1067
+ kcu.column_name,
1068
+ kcu.ordinal_position,
1069
+ ref_ns.nspname AS referenced_table_schema,
1070
+ ref_cl.relname AS referenced_table_name,
1071
+ ref_att.attname AS referenced_column_name,
1072
+ rc.delete_rule,
1073
+ rc.update_rule
1074
+ FROM information_schema.table_constraints tc
1075
+ JOIN information_schema.key_column_usage kcu
1076
+ ON tc.constraint_name = kcu.constraint_name
1077
+ AND tc.table_schema = kcu.table_schema
1078
+ AND tc.table_name = kcu.table_name
1079
+ JOIN pg_catalog.pg_constraint pgc
1080
+ ON pgc.conname = tc.constraint_name
1081
+ AND pgc.connamespace = (
1082
+ SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema
1083
+ )
1084
+ JOIN pg_catalog.pg_class ref_cl
1085
+ ON ref_cl.oid = pgc.confrelid
1086
+ JOIN pg_catalog.pg_namespace ref_ns
1087
+ ON ref_ns.oid = ref_cl.relnamespace
1088
+ JOIN pg_catalog.pg_attribute ref_att
1089
+ ON ref_att.attrelid = pgc.confrelid
1090
+ AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]
1091
+ JOIN information_schema.referential_constraints rc
1092
+ ON rc.constraint_name = tc.constraint_name
1093
+ AND rc.constraint_schema = tc.table_schema
1094
+ WHERE tc.table_schema = $1
1095
+ AND tc.constraint_type = 'FOREIGN KEY'
1096
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1097
+ driver.query(`SELECT
1098
+ tc.table_name,
1099
+ tc.constraint_name,
1100
+ kcu.column_name,
1101
+ kcu.ordinal_position
1102
+ FROM information_schema.table_constraints tc
1103
+ JOIN information_schema.key_column_usage kcu
1104
+ ON tc.constraint_name = kcu.constraint_name
1105
+ AND tc.table_schema = kcu.table_schema
1106
+ AND tc.table_name = kcu.table_name
1107
+ WHERE tc.table_schema = $1
1108
+ AND tc.constraint_type = 'UNIQUE'
1109
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1110
+ driver.query(`SELECT
1111
+ i.tablename,
1112
+ i.indexname,
1113
+ ix.indisunique,
1114
+ a.attname,
1115
+ k.ord AS index_position,
1116
+ am.amname,
1117
+ ic.reloptions
1118
+ FROM pg_indexes i
1119
+ JOIN pg_class ic ON ic.relname = i.indexname
1120
+ JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1
1121
+ JOIN pg_index ix ON ix.indexrelid = ic.oid
1122
+ JOIN pg_am am ON am.oid = ic.relam
1123
+ JOIN pg_class t ON t.oid = ix.indrelid
1124
+ JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1
1125
+ JOIN LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY AS k(attnum, ord) ON true
1126
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND a.attnum > 0
1127
+ WHERE i.schemaname = $1
1128
+ AND NOT EXISTS (
1129
+ SELECT 1
1130
+ FROM information_schema.table_constraints tc
1131
+ WHERE tc.table_schema = $1
1132
+ AND tc.table_name = i.tablename
1133
+ AND tc.constraint_name = i.indexname
1134
+ )
1135
+ ORDER BY i.tablename, i.indexname, k.ord`, [schema])
1136
+ ]);
1137
+ const columnsByTable = groupBy(columnsResult.rows, "table_name");
1138
+ const pksByTable = groupBy(pkResult.rows, "table_name");
1139
+ const fksByTable = groupBy(fkResult.rows, "table_name");
1140
+ const uniquesByTable = groupBy(uniqueResult.rows, "table_name");
1141
+ const indexesByTable = groupBy(indexResult.rows, "tablename");
1142
+ const pkConstraintsByTable = /* @__PURE__ */ new Map();
1143
+ for (const row of pkResult.rows) {
1144
+ let constraints = pkConstraintsByTable.get(row.table_name);
1145
+ if (!constraints) {
1146
+ constraints = /* @__PURE__ */ new Set();
1147
+ pkConstraintsByTable.set(row.table_name, constraints);
1148
+ }
1149
+ constraints.add(row.constraint_name);
1150
+ }
1151
+ const tables = {};
1152
+ for (const tableRow of tablesResult.rows) {
1153
+ const tableName = tableRow.table_name;
1154
+ const columns = {};
1155
+ for (const colRow of columnsByTable.get(tableName) ?? []) {
1156
+ let nativeType = colRow.udt_name;
1157
+ const formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;
1158
+ if (formattedType) nativeType = formattedType;
1159
+ else if (colRow.data_type === "character varying" || colRow.data_type === "character") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;
1160
+ else nativeType = colRow.data_type;
1161
+ else if (colRow.data_type === "numeric" || colRow.data_type === "decimal") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;
1162
+ else if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;
1163
+ else nativeType = colRow.data_type;
1164
+ else nativeType = colRow.udt_name || colRow.data_type;
1165
+ columns[colRow.column_name] = {
1166
+ name: colRow.column_name,
1167
+ nativeType,
1168
+ nullable: colRow.is_nullable === "YES",
1169
+ ...ifDefined("default", colRow.column_default ?? void 0)
1170
+ };
1171
+ }
1172
+ const pkRows = [...pksByTable.get(tableName) ?? []];
1173
+ const primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);
1174
+ const primaryKey = primaryKeyColumns.length > 0 ? {
1175
+ columns: primaryKeyColumns,
1176
+ ...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}
1177
+ } : void 0;
1178
+ const foreignKeysMap = /* @__PURE__ */ new Map();
1179
+ for (const fkRow of fksByTable.get(tableName) ?? []) {
1180
+ const existing = foreignKeysMap.get(fkRow.constraint_name);
1181
+ if (existing) {
1182
+ existing.columns.push(fkRow.column_name);
1183
+ existing.referencedColumns.push(fkRow.referenced_column_name);
1184
+ } else foreignKeysMap.set(fkRow.constraint_name, {
1185
+ columns: [fkRow.column_name],
1186
+ referencedTable: fkRow.referenced_table_name,
1187
+ referencedSchema: fkRow.referenced_table_schema,
1188
+ referencedColumns: [fkRow.referenced_column_name],
1189
+ name: fkRow.constraint_name,
1190
+ deleteRule: fkRow.delete_rule,
1191
+ updateRule: fkRow.update_rule
1192
+ });
1193
+ }
1194
+ const foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({
1195
+ columns: Object.freeze([...fk.columns]),
1196
+ referencedTable: fk.referencedTable,
1197
+ referencedSchema: fk.referencedSchema,
1198
+ referencedColumns: Object.freeze([...fk.referencedColumns]),
1199
+ name: fk.name,
1200
+ ...ifDefined("onDelete", mapReferentialAction(fk.deleteRule)),
1201
+ ...ifDefined("onUpdate", mapReferentialAction(fk.updateRule))
1202
+ }));
1203
+ const pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();
1204
+ const uniquesMap = /* @__PURE__ */ new Map();
1205
+ for (const uniqueRow of uniquesByTable.get(tableName) ?? []) {
1206
+ if (pkConstraints.has(uniqueRow.constraint_name)) continue;
1207
+ const existing = uniquesMap.get(uniqueRow.constraint_name);
1208
+ if (existing) existing.columns.push(uniqueRow.column_name);
1209
+ else uniquesMap.set(uniqueRow.constraint_name, {
1210
+ columns: [uniqueRow.column_name],
1211
+ name: uniqueRow.constraint_name
1212
+ });
1213
+ }
1214
+ const uniques = Array.from(uniquesMap.values()).map((uq) => ({
1215
+ columns: Object.freeze([...uq.columns]),
1216
+ name: uq.name
1217
+ }));
1218
+ const indexesMap = /* @__PURE__ */ new Map();
1219
+ for (const idxRow of indexesByTable.get(tableName) ?? []) {
1220
+ if (!idxRow.attname) continue;
1221
+ const existing = indexesMap.get(idxRow.indexname);
1222
+ if (existing) existing.columns.push(idxRow.attname);
1223
+ else {
1224
+ const indexType = idxRow.amname && idxRow.amname !== "btree" ? idxRow.amname : void 0;
1225
+ const indexOptions = parsePgReloptions(idxRow.reloptions, idxRow.indexname);
1226
+ indexesMap.set(idxRow.indexname, {
1227
+ columns: [idxRow.attname],
1228
+ name: idxRow.indexname,
1229
+ unique: idxRow.indisunique,
1230
+ type: indexType,
1231
+ options: indexOptions
1232
+ });
1233
+ }
1234
+ }
1235
+ const indexes = Array.from(indexesMap.values()).map((idx) => ({
1236
+ columns: Object.freeze([...idx.columns]),
1237
+ name: idx.name,
1238
+ unique: idx.unique,
1239
+ ...idx.type !== void 0 && { type: idx.type },
1240
+ ...idx.options !== void 0 && { options: idx.options }
1241
+ }));
1242
+ tables[tableName] = {
1243
+ name: tableName,
1244
+ columns,
1245
+ ...ifDefined("primaryKey", primaryKey),
1246
+ foreignKeys,
1247
+ uniques,
1248
+ indexes
1249
+ };
1250
+ }
1251
+ const rawStorageTypes = await introspectPostgresEnumTypes({
1252
+ driver,
1253
+ schemaName: schema
1254
+ });
1255
+ const storageTypes = {};
1256
+ for (const [typeName, annotation] of Object.entries(rawStorageTypes)) storageTypes[enumStorageCompoundKey(schema, typeName)] = annotation;
1257
+ return {
1258
+ tables,
1259
+ annotations: { pg: {
1260
+ schema,
1261
+ version: await this.getPostgresVersion(driver),
1262
+ ...ifDefined("storageTypes", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)
1263
+ } }
1264
+ };
1265
+ }
1266
+ /**
1267
+ * Gets the Postgres version from the database.
1268
+ */
1269
+ async getPostgresVersion(driver) {
1270
+ return ((await driver.query("SELECT version() AS version", [])).rows[0]?.version ?? "").match(/PostgreSQL (\d+\.\d+)/)?.[1] ?? "unknown";
1271
+ }
1272
+ };
1273
+ /**
1274
+ * Extracts the namespace coordinate ids declared on a contract's storage,
1275
+ * or returns an empty array when no contract (or no storage / namespaces)
1276
+ * is present. Used by `PostgresControlAdapter.introspect` to decide
1277
+ * between the multi-namespace walk and the single-schema fallback.
1278
+ */
1279
+ function extractContractNamespaceIds(contract) {
1280
+ if (contract === null || typeof contract !== "object") return [];
1281
+ const storage = contract.storage;
1282
+ if (storage === null || typeof storage !== "object") return [];
1283
+ const namespaces = storage.namespaces;
1284
+ if (namespaces === null || typeof namespaces !== "object") return [];
1285
+ return Object.keys(namespaces);
1286
+ }
1287
+ function normalizeFormattedType(formattedType, dataType, udtName) {
1288
+ if (formattedType === "integer") return "int4";
1289
+ if (formattedType === "smallint") return "int2";
1290
+ if (formattedType === "bigint") return "int8";
1291
+ if (formattedType === "real") return "float4";
1292
+ if (formattedType === "double precision") return "float8";
1293
+ if (formattedType === "boolean") return "bool";
1294
+ if (formattedType.startsWith("varchar")) return formattedType.replace("varchar", "character varying");
1295
+ if (formattedType.startsWith("bpchar")) return formattedType.replace("bpchar", "character");
1296
+ if (formattedType.startsWith("varbit")) return formattedType.replace("varbit", "bit varying");
1297
+ if (dataType === "timestamp with time zone" || udtName === "timestamptz") return formattedType.replace("timestamp", "timestamptz").replace(" with time zone", "").trim();
1298
+ if (dataType === "timestamp without time zone" || udtName === "timestamp") return formattedType.replace(" without time zone", "").trim();
1299
+ if (dataType === "time with time zone" || udtName === "timetz") return formattedType.replace("time", "timetz").replace(" with time zone", "").trim();
1300
+ if (dataType === "time without time zone" || udtName === "time") return formattedType.replace(" without time zone", "").trim();
1301
+ if (formattedType.startsWith("\"") && formattedType.endsWith("\"")) return formattedType.slice(1, -1);
1302
+ return formattedType;
1303
+ }
1304
+ const PG_REFERENTIAL_ACTION_MAP = {
1305
+ "NO ACTION": "noAction",
1306
+ RESTRICT: "restrict",
1307
+ CASCADE: "cascade",
1308
+ "SET NULL": "setNull",
1309
+ "SET DEFAULT": "setDefault"
1310
+ };
1311
+ /**
1312
+ * Maps a Postgres referential action rule to the canonical SqlReferentialAction.
1313
+ * Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.
1314
+ * Throws for unrecognized rules to prevent silent data loss.
1315
+ */
1316
+ function mapReferentialAction(rule) {
1317
+ const mapped = PG_REFERENTIAL_ACTION_MAP[rule];
1318
+ if (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
1319
+ if (mapped === "noAction") return void 0;
1320
+ return mapped;
1321
+ }
1322
+ /**
1323
+ * Groups an array of objects by a specified key.
1324
+ * Returns a Map for O(1) lookup by group key.
1325
+ */
1326
+ /**
1327
+ * Parses a `pg_class.reloptions` array into a `Record<string, string>`.
1328
+ *
1329
+ * Postgres returns reloptions as a `text[]` whose entries are `key=value`
1330
+ * strings; the value side is always a string regardless of the underlying
1331
+ * scalar type. The verifier compares contract options to introspected
1332
+ * options after coercing both sides to strings, so keeping the raw text
1333
+ * here is correct.
1334
+ *
1335
+ * Returns `undefined` when the input is null/empty (no WITH clause).
1336
+ */
1337
+ function parsePgReloptions(reloptions, indexName) {
1338
+ if (!reloptions || reloptions.length === 0) return;
1339
+ const result = {};
1340
+ for (const entry of reloptions) {
1341
+ const eq = entry.indexOf("=");
1342
+ if (eq === -1) throw new Error(`Postgres introspection: malformed reloption entry "${entry}" on index "${indexName}" (expected "key=value")`);
1343
+ const key = entry.slice(0, eq);
1344
+ result[key] = entry.slice(eq + 1);
1345
+ }
1346
+ return Object.keys(result).length > 0 ? result : void 0;
1347
+ }
1348
+ function groupBy(items, key) {
1349
+ const map = /* @__PURE__ */ new Map();
1350
+ for (const item of items) {
1351
+ const groupKey = item[key];
1352
+ let group = map.get(groupKey);
1353
+ if (!group) {
1354
+ group = [];
1355
+ map.set(groupKey, group);
1356
+ }
1357
+ group.push(item);
1358
+ }
1359
+ return map;
1360
+ }
1361
+ //#endregion
1362
+ export { createPostgresBuiltinCodecLookup as i, renderLoweredSql as n, renderLoweredDdl as r, PostgresControlAdapter as t };
1363
+
1364
+ //# sourceMappingURL=control-adapter-5BSAQMQc.mjs.map