@prisma-next/adapter-postgres 0.5.0-dev.2 → 0.5.0-dev.21

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 (36) hide show
  1. package/dist/{adapter-hNElNHo4.mjs → adapter-cXPXgEG0.mjs} +9 -5
  2. package/dist/adapter-cXPXgEG0.mjs.map +1 -0
  3. package/dist/adapter.d.mts +2 -1
  4. package/dist/adapter.d.mts.map +1 -1
  5. package/dist/adapter.mjs +1 -1
  6. package/dist/control.d.mts +76 -3
  7. package/dist/control.d.mts.map +1 -1
  8. package/dist/control.mjs +44 -6
  9. package/dist/control.mjs.map +1 -1
  10. package/dist/{descriptor-meta-RTDzyrae.mjs → descriptor-meta-Dxnoq_rr.mjs} +22 -21
  11. package/dist/descriptor-meta-Dxnoq_rr.mjs.map +1 -0
  12. package/dist/operation-types.d.mts +11 -10
  13. package/dist/operation-types.d.mts.map +1 -1
  14. package/dist/runtime.d.mts +2 -2
  15. package/dist/runtime.d.mts.map +1 -1
  16. package/dist/runtime.mjs +10 -5
  17. package/dist/runtime.mjs.map +1 -1
  18. package/dist/{sql-renderer-pEaSP82_.mjs → sql-renderer-Dd_Y8oK_.mjs} +80 -27
  19. package/dist/sql-renderer-Dd_Y8oK_.mjs.map +1 -0
  20. package/dist/{types-CfRPdAk8.d.mts → types-tLtmYqCO.d.mts} +12 -1
  21. package/dist/types-tLtmYqCO.d.mts.map +1 -0
  22. package/dist/types.d.mts +1 -1
  23. package/package.json +21 -21
  24. package/src/core/adapter.ts +10 -2
  25. package/src/core/codec-lookup.ts +24 -0
  26. package/src/core/control-adapter.ts +68 -1
  27. package/src/core/descriptor-meta.ts +29 -11
  28. package/src/core/sql-renderer.ts +90 -40
  29. package/src/core/types.ts +11 -0
  30. package/src/exports/control.ts +3 -2
  31. package/src/exports/runtime.ts +16 -3
  32. package/src/types/operation-types.ts +19 -9
  33. package/dist/adapter-hNElNHo4.mjs.map +0 -1
  34. package/dist/descriptor-meta-RTDzyrae.mjs.map +0 -1
  35. package/dist/sql-renderer-pEaSP82_.mjs.map +0 -1
  36. package/dist/types-CfRPdAk8.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-Dxnoq_rr.mjs","names":["result: string[]","operations: SqlMigrationPlanOperation<unknown>[]","columns: Array<{ table: string; column: string }>","result: Array<{ table: string; column: string }>","pgEnumControlHooks: CodecControlHooks","types: Record<string, StorageTypeInstance>","lengthHooks: CodecControlHooks","precisionHooks: CodecControlHooks","numericHooks: CodecControlHooks","identityHooks: CodecControlHooks"],"sources":["../src/core/enum-control-hooks.ts","../src/core/descriptor-meta.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport { arraysEqual } from '@prisma-next/family-sql/schema-verify';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { PG_ENUM_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';\nimport {\n escapeLiteral,\n qualifyName,\n quoteIdentifier,\n validateEnumValueLength,\n} from '@prisma-next/target-postgres/sql-utils';\n\n/**\n * Postgres enum control hooks.\n *\n * - Plans enum type operations for migrations\n * - Verifies enum types in schema IR\n * - Introspects enum types from the database\n */\ntype EnumRow = {\n schema_name: string;\n type_name: string;\n values: string[];\n};\n\ntype EnumDiff =\n | { kind: 'unchanged' }\n | { kind: 'add_values'; values: readonly string[] }\n | { kind: 'rebuild'; removedValues: readonly string[] };\n\n// ============================================================================\n// Introspection SQL\n// ============================================================================\n\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n\n// ============================================================================\n// Schema Helpers (Simplified)\n// ============================================================================\n\n/**\n * Type guard for string arrays. Used for runtime validation of introspected data.\n */\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Parses a PostgreSQL array value into a JavaScript string array.\n *\n * PostgreSQL's `pg` library may return `array_agg` results either as:\n * - A JavaScript array (when type parsers are configured)\n * - A string in PostgreSQL array literal format: `{value1,value2,...}`\n *\n * Handles PostgreSQL's quoting rules for array elements:\n * - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n * - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n *\n * @param value - The value to parse (array or PostgreSQL array string)\n * @returns A string array, or null if the value cannot be parsed\n */\nexport function parsePostgresArray(value: unknown): string[] | null {\n if (isStringArray(value)) {\n return value;\n }\n if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) {\n const inner = value.slice(1, -1);\n if (inner === '') {\n return [];\n }\n return parseArrayElements(inner);\n }\n return null;\n}\n\nfunction parseArrayElements(input: string): string[] {\n const result: string[] = [];\n let i = 0;\n while (i < input.length) {\n if (input[i] === ',') {\n i++;\n continue;\n }\n if (input[i] === '\"') {\n i++;\n let element = '';\n while (i < input.length && input[i] !== '\"') {\n if (input[i] === '\\\\' && i + 1 < input.length) {\n i++;\n element += input[i];\n } else {\n element += input[i];\n }\n i++;\n }\n i++;\n result.push(element);\n } else {\n const nextComma = input.indexOf(',', i);\n if (nextComma === -1) {\n result.push(input.slice(i).trim());\n i = input.length;\n } else {\n result.push(input.slice(i, nextComma).trim());\n i = nextComma;\n }\n }\n }\n return result;\n}\n\n/**\n * Extracts enum values from a StorageTypeInstance.\n * Returns null if values are missing or invalid.\n */\nfunction getEnumValues(typeInstance: StorageTypeInstance): readonly string[] | null {\n const values = typeInstance.typeParams?.['values'];\n return isStringArray(values) ? values : null;\n}\n\n/**\n * Reads existing enum values from the schema IR for a given native type.\n * Uses optional chaining to simplify navigation through the annotations structure.\n */\nfunction readExistingEnumValues(schema: SqlSchemaIR, nativeType: string): readonly string[] | null {\n const storageTypes = (schema.annotations?.['pg'] as Record<string, unknown> | undefined)?.[\n 'storageTypes'\n ] as Record<string, StorageTypeInstance> | undefined;\n\n const existing = storageTypes?.[nativeType];\n if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {\n return null;\n }\n return getEnumValues(existing);\n}\n\n/**\n * Determines what changes are needed to transform existing enum values to desired values.\n *\n * Returns one of:\n * - `unchanged`: No changes needed, values match exactly\n * - `add_values`: New values can be safely appended (PostgreSQL supports this)\n * - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n *\n * Note: PostgreSQL enums can only have values added (not removed or reordered) without\n * a full type rebuild involving temp type creation and column migration.\n *\n * @param existing - Current enum values in the database\n * @param desired - Target enum values from the contract\n * @returns The type of change required\n */\nfunction determineEnumDiff(existing: readonly string[], desired: readonly string[]): EnumDiff {\n if (arraysEqual(existing, desired)) {\n return { kind: 'unchanged' };\n }\n\n // Use Sets for O(1) lookups instead of O(n) array.includes()\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\n\n const missingValues = desired.filter((value) => !existingSet.has(value));\n const removedValues = existing.filter((value) => !desiredSet.has(value));\n const orderMismatch =\n missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\n if (removedValues.length > 0 || orderMismatch) {\n return { kind: 'rebuild', removedValues };\n }\n\n return { kind: 'add_values', values: missingValues };\n}\n\n// ============================================================================\n// SQL Helpers\n// ============================================================================\n\nfunction enumTypeExistsCheck(schemaName: string, typeName: string, exists = true): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\n\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildCreateEnumOperation(\n typeName: string,\n nativeType: string,\n schemaName: string,\n values: readonly string[],\n): SqlMigrationPlanOperation<unknown> {\n // Validate all enum values don't exceed PostgreSQL's label length limit\n for (const value of values) {\n validateEnumValueLength(value, typeName);\n }\n const literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(', ');\n const qualifiedType = qualifyName(schemaName, nativeType);\n return {\n id: `type.${typeName}`,\n label: `Create type ${typeName}`,\n summary: `Creates enum type ${typeName}`,\n operationClass: 'additive',\n target: { id: 'postgres' },\n precheck: [\n {\n description: `ensure type \"${nativeType}\" does not exist`,\n sql: enumTypeExistsCheck(schemaName, nativeType, false),\n },\n ],\n execute: [\n {\n description: `create type \"${nativeType}\"`,\n sql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`,\n },\n ],\n postcheck: [\n {\n description: `verify type \"${nativeType}\" exists`,\n sql: enumTypeExistsCheck(schemaName, nativeType),\n },\n ],\n };\n}\n\n/**\n * Computes the optimal position for inserting a new enum value to maintain\n * the desired order relative to existing values.\n *\n * PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n * This function finds the best reference value by:\n * 1. Looking for the nearest preceding value that already exists\n * 2. Falling back to the nearest following value if no preceding exists\n * 3. Defaulting to end-of-list if no reference is found\n *\n * @param options.desired - The target ordered list of all enum values\n * @param options.desiredIndex - Index of the value being inserted in the desired list\n * @param options.current - Current list of enum values (being built up incrementally)\n * @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n */\nfunction computeInsertPosition(options: {\n desired: readonly string[];\n desiredIndex: number;\n current: readonly string[];\n}): { clause: string; insertAt: number } {\n const { desired, desiredIndex, current } = options;\n const currentSet = new Set(current);\n const previous = desired\n .slice(0, desiredIndex)\n .reverse()\n .find((candidate) => currentSet.has(candidate));\n const next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n const clause = previous\n ? ` AFTER '${escapeLiteral(previous)}'`\n : next\n ? ` BEFORE '${escapeLiteral(next)}'`\n : '';\n const insertAt = previous\n ? current.indexOf(previous) + 1\n : next\n ? current.indexOf(next)\n : current.length;\n\n return { clause, insertAt };\n}\n\n/**\n * Builds operations to add new enum values to an existing PostgreSQL enum type.\n *\n * Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n * Values are inserted in the correct order using BEFORE/AFTER positioning to match\n * the desired final order.\n *\n * This is a safe, non-destructive operation - existing data is not affected.\n *\n * @param options.typeName - Contract-level type name (e.g., 'Role')\n * @param options.nativeType - PostgreSQL type name (e.g., 'role')\n * @param options.schemaName - PostgreSQL schema (e.g., 'public')\n * @param options.desired - Target ordered list of all enum values\n * @param options.existing - Current enum values in the database\n * @returns Array of migration operations to add each missing value\n */\nfunction buildAddValueOperations(options: {\n typeName: string;\n nativeType: string;\n schemaName: string;\n desired: readonly string[];\n existing: readonly string[];\n}): SqlMigrationPlanOperation<unknown>[] {\n const { typeName, nativeType, schemaName } = options;\n const current = [...options.existing];\n const currentSet = new Set(current);\n const operations: SqlMigrationPlanOperation<unknown>[] = [];\n for (let index = 0; index < options.desired.length; index += 1) {\n const value = options.desired[index];\n if (value === undefined) {\n continue;\n }\n if (currentSet.has(value)) {\n continue;\n }\n // Validate the new value doesn't exceed PostgreSQL's label length limit\n validateEnumValueLength(value, typeName);\n const { clause, insertAt } = computeInsertPosition({\n desired: options.desired,\n desiredIndex: index,\n current,\n });\n // Use IF NOT EXISTS for idempotency - safe to re-run after partial failures.\n // Supported in PostgreSQL 9.3+, and we require PostgreSQL 12+.\n operations.push({\n id: `type.${typeName}.value.${value}`,\n label: `Add value ${value} to ${typeName}`,\n summary: `Adds enum value ${value} to ${typeName}`,\n operationClass: 'widening',\n target: { id: 'postgres' },\n precheck: [],\n execute: [\n {\n description: `add value \"${value}\" if not exists`,\n sql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(\n value,\n )}'${clause}`,\n },\n ],\n postcheck: [],\n });\n current.splice(insertAt, 0, value);\n currentSet.add(value);\n }\n return operations;\n}\n\n/**\n * Collects columns using the enum type from the contract (desired state).\n * Used for type-safe reference tracking.\n */\nfunction collectEnumColumnsFromContract(\n contract: Contract<SqlStorage>,\n typeName: string,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const columns: Array<{ table: string; column: string }> = [];\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (\n column.typeRef === typeName ||\n (column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID)\n ) {\n columns.push({ table: tableName, column: columnName });\n }\n }\n }\n return columns;\n}\n\n/**\n * Collects columns using the enum type from the schema IR (live database state).\n * This ensures we find ALL dependent columns, including those added outside the contract\n * (e.g., manual DDL), which is critical for safe enum rebuild operations.\n */\nfunction collectEnumColumnsFromSchema(\n schema: SqlSchemaIR,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const columns: Array<{ table: string; column: string }> = [];\n for (const [tableName, table] of Object.entries(schema.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n // Match by nativeType since schema IR doesn't have codecId/typeRef\n if (column.nativeType === nativeType) {\n columns.push({ table: tableName, column: columnName });\n }\n }\n }\n return columns;\n}\n\n/**\n * Collects all columns using the enum type from both contract AND live database.\n * Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n *\n * This is critical for data integrity: if a column exists in the database using\n * this enum but is not in the contract (e.g., added via manual DDL), we must\n * still migrate it to avoid DROP TYPE failures.\n */\nfunction collectAllEnumColumns(\n contract: Contract<SqlStorage>,\n schema: SqlSchemaIR,\n typeName: string,\n nativeType: string,\n): ReadonlyArray<{ table: string; column: string }> {\n const contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n const schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\n // Merge and deduplicate using a Set of \"table.column\" keys\n const seen = new Set<string>();\n const result: Array<{ table: string; column: string }> = [];\n\n for (const col of [...contractColumns, ...schemaColumns]) {\n const key = `${col.table}.${col.column}`;\n if (!seen.has(key)) {\n seen.add(key);\n result.push(col);\n }\n }\n\n // Sort for deterministic operation order\n return result.sort((a, b) => {\n const tableCompare = a.table.localeCompare(b.table);\n return tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n });\n}\n\n/**\n * Builds a SQL check to verify a column's type matches an expected type.\n */\nfunction columnTypeCheck(options: {\n schemaName: string;\n tableName: string;\n columnName: string;\n expectedType: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = '__pn_rebuild';\n\n/**\n * Builds an SQL check to verify no rows contain any of the removed enum values.\n * This prevents data loss during enum rebuild operations.\n *\n * @param schemaName - PostgreSQL schema name\n * @param tableName - Table containing the enum column\n * @param columnName - Column using the enum type\n * @param removedValues - Array of enum values being removed\n * @returns SQL query that returns true if no rows contain removed values\n */\nfunction noRemovedValuesExistCheck(\n schemaName: string,\n tableName: string,\n columnName: string,\n removedValues: readonly string[],\n): string {\n if (removedValues.length === 0) {\n // No values being removed, always passes\n return 'SELECT true';\n }\n const valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n return `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n\n/**\n * Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n *\n * This is required when:\n * - Enum values are removed (PostgreSQL doesn't support direct removal)\n * - Enum values are reordered (PostgreSQL doesn't support reordering)\n *\n * The operation:\n * 1. Creates a new enum type with the desired values (temp name)\n * 2. Migrates all columns to use the new type via text cast\n * 3. Drops the original type\n * 4. Renames the temp type to the original name\n *\n * IMPORTANT: If values are being removed and data exists using those values,\n * the operation will fail at the precheck stage with a clear error message.\n * This prevents silent data loss.\n *\n * @param options.typeName - Contract-level type name\n * @param options.nativeType - PostgreSQL type name\n * @param options.schemaName - PostgreSQL schema\n * @param options.values - Desired final enum values\n * @param options.removedValues - Values being removed (for data loss checks)\n * @param options.contract - Full contract for column discovery\n * @param options.schema - Current schema IR for column discovery\n * @returns Migration operation for full enum rebuild\n */\nfunction buildRecreateEnumOperation(options: {\n typeName: string;\n nativeType: string;\n schemaName: string;\n values: readonly string[];\n removedValues: readonly string[];\n contract: Contract<SqlStorage>;\n schema: SqlSchemaIR;\n}): SqlMigrationPlanOperation<unknown> {\n const tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\n // Validate temp type name length won't exceed PostgreSQL's 63-character limit.\n // If it would, PostgreSQL silently truncates which could cause conflicts.\n if (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n const maxBaseLength = MAX_IDENTIFIER_LENGTH - REBUILD_SUFFIX.length;\n throw new Error(\n `Enum type name \"${options.nativeType}\" is too long for rebuild operation. ` +\n `Maximum length is ${maxBaseLength} characters (type name + \"${REBUILD_SUFFIX}\" suffix ` +\n `must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`,\n );\n }\n\n const qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n const qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n const literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(', ');\n\n // CRITICAL: Collect columns from BOTH contract AND live database.\n // This ensures we migrate ALL dependent columns, including those added\n // outside of Prisma Next (e.g., manual DDL). Without this, DROP TYPE\n // would fail if the database has columns not tracked in the contract.\n const columnRefs = collectAllEnumColumns(\n options.contract,\n options.schema,\n options.typeName,\n options.nativeType,\n );\n\n const alterColumns = columnRefs.map((ref) => ({\n description: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n sql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`,\n }));\n\n // Build postchecks to verify:\n // 1. The final type exists with the correct name\n // 2. The temp type was cleaned up (renamed away)\n // 3. All migrated columns now reference the final type\n const postchecks = [\n {\n description: `verify type \"${options.nativeType}\" exists`,\n sql: enumTypeExistsCheck(options.schemaName, options.nativeType),\n },\n {\n description: `verify temp type \"${tempTypeName}\" was removed`,\n sql: enumTypeExistsCheck(options.schemaName, tempTypeName, false),\n },\n // Verify each column was successfully migrated to the final type\n ...columnRefs.map((ref) => ({\n description: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n sql: columnTypeCheck({\n schemaName: options.schemaName,\n tableName: ref.table,\n columnName: ref.column,\n expectedType: options.nativeType,\n }),\n })),\n ];\n\n return {\n id: `type.${options.typeName}.rebuild`,\n label: `Rebuild type ${options.typeName}`,\n summary: `Recreates enum type ${options.typeName} with updated values`,\n operationClass: 'destructive',\n target: { id: 'postgres' },\n precheck: [\n {\n description: `ensure type \"${options.nativeType}\" exists`,\n sql: enumTypeExistsCheck(options.schemaName, options.nativeType),\n },\n // Note: We don't precheck that temp type doesn't exist because we handle\n // orphaned temp types in the execute step below.\n\n // CRITICAL: If values are being removed, verify no data exists using those values.\n // This prevents silent data loss during the rebuild - the USING cast would fail\n // at runtime if rows contain values that don't exist in the new enum.\n ...(options.removedValues.length > 0\n ? columnRefs.map((ref) => ({\n description: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(', ')})`,\n sql: noRemovedValuesExistCheck(\n options.schemaName,\n ref.table,\n ref.column,\n options.removedValues,\n ),\n }))\n : []),\n ],\n execute: [\n // Clean up any orphaned temp type from a previous failed migration.\n // This makes the operation recoverable without manual intervention.\n // DROP TYPE IF EXISTS is safe - it's a no-op if the type doesn't exist.\n {\n description: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n sql: `DROP TYPE IF EXISTS ${qualifiedTemp}`,\n },\n {\n description: `create temp type \"${tempTypeName}\"`,\n sql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`,\n },\n ...alterColumns,\n {\n description: `drop type \"${options.nativeType}\"`,\n sql: `DROP TYPE ${qualifiedOriginal}`,\n },\n {\n description: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n sql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`,\n },\n ],\n postcheck: postchecks,\n };\n}\n\n// ============================================================================\n// Codec Control Hooks\n// ============================================================================\n\n/**\n * Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n */\nexport const pgEnumControlHooks: CodecControlHooks = {\n planTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n const desired = getEnumValues(typeInstance);\n if (!desired || desired.length === 0) {\n return { operations: [] };\n }\n\n const schemaNamespace = schemaName ?? 'public';\n const existing = readExistingEnumValues(schema, typeInstance.nativeType);\n if (!existing) {\n return {\n operations: [\n buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired),\n ],\n };\n }\n\n const diff = determineEnumDiff(existing, desired);\n if (diff.kind === 'unchanged') {\n return { operations: [] };\n }\n\n if (diff.kind === 'rebuild') {\n return {\n operations: [\n buildRecreateEnumOperation({\n typeName,\n nativeType: typeInstance.nativeType,\n schemaName: schemaNamespace,\n values: desired,\n removedValues: diff.removedValues,\n contract,\n schema,\n }),\n ],\n };\n }\n\n return {\n operations: buildAddValueOperations({\n typeName,\n nativeType: typeInstance.nativeType,\n schemaName: schemaNamespace,\n desired,\n existing,\n }),\n };\n },\n verifyType: ({ typeName, typeInstance, schema }) => {\n const desired = getEnumValues(typeInstance);\n if (!desired) {\n return [];\n }\n const existing = readExistingEnumValues(schema, typeInstance.nativeType);\n if (!existing) {\n return [\n {\n kind: 'type_missing',\n typeName,\n message: `Type \"${typeName}\" is missing from database`,\n },\n ];\n }\n const diff = determineEnumDiff(existing, desired);\n if (diff.kind === 'unchanged') return [];\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\n const addedValues = desired.filter((v) => !existingSet.has(v));\n const removedValues = existing.filter((v) => !desiredSet.has(v));\n return [\n {\n kind: 'enum_values_changed' as const,\n typeName,\n addedValues,\n removedValues,\n message:\n diff.kind === 'add_values'\n ? `Enum type \"${typeName}\" needs new values: ${addedValues.join(', ')}`\n : `Enum type \"${typeName}\" values changed (requires rebuild): +[${addedValues.join(', ')}] -[${removedValues.join(', ')}]`,\n },\n ];\n },\n introspectTypes: async ({ driver, schemaName }) => {\n const namespace = schemaName ?? 'public';\n const result = await driver.query<EnumRow>(ENUM_INTROSPECT_QUERY, [namespace]);\n const types: Record<string, StorageTypeInstance> = {};\n for (const row of result.rows) {\n const values = parsePostgresArray(row.values);\n if (!values) {\n throw new Error(\n `Failed to parse enum values for type \"${row.type_name}\": ` +\n `unexpected format: ${JSON.stringify(row.values)}`,\n );\n }\n types[row.type_name] = {\n codecId: PG_ENUM_CODEC_ID,\n nativeType: row.type_name,\n typeParams: { values },\n };\n }\n return types;\n },\n};\n","import type { CodecControlHooks, ExpandNativeTypeInput } from '@prisma-next/family-sql/control';\nimport type { SqlOperationDescriptor } from '@prisma-next/sql-operations';\nimport {\n buildOperation,\n type CodecExpression,\n type Expression,\n type TraitExpression,\n toExpr,\n} from '@prisma-next/sql-relational-core/expression';\nimport {\n PG_BIT_CODEC_ID,\n PG_BOOL_CODEC_ID,\n PG_CHAR_CODEC_ID,\n PG_ENUM_CODEC_ID,\n PG_FLOAT_CODEC_ID,\n PG_FLOAT4_CODEC_ID,\n PG_FLOAT8_CODEC_ID,\n PG_INT_CODEC_ID,\n PG_INT2_CODEC_ID,\n PG_INT4_CODEC_ID,\n PG_INT8_CODEC_ID,\n PG_INTERVAL_CODEC_ID,\n PG_JSON_CODEC_ID,\n PG_JSONB_CODEC_ID,\n PG_NUMERIC_CODEC_ID,\n PG_TEXT_CODEC_ID,\n PG_TIME_CODEC_ID,\n PG_TIMESTAMP_CODEC_ID,\n PG_TIMESTAMPTZ_CODEC_ID,\n PG_TIMETZ_CODEC_ID,\n PG_VARBIT_CODEC_ID,\n PG_VARCHAR_CODEC_ID,\n SQL_CHAR_CODEC_ID,\n SQL_FLOAT_CODEC_ID,\n SQL_INT_CODEC_ID,\n SQL_TEXT_CODEC_ID,\n SQL_TIMESTAMP_CODEC_ID,\n SQL_VARCHAR_CODEC_ID,\n} from '@prisma-next/target-postgres/codec-ids';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\nimport { pgEnumControlHooks } from './enum-control-hooks';\n\n// ============================================================================\n// Helper functions for reducing boilerplate\n// ============================================================================\n\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named: string) =>\n ({\n package: '@prisma-next/target-postgres/codec-types',\n named,\n alias: named,\n }) as const;\n\nfunction isPositiveInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value >= 0\n );\n}\n\nfunction expandLength({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('length' in typeParams)) {\n return nativeType;\n }\n const length = typeParams['length'];\n if (!isPositiveInteger(length)) {\n throw new Error(\n `Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`,\n );\n }\n return `${nativeType}(${length})`;\n}\n\nfunction expandPrecision({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('precision' in typeParams)) {\n return nativeType;\n }\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n return `${nativeType}(${precision})`;\n}\n\nfunction expandNumeric({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n const hasPrecision = typeParams && 'precision' in typeParams;\n const hasScale = typeParams && 'scale' in typeParams;\n\n if (!hasPrecision && !hasScale) {\n return nativeType;\n }\n\n if (!hasPrecision && hasScale) {\n throw new Error(\n `Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`,\n );\n }\n\n if (hasPrecision) {\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n if (hasScale) {\n const scale = typeParams['scale'];\n if (!isNonNegativeInteger(scale)) {\n throw new Error(\n `Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`,\n );\n }\n return `${nativeType}(${precision},${scale})`;\n }\n return `${nativeType}(${precision})`;\n }\n\n return nativeType;\n}\n\nconst lengthHooks: CodecControlHooks = { expandNativeType: expandLength };\nconst precisionHooks: CodecControlHooks = { expandNativeType: expandPrecision };\nconst numericHooks: CodecControlHooks = { expandNativeType: expandNumeric };\nconst identityHooks: CodecControlHooks = { expandNativeType: ({ nativeType }) => nativeType };\n\n// ============================================================================\n// Descriptor metadata\n// ============================================================================\n\ntype CodecTypesBase = Record<string, { readonly input: unknown; readonly output: unknown }>;\n\nexport function postgresQueryOperations<\n CT extends CodecTypesBase,\n>(): readonly SqlOperationDescriptor[] {\n return [\n {\n method: 'ilike',\n self: { traits: ['textual'] },\n impl: (\n self: TraitExpression<readonly ['textual'], false, CT>,\n pattern: CodecExpression<'pg/text@1', false, CT>,\n ): Expression<{ codecId: 'pg/bool@1'; nullable: false }> =>\n buildOperation({\n method: 'ilike',\n args: [toExpr(self), toExpr(pattern, PG_TEXT_CODEC_ID)],\n returns: { codecId: PG_BOOL_CODEC_ID, nullable: false },\n lowering: { targetFamily: 'sql', strategy: 'infix', template: '{{self}} ILIKE {{arg0}}' },\n }),\n },\n ];\n}\n\nexport const postgresAdapterDescriptorMeta = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n sql: {\n enums: true,\n returning: true,\n defaultInInsert: true,\n },\n },\n types: {\n codecTypes: {\n codecInstances: Object.values(codecDefinitions).map((def) => def.codec),\n import: {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'CodecTypes',\n alias: 'PgTypes',\n },\n typeImports: [\n {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'JsonValue',\n alias: 'JsonValue',\n },\n codecTypeImport('Char'),\n codecTypeImport('Varchar'),\n codecTypeImport('Numeric'),\n codecTypeImport('Bit'),\n codecTypeImport('VarBit'),\n codecTypeImport('Timestamp'),\n codecTypeImport('Timestamptz'),\n codecTypeImport('Time'),\n codecTypeImport('Timetz'),\n codecTypeImport('Interval'),\n ],\n controlPlaneHooks: {\n [SQL_CHAR_CODEC_ID]: lengthHooks,\n [SQL_VARCHAR_CODEC_ID]: lengthHooks,\n [SQL_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_CHAR_CODEC_ID]: lengthHooks,\n [PG_VARCHAR_CODEC_ID]: lengthHooks,\n [PG_NUMERIC_CODEC_ID]: numericHooks,\n [PG_BIT_CODEC_ID]: lengthHooks,\n [PG_VARBIT_CODEC_ID]: lengthHooks,\n [PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n [PG_TIME_CODEC_ID]: precisionHooks,\n [PG_TIMETZ_CODEC_ID]: precisionHooks,\n [PG_INTERVAL_CODEC_ID]: precisionHooks,\n [PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n [PG_JSON_CODEC_ID]: identityHooks,\n [PG_JSONB_CODEC_ID]: identityHooks,\n },\n },\n storage: [\n { typeId: PG_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: SQL_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: SQL_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: SQL_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n {\n typeId: SQL_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n { typeId: PG_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: PG_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: PG_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_INT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_INT2_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int2' },\n { typeId: PG_INT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int8' },\n { typeId: PG_FLOAT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float4' },\n { typeId: PG_FLOAT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_NUMERIC_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'numeric' },\n {\n typeId: PG_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n {\n typeId: PG_TIMESTAMPTZ_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamptz',\n },\n { typeId: PG_TIME_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'time' },\n { typeId: PG_TIMETZ_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'timetz' },\n { typeId: PG_BOOL_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bool' },\n { typeId: PG_BIT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bit' },\n {\n typeId: PG_VARBIT_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'bit varying',\n },\n {\n typeId: PG_INTERVAL_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'interval',\n },\n { typeId: PG_JSON_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'json' },\n { typeId: PG_JSONB_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'jsonb' },\n ],\n queryOperationTypes: {\n import: {\n package: '@prisma-next/adapter-postgres/operation-types',\n named: 'QueryOperationTypes',\n alias: 'PgAdapterQueryOps',\n },\n },\n },\n} as const;\n"],"mappings":";;;;;;;AAmCA,MAAM,wBAAwB;;;;;;;;;;;;;;;AAoB9B,SAAS,cAAc,OAAmC;AACxD,QAAO,MAAM,QAAQ,MAAM,IAAI,MAAM,OAAO,UAAU,OAAO,UAAU,SAAS;;;;;;;;;;;;;;;;AAiBlF,SAAgB,mBAAmB,OAAiC;AAClE,KAAI,cAAc,MAAM,CACtB,QAAO;AAET,KAAI,OAAO,UAAU,YAAY,MAAM,WAAW,IAAI,IAAI,MAAM,SAAS,IAAI,EAAE;EAC7E,MAAM,QAAQ,MAAM,MAAM,GAAG,GAAG;AAChC,MAAI,UAAU,GACZ,QAAO,EAAE;AAEX,SAAO,mBAAmB,MAAM;;AAElC,QAAO;;AAGT,SA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AQ;GACN,SAAS;GACT,OAAO;GACP,OAAO;GACR,EACF;EACF;CACF"}
