@prisma-next/adapter-postgres 0.3.0-dev.6 → 0.3.0-dev.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +64 -2
  3. package/dist/adapter-DtehReRR.mjs +271 -0
  4. package/dist/adapter-DtehReRR.mjs.map +1 -0
  5. package/dist/adapter.d.mts +23 -0
  6. package/dist/adapter.d.mts.map +1 -0
  7. package/dist/adapter.mjs +5 -0
  8. package/dist/codec-ids-Bsm9c7ns.mjs +29 -0
  9. package/dist/codec-ids-Bsm9c7ns.mjs.map +1 -0
  10. package/dist/codec-types.d.mts +141 -0
  11. package/dist/codec-types.d.mts.map +1 -0
  12. package/dist/codec-types.mjs +4 -0
  13. package/dist/codecs-BfC_5c-4.mjs +207 -0
  14. package/dist/codecs-BfC_5c-4.mjs.map +1 -0
  15. package/dist/column-types.d.mts +110 -0
  16. package/dist/column-types.d.mts.map +1 -0
  17. package/dist/column-types.mjs +180 -0
  18. package/dist/column-types.mjs.map +1 -0
  19. package/dist/control.d.mts +111 -0
  20. package/dist/control.d.mts.map +1 -0
  21. package/dist/control.mjs +463 -0
  22. package/dist/control.mjs.map +1 -0
  23. package/dist/descriptor-meta-ilnFI7bx.mjs +921 -0
  24. package/dist/descriptor-meta-ilnFI7bx.mjs.map +1 -0
  25. package/dist/runtime.d.mts +19 -0
  26. package/dist/runtime.d.mts.map +1 -0
  27. package/dist/runtime.mjs +85 -0
  28. package/dist/runtime.mjs.map +1 -0
  29. package/dist/sql-utils-CSfAGEwF.mjs +78 -0
  30. package/dist/sql-utils-CSfAGEwF.mjs.map +1 -0
  31. package/dist/types-CXO7EB60.d.mts +19 -0
  32. package/dist/types-CXO7EB60.d.mts.map +1 -0
  33. package/dist/types.d.mts +2 -0
  34. package/dist/types.mjs +1 -0
  35. package/package.json +37 -46
  36. package/src/core/adapter.ts +139 -28
  37. package/src/core/codec-ids.ts +28 -0
  38. package/src/core/codecs.ts +325 -23
  39. package/src/core/control-adapter.ts +400 -178
  40. package/src/core/default-normalizer.ts +90 -0
  41. package/src/core/descriptor-meta.ts +221 -9
  42. package/src/core/enum-control-hooks.ts +735 -0
  43. package/src/core/json-schema-type-expression.ts +131 -0
  44. package/src/core/json-schema-validator.ts +53 -0
  45. package/src/core/parameterized-types.ts +118 -0
  46. package/src/core/sql-utils.ts +111 -0
  47. package/src/core/standard-schema.ts +71 -0
  48. package/src/exports/codec-types.ts +73 -1
  49. package/src/exports/column-types.ts +233 -9
  50. package/src/exports/control.ts +16 -9
  51. package/src/exports/runtime.ts +61 -18
  52. package/dist/chunk-HD5YISNQ.js +0 -47
  53. package/dist/chunk-HD5YISNQ.js.map +0 -1
  54. package/dist/chunk-J3XSOAM2.js +0 -162
  55. package/dist/chunk-J3XSOAM2.js.map +0 -1
  56. package/dist/chunk-T6S3A6VT.js +0 -301
  57. package/dist/chunk-T6S3A6VT.js.map +0 -1
  58. package/dist/core/adapter.d.ts +0 -19
  59. package/dist/core/adapter.d.ts.map +0 -1
  60. package/dist/core/codecs.d.ts +0 -110
  61. package/dist/core/codecs.d.ts.map +0 -1
  62. package/dist/core/control-adapter.d.ts +0 -33
  63. package/dist/core/control-adapter.d.ts.map +0 -1
  64. package/dist/core/descriptor-meta.d.ts +0 -72
  65. package/dist/core/descriptor-meta.d.ts.map +0 -1
  66. package/dist/core/types.d.ts +0 -16
  67. package/dist/core/types.d.ts.map +0 -1
  68. package/dist/exports/adapter.d.ts +0 -2
  69. package/dist/exports/adapter.d.ts.map +0 -1
  70. package/dist/exports/adapter.js +0 -8
  71. package/dist/exports/adapter.js.map +0 -1
  72. package/dist/exports/codec-types.d.ts +0 -11
  73. package/dist/exports/codec-types.d.ts.map +0 -1
  74. package/dist/exports/codec-types.js +0 -7
  75. package/dist/exports/codec-types.js.map +0 -1
  76. package/dist/exports/column-types.d.ts +0 -17
  77. package/dist/exports/column-types.d.ts.map +0 -1
  78. package/dist/exports/column-types.js +0 -49
  79. package/dist/exports/column-types.js.map +0 -1
  80. package/dist/exports/control.d.ts +0 -8
  81. package/dist/exports/control.d.ts.map +0 -1
  82. package/dist/exports/control.js +0 -279
  83. package/dist/exports/control.js.map +0 -1
  84. package/dist/exports/runtime.d.ts +0 -15
  85. package/dist/exports/runtime.d.ts.map +0 -1
  86. package/dist/exports/runtime.js +0 -20
  87. package/dist/exports/runtime.js.map +0 -1
  88. package/dist/exports/types.d.ts +0 -2
  89. package/dist/exports/types.d.ts.map +0 -1
  90. package/dist/exports/types.js +0 -1
  91. package/dist/exports/types.js.map +0 -1
@@ -0,0 +1,921 @@
1
+ import { C as SQL_CHAR_CODEC_ID, E as SQL_VARCHAR_CODEC_ID, S as PG_VARCHAR_CODEC_ID, T as SQL_INT_CODEC_ID, _ as PG_TIMESTAMPTZ_CODEC_ID, a as PG_FLOAT4_CODEC_ID, b as PG_TIME_CODEC_ID, c as PG_INT2_CODEC_ID, d as PG_INTERVAL_CODEC_ID, f as PG_INT_CODEC_ID, g as PG_TEXT_CODEC_ID, h as PG_NUMERIC_CODEC_ID, i as PG_ENUM_CODEC_ID, l as PG_INT4_CODEC_ID, m as PG_JSON_CODEC_ID, n as PG_BOOL_CODEC_ID, o as PG_FLOAT8_CODEC_ID, p as PG_JSONB_CODEC_ID, r as PG_CHAR_CODEC_ID, s as PG_FLOAT_CODEC_ID, t as PG_BIT_CODEC_ID, u as PG_INT8_CODEC_ID, v as PG_TIMESTAMP_CODEC_ID, w as SQL_FLOAT_CODEC_ID, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from "./codec-ids-Bsm9c7ns.mjs";
2
+ import { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from "./sql-utils-CSfAGEwF.mjs";
3
+ import { arraysEqual } from "@prisma-next/family-sql/schema-verify";
4
+
5
+ //#region src/core/enum-control-hooks.ts
6
+ const ENUM_INTROSPECT_QUERY = `
7
+ SELECT
8
+ n.nspname AS schema_name,
9
+ t.typname AS type_name,
10
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
11
+ FROM pg_type t
12
+ JOIN pg_namespace n ON t.typnamespace = n.oid
13
+ JOIN pg_enum e ON t.oid = e.enumtypid
14
+ WHERE n.nspname = $1
15
+ GROUP BY n.nspname, t.typname
16
+ ORDER BY n.nspname, t.typname
17
+ `;
18
+ /**
19
+ * Type guard for string arrays. Used for runtime validation of introspected data.
20
+ */
21
+ function isStringArray(value) {
22
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
23
+ }
24
+ /**
25
+ * Parses a PostgreSQL array value into a JavaScript string array.
26
+ *
27
+ * PostgreSQL's `pg` library may return `array_agg` results either as:
28
+ * - A JavaScript array (when type parsers are configured)
29
+ * - A string in PostgreSQL array literal format: `{value1,value2,...}`
30
+ *
31
+ * Handles PostgreSQL's quoting rules for array elements:
32
+ * - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted
33
+ * - Inside quoted elements, `\"` represents `"` and `\\` represents `\`
34
+ *
35
+ * @param value - The value to parse (array or PostgreSQL array string)
36
+ * @returns A string array, or null if the value cannot be parsed
37
+ */
38
+ function parsePostgresArray(value) {
39
+ if (isStringArray(value)) return value;
40
+ if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
41
+ const inner = value.slice(1, -1);
42
+ if (inner === "") return [];
43
+ return parseArrayElements(inner);
44
+ }
45
+ return null;
46
+ }
47
+ function parseArrayElements(input) {
48
+ const result = [];
49
+ let i = 0;
50
+ while (i < input.length) {
51
+ if (input[i] === ",") {
52
+ i++;
53
+ continue;
54
+ }
55
+ if (input[i] === "\"") {
56
+ i++;
57
+ let element = "";
58
+ while (i < input.length && input[i] !== "\"") {
59
+ if (input[i] === "\\" && i + 1 < input.length) {
60
+ i++;
61
+ element += input[i];
62
+ } else element += input[i];
63
+ i++;
64
+ }
65
+ i++;
66
+ result.push(element);
67
+ } else {
68
+ const nextComma = input.indexOf(",", i);
69
+ if (nextComma === -1) {
70
+ result.push(input.slice(i).trim());
71
+ i = input.length;
72
+ } else {
73
+ result.push(input.slice(i, nextComma).trim());
74
+ i = nextComma;
75
+ }
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+ /**
81
+ * Extracts enum values from a StorageTypeInstance.
82
+ * Returns null if values are missing or invalid.
83
+ */
84
+ function getEnumValues(typeInstance) {
85
+ const values = typeInstance.typeParams?.["values"];
86
+ return isStringArray(values) ? values : null;
87
+ }
88
+ /**
89
+ * Reads existing enum values from the schema IR for a given native type.
90
+ * Uses optional chaining to simplify navigation through the annotations structure.
91
+ */
92
+ function readExistingEnumValues(schema, nativeType) {
93
+ const existing = ((schema.annotations?.["pg"])?.["storageTypes"])?.[nativeType];
94
+ if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;
95
+ return getEnumValues(existing);
96
+ }
97
+ /**
98
+ * Determines what changes are needed to transform existing enum values to desired values.
99
+ *
100
+ * Returns one of:
101
+ * - `unchanged`: No changes needed, values match exactly
102
+ * - `add_values`: New values can be safely appended (PostgreSQL supports this)
103
+ * - `rebuild`: Full enum rebuild required (value removal, reordering, or both)
104
+ *
105
+ * Note: PostgreSQL enums can only have values added (not removed or reordered) without
106
+ * a full type rebuild involving temp type creation and column migration.
107
+ *
108
+ * @param existing - Current enum values in the database
109
+ * @param desired - Target enum values from the contract
110
+ * @returns The type of change required
111
+ */
112
+ function determineEnumDiff(existing, desired) {
113
+ if (arraysEqual(existing, desired)) return { kind: "unchanged" };
114
+ const existingSet = new Set(existing);
115
+ const desiredSet = new Set(desired);
116
+ const missingValues = desired.filter((value) => !existingSet.has(value));
117
+ const removedValues = existing.filter((value) => !desiredSet.has(value));
118
+ const orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);
119
+ if (removedValues.length > 0 || orderMismatch) return {
120
+ kind: "rebuild",
121
+ removedValues
122
+ };
123
+ return {
124
+ kind: "add_values",
125
+ values: missingValues
126
+ };
127
+ }
128
+ function enumTypeExistsCheck(schemaName, typeName, exists = true) {
129
+ return `SELECT ${exists ? "EXISTS" : "NOT EXISTS"} (
130
+ SELECT 1
131
+ FROM pg_type t
132
+ JOIN pg_namespace n ON t.typnamespace = n.oid
133
+ WHERE n.nspname = '${escapeLiteral(schemaName)}'
134
+ AND t.typname = '${escapeLiteral(typeName)}'
135
+ )`;
136
+ }
137
+ function buildCreateEnumOperation(typeName, nativeType, schemaName, values) {
138
+ for (const value of values) validateEnumValueLength(value, typeName);
139
+ const literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(", ");
140
+ const qualifiedType = qualifyName(schemaName, nativeType);
141
+ return {
142
+ id: `type.${typeName}`,
143
+ label: `Create type ${typeName}`,
144
+ summary: `Creates enum type ${typeName}`,
145
+ operationClass: "additive",
146
+ target: { id: "postgres" },
147
+ precheck: [{
148
+ description: `ensure type "${nativeType}" does not exist`,
149
+ sql: enumTypeExistsCheck(schemaName, nativeType, false)
150
+ }],
151
+ execute: [{
152
+ description: `create type "${nativeType}"`,
153
+ sql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`
154
+ }],
155
+ postcheck: [{
156
+ description: `verify type "${nativeType}" exists`,
157
+ sql: enumTypeExistsCheck(schemaName, nativeType)
158
+ }]
159
+ };
160
+ }
161
+ /**
162
+ * Computes the optimal position for inserting a new enum value to maintain
163
+ * the desired order relative to existing values.
164
+ *
165
+ * PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.
166
+ * This function finds the best reference value by:
167
+ * 1. Looking for the nearest preceding value that already exists
168
+ * 2. Falling back to the nearest following value if no preceding exists
169
+ * 3. Defaulting to end-of-list if no reference is found
170
+ *
171
+ * @param options.desired - The target ordered list of all enum values
172
+ * @param options.desiredIndex - Index of the value being inserted in the desired list
173
+ * @param options.current - Current list of enum values (being built up incrementally)
174
+ * @returns SQL clause (e.g., " AFTER 'x'") and insert position for tracking
175
+ */
176
+ function computeInsertPosition(options) {
177
+ const { desired, desiredIndex, current } = options;
178
+ const currentSet = new Set(current);
179
+ const previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));
180
+ const next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));
181
+ return {
182
+ clause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : "",
183
+ insertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length
184
+ };
185
+ }
186
+ /**
187
+ * Builds operations to add new enum values to an existing PostgreSQL enum type.
188
+ *
189
+ * Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.
190
+ * Values are inserted in the correct order using BEFORE/AFTER positioning to match
191
+ * the desired final order.
192
+ *
193
+ * This is a safe, non-destructive operation - existing data is not affected.
194
+ *
195
+ * @param options.typeName - Contract-level type name (e.g., 'Role')
196
+ * @param options.nativeType - PostgreSQL type name (e.g., 'role')
197
+ * @param options.schemaName - PostgreSQL schema (e.g., 'public')
198
+ * @param options.desired - Target ordered list of all enum values
199
+ * @param options.existing - Current enum values in the database
200
+ * @returns Array of migration operations to add each missing value
201
+ */
202
+ function buildAddValueOperations(options) {
203
+ const { typeName, nativeType, schemaName } = options;
204
+ const current = [...options.existing];
205
+ const currentSet = new Set(current);
206
+ const operations = [];
207
+ for (let index = 0; index < options.desired.length; index += 1) {
208
+ const value = options.desired[index];
209
+ if (value === void 0) continue;
210
+ if (currentSet.has(value)) continue;
211
+ validateEnumValueLength(value, typeName);
212
+ const { clause, insertAt } = computeInsertPosition({
213
+ desired: options.desired,
214
+ desiredIndex: index,
215
+ current
216
+ });
217
+ operations.push({
218
+ id: `type.${typeName}.value.${value}`,
219
+ label: `Add value ${value} to ${typeName}`,
220
+ summary: `Adds enum value ${value} to ${typeName}`,
221
+ operationClass: "widening",
222
+ target: { id: "postgres" },
223
+ precheck: [],
224
+ execute: [{
225
+ description: `add value "${value}" if not exists`,
226
+ sql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`
227
+ }],
228
+ postcheck: []
229
+ });
230
+ current.splice(insertAt, 0, value);
231
+ currentSet.add(value);
232
+ }
233
+ return operations;
234
+ }
235
+ /**
236
+ * Collects columns using the enum type from the contract (desired state).
237
+ * Used for type-safe reference tracking.
238
+ */
239
+ function collectEnumColumnsFromContract(contract, typeName, nativeType) {
240
+ const columns = [];
241
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeRef === typeName || column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID) columns.push({
242
+ table: tableName,
243
+ column: columnName
244
+ });
245
+ return columns;
246
+ }
247
+ /**
248
+ * Collects columns using the enum type from the schema IR (live database state).
249
+ * This ensures we find ALL dependent columns, including those added outside the contract
250
+ * (e.g., manual DDL), which is critical for safe enum rebuild operations.
251
+ */
252
+ function collectEnumColumnsFromSchema(schema, nativeType) {
253
+ const columns = [];
254
+ for (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({
255
+ table: tableName,
256
+ column: columnName
257
+ });
258
+ return columns;
259
+ }
260
+ /**
261
+ * Collects all columns using the enum type from both contract AND live database.
262
+ * Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.
263
+ *
264
+ * This is critical for data integrity: if a column exists in the database using
265
+ * this enum but is not in the contract (e.g., added via manual DDL), we must
266
+ * still migrate it to avoid DROP TYPE failures.
267
+ */
268
+ function collectAllEnumColumns(contract, schema, typeName, nativeType) {
269
+ const contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);
270
+ const schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);
271
+ const seen = /* @__PURE__ */ new Set();
272
+ const result = [];
273
+ for (const col of [...contractColumns, ...schemaColumns]) {
274
+ const key = `${col.table}.${col.column}`;
275
+ if (!seen.has(key)) {
276
+ seen.add(key);
277
+ result.push(col);
278
+ }
279
+ }
280
+ return result.sort((a, b) => {
281
+ const tableCompare = a.table.localeCompare(b.table);
282
+ return tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);
283
+ });
284
+ }
285
+ /**
286
+ * Builds a SQL check to verify a column's type matches an expected type.
287
+ */
288
+ function columnTypeCheck(options) {
289
+ return `SELECT EXISTS (
290
+ SELECT 1
291
+ FROM information_schema.columns
292
+ WHERE table_schema = '${escapeLiteral(options.schemaName)}'
293
+ AND table_name = '${escapeLiteral(options.tableName)}'
294
+ AND column_name = '${escapeLiteral(options.columnName)}'
295
+ AND udt_name = '${escapeLiteral(options.expectedType)}'
296
+ )`;
297
+ }
298
+ /** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */
299
+ const MAX_IDENTIFIER_LENGTH = 63;
300
+ /** Suffix added to enum type names during rebuild operations */
301
+ const REBUILD_SUFFIX = "__pn_rebuild";
302
+ /**
303
+ * Builds an SQL check to verify no rows contain any of the removed enum values.
304
+ * This prevents data loss during enum rebuild operations.
305
+ *
306
+ * @param schemaName - PostgreSQL schema name
307
+ * @param tableName - Table containing the enum column
308
+ * @param columnName - Column using the enum type
309
+ * @param removedValues - Array of enum values being removed
310
+ * @returns SQL query that returns true if no rows contain removed values
311
+ */
312
+ function noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {
313
+ if (removedValues.length === 0) return "SELECT true";
314
+ const valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(", ");
315
+ return `SELECT NOT EXISTS (
316
+ SELECT 1 FROM ${qualifyName(schemaName, tableName)}
317
+ WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})
318
+ LIMIT 1
319
+ )`;
320
+ }
321
+ /**
322
+ * Builds a migration operation to recreate a PostgreSQL enum type with updated values.
323
+ *
324
+ * This is required when:
325
+ * - Enum values are removed (PostgreSQL doesn't support direct removal)
326
+ * - Enum values are reordered (PostgreSQL doesn't support reordering)
327
+ *
328
+ * The operation:
329
+ * 1. Creates a new enum type with the desired values (temp name)
330
+ * 2. Migrates all columns to use the new type via text cast
331
+ * 3. Drops the original type
332
+ * 4. Renames the temp type to the original name
333
+ *
334
+ * IMPORTANT: If values are being removed and data exists using those values,
335
+ * the operation will fail at the precheck stage with a clear error message.
336
+ * This prevents silent data loss.
337
+ *
338
+ * @param options.typeName - Contract-level type name
339
+ * @param options.nativeType - PostgreSQL type name
340
+ * @param options.schemaName - PostgreSQL schema
341
+ * @param options.values - Desired final enum values
342
+ * @param options.removedValues - Values being removed (for data loss checks)
343
+ * @param options.contract - Full contract for column discovery
344
+ * @param options.schema - Current schema IR for column discovery
345
+ * @returns Migration operation for full enum rebuild
346
+ */
347
+ function buildRecreateEnumOperation(options) {
348
+ const tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;
349
+ if (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {
350
+ const maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;
351
+ throw new Error(`Enum type name "${options.nativeType}" is too long for rebuild operation. Maximum length is ${maxBaseLength} characters (type name + "${REBUILD_SUFFIX}" suffix must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`);
352
+ }
353
+ const qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);
354
+ const qualifiedTemp = qualifyName(options.schemaName, tempTypeName);
355
+ const literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(", ");
356
+ const columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);
357
+ const alterColumns = columnRefs.map((ref) => ({
358
+ description: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,
359
+ sql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}
360
+ ALTER COLUMN ${quoteIdentifier(ref.column)}
361
+ TYPE ${qualifiedTemp}
362
+ USING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`
363
+ }));
364
+ const postchecks = [
365
+ {
366
+ description: `verify type "${options.nativeType}" exists`,
367
+ sql: enumTypeExistsCheck(options.schemaName, options.nativeType)
368
+ },
369
+ {
370
+ description: `verify temp type "${tempTypeName}" was removed`,
371
+ sql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)
372
+ },
373
+ ...columnRefs.map((ref) => ({
374
+ description: `verify ${ref.table}.${ref.column} uses type "${options.nativeType}"`,
375
+ sql: columnTypeCheck({
376
+ schemaName: options.schemaName,
377
+ tableName: ref.table,
378
+ columnName: ref.column,
379
+ expectedType: options.nativeType
380
+ })
381
+ }))
382
+ ];
383
+ return {
384
+ id: `type.${options.typeName}.rebuild`,
385
+ label: `Rebuild type ${options.typeName}`,
386
+ summary: `Recreates enum type ${options.typeName} with updated values`,
387
+ operationClass: "destructive",
388
+ target: { id: "postgres" },
389
+ precheck: [{
390
+ description: `ensure type "${options.nativeType}" exists`,
391
+ sql: enumTypeExistsCheck(options.schemaName, options.nativeType)
392
+ }, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({
393
+ description: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(", ")})`,
394
+ sql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)
395
+ })) : []],
396
+ execute: [
397
+ {
398
+ description: `drop orphaned temp type "${tempTypeName}" if exists`,
399
+ sql: `DROP TYPE IF EXISTS ${qualifiedTemp}`
400
+ },
401
+ {
402
+ description: `create temp type "${tempTypeName}"`,
403
+ sql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`
404
+ },
405
+ ...alterColumns,
406
+ {
407
+ description: `drop type "${options.nativeType}"`,
408
+ sql: `DROP TYPE ${qualifiedOriginal}`
409
+ },
410
+ {
411
+ description: `rename type "${tempTypeName}" to "${options.nativeType}"`,
412
+ sql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`
413
+ }
414
+ ],
415
+ postcheck: postchecks
416
+ };
417
+ }
418
+ /**
419
+ * Postgres enum hooks for planning, verifying, and introspecting `storage.types`.
420
+ */
421
+ const pgEnumControlHooks = {
422
+ planTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {
423
+ const desired = getEnumValues(typeInstance);
424
+ if (!desired || desired.length === 0) return { operations: [] };
425
+ const schemaNamespace = schemaName ?? "public";
426
+ const existing = readExistingEnumValues(schema, typeInstance.nativeType);
427
+ if (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };
428
+ const diff = determineEnumDiff(existing, desired);
429
+ if (diff.kind === "unchanged") return { operations: [] };
430
+ if (diff.kind === "rebuild") return { operations: [buildRecreateEnumOperation({
431
+ typeName,
432
+ nativeType: typeInstance.nativeType,
433
+ schemaName: schemaNamespace,
434
+ values: desired,
435
+ removedValues: diff.removedValues,
436
+ contract,
437
+ schema
438
+ })] };
439
+ return { operations: buildAddValueOperations({
440
+ typeName,
441
+ nativeType: typeInstance.nativeType,
442
+ schemaName: schemaNamespace,
443
+ desired,
444
+ existing
445
+ }) };
446
+ },
447
+ verifyType: ({ typeName, typeInstance, schema }) => {
448
+ const desired = getEnumValues(typeInstance);
449
+ if (!desired) return [];
450
+ const existing = readExistingEnumValues(schema, typeInstance.nativeType);
451
+ if (!existing) return [{
452
+ kind: "type_missing",
453
+ table: "",
454
+ typeName,
455
+ message: `Type "${typeName}" is missing from database`
456
+ }];
457
+ if (!arraysEqual(existing, desired)) return [{
458
+ kind: "type_values_mismatch",
459
+ table: "",
460
+ typeName,
461
+ expected: desired.join(", "),
462
+ actual: existing.join(", "),
463
+ message: `Type "${typeName}" values do not match contract`
464
+ }];
465
+ return [];
466
+ },
467
+ introspectTypes: async ({ driver, schemaName }) => {
468
+ const namespace = schemaName ?? "public";
469
+ const result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);
470
+ const types = {};
471
+ for (const row of result.rows) {
472
+ const values = parsePostgresArray(row.values);
473
+ if (!values) throw new Error(`Failed to parse enum values for type "${row.type_name}": unexpected format: ${JSON.stringify(row.values)}`);
474
+ types[row.type_name] = {
475
+ codecId: PG_ENUM_CODEC_ID,
476
+ nativeType: row.type_name,
477
+ typeParams: { values }
478
+ };
479
+ }
480
+ return types;
481
+ }
482
+ };
483
+
484
+ //#endregion
485
+ //#region src/core/json-schema-type-expression.ts
486
+ const MAX_DEPTH = 32;
487
+ function isRecord(value) {
488
+ return typeof value === "object" && value !== null;
489
+ }
490
+ function escapeStringLiteral(str) {
491
+ return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
492
+ }
493
+ function quotePropertyKey(key) {
494
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;
495
+ }
496
+ function renderLiteral(value) {
497
+ if (typeof value === "string") return `'${escapeStringLiteral(value)}'`;
498
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
499
+ if (value === null) return "null";
500
+ return "unknown";
501
+ }
502
+ function renderUnion(items, depth) {
503
+ return items.map((item) => render(item, depth)).join(" | ");
504
+ }
505
+ function renderObjectType(schema, depth) {
506
+ const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
507
+ const required = Array.isArray(schema["required"]) ? new Set(schema["required"].filter((key) => typeof key === "string")) : /* @__PURE__ */ new Set();
508
+ const keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));
509
+ if (keys.length === 0) {
510
+ const additionalProperties = schema["additionalProperties"];
511
+ if (additionalProperties === true || additionalProperties === void 0) return "Record<string, unknown>";
512
+ return `Record<string, ${render(additionalProperties, depth)}>`;
513
+ }
514
+ return `{ ${keys.map((key) => {
515
+ const valueSchema = properties[key];
516
+ const optionalMarker = required.has(key) ? "" : "?";
517
+ return `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;
518
+ }).join("; ")} }`;
519
+ }
520
+ function renderArrayType(schema, depth) {
521
+ if (Array.isArray(schema["items"])) return `readonly [${schema["items"].map((item) => render(item, depth)).join(", ")}]`;
522
+ if (schema["items"] !== void 0) {
523
+ const itemType = render(schema["items"], depth);
524
+ return itemType.includes(" | ") || itemType.includes(" & ") ? `(${itemType})[]` : `${itemType}[]`;
525
+ }
526
+ return "unknown[]";
527
+ }
528
+ function render(schema, depth) {
529
+ if (depth > MAX_DEPTH || !isRecord(schema)) return "JsonValue";
530
+ const nextDepth = depth + 1;
531
+ if ("const" in schema) return renderLiteral(schema["const"]);
532
+ if (Array.isArray(schema["enum"])) return schema["enum"].map((value) => renderLiteral(value)).join(" | ");
533
+ if (Array.isArray(schema["oneOf"])) return renderUnion(schema["oneOf"], nextDepth);
534
+ if (Array.isArray(schema["anyOf"])) return renderUnion(schema["anyOf"], nextDepth);
535
+ if (Array.isArray(schema["allOf"])) return schema["allOf"].map((item) => render(item, nextDepth)).join(" & ");
536
+ if (Array.isArray(schema["type"])) return schema["type"].map((item) => render({
537
+ ...schema,
538
+ type: item
539
+ }, nextDepth)).join(" | ");
540
+ switch (schema["type"]) {
541
+ case "string": return "string";
542
+ case "number":
543
+ case "integer": return "number";
544
+ case "boolean": return "boolean";
545
+ case "null": return "null";
546
+ case "array": return renderArrayType(schema, nextDepth);
547
+ case "object": return renderObjectType(schema, nextDepth);
548
+ default: break;
549
+ }
550
+ return "JsonValue";
551
+ }
552
+ function renderTypeScriptTypeFromJsonSchema(schema) {
553
+ return render(schema, 0);
554
+ }
555
+
556
+ //#endregion
557
+ //#region src/core/parameterized-types.ts
558
+ /**
559
+ * Shared utility for expanding parameterized Postgres types to their full SQL representation.
560
+ *
561
+ * This module provides a single source of truth for type expansion logic, used by:
562
+ * - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook
563
+ * - Migration planner (planner.ts) via direct import
564
+ *
565
+ * @module
566
+ */
567
+ /** Set of codec IDs that use the 'length' parameter */
568
+ const LENGTH_CODEC_IDS = new Set([
569
+ SQL_CHAR_CODEC_ID,
570
+ SQL_VARCHAR_CODEC_ID,
571
+ PG_CHAR_CODEC_ID,
572
+ PG_VARCHAR_CODEC_ID,
573
+ PG_BIT_CODEC_ID,
574
+ PG_VARBIT_CODEC_ID
575
+ ]);
576
+ /** Set of codec IDs that use the 'precision' parameter for temporal types */
577
+ const TEMPORAL_PRECISION_CODEC_IDS = new Set([
578
+ PG_TIMESTAMP_CODEC_ID,
579
+ PG_TIMESTAMPTZ_CODEC_ID,
580
+ PG_TIME_CODEC_ID,
581
+ PG_TIMETZ_CODEC_ID,
582
+ PG_INTERVAL_CODEC_ID
583
+ ]);
584
+ /**
585
+ * Validates that a value is a valid type parameter number.
586
+ * Type parameters must be finite, non-negative integers.
587
+ */
588
+ function isValidTypeParamNumber(value) {
589
+ return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;
590
+ }
591
+ /**
592
+ * Expands a parameterized native type to its full SQL representation.
593
+ *
594
+ * For example:
595
+ * - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'
596
+ * - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'
597
+ * - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'
598
+ *
599
+ * Returns the original nativeType if:
600
+ * - No typeParams are provided
601
+ * - No codecId is provided
602
+ * - The codecId is not a known parameterized type
603
+ * - The typeParams values are invalid
604
+ */
605
+ function expandParameterizedNativeType(input) {
606
+ const { nativeType, codecId, typeParams } = input;
607
+ if (!typeParams || !codecId) return nativeType;
608
+ if (LENGTH_CODEC_IDS.has(codecId)) {
609
+ const length = typeParams["length"];
610
+ if (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;
611
+ return nativeType;
612
+ }
613
+ if (codecId === PG_NUMERIC_CODEC_ID) {
614
+ const precision = typeParams["precision"];
615
+ const scale = typeParams["scale"];
616
+ if (isValidTypeParamNumber(precision)) {
617
+ if (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;
618
+ return `${nativeType}(${precision})`;
619
+ }
620
+ return nativeType;
621
+ }
622
+ if (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {
623
+ const precision = typeParams["precision"];
624
+ if (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;
625
+ return nativeType;
626
+ }
627
+ return nativeType;
628
+ }
629
+
630
+ //#endregion
631
+ //#region src/core/descriptor-meta.ts
632
+ /** Creates a type import spec for codec types */
633
+ const codecTypeImport = (named) => ({
634
+ package: "@prisma-next/adapter-postgres/codec-types",
635
+ named,
636
+ alias: named
637
+ });
638
+ /** Creates a precision-based TypeScript type renderer for temporal types */
639
+ const precisionRenderer = (typeName) => ({
640
+ kind: "function",
641
+ render: (params) => {
642
+ const precision = params["precision"];
643
+ return typeof precision === "number" ? `${typeName}<${precision}>` : typeName;
644
+ }
645
+ });
646
+ /** Creates control hooks with just expandNativeType for parameterized types */
647
+ const parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };
648
+ /**
649
+ * Validates that a type expression string is safe to embed in generated .d.ts files.
650
+ * Rejects expressions containing patterns that could inject executable code.
651
+ */
652
+ function isSafeTypeExpression(expr) {
653
+ return !/import\s*\(|require\s*\(|declare\s|export\s|eval\s*\(/.test(expr);
654
+ }
655
+ function renderJsonTypeExpression(params) {
656
+ const typeName = params["type"];
657
+ if (typeof typeName === "string" && typeName.trim().length > 0) {
658
+ const trimmed = typeName.trim();
659
+ if (!isSafeTypeExpression(trimmed)) return "JsonValue";
660
+ return trimmed;
661
+ }
662
+ const schema = params["schemaJson"];
663
+ if (schema && typeof schema === "object") {
664
+ const rendered = renderTypeScriptTypeFromJsonSchema(schema);
665
+ if (!isSafeTypeExpression(rendered)) return "JsonValue";
666
+ return rendered;
667
+ }
668
+ return "JsonValue";
669
+ }
670
+ const postgresAdapterDescriptorMeta = {
671
+ kind: "adapter",
672
+ familyId: "sql",
673
+ targetId: "postgres",
674
+ id: "postgres",
675
+ version: "0.0.1",
676
+ capabilities: {
677
+ postgres: {
678
+ orderBy: true,
679
+ limit: true,
680
+ lateral: true,
681
+ jsonAgg: true,
682
+ returning: true
683
+ },
684
+ sql: { enums: true }
685
+ },
686
+ types: {
687
+ codecTypes: {
688
+ import: {
689
+ package: "@prisma-next/adapter-postgres/codec-types",
690
+ named: "CodecTypes",
691
+ alias: "PgTypes"
692
+ },
693
+ parameterized: {
694
+ [SQL_CHAR_CODEC_ID]: "Char<{{length}}>",
695
+ [SQL_VARCHAR_CODEC_ID]: "Varchar<{{length}}>",
696
+ [PG_CHAR_CODEC_ID]: "Char<{{length}}>",
697
+ [PG_VARCHAR_CODEC_ID]: "Varchar<{{length}}>",
698
+ [PG_NUMERIC_CODEC_ID]: {
699
+ kind: "function",
700
+ render: (params) => {
701
+ const precision = params["precision"];
702
+ if (typeof precision !== "number") throw new Error("pg/numeric@1 renderer expects precision");
703
+ const scale = params["scale"];
704
+ return typeof scale === "number" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;
705
+ }
706
+ },
707
+ [PG_BIT_CODEC_ID]: "Bit<{{length}}>",
708
+ [PG_VARBIT_CODEC_ID]: "VarBit<{{length}}>",
709
+ [PG_TIMESTAMP_CODEC_ID]: precisionRenderer("Timestamp"),
710
+ [PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer("Timestamptz"),
711
+ [PG_TIME_CODEC_ID]: precisionRenderer("Time"),
712
+ [PG_TIMETZ_CODEC_ID]: precisionRenderer("Timetz"),
713
+ [PG_INTERVAL_CODEC_ID]: precisionRenderer("Interval"),
714
+ [PG_ENUM_CODEC_ID]: {
715
+ kind: "function",
716
+ render: (params) => {
717
+ const values = params["values"];
718
+ if (!Array.isArray(values)) throw new Error("pg/enum@1 renderer expects values array");
719
+ return values.map((value) => `'${String(value).replace(/'/g, "\\'")}'`).join(" | ");
720
+ }
721
+ },
722
+ [PG_JSON_CODEC_ID]: {
723
+ kind: "function",
724
+ render: renderJsonTypeExpression
725
+ },
726
+ [PG_JSONB_CODEC_ID]: {
727
+ kind: "function",
728
+ render: renderJsonTypeExpression
729
+ }
730
+ },
731
+ typeImports: [
732
+ {
733
+ package: "@prisma-next/adapter-postgres/codec-types",
734
+ named: "JsonValue",
735
+ alias: "JsonValue"
736
+ },
737
+ codecTypeImport("Char"),
738
+ codecTypeImport("Varchar"),
739
+ codecTypeImport("Numeric"),
740
+ codecTypeImport("Bit"),
741
+ codecTypeImport("VarBit"),
742
+ codecTypeImport("Timestamp"),
743
+ codecTypeImport("Timestamptz"),
744
+ codecTypeImport("Time"),
745
+ codecTypeImport("Timetz"),
746
+ codecTypeImport("Interval")
747
+ ],
748
+ controlPlaneHooks: {
749
+ [SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,
750
+ [SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,
751
+ [PG_CHAR_CODEC_ID]: parameterizedTypeHooks,
752
+ [PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,
753
+ [PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,
754
+ [PG_BIT_CODEC_ID]: parameterizedTypeHooks,
755
+ [PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,
756
+ [PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,
757
+ [PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,
758
+ [PG_TIME_CODEC_ID]: parameterizedTypeHooks,
759
+ [PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,
760
+ [PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,
761
+ [PG_ENUM_CODEC_ID]: pgEnumControlHooks
762
+ }
763
+ },
764
+ storage: [
765
+ {
766
+ typeId: PG_TEXT_CODEC_ID,
767
+ familyId: "sql",
768
+ targetId: "postgres",
769
+ nativeType: "text"
770
+ },
771
+ {
772
+ typeId: SQL_CHAR_CODEC_ID,
773
+ familyId: "sql",
774
+ targetId: "postgres",
775
+ nativeType: "character"
776
+ },
777
+ {
778
+ typeId: SQL_VARCHAR_CODEC_ID,
779
+ familyId: "sql",
780
+ targetId: "postgres",
781
+ nativeType: "character varying"
782
+ },
783
+ {
784
+ typeId: SQL_INT_CODEC_ID,
785
+ familyId: "sql",
786
+ targetId: "postgres",
787
+ nativeType: "int4"
788
+ },
789
+ {
790
+ typeId: SQL_FLOAT_CODEC_ID,
791
+ familyId: "sql",
792
+ targetId: "postgres",
793
+ nativeType: "float8"
794
+ },
795
+ {
796
+ typeId: PG_CHAR_CODEC_ID,
797
+ familyId: "sql",
798
+ targetId: "postgres",
799
+ nativeType: "character"
800
+ },
801
+ {
802
+ typeId: PG_VARCHAR_CODEC_ID,
803
+ familyId: "sql",
804
+ targetId: "postgres",
805
+ nativeType: "character varying"
806
+ },
807
+ {
808
+ typeId: PG_INT_CODEC_ID,
809
+ familyId: "sql",
810
+ targetId: "postgres",
811
+ nativeType: "int4"
812
+ },
813
+ {
814
+ typeId: PG_FLOAT_CODEC_ID,
815
+ familyId: "sql",
816
+ targetId: "postgres",
817
+ nativeType: "float8"
818
+ },
819
+ {
820
+ typeId: PG_INT4_CODEC_ID,
821
+ familyId: "sql",
822
+ targetId: "postgres",
823
+ nativeType: "int4"
824
+ },
825
+ {
826
+ typeId: PG_INT2_CODEC_ID,
827
+ familyId: "sql",
828
+ targetId: "postgres",
829
+ nativeType: "int2"
830
+ },
831
+ {
832
+ typeId: PG_INT8_CODEC_ID,
833
+ familyId: "sql",
834
+ targetId: "postgres",
835
+ nativeType: "int8"
836
+ },
837
+ {
838
+ typeId: PG_FLOAT4_CODEC_ID,
839
+ familyId: "sql",
840
+ targetId: "postgres",
841
+ nativeType: "float4"
842
+ },
843
+ {
844
+ typeId: PG_FLOAT8_CODEC_ID,
845
+ familyId: "sql",
846
+ targetId: "postgres",
847
+ nativeType: "float8"
848
+ },
849
+ {
850
+ typeId: PG_NUMERIC_CODEC_ID,
851
+ familyId: "sql",
852
+ targetId: "postgres",
853
+ nativeType: "numeric"
854
+ },
855
+ {
856
+ typeId: PG_TIMESTAMP_CODEC_ID,
857
+ familyId: "sql",
858
+ targetId: "postgres",
859
+ nativeType: "timestamp"
860
+ },
861
+ {
862
+ typeId: PG_TIMESTAMPTZ_CODEC_ID,
863
+ familyId: "sql",
864
+ targetId: "postgres",
865
+ nativeType: "timestamptz"
866
+ },
867
+ {
868
+ typeId: PG_TIME_CODEC_ID,
869
+ familyId: "sql",
870
+ targetId: "postgres",
871
+ nativeType: "time"
872
+ },
873
+ {
874
+ typeId: PG_TIMETZ_CODEC_ID,
875
+ familyId: "sql",
876
+ targetId: "postgres",
877
+ nativeType: "timetz"
878
+ },
879
+ {
880
+ typeId: PG_BOOL_CODEC_ID,
881
+ familyId: "sql",
882
+ targetId: "postgres",
883
+ nativeType: "bool"
884
+ },
885
+ {
886
+ typeId: PG_BIT_CODEC_ID,
887
+ familyId: "sql",
888
+ targetId: "postgres",
889
+ nativeType: "bit"
890
+ },
891
+ {
892
+ typeId: PG_VARBIT_CODEC_ID,
893
+ familyId: "sql",
894
+ targetId: "postgres",
895
+ nativeType: "bit varying"
896
+ },
897
+ {
898
+ typeId: PG_INTERVAL_CODEC_ID,
899
+ familyId: "sql",
900
+ targetId: "postgres",
901
+ nativeType: "interval"
902
+ },
903
+ {
904
+ typeId: PG_JSON_CODEC_ID,
905
+ familyId: "sql",
906
+ targetId: "postgres",
907
+ nativeType: "json"
908
+ },
909
+ {
910
+ typeId: PG_JSONB_CODEC_ID,
911
+ familyId: "sql",
912
+ targetId: "postgres",
913
+ nativeType: "jsonb"
914
+ }
915
+ ]
916
+ }
917
+ };
918
+
919
+ //#endregion
920
+ export { expandParameterizedNativeType as n, pgEnumControlHooks as r, postgresAdapterDescriptorMeta as t };
921
+ //# sourceMappingURL=descriptor-meta-ilnFI7bx.mjs.map