@@ -1,19 +1,20 @@
1
+ import { CodecExpression, Expression, TraitExpression } from "@prisma-next/sql-relational-core/expression";
1
2
  import { SqlQueryOperationTypes } from "@prisma-next/sql-contract/types";
2
3
 
3
4
  //#region src/types/operation-types.d.ts
4
- type QueryOperationTypes = SqlQueryOperationTypes<{
5
+ type CodecTypesBase = Record<string, {
6
+ readonly input: unknown;
7
+ readonly output: unknown;
8
+ }>;
9
+ type QueryOperationTypes<CT extends CodecTypesBase> = SqlQueryOperationTypes<CT, {
5
10
  readonly ilike: {
6
- readonly args: readonly [{
11
+ readonly self: {
7
12
  readonly traits: readonly ['textual'];
8
- readonly nullable: false;
9
- }, {
10
- readonly codecId: 'pg/text@1';
11
- readonly nullable: false;
12
- }];
13
- readonly returns: {
14
- readonly codecId: 'pg/bool@1';
15
- readonly nullable: false;
16
13
  };
14
+ readonly impl: (self: TraitExpression<readonly ['textual'], false, CT>, pattern: CodecExpression<'pg/text@1', false, CT>) => Expression<{
15
+ codecId: 'pg/bool@1';
16
+ nullable: false;
17
+ }>;
17
18
  };
18
19
  }>;
19
20
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"operation-types.d.mts","names":[],"sources":["../src/types/operation-types.ts"],"sourcesContent":[],"mappings":";;;KAEY,mBAAA,GAAsB;;IAAtB,SAAA,IAAA,EAAA,SAAmB"}
1
+ {"version":3,"file":"operation-types.d.mts","names":[],"sources":["../src/types/operation-types.ts"],"sourcesContent":[],"mappings":";;;;KAOK,cAAA,GAAiB;;EAAjB,SAAA,MAAA,EAAc,OAAA;AAEnB,CAAA,CAAA;AAA2C,KAA/B,mBAA+B,CAAA,WAAA,cAAA,CAAA,GAAkB,sBAAlB,CACzC,EADyC,EAAA;EACzC,SAAA,KAAA,EAAA;IAKyD,SAAA,IAAA,EAAA;MAA7C,SAAA,MAAA,EAAA,SAAA,CAAA,SAAA,CAAA;IACuC,CAAA;IAApC,SAAA,IAAA,EAAA,CAAA,IAAA,EADH,eACG,CAAA,SAAA,CAAA,SAAA,CAAA,EAAA,KAAA,EAD0C,EAC1C,CAAA,EAAA,OAAA,EAAA,eAAA,CAAA,WAAA,EAAA,KAAA,EAAoC,EAApC,CAAA,EAAA,GACN,UADM,CAAA;MACN,OAAA,EAAA,WAAA;MARkD,QAAA,EAAA,KAAA;IAAsB,CAAA,CAAA"}
@@ -1,7 +1,7 @@
1
- import { c as PostgresContract, l as PostgresLoweredStatement } from "./types-CfRPdAk8.mjs";
1
+ import { c as PostgresContract, l as PostgresLoweredStatement } from "./types-tLtmYqCO.mjs";
2
2
  import { Adapter, AnyQueryAst } from "@prisma-next/sql-relational-core/ast";
3
- import { RuntimeAdapterInstance } from "@prisma-next/framework-components/execution";
4
3
  import { SqlRuntimeAdapterDescriptor } from "@prisma-next/sql-runtime";
4
+ import { RuntimeAdapterInstance } from "@prisma-next/framework-components/execution";
5
5
  import { JsonSchemaValidateFn } from "@prisma-next/sql-relational-core/query-lane-context";
6
6
 
7
7
  //#region src/exports/runtime.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/exports/runtime.ts"],"sourcesContent":[],"mappings":";;;;;;;UAqBiB,iBAAA,SACP,2CACN,QAAQ,aAAa,kBAAkB;AAF3C;;;;AACU,KAuBE,eAAA,GAvBF;EACN,SAAA,QAAA,EAsB+C,oBAtB/C;CAAO;AAsBX,cA+BM,gCA/B6C,EA+BX,2BA/B+B,CAAA,UAAA,EA+BS,iBA/BT,CAAA"}
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/exports/runtime.ts"],"sourcesContent":[],"mappings":";;;;;;;UAsBiB,iBAAA,SACP,2CACN,QAAQ,aAAa,kBAAkB;AAF3C;;;;AACU,KAuBE,eAAA,GAvBF;EACN,SAAA,QAAA,EAsB+C,oBAtB/C;CAAO;AAsBX,cA+BM,gCA/B6C,EA+BX,2BA/B+B,CAAA,UAAA,EA+BS,iBA/BT,CAAA"}
package/dist/runtime.mjs CHANGED
@@ -1,9 +1,10 @@
1
- import { t as createPostgresAdapter } from "./adapter-hNElNHo4.mjs";
2
- import { n as postgresQueryOperations, t as postgresAdapterDescriptorMeta } from "./descriptor-meta-RTDzyrae.mjs";
1
+ import { t as createPostgresAdapter } from "./adapter-cXPXgEG0.mjs";
2
+ import { n as postgresQueryOperations, t as postgresAdapterDescriptorMeta } from "./descriptor-meta-Dxnoq_rr.mjs";
3
3
  import { createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
4
4
  import { codecDefinitions } from "@prisma-next/target-postgres/codecs";
5
5
  import { PG_JSONB_CODEC_ID, PG_JSON_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
6
6
  import { builtinGeneratorIds } from "@prisma-next/ids";
7
+ import { extractCodecLookup } from "@prisma-next/framework-components/control";
7
8
  import { generateId } from "@prisma-next/ids/runtime";
8
9
  import { type } from "arktype";
9
10
  import Ajv from "ajv";
@@ -86,10 +87,14 @@ const postgresRuntimeAdapterDescriptor = {
86
87
  ...postgresAdapterDescriptorMeta,
87
88
  codecs: createPostgresCodecRegistry,
88
89
  parameterizedCodecs: () => parameterizedCodecDescriptors,
89
- queryOperations: () => postgresQueryOperations,
90
+ queryOperations: () => postgresQueryOperations(),
90
91
  mutationDefaultGenerators: createPostgresMutationDefaultGenerators,
91
- create(_stack) {
92
- return createPostgresAdapter();
92
+ create(stack) {
93
+ return createPostgresAdapter({ codecLookup: extractCodecLookup([
94
+ stack.target,
95
+ stack.adapter,
96
+ ...stack.extensionPacks
97
+ ]) });
93
98
  }
94
99
  };
95
100
  var runtime_default = postgresRuntimeAdapterDescriptor;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["sharedAjv: Ajv | undefined","arktype","postgresRuntimeAdapterDescriptor: SqlRuntimeAdapterDescriptor<'postgres', SqlRuntimeAdapter>"],"sources":["../src/core/json-schema-validator.ts","../src/exports/runtime.ts"],"sourcesContent":["import type {\n JsonSchemaValidateFn,\n JsonSchemaValidationError,\n JsonSchemaValidationResult,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport Ajv from 'ajv';\n\nexport type { JsonSchemaValidateFn, JsonSchemaValidationError, JsonSchemaValidationResult };\n\n/**\n * Shared Ajv instance for all JSON Schema validators.\n * Reusing a single instance avoids ~50-100KB memory overhead per compiled schema.\n */\nlet sharedAjv: Ajv | undefined;\n\nfunction getSharedAjv(): Ajv {\n if (!sharedAjv) {\n sharedAjv = new Ajv({ allErrors: false, strict: false });\n }\n return sharedAjv;\n}\n\n/**\n * Compiles a JSON Schema object into a reusable validate function using Ajv.\n *\n * The returned function validates a value against the schema and returns\n * a structured result with error details on failure.\n *\n * Uses a shared Ajv instance and fail-fast mode (`allErrors: false`)\n * to minimize memory and CPU overhead.\n *\n * @param schema - A JSON Schema object (draft-07 compatible)\n * @returns A validate function\n */\nexport function compileJsonSchemaValidator(schema: Record<string, unknown>): JsonSchemaValidateFn {\n const ajv = getSharedAjv();\n const validate = ajv.compile(schema);\n\n return (value: unknown): JsonSchemaValidationResult => {\n const valid = validate(value);\n if (valid) {\n return { valid: true };\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Ajv guarantees `errors` is populated whenever `validate(...)` returns false.\n const errors: JsonSchemaValidationError[] = validate.errors!.map((err) => ({\n path: err.instancePath || '/',\n message: err.message ?? 'unknown validation error',\n keyword: err.keyword,\n }));\n\n return { valid: false, errors };\n };\n}\n","import type { GeneratedValueSpec } from '@prisma-next/contract/types';\nimport type { RuntimeAdapterInstance } from '@prisma-next/framework-components/execution';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { Adapter, AnyQueryAst, CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type {\n RuntimeParameterizedCodecDescriptor,\n SqlRuntimeAdapterDescriptor,\n} from '@prisma-next/sql-runtime';\nimport { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\nimport { type as arktype } from 'arktype';\nimport { createPostgresAdapter } from '../core/adapter';\nimport { postgresAdapterDescriptorMeta, postgresQueryOperations } from '../core/descriptor-meta';\nimport {\n compileJsonSchemaValidator,\n type JsonSchemaValidateFn,\n} from '../core/json-schema-validator';\nimport type { PostgresContract, PostgresLoweredStatement } from '../core/types';\n\nexport interface SqlRuntimeAdapter\n extends RuntimeAdapterInstance<'sql', 'postgres'>,\n Adapter<AnyQueryAst, PostgresContract, PostgresLoweredStatement> {}\n\nfunction createPostgresCodecRegistry(): CodecRegistry {\n const registry = createCodecRegistry();\n for (const definition of Object.values(codecDefinitions)) {\n registry.register(definition.codec);\n }\n return registry;\n}\n\nconst jsonTypeParamsSchema = arktype({\n schemaJson: 'object',\n 'type?': 'string',\n});\n\n/** The inferred type params shape from the arktype schema. */\ntype JsonTypeParams = typeof jsonTypeParamsSchema.infer;\n\n/**\n * Helper returned by the JSON/JSONB `init` hook.\n * Contains a compiled JSON Schema validate function for runtime conformance checks.\n */\nexport type JsonCodecHelper = { readonly validate: JsonSchemaValidateFn };\n\nfunction createPostgresMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => {\n const spec: GeneratedValueSpec = params ? { id, params } : { id };\n return generateId(spec);\n },\n }));\n}\n\nfunction initJsonCodecHelper(params: JsonTypeParams): JsonCodecHelper {\n return { validate: compileJsonSchemaValidator(params.schemaJson as Record<string, unknown>) };\n}\n\nconst parameterizedCodecDescriptors = [\n {\n codecId: PG_JSON_CODEC_ID,\n paramsSchema: jsonTypeParamsSchema,\n init: initJsonCodecHelper,\n },\n {\n codecId: PG_JSONB_CODEC_ID,\n paramsSchema: jsonTypeParamsSchema,\n init: initJsonCodecHelper,\n },\n] as const satisfies ReadonlyArray<\n RuntimeParameterizedCodecDescriptor<JsonTypeParams, JsonCodecHelper>\n>;\n\nconst postgresRuntimeAdapterDescriptor: SqlRuntimeAdapterDescriptor<'postgres', SqlRuntimeAdapter> =\n {\n ...postgresAdapterDescriptorMeta,\n codecs: createPostgresCodecRegistry,\n parameterizedCodecs: () => parameterizedCodecDescriptors,\n queryOperations: () => postgresQueryOperations,\n mutationDefaultGenerators: createPostgresMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapter {\n return createPostgresAdapter();\n },\n };\n\nexport default postgresRuntimeAdapterDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;AAaA,IAAIA;AAEJ,SAAS,eAAoB;AAC3B,KAAI,CAAC,UACH,aAAY,IAAI,IAAI;EAAE,WAAW;EAAO,QAAQ;EAAO,CAAC;AAE1D,QAAO;;;;;;;;;;;;;;AAeT,SAAgB,2BAA2B,QAAuD;CAEhG,MAAM,WADM,cAAc,CACL,QAAQ,OAAO;AAEpC,SAAQ,UAA+C;AAErD,MADc,SAAS,MAAM,CAE3B,QAAO,EAAE,OAAO,MAAM;AAUxB,SAAO;GAAE,OAAO;GAAO,QANqB,SAAS,OAAQ,KAAK,SAAS;IACzE,MAAM,IAAI,gBAAgB;IAC1B,SAAS,IAAI,WAAW;IACxB,SAAS,IAAI;IACd,EAAE;GAE4B;;;;;;AC1BnC,SAAS,8BAA6C;CACpD,MAAM,WAAW,qBAAqB;AACtC,MAAK,MAAM,cAAc,OAAO,OAAO,iBAAiB,CACtD,UAAS,SAAS,WAAW,MAAM;AAErC,QAAO;;AAGT,MAAM,uBAAuBC,KAAQ;CACnC,YAAY;CACZ,SAAS;CACV,CAAC;AAWF,SAAS,0CAA0C;AACjD,QAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC;AAE9C,UAAO,WAD0B,SAAS;IAAE;IAAI;IAAQ,GAAG,EAAE,IAAI,CAC1C;;EAE1B,EAAE;;AAGL,SAAS,oBAAoB,QAAyC;AACpE,QAAO,EAAE,UAAU,2BAA2B,OAAO,WAAsC,EAAE;;AAG/F,MAAM,gCAAgC,CACpC;CACE,SAAS;CACT,cAAc;CACd,MAAM;CACP,EACD;CACE,SAAS;CACT,cAAc;CACd,MAAM;CACP,CACF;AAID,MAAMC,mCACJ;CACE,GAAG;CACH,QAAQ;CACR,2BAA2B;CAC3B,uBAAuB;CACvB,2BAA2B;CAC3B,OAAO,QAA2B;AAChC,SAAO,uBAAuB;;CAEjC;AAEH,sBAAe"}
1
+ {"version":3,"file":"runtime.mjs","names":["sharedAjv: Ajv | undefined","arktype","postgresRuntimeAdapterDescriptor: SqlRuntimeAdapterDescriptor<'postgres', SqlRuntimeAdapter>"],"sources":["../src/core/json-schema-validator.ts","../src/exports/runtime.ts"],"sourcesContent":["import type {\n JsonSchemaValidateFn,\n JsonSchemaValidationError,\n JsonSchemaValidationResult,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport Ajv from 'ajv';\n\nexport type { JsonSchemaValidateFn, JsonSchemaValidationError, JsonSchemaValidationResult };\n\n/**\n * Shared Ajv instance for all JSON Schema validators.\n * Reusing a single instance avoids ~50-100KB memory overhead per compiled schema.\n */\nlet sharedAjv: Ajv | undefined;\n\nfunction getSharedAjv(): Ajv {\n if (!sharedAjv) {\n sharedAjv = new Ajv({ allErrors: false, strict: false });\n }\n return sharedAjv;\n}\n\n/**\n * Compiles a JSON Schema object into a reusable validate function using Ajv.\n *\n * The returned function validates a value against the schema and returns\n * a structured result with error details on failure.\n *\n * Uses a shared Ajv instance and fail-fast mode (`allErrors: false`)\n * to minimize memory and CPU overhead.\n *\n * @param schema - A JSON Schema object (draft-07 compatible)\n * @returns A validate function\n */\nexport function compileJsonSchemaValidator(schema: Record<string, unknown>): JsonSchemaValidateFn {\n const ajv = getSharedAjv();\n const validate = ajv.compile(schema);\n\n return (value: unknown): JsonSchemaValidationResult => {\n const valid = validate(value);\n if (valid) {\n return { valid: true };\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Ajv guarantees `errors` is populated whenever `validate(...)` returns false.\n const errors: JsonSchemaValidationError[] = validate.errors!.map((err) => ({\n path: err.instancePath || '/',\n message: err.message ?? 'unknown validation error',\n keyword: err.keyword,\n }));\n\n return { valid: false, errors };\n };\n}\n","import type { GeneratedValueSpec } from '@prisma-next/contract/types';\nimport { extractCodecLookup } from '@prisma-next/framework-components/control';\nimport type { RuntimeAdapterInstance } from '@prisma-next/framework-components/execution';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { Adapter, AnyQueryAst, CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type {\n RuntimeParameterizedCodecDescriptor,\n SqlRuntimeAdapterDescriptor,\n} from '@prisma-next/sql-runtime';\nimport { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\nimport { type as arktype } from 'arktype';\nimport { createPostgresAdapter } from '../core/adapter';\nimport { postgresAdapterDescriptorMeta, postgresQueryOperations } from '../core/descriptor-meta';\nimport {\n compileJsonSchemaValidator,\n type JsonSchemaValidateFn,\n} from '../core/json-schema-validator';\nimport type { PostgresContract, PostgresLoweredStatement } from '../core/types';\n\nexport interface SqlRuntimeAdapter\n extends RuntimeAdapterInstance<'sql', 'postgres'>,\n Adapter<AnyQueryAst, PostgresContract, PostgresLoweredStatement> {}\n\nfunction createPostgresCodecRegistry(): CodecRegistry {\n const registry = createCodecRegistry();\n for (const definition of Object.values(codecDefinitions)) {\n registry.register(definition.codec);\n }\n return registry;\n}\n\nconst jsonTypeParamsSchema = arktype({\n schemaJson: 'object',\n 'type?': 'string',\n});\n\n/** The inferred type params shape from the arktype schema. */\ntype JsonTypeParams = typeof jsonTypeParamsSchema.infer;\n\n/**\n * Helper returned by the JSON/JSONB `init` hook.\n * Contains a compiled JSON Schema validate function for runtime conformance checks.\n */\nexport type JsonCodecHelper = { readonly validate: JsonSchemaValidateFn };\n\nfunction createPostgresMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => {\n const spec: GeneratedValueSpec = params ? { id, params } : { id };\n return generateId(spec);\n },\n }));\n}\n\nfunction initJsonCodecHelper(params: JsonTypeParams): JsonCodecHelper {\n return { validate: compileJsonSchemaValidator(params.schemaJson as Record<string, unknown>) };\n}\n\nconst parameterizedCodecDescriptors = [\n {\n codecId: PG_JSON_CODEC_ID,\n paramsSchema: jsonTypeParamsSchema,\n init: initJsonCodecHelper,\n },\n {\n codecId: PG_JSONB_CODEC_ID,\n paramsSchema: jsonTypeParamsSchema,\n init: initJsonCodecHelper,\n },\n] as const satisfies ReadonlyArray<\n RuntimeParameterizedCodecDescriptor<JsonTypeParams, JsonCodecHelper>\n>;\n\nconst postgresRuntimeAdapterDescriptor: SqlRuntimeAdapterDescriptor<'postgres', SqlRuntimeAdapter> =\n {\n ...postgresAdapterDescriptorMeta,\n codecs: createPostgresCodecRegistry,\n parameterizedCodecs: () => parameterizedCodecDescriptors,\n queryOperations: () => postgresQueryOperations(),\n mutationDefaultGenerators: createPostgresMutationDefaultGenerators,\n create(stack): SqlRuntimeAdapter {\n // The runtime `ExecutionStack` does not (yet) carry a pre-assembled\n // `codecLookup` field the way the control `ControlStack` does, so we\n // derive an equivalent lookup here from the stack's component metadata\n // (target + adapter + extension packs) using the same assembly helper\n // that `createControlStack` uses. This keeps the renderer fed with the\n // same codec set on both planes — including extension-contributed\n // codecs like `pg/vector@1` from `@prisma-next/extension-pgvector`.\n const codecLookup = extractCodecLookup([\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ]);\n return createPostgresAdapter({ codecLookup });\n },\n };\n\nexport default postgresRuntimeAdapterDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,IAAIA;AAEJ,SAAS,eAAoB;AAC3B,KAAI,CAAC,UACH,aAAY,IAAI,IAAI;EAAE,WAAW;EAAO,QAAQ;EAAO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JSON_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
2
+ import { codecDefinitions } from "@prisma-next/target-postgres/codecs";
3
3
  import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
4
4
 
5
- //#region src/core/sql-renderer.ts
6
- const VECTOR_CODEC_ID = "pg/vector@1";
5
+ //#region src/core/codec-lookup.ts
7
6
  /**
8
- * Map a codec ID to its `::cast` suffix, if Postgres requires one for
9
- * parameterized values (e.g. `$1::vector`, `$1::jsonb`).
7
+ * Build a {@link CodecLookup} populated with the Postgres-builtin codec
8
+ * definitions only.
9
+ *
10
+ * This is the default lookup used by `createPostgresAdapter()` and
11
+ * `new PostgresControlAdapter()` when called without a stack-derived lookup
12
+ * (e.g. from tests, or one-off scripts that don't compose a full stack).
10
13
  *
11
- * NOTE: hardcoded codec IDs here are a known wart, tracked separately by
12
- * TML-2310 ("Move SQL param-cast metadata onto codec descriptors").
13
- * Until that lands the cast lives on the renderer rather than the codec.
14
+ * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`)
15
+ * are intentionally NOT included here: a bare adapter cannot see extensions.
16
+ * Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` /
17
+ * `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader,
18
+ * extension-inclusive lookup at construction time.
14
19
  */
15
- function getCodecParamCast(codecId) {
16
- if (codecId === VECTOR_CODEC_ID) return "vector";
17
- if (codecId === PG_JSON_CODEC_ID) return "json";
18
- if (codecId === PG_JSONB_CODEC_ID) return "jsonb";
20
+ function createPostgresBuiltinCodecLookup() {
21
+ const byId = /* @__PURE__ */ new Map();
22
+ for (const definition of Object.values(codecDefinitions)) byId.set(definition.codec.id, definition.codec);
23
+ return { get: (id) => byId.get(id) };
19
24
  }
20
- function renderTypedParam(index, codecId) {
21
- const cast = getCodecParamCast(codecId);
22
- return cast ? `$${index}::${cast}` : `$${index}`;
25
+
26
+ //#endregion
27
+ //#region src/core/sql-renderer.ts
28
+ /**
29
+ * Postgres native types whose unknown-OID parameter inference is reliable in
30
+ * arbitrary expression positions. Parameters bound to a codec whose
31
+ * `meta.db.sql.postgres.nativeType` falls in this set are emitted as plain
32
+ * `$N`; everything else (including `json`, `jsonb`, extension types like
33
+ * `vector`, and unknown user types) is emitted as `$N::<nativeType>` so the
34
+ * planner picks an unambiguous overload.
35
+ *
36
+ * `json` / `jsonb` are intentionally excluded despite being Postgres builtins:
37
+ * their operator overloads make context inference unreliable in expression
38
+ * positions (e.g. `$1 -> 'key'` is ambiguous between the two).
39
+ *
40
+ * Spellings match the on-disk `meta.db.sql.postgres.nativeType` values in
41
+ * `@prisma-next/target-postgres`'s codec definitions, not the `udt_name`
42
+ * abbreviations that ADR 205 used as illustrative shorthand. The lookup-based
43
+ * cast policy compares against these strings directly.
44
+ */
45
+ const POSTGRES_INFERRABLE_NATIVE_TYPES = new Set([
46
+ "integer",
47
+ "smallint",
48
+ "bigint",
49
+ "real",
50
+ "double precision",
51
+ "numeric",
52
+ "boolean",
53
+ "text",
54
+ "character",
55
+ "character varying",
56
+ "timestamp",
57
+ "timestamp without time zone",
58
+ "timestamp with time zone",
59
+ "time",
60
+ "timetz",
61
+ "interval",
62
+ "bit",
63
+ "bit varying"
64
+ ]);
65
+ function renderTypedParam(index, codecId, codecLookup) {
66
+ if (codecId === void 0) return `$${index}`;
67
+ const codec = codecLookup.get(codecId);
68
+ if (codec === 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.`);
69
+ const nativeType = codec.meta?.db?.sql?.postgres?.nativeType;
70
+ if (nativeType !== void 0 && !POSTGRES_INFERRABLE_NATIVE_TYPES.has(nativeType)) return `$${index}::${nativeType}`;
71
+ return `$${index}`;
23
72
  }
24
73
  /**
25
74
  * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.
@@ -28,29 +77,33 @@ function renderTypedParam(index, codecId) {
28
77
  * (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time
29
78
  * paths produce byte-identical output for the same AST.
30
79
  */
31
- function renderLoweredSql(ast, contract) {
80
+ function renderLoweredSql(ast, contract, codecLookup) {
32
81
  const collectedParamRefs = ast.collectParamRefs();
33
- const paramIndexMap = /* @__PURE__ */ new Map();
82
+ const indexMap = /* @__PURE__ */ new Map();
34
83
  const params = [];
35
84
  for (const ref of collectedParamRefs) {
36
- if (paramIndexMap.has(ref)) continue;
37
- paramIndexMap.set(ref, params.length + 1);
85
+ if (indexMap.has(ref)) continue;
86
+ indexMap.set(ref, params.length + 1);
38
87
  params.push(ref.value);
39
88
  }
89
+ const pim = {
90
+ indexMap,
91
+ codecLookup
92
+ };
40
93
  const node = ast;
41
94
  let sql;
42
95
  switch (node.kind) {
43
96
  case "select":
44
- sql = renderSelect(node, contract, paramIndexMap);
97
+ sql = renderSelect(node, contract, pim);
45
98
  break;
46
99
  case "insert":
47
- sql = renderInsert(node, contract, paramIndexMap);
100
+ sql = renderInsert(node, contract, pim);
48
101
  break;
49
102
  case "update":
50
- sql = renderUpdate(node, contract, paramIndexMap);
103
+ sql = renderUpdate(node, contract, pim);
51
104
  break;
52
105
  case "delete":
53
- sql = renderDelete(node, contract, paramIndexMap);
106
+ sql = renderDelete(node, contract, pim);
54
107
  break;
55
108
  default: throw new Error(`Unsupported AST node kind: ${node.kind}`);
56
109
  }
@@ -243,9 +296,9 @@ function renderExpr(expr, contract, pim) {
243
296
  }
244
297
  }
245
298
  function renderParamRef(ref, pim) {
246
- const index = pim.get(ref);
299
+ const index = pim.indexMap.get(ref);
247
300
  if (index === void 0) throw new Error("ParamRef not found in index map");
248
- return renderTypedParam(index, ref.codecId);
301
+ return renderTypedParam(index, ref.codecId, pim.codecLookup);
249
302
  }
250
303
  function renderLiteral(expr) {
251
304
  if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
@@ -366,5 +419,5 @@ function renderDelete(ast, contract, pim) {
366
419
  }
367
420
 
368
421
  //#endregion
369
- export { renderLoweredSql as t };
370
- //# sourceMappingURL=sql-renderer-pEaSP82_.mjs.map
422
+ export { createPostgresBuiltinCodecLookup as n, renderLoweredSql as t };
423
+ //# sourceMappingURL=sql-renderer-Dd_Y8oK_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-renderer-Dd_Y8oK_.mjs","names":["POSTGRES_INFERRABLE_NATIVE_TYPES: ReadonlySet<string>","params: unknown[]","pim: ParamIndexMap","sql: string","right: string","orderedColumns: string[]","value: string"],"sources":["../src/core/codec-lookup.ts","../src/core/sql-renderer.ts"],"sourcesContent":["import type { Codec, CodecLookup } from '@prisma-next/framework-components/codec';\nimport { codecDefinitions } from '@prisma-next/target-postgres/codecs';\n\n/**\n * Build a {@link CodecLookup} populated with the Postgres-builtin codec\n * definitions only.\n *\n * This is the default lookup used by `createPostgresAdapter()` and\n * `new PostgresControlAdapter()` when called without a stack-derived lookup\n * (e.g. from tests, or one-off scripts that don't compose a full stack).\n *\n * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`)\n * are intentionally NOT included here: a bare adapter cannot see extensions.\n * Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` /\n * `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader,\n * extension-inclusive lookup at construction time.\n */\nexport function createPostgresBuiltinCodecLookup(): CodecLookup {\n const byId = new Map<string, Codec>();\n for (const definition of Object.values(codecDefinitions)) {\n byId.set(definition.codec.id, definition.codec);\n }\n return { get: (id) => byId.get(id) };\n}\n","import type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport {\n type AggregateExpr,\n type AnyExpression,\n type AnyFromSource,\n type AnyQueryAst,\n type BinaryExpr,\n type ColumnRef,\n type DeleteAst,\n type InsertAst,\n type InsertValue,\n type JoinAst,\n type JoinOnExpr,\n type JsonArrayAggExpr,\n type JsonObjectExpr,\n type ListExpression,\n LiteralExpr,\n type NullCheckExpr,\n type OperationExpr,\n type OrderByItem,\n type ParamRef,\n type ProjectionItem,\n type SelectAst,\n type Codec as SqlCodec,\n type SubqueryExpr,\n type UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { escapeLiteral, quoteIdentifier } from '@prisma-next/target-postgres/sql-utils';\nimport type { PostgresContract } from './types';\n\n/**\n * Postgres native types whose unknown-OID parameter inference is reliable in\n * arbitrary expression positions. Parameters bound to a codec whose\n * `meta.db.sql.postgres.nativeType` falls in this set are emitted as plain\n * `$N`; everything else (including `json`, `jsonb`, extension types like\n * `vector`, and unknown user types) is emitted as `$N::<nativeType>` so the\n * planner picks an unambiguous overload.\n *\n * `json` / `jsonb` are intentionally excluded despite being Postgres builtins:\n * their operator overloads make context inference unreliable in expression\n * positions (e.g. `$1 -> 'key'` is ambiguous between the two).\n *\n * Spellings match the on-disk `meta.db.sql.postgres.nativeType` values in\n * `@prisma-next/target-postgres`'s codec definitions, not the `udt_name`\n * abbreviations that ADR 205 used as illustrative shorthand. The lookup-based\n * cast policy compares against these strings directly.\n */\nconst POSTGRES_INFERRABLE_NATIVE_TYPES: ReadonlySet<string> = new Set([\n // Numeric\n 'integer',\n 'smallint',\n 'bigint',\n 'real',\n 'double precision',\n 'numeric',\n // Boolean\n 'boolean',\n // Strings\n 'text',\n 'character',\n 'character varying',\n // Temporal\n 'timestamp',\n 'timestamp without time zone',\n 'timestamp with time zone',\n 'time',\n 'timetz',\n 'interval',\n // Bit strings\n 'bit',\n 'bit varying',\n]);\n\nfunction renderTypedParam(\n index: number,\n codecId: string | undefined,\n codecLookup: CodecLookup,\n): string {\n if (codecId === undefined) {\n return `$${index}`;\n }\n // SQL codecs extend the framework `Codec` base with an optional\n // `meta: CodecMeta`; the framework `CodecLookup.get` returns the base type,\n // so we narrow to `SqlCodec` to read `meta`. Every codec actually\n // registered into a SQL codec lookup conforms to `SqlCodec`.\n const codec = codecLookup.get(codecId) as SqlCodec | undefined;\n if (codec === undefined) {\n throw new Error(\n `Postgres lowering: ParamRef carries codecId \"${codecId}\" but the ` +\n 'assembled codec lookup has no entry for it. This usually indicates ' +\n 'a missing extension pack in the runtime stack — register the pack ' +\n 'that contributes this codec (e.g. `extensionPacks: [pgvectorRuntime]`), ' +\n 'or use the codec directly from `@prisma-next/target-postgres/codecs` ' +\n \"if it's a builtin.\",\n );\n }\n const nativeType = codec.meta?.db?.sql?.postgres?.nativeType;\n if (nativeType !== undefined && !POSTGRES_INFERRABLE_NATIVE_TYPES.has(nativeType)) {\n return `$${index}::${nativeType}`;\n }\n return `$${index}`;\n}\n\n/**\n * Per-render carrier threaded through every helper. Bundles the param-index\n * map (for `$N` numbering) and the assembled-stack `codecLookup` (for\n * cast policy at the `renderTypedParam` chokepoint). Carrying both on a\n * single value keeps helper signatures stable.\n */\ninterface ParamIndexMap {\n readonly indexMap: Map<ParamRef, number>;\n readonly codecLookup: CodecLookup;\n}\n\n/**\n * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.\n *\n * Shared between the runtime (`PostgresAdapterImpl.lower`) and control\n * (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time\n * paths produce byte-identical output for the same AST.\n */\nexport function renderLoweredSql(\n ast: AnyQueryAst,\n contract: PostgresContract,\n codecLookup: CodecLookup,\n): { readonly sql: string; readonly params: readonly unknown[] } {\n const collectedParamRefs = ast.collectParamRefs();\n const indexMap = new Map<ParamRef, number>();\n const params: unknown[] = [];\n for (const ref of collectedParamRefs) {\n if (indexMap.has(ref)) {\n continue;\n }\n indexMap.set(ref, params.length + 1);\n params.push(ref.value);\n }\n const pim: ParamIndexMap = { indexMap, codecLookup };\n\n const node = ast;\n let sql: string;\n switch (node.kind) {\n case 'select':\n sql = renderSelect(node, contract, pim);\n break;\n case 'insert':\n sql = renderInsert(node, contract, pim);\n break;\n case 'update':\n sql = renderUpdate(node, contract, pim);\n break;\n case 'delete':\n sql = renderDelete(node, contract, pim);\n break;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported AST node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n\n return Object.freeze({ sql, params: Object.freeze(params) });\n}\n\nfunction renderSelect(ast: SelectAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const selectClause = `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(\n ast.projection,\n contract,\n pim,\n )}`;\n const fromClause = `FROM ${renderSource(ast.from, contract, pim)}`;\n\n const joinsClause = ast.joins?.length\n ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(' ')\n : '';\n\n const whereClause = ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const groupByClause = ast.groupBy?.length\n ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(', ')}`\n : '';\n const havingClause = ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : '';\n const orderClause = ast.orderBy?.length\n ? `ORDER BY ${ast.orderBy\n .map((order) => {\n const expr = renderExpr(order.expr, contract, pim);\n return `${expr} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n const limitClause = typeof ast.limit === 'number' ? `LIMIT ${ast.limit}` : '';\n const offsetClause = typeof ast.offset === 'number' ? `OFFSET ${ast.offset}` : '';\n\n const clauses = [\n selectClause,\n fromClause,\n joinsClause,\n whereClause,\n groupByClause,\n havingClause,\n orderClause,\n limitClause,\n offsetClause,\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n return clauses.trim();\n}\n\nfunction renderProjection(\n projection: ReadonlyArray<ProjectionItem>,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n return projection\n .map((item) => {\n const alias = quoteIdentifier(item.alias);\n if (item.expr.kind === 'literal') {\n return `${renderLiteral(item.expr)} AS ${alias}`;\n }\n return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;\n })\n .join(', ');\n}\n\nfunction renderDistinctPrefix(\n distinct: true | undefined,\n distinctOn: ReadonlyArray<AnyExpression> | undefined,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n if (distinctOn && distinctOn.length > 0) {\n const rendered = distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(', ');\n return `DISTINCT ON (${rendered}) `;\n }\n if (distinct) {\n return 'DISTINCT ';\n }\n return '';\n}\n\nfunction renderSource(\n source: AnyFromSource,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const node = source;\n switch (node.kind) {\n case 'table-source': {\n const table = quoteIdentifier(node.name);\n if (!node.alias) {\n return table;\n }\n return `${table} AS ${quoteIdentifier(node.alias)}`;\n }\n case 'derived-table-source':\n return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction assertScalarSubquery(query: SelectAst): void {\n if (query.projection.length !== 1) {\n throw new Error('Subquery expressions must project exactly one column');\n }\n}\n\nfunction renderSubqueryExpr(\n expr: SubqueryExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n assertScalarSubquery(expr.query);\n return `(${renderSelect(expr.query, contract, pim)})`;\n}\n\nfunction renderWhere(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {\n return renderExpr(expr, contract, pim);\n}\n\nfunction renderNullCheck(\n expr: NullCheckExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const rendered = renderExpr(expr.expr, contract, pim);\n const renderedExpr = isAtomicExpressionKind(expr.expr.kind) ? rendered : `(${rendered})`;\n return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;\n}\n\n/**\n * Atomic expression kinds whose rendered SQL is already self-delimited\n * (a column reference, parameter, literal, function call, aggregate, etc.)\n * and therefore does not need surrounding parentheses when used as the\n * left operand of a postfix predicate like `IS NULL` or `IS NOT NULL`,\n * or as either operand of a binary infix operator.\n *\n * Anything not in this set is treated as composite (binary, AND/OR/NOT,\n * EXISTS, nested IS NULL, subqueries, operation templates) and gets\n * wrapped to preserve grouping.\n */\nfunction isAtomicExpressionKind(kind: AnyExpression['kind']): boolean {\n switch (kind) {\n case 'column-ref':\n case 'identifier-ref':\n case 'param-ref':\n case 'literal':\n case 'aggregate':\n case 'json-object':\n case 'json-array-agg':\n case 'list':\n return true;\n case 'subquery':\n case 'operation':\n case 'binary':\n case 'and':\n case 'or':\n case 'exists':\n case 'null-check':\n case 'not':\n return false;\n }\n}\n\nfunction renderBinary(expr: BinaryExpr, contract: PostgresContract, pim: ParamIndexMap): string {\n if (expr.right.kind === 'list' && expr.right.values.length === 0) {\n if (expr.op === 'in') {\n return 'FALSE';\n }\n if (expr.op === 'notIn') {\n return 'TRUE';\n }\n }\n\n const leftExpr = expr.left;\n const left = renderExpr(leftExpr, contract, pim);\n const leftRendered =\n leftExpr.kind === 'operation' || leftExpr.kind === 'subquery' ? `(${left})` : left;\n\n const rightNode = expr.right;\n let right: string;\n switch (rightNode.kind) {\n case 'list':\n right = renderListLiteral(rightNode, contract, pim);\n break;\n case 'literal':\n right = renderLiteral(rightNode);\n break;\n case 'column-ref':\n right = renderColumn(rightNode);\n break;\n case 'param-ref':\n right = renderParamRef(rightNode, pim);\n break;\n default:\n right = renderExpr(rightNode, contract, pim);\n break;\n }\n\n const operatorMap: Record<BinaryExpr['op'], string> = {\n eq: '=',\n neq: '!=',\n gt: '>',\n lt: '<',\n gte: '>=',\n lte: '<=',\n like: 'LIKE',\n in: 'IN',\n notIn: 'NOT IN',\n };\n\n return `${leftRendered} ${operatorMap[expr.op]} ${right}`;\n}\n\nfunction renderListLiteral(\n expr: ListExpression,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n if (expr.values.length === 0) {\n return '(NULL)';\n }\n const values = expr.values\n .map((v) => {\n if (v.kind === 'param-ref') return renderParamRef(v, pim);\n if (v.kind === 'literal') return renderLiteral(v);\n return renderExpr(v, contract, pim);\n })\n .join(', ');\n return `(${values})`;\n}\n\nfunction renderColumn(ref: ColumnRef): string {\n if (ref.table === 'excluded') {\n return `excluded.${quoteIdentifier(ref.column)}`;\n }\n return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\n\nfunction renderAggregateExpr(\n expr: AggregateExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const fn = expr.fn.toUpperCase();\n if (!expr.expr) {\n return `${fn}(*)`;\n }\n return `${fn}(${renderExpr(expr.expr, contract, pim)})`;\n}\n\nfunction renderJsonObjectExpr(\n expr: JsonObjectExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const args = expr.entries\n .flatMap((entry): [string, string] => {\n const key = `'${escapeLiteral(entry.key)}'`;\n if (entry.value.kind === 'literal') {\n return [key, renderLiteral(entry.value)];\n }\n return [key, renderExpr(entry.value, contract, pim)];\n })\n .join(', ');\n return `json_build_object(${args})`;\n}\n\nfunction renderOrderByItems(\n items: ReadonlyArray<OrderByItem>,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n return items\n .map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`)\n .join(', ');\n}\n\nfunction renderJsonArrayAggExpr(\n expr: JsonArrayAggExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const aggregateOrderBy =\n expr.orderBy && expr.orderBy.length > 0\n ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}`\n : '';\n const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;\n if (expr.onEmpty === 'emptyArray') {\n return `coalesce(${aggregated}, json_build_array())`;\n }\n return aggregated;\n}\n\nfunction renderExpr(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {\n const node = expr;\n switch (node.kind) {\n case 'column-ref':\n return renderColumn(node);\n case 'identifier-ref':\n return quoteIdentifier(node.name);\n case 'operation':\n return renderOperation(node, contract, pim);\n case 'subquery':\n return renderSubqueryExpr(node, contract, pim);\n case 'aggregate':\n return renderAggregateExpr(node, contract, pim);\n case 'json-object':\n return renderJsonObjectExpr(node, contract, pim);\n case 'json-array-agg':\n return renderJsonArrayAggExpr(node, contract, pim);\n case 'binary':\n return renderBinary(node, contract, pim);\n case 'and':\n if (node.exprs.length === 0) {\n return 'TRUE';\n }\n return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' AND ')})`;\n case 'or':\n if (node.exprs.length === 0) {\n return 'FALSE';\n }\n return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' OR ')})`;\n case 'exists': {\n const notKeyword = node.notExists ? 'NOT ' : '';\n const subquery = renderSelect(node.subquery, contract, pim);\n return `${notKeyword}EXISTS (${subquery})`;\n }\n case 'null-check':\n return renderNullCheck(node, contract, pim);\n case 'not':\n return `NOT (${renderExpr(node.expr, contract, pim)})`;\n case 'param-ref':\n return renderParamRef(node, pim);\n case 'literal':\n return renderLiteral(node);\n case 'list':\n return renderListLiteral(node, contract, pim);\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported expression node kind: ${(node satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction renderParamRef(ref: ParamRef, pim: ParamIndexMap): string {\n const index = pim.indexMap.get(ref);\n if (index === undefined) {\n throw new Error('ParamRef not found in index map');\n }\n return renderTypedParam(index, ref.codecId, pim.codecLookup);\n}\n\nfunction renderLiteral(expr: LiteralExpr): string {\n if (typeof expr.value === 'string') {\n return `'${escapeLiteral(expr.value)}'`;\n }\n if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {\n return String(expr.value);\n }\n if (typeof expr.value === 'bigint') {\n return String(expr.value);\n }\n if (expr.value === null) {\n return 'NULL';\n }\n if (expr.value === undefined) {\n return 'NULL';\n }\n if (expr.value instanceof Date) {\n return `'${escapeLiteral(expr.value.toISOString())}'`;\n }\n if (Array.isArray(expr.value)) {\n return `ARRAY[${expr.value.map((v: unknown) => renderLiteral(new LiteralExpr(v))).join(', ')}]`;\n }\n const json = JSON.stringify(expr.value);\n if (json === undefined) {\n return 'NULL';\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nfunction renderOperation(\n expr: OperationExpr,\n contract: PostgresContract,\n pim: ParamIndexMap,\n): string {\n const self = renderExpr(expr.self, contract, pim);\n const args = expr.args.map((arg) => {\n return renderExpr(arg, contract, pim);\n });\n\n // Resolve `{{self}}` and `{{argN}}` from the original template in a single\n // pass. Doing this with sequential `String.prototype.replace` calls is\n // unsafe: a substituted fragment can itself contain text that matches a\n // later token (e.g. an arg literal containing the substring `{{arg1}}`),\n // and the next iteration would corrupt it. A single regex callback never\n // re-scans already-substituted output.\n return expr.lowering.template.replace(\n /\\{\\{self\\}\\}|\\{\\{arg(\\d+)\\}\\}/g,\n (token, argIndex: string | undefined) => {\n if (token === '{{self}}') {\n return self;\n }\n const arg = args[Number(argIndex)];\n if (arg === undefined) {\n throw new Error(\n `Operation lowering template for \"${expr.method}\" referenced missing argument {{arg${argIndex}}}; template has ${args.length} arg(s)`,\n );\n }\n return arg;\n },\n );\n}\n\nfunction renderJoin(join: JoinAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const joinType = join.joinType.toUpperCase();\n const lateral = join.lateral ? 'LATERAL ' : '';\n const source = renderSource(join.source, contract, pim);\n const onClause = renderJoinOn(join.on, contract, pim);\n return `${joinType} JOIN ${lateral}${source} ON ${onClause}`;\n}\n\nfunction renderJoinOn(on: JoinOnExpr, contract: PostgresContract, pim: ParamIndexMap): string {\n if (on.kind === 'eq-col-join-on') {\n const left = renderColumn(on.left);\n const right = renderColumn(on.right);\n return `${left} = ${right}`;\n }\n return renderWhere(on, contract, pim);\n}\n\nfunction getInsertColumnOrder(\n rows: ReadonlyArray<Record<string, InsertValue>>,\n contract: PostgresContract,\n tableName: string,\n): string[] {\n const orderedColumns: string[] = [];\n const seenColumns = new Set<string>();\n\n for (const row of rows) {\n for (const column of Object.keys(row)) {\n if (seenColumns.has(column)) {\n continue;\n }\n seenColumns.add(column);\n orderedColumns.push(column);\n }\n }\n\n if (orderedColumns.length > 0) {\n return orderedColumns;\n }\n\n const table = contract.storage.tables[tableName];\n if (!table) {\n throw new Error(`INSERT target table not found in contract storage: ${tableName}`);\n }\n return Object.keys(table.columns);\n}\n\nfunction renderInsertValue(value: InsertValue | undefined, pim: ParamIndexMap): string {\n if (!value || value.kind === 'default-value') {\n return 'DEFAULT';\n }\n\n switch (value.kind) {\n case 'param-ref':\n return renderParamRef(value, pim);\n case 'column-ref':\n return renderColumn(value);\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported value node in INSERT: ${(value satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction renderInsert(ast: InsertAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const rows = ast.rows;\n if (rows.length === 0) {\n throw new Error('INSERT requires at least one row');\n }\n const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);\n const insertClause = (() => {\n if (!hasExplicitValues) {\n if (rows.length === 1) {\n return `INSERT INTO ${table} DEFAULT VALUES`;\n }\n\n const defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);\n if (defaultColumns.length === 0) {\n return `INSERT INTO ${table} VALUES ${rows.map(() => '()').join(', ')}`;\n }\n\n const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));\n const defaultRow = `(${defaultColumns.map(() => 'DEFAULT').join(', ')})`;\n return `INSERT INTO ${table} (${quotedColumns.join(', ')}) VALUES ${rows\n .map(() => defaultRow)\n .join(', ')}`;\n }\n\n const columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);\n const columns = columnOrder.map((column) => quoteIdentifier(column));\n const values = rows\n .map((row) => {\n const renderedRow = columnOrder.map((column) => renderInsertValue(row[column], pim));\n return `(${renderedRow.join(', ')})`;\n })\n .join(', ');\n\n return `INSERT INTO ${table} (${columns.join(', ')}) VALUES ${values}`;\n })();\n const onConflictClause = ast.onConflict\n ? (() => {\n const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));\n if (conflictColumns.length === 0) {\n throw new Error('INSERT onConflict requires at least one conflict column');\n }\n\n const action = ast.onConflict.action;\n switch (action.kind) {\n case 'do-nothing':\n return ` ON CONFLICT (${conflictColumns.join(', ')}) DO NOTHING`;\n case 'do-update-set': {\n const updateEntries = Object.entries(action.set);\n if (updateEntries.length === 0) {\n throw new Error('INSERT onConflict do-update-set requires at least one assignment');\n }\n const updates = updateEntries.map(([colName, value]) => {\n const target = quoteIdentifier(colName);\n if (value.kind === 'param-ref') {\n return `${target} = ${renderParamRef(value, pim)}`;\n }\n return `${target} = ${renderColumn(value)}`;\n });\n return ` ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${updates.join(', ')}`;\n }\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported onConflict action: ${(action satisfies never as { kind: string }).kind}`,\n );\n }\n })()\n : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `${insertClause}${onConflictClause}${returningClause}`;\n}\n\nfunction renderUpdate(ast: UpdateAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const setEntries = Object.entries(ast.set);\n if (setEntries.length === 0) {\n throw new Error('UPDATE requires at least one SET assignment');\n }\n const setClauses = setEntries.map(([col, val]) => {\n const column = quoteIdentifier(col);\n let value: string;\n switch (val.kind) {\n case 'param-ref':\n value = renderParamRef(val, pim);\n break;\n case 'column-ref':\n value = renderColumn(val);\n break;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported value node in UPDATE: ${(val satisfies never as { kind: string }).kind}`,\n );\n }\n return `${column} = ${value}`;\n });\n\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;\n}\n\nfunction renderDelete(ast: DeleteAst, contract: PostgresContract, pim: ParamIndexMap): string {\n const table = quoteIdentifier(ast.table.name);\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `DELETE FROM ${table}${whereClause}${returningClause}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,mCAAgD;CAC9D,MAAM,uBAAO,IAAI,KAAoB;AACrC,MAAK,MAAM,cAAc,OAAO,OAAO,iBAAiB,CACtD,MAAK,IAAI,WAAW,MAAM,IAAI,WAAW,MAAM;AAEjD,QAAO,EAAE,MAAM,OAAO,KAAK,IAAI,GAAG,EAAE;;;;;;;;;;;;;;;;;;;;;;ACyBtC,MAAMA,mCAAwD,IAAI,IAAI;CAEpE;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACD,CAAC;AAEF,SAAS,iBACP,OACA,SACA,aACQ;AACR,KAAI,YAAY,OACd,QAAO,IAAI;CAMb,MAAM,QAAQ,YAAY,IAAI,QAAQ;AACtC,KAAI,UAAU,OACZ,OAAM,IAAI,MACR,gDAAgD,QAAQ,oTAMzD;CAEH,MAAM,aAAa,MAAM,MAAM,IAAI,KAAK,UAAU;AAClD,KAAI,eAAe,UAAa,CAAC,iCAAiC,IAAI,WAAW,CAC/E,QAAO,IAAI,MAAM,IAAI;AAEvB,QAAO,IAAI;;;;;;;;;AAqBb,SAAgB,iBACd,KACA,UACA,aAC+D;CAC/D,MAAM,qBAAqB,IAAI,kBAAkB;CACjD,MAAM,2BAAW,IAAI,KAAuB;CAC5C,MAAMC,SAAoB,EAAE;AAC5B,MAAK,MAAM,OAAO,oBAAoB;AACpC,MAA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AAI,MAAM,CAAC,GAAG,gBAAgB,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,KACnH;AAEJ,QAAO,UAAU,MAAM,OAAO,WAAW,KAAK,KAAK,GAAG,cAAc;;AAGtE,SAAS,aAAa,KAAgB,UAA4B,KAA4B;AAO5F,QAAO,eANO,gBAAgB,IAAI,MAAM,KAAK,GACzB,IAAI,QAAQ,UAAU,YAAY,IAAI,OAAO,UAAU,IAAI,KAAK,KAC5D,IAAI,WAAW,SACnC,cAAc,IAAI,UAAU,KAAK,QAAQ,GAAG,gBAAgB,IAAI,MAAM,CAAC,GAAG,gBAAgB,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,KACnH"}
@@ -1,10 +1,21 @@
1
1
  import { BinaryExpr, ColumnRef, DefaultValueExpr, Direction, LoweredStatement, ParamRef, SelectAst } from "@prisma-next/sql-relational-core/ast";
2
2
  import { Contract } from "@prisma-next/contract/types";
3
+ import { CodecLookup } from "@prisma-next/framework-components/codec";
3
4
  import { SqlStorage, StorageColumn, StorageTable } from "@prisma-next/sql-contract/types";
4
5
 
5
6
  //#region src/core/types.d.ts
6
7
  interface PostgresAdapterOptions {
7
8
  readonly profileId?: string;
9
+ /**
10
+ * Codec lookup used by the SQL renderer to resolve per-codec metadata at
11
+ * lower-time. Defaults to a Postgres-builtins-only lookup when omitted —
12
+ * see {@link createPostgresBuiltinCodecLookup} in `./codec-lookup`.
13
+ *
14
+ * Stack-aware callers (`SqlRuntimeAdapterDescriptor.create(stack)` /
15
+ * `SqlControlAdapterDescriptor.create(stack)`) supply the assembled stack
16
+ * lookup so extension codecs are visible to the renderer.
17
+ */
18
+ readonly codecLookup?: CodecLookup;
8
19
  }
9
20
  type PostgresContract = Contract<SqlStorage> & {
10
21
  readonly target: 'postgres';
@@ -17,4 +28,4 @@ interface OrderClause {
17
28
  type PostgresLoweredStatement = LoweredStatement;
18
29
  //#endregion
19
30
  export { OrderClause as a, PostgresContract as c, StorageColumn as d, StorageTable as f, Expr as i, PostgresLoweredStatement as l, ColumnRef as n, ParamRef as o, Direction as r, PostgresAdapterOptions as s, BinaryExpr as t, SelectAst as u };
20
- //# sourceMappingURL=types-CfRPdAk8.d.mts.map
31
+ //# sourceMappingURL=types-tLtmYqCO.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-tLtmYqCO.d.mts","names":[],"sources":["../src/core/types.ts"],"sourcesContent":[],"mappings":";;;;;;UAoBiB,sBAAA;;EAAA;AAcjB;AAEA;;;;;AAEA;AAKA;yBAZyB;;KAGb,gBAAA,GAAmB,SAAS;;;KAE5B,IAAA,GAAO,YAAY,WAAW;UAEzB,WAAA;iBACA;gBACD;;KAGJ,wBAAA,GAA2B"}
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as OrderClause, c as PostgresContract, d as StorageColumn, f as StorageTable, i as Expr, l as PostgresLoweredStatement, n as ColumnRef, o as ParamRef, r as Direction, s as PostgresAdapterOptions, t as BinaryExpr, u as SelectAst } from "./types-CfRPdAk8.mjs";
1
+ import { a as OrderClause, c as PostgresContract, d as StorageColumn, f as StorageTable, i as Expr, l as PostgresLoweredStatement, n as ColumnRef, o as ParamRef, r as Direction, s as PostgresAdapterOptions, t as BinaryExpr, u as SelectAst } from "./types-tLtmYqCO.mjs";
2
2
  export { type BinaryExpr, type ColumnRef, type Direction, type Expr, type OrderClause, type ParamRef, type PostgresAdapterOptions, type PostgresContract, type PostgresLoweredStatement, type SelectAst, type StorageColumn, type StorageTable };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma-next/adapter-postgres",
3
- "version": "0.5.0-dev.2",
3
+ "version": "0.5.0-dev.21",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -10,33 +10,33 @@
10
10
  "dependencies": {
11
11
  "ajv": "^8.18.0",
12
12
  "arktype": "^2.0.0",
13
- "@prisma-next/contract": "0.5.0-dev.2",
14
- "@prisma-next/contract-authoring": "0.5.0-dev.2",
15
- "@prisma-next/framework-components": "0.5.0-dev.2",
16
- "@prisma-next/family-sql": "0.5.0-dev.2",
17
- "@prisma-next/ids": "0.5.0-dev.2",
18
- "@prisma-next/sql-contract": "0.5.0-dev.2",
19
- "@prisma-next/sql-contract-psl": "0.5.0-dev.2",
20
- "@prisma-next/sql-contract-ts": "0.5.0-dev.2",
21
- "@prisma-next/sql-operations": "0.5.0-dev.2",
22
- "@prisma-next/sql-relational-core": "0.5.0-dev.2",
23
- "@prisma-next/sql-runtime": "0.5.0-dev.2",
24
- "@prisma-next/sql-schema-ir": "0.5.0-dev.2",
25
- "@prisma-next/utils": "0.5.0-dev.2",
26
- "@prisma-next/target-postgres": "0.5.0-dev.2"
13
+ "@prisma-next/contract": "0.5.0-dev.21",
14
+ "@prisma-next/family-sql": "0.5.0-dev.21",
15
+ "@prisma-next/framework-components": "0.5.0-dev.21",
16
+ "@prisma-next/ids": "0.5.0-dev.21",
17
+ "@prisma-next/contract-authoring": "0.5.0-dev.21",
18
+ "@prisma-next/sql-contract-psl": "0.5.0-dev.21",
19
+ "@prisma-next/sql-contract-ts": "0.5.0-dev.21",
20
+ "@prisma-next/sql-operations": "0.5.0-dev.21",
21
+ "@prisma-next/sql-relational-core": "0.5.0-dev.21",
22
+ "@prisma-next/sql-runtime": "0.5.0-dev.21",
23
+ "@prisma-next/sql-contract": "0.5.0-dev.21",
24
+ "@prisma-next/sql-schema-ir": "0.5.0-dev.21",
25
+ "@prisma-next/target-postgres": "0.5.0-dev.21",
26
+ "@prisma-next/utils": "0.5.0-dev.21"
27
27
  },
28
28
  "devDependencies": {
29
29
  "pathe": "^2.0.3",
30
30
  "tsdown": "0.18.4",
31
31
  "typescript": "5.9.3",
32
32
  "vitest": "4.0.17",
33
- "@prisma-next/cli": "0.5.0-dev.2",
34
- "@prisma-next/driver-postgres": "0.5.0-dev.2",
35
- "@prisma-next/errors": "0.5.0-dev.2",
36
- "@prisma-next/extension-pgvector": "0.5.0-dev.2",
37
- "@prisma-next/tsconfig": "0.0.0",
33
+ "@prisma-next/driver-postgres": "0.5.0-dev.21",
34
+ "@prisma-next/cli": "0.5.0-dev.21",
35
+ "@prisma-next/errors": "0.5.0-dev.21",
36
+ "@prisma-next/extension-pgvector": "0.5.0-dev.21",
37
+ "@prisma-next/test-utils": "0.0.1",
38
38
  "@prisma-next/tsdown": "0.0.0",
39
- "@prisma-next/test-utils": "0.0.1"
39
+ "@prisma-next/tsconfig": "0.0.0"
40
40
  },
41
41
  "exports": {
42
42
  "./adapter": "./dist/adapter.mjs",