@prisma-next/target-postgres 0.13.0-dev.7 → 0.13.0-dev.9

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.
@@ -1 +1 @@
1
- {"version":3,"file":"planner-CAYPJObw.mjs","names":["#lowerer"],"sources":["../src/core/migrations/control-policy.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlPolicySubject } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n isPostgresEnumStorageEntry,\n type SqlStorage,\n storageTableAt,\n} from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { isPostgresSchema } from '../postgres-schema';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\n\n/**\n * Factory calls that create a whole, previously-absent top-level storage\n * object. Used to decide whether `tolerated` permits a call (it only allows\n * creating absent objects, never modifying existing ones).\n *\n * Deliberately an explicit, closed set rather than a `factoryName`\n * create/alter/drop classification: it answers exactly one yes/no question\n * and is fail-closed. Any call not listed here — including future or\n * extension-contributed factories — is treated as NOT object-creation, so it\n * is suppressed under `tolerated` rather than permissively emitted.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>([\n 'createTable',\n 'createEnumType',\n 'createSchema',\n]);\n\nfunction createsNewTopLevelObject(call: PostgresOpFactoryCall): boolean {\n return OBJECT_CREATION_FACTORIES.has(call.factoryName);\n}\n\nfunction ddlSchemaNameForNamespace(contract: Contract<SqlStorage>, namespaceId: string): string {\n const namespace = contract.storage.namespaces[namespaceId];\n return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;\n}\n\nfunction resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const table = storageTableAt(contract.storage, namespaceId, tableName);\n if (!table) continue;\n if (\n ddlSchemaName === undefined ||\n ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName\n ) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\nfunction resolveNamespaceIdForDdlSchema(\n contract: Contract<SqlStorage>,\n ddlSchemaName: string,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const ns = contract.storage.namespaces[namespaceId];\n if (isPostgresSchema(ns) && ns.ddlSchemaName(contract.storage) === ddlSchemaName) {\n return namespaceId;\n }\n if (namespaceId === ddlSchemaName) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\ninterface PostgresCallFields {\n readonly schemaName?: string;\n readonly tableName?: string;\n readonly columnName?: string;\n readonly typeName?: string;\n}\n\nfunction postgresCallFields(call: PostgresOpFactoryCall): PostgresCallFields {\n return {\n ...ifDefined('schemaName', 'schemaName' in call ? call.schemaName : undefined),\n ...ifDefined('tableName', 'tableName' in call ? call.tableName : undefined),\n ...ifDefined('columnName', 'columnName' in call ? call.columnName : undefined),\n ...ifDefined('typeName', 'typeName' in call ? call.typeName : undefined),\n };\n}\n\nexport function formatPostgresControlPolicySubjectLabel(\n factoryName: string,\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject?.table) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.table})`;\n }\n if (subject?.typeName) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.typeName})`;\n }\n return factoryName;\n}\n\nexport function resolvePostgresCallControlPolicySubject(\n call: PostgresOpFactoryCall,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const callFields = postgresCallFields(call);\n const createsNewObject = createsNewTopLevelObject(call);\n\n if (call.factoryName === 'createSchema' && callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n if (callFields.typeName && call.factoryName !== 'addColumn') {\n const namespaceId = callFields.schemaName\n ? resolveNamespaceIdForDdlSchema(contract, callFields.schemaName)\n : UNBOUND_NAMESPACE_ID;\n const ns = contract.storage.namespaces[namespaceId];\n const rawEnum = isPostgresSchema(ns) ? ns.entries.type[callFields.typeName] : undefined;\n const controlPolicy = isPostgresEnumStorageEntry(rawEnum) ? rawEnum.control : undefined;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', controlPolicy),\n typeName: callFields.typeName,\n createsNewObject,\n };\n }\n\n if (callFields.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const table = storageTableAt(contract.storage, namespaceId, callFields.tableName);\n const tableControlPolicy = table?.control;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\n table: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n createsNewObject,\n };\n }\n\n if (callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n\n/**\n * Issue kinds that describe the absence of a whole, top-level Postgres\n * object — the same kinds `createsNewTopLevelObject` recognises for calls.\n * Used by {@link resolvePostgresIssueCreationFactoryName} to decide whether\n * a `tolerated` subject permits the issue to flow into the planner\n * (create-if-absent) and to seed the suppressed-subject warning's\n * `factoryName` when the planner is skipped.\n */\nconst POSTGRES_ISSUE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n missing_schema: 'createSchema',\n missing_table: 'createTable',\n type_missing: 'createEnumType',\n});\n\nexport function resolvePostgresIssueCreationFactoryName(issue: SchemaIssue): string | undefined {\n return POSTGRES_ISSUE_CREATION_FACTORY[issue.kind];\n}\n\n/**\n * Resolve the control-policy subject coordinate for a single\n * {@link SchemaIssue}. Mirrors the resolution `resolvePostgresCallControlPolicySubject`\n * performs for a generated DDL call, but works *off the issue* — so the\n * planner can partition issues by effective policy before the diff engine\n * runs. `createsNewObject` is derived from the issue's kind: schema/table/\n * type-missing issues describe a brand-new top-level object; everything else\n * touches an existing object.\n *\n * An `extra_table` issue carries no contract namespace coordinate (the table\n * isn't in any contract namespace), so the subject's `namespaceId` falls\n * back to {@link UNBOUND_NAMESPACE_ID}; the call-side resolver does the same\n * for the `DropTableCall` it produces.\n */\nexport function resolvePostgresIssueControlPolicySubject(\n issue: SchemaIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const createsNewObject = POSTGRES_ISSUE_CREATION_FACTORY[issue.kind] !== undefined;\n\n if (issue.kind === 'missing_schema' && issue.namespaceId) {\n return { namespaceId: issue.namespaceId, createsNewObject };\n }\n\n if ('typeName' in issue && issue.typeName) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId ? issue.namespaceId : UNBOUND_NAMESPACE_ID;\n const ns = contract.storage.namespaces[namespaceId];\n const rawEnum = isPostgresSchema(ns) ? ns.entries.type[issue.typeName] : undefined;\n const controlPolicy = isPostgresEnumStorageEntry(rawEnum) ? rawEnum.control : undefined;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', controlPolicy),\n typeName: issue.typeName,\n createsNewObject,\n };\n }\n\n if ('table' in issue && issue.table) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId\n ? issue.namespaceId\n : resolveNamespaceIdForTable(contract, issue.table, undefined);\n const table = storageTableAt(contract.storage, namespaceId, issue.table);\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n table: issue.table,\n ...ifDefined('column', 'column' in issue ? issue.column : undefined),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the Postgres-flavoured\n * annotations slot on the schema IR. Defaults to the always-present\n * `public` schema when introspection did not populate the slot — a fresh\n * Postgres database always carries `public` (unless an operator dropped\n * it manually), so any verifier path that runs without an enriched\n * introspection still suppresses the redundant `CREATE SCHEMA \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and writes every\n * non-system schema into `annotations.pg.existingSchemas`. Tests that\n * want to assert against a richer initial state pass the slot\n * explicitly via the schema IR.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIR): readonly string[] {\n const annotations = (schema as { annotations?: { pg?: { existingSchemas?: unknown } } })\n .annotations;\n const slot = annotations?.pg?.existingSchemas;\n if (Array.isArray(slot)) {\n return slot.filter((s): s is string => typeof s === 'string');\n }\n return ['public'];\n}\n\n/**\n * Emits a `missing_schema` issue for every contract-declared Postgres\n * namespace whose live container does not yet exist.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue stamps `namespaceId` with the contract namespace\n * coordinate so the downstream `mapIssueToCall` re-resolves the DDL\n * schema name through the same polymorphic path — keeping the\n * coordinate, not the resolved name, as the issue's stable identity.\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIR;\n}): readonly SchemaIssue[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaIssue[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n issues.push({\n kind: 'missing_schema',\n namespaceId,\n message: `Schema \"${ddlName}\" is missing from database`,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerConflict,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n partitionCallsByControlPolicy,\n partitionIssuesByControlPolicy,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport type { Lowerer } from '@prisma-next/family-sql/control-adapter';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { createResolveExistingEnumValues } from './enum-planning';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(lowerer: Lowerer): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner(lowerer);\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | {\n readonly kind: 'success';\n readonly plan: TypeScriptRenderablePostgresMigration;\n readonly warnings?: readonly SqlPlannerConflict[];\n }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n readonly #lowerer: Lowerer | undefined;\n\n constructor(lowerer?: Lowerer) {\n this.#lowerer = lowerer;\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n this.#lowerer,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n // Input-side control-policy partition. `external` / `observed` subjects\n // — and non-creation issues for `tolerated` subjects — are dropped from\n // the planner's input entirely; the planner never observes them, never\n // diffs them, never generates DDL for them. Suppression warnings are\n // built directly from the suppressed partition (one per subject), so the\n // user-visible message survives even when the planner would have failed\n // to model the subject's live shape.\n const issuePartition = partitionIssuesByControlPolicy({\n issues: schemaIssues,\n contract: options.contract,\n resolveControlPolicySubject: (issue) =>\n resolvePostgresIssueControlPolicySubject(issue, options.contract),\n resolveCreationFactoryName: resolvePostgresIssueCreationFactoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n const result = planIssues({\n issues: issuePartition.plannable,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec hook ops are target-agnostic `OpFactoryCall`; Postgres planning\n // lifts them at this integration boundary (see field-event-planner JSDoc).\n const fieldEventPostgresCalls = blindCast<\n readonly PostgresOpFactoryCall[],\n 'Codec hook ops conform to PostgresOpFactoryCall at the app emitter boundary'\n >(fieldEventOps);\n const fieldEventPartition = partitionCallsByControlPolicy({\n calls: fieldEventPostgresCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n const calls = [...result.value.calls, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...fieldEventPartition.warnings,\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n this.#lowerer,\n ),\n ...(warnings.length > 0 ? { warnings: Object.freeze(warnings) } : {}),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage),\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n // Schema presence is a Postgres-specific concern (no equivalent in\n // SQLite / Mongo), so the issue emission lives in the target layer\n // rather than in the family verifier. Stitch it in here so a single\n // `SchemaIssue[]` flows through `planIssues` and the planner emits\n // CREATE SCHEMA in the dep bucket before any CreateTableCall.\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n if (namespaceIssues.length === 0) {\n return verifyResult.schema.issues;\n }\n return [...namespaceIssues, ...verifyResult.schema.issues];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,4BAAiD,IAAI,IAAY;CACrE;CACA;CACA;AACF,CAAC;AAED,SAAS,yBAAyB,MAAsC;CACtE,OAAO,0BAA0B,IAAI,KAAK,WAAW;AACvD;AAEA,SAAS,0BAA0B,UAAgC,aAA6B;CAC9F,MAAM,YAAY,SAAS,QAAQ,WAAW;CAC9C,OAAO,iBAAiB,SAAS,IAAI,UAAU,cAAc,SAAS,OAAO,IAAI;AACnF;AAEA,SAAS,2BACP,UACA,WACA,eACQ;CACR,KAAK,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,UAAU,GAAG;EAElE,IAAI,CADU,eAAe,SAAS,SAAS,aAAa,SACnD,GAAG;EACZ,IACE,kBAAkB,KAAA,KAClB,0BAA0B,UAAU,WAAW,MAAM,eAErD,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,+BACP,UACA,eACQ;CACR,KAAK,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,UAAU,GAAG;EAClE,MAAM,KAAK,SAAS,QAAQ,WAAW;EACvC,IAAI,iBAAiB,EAAE,KAAK,GAAG,cAAc,SAAS,OAAO,MAAM,eACjE,OAAO;EAET,IAAI,gBAAgB,eAClB,OAAO;CAEX;CACA,OAAO;AACT;AASA,SAAS,mBAAmB,MAAiD;CAC3E,OAAO;EACL,GAAG,UAAU,cAAc,gBAAgB,OAAO,KAAK,aAAa,KAAA,CAAS;EAC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IAAI,EAAE,UAAU,OAAO,OAAO,QAAQ,EAAE,IAAI,CAAC;EACrE,CAAC;CACH;CAEA,qBAA6B,QAAkC;EAC7D,IAAI,CAAC,OAAO,wBAAwB,SAAS,UAAU,GACrD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;EACP,CACF,CAAC;EAEH,OAAO;CACT;CAEA,oBAA4B,SAA+D;EAIzF,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,aAAa;EAW7E,MAAM,eAAe,gBAAgB;GATnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,IAAI;GAC9B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACrB,2BAA2B,gCAAgC,QAAQ,SAAS,OAAO;EAEpC,CAAC;EAMlD,MAAM,kBAAkB,gCAAgC;GACtD,UAAU,QAAQ;GAClB,QAAQ,QAAQ;EAClB,CAAC;EACD,IAAI,gBAAgB,WAAW,GAC7B,OAAO,aAAa,OAAO;EAE7B,OAAO,CAAC,GAAG,iBAAiB,GAAG,aAAa,OAAO,MAAM;CAC3D;AACF"}
1
+ {"version":3,"file":"planner-DSrPHeFC.mjs","names":["#lowerer"],"sources":["../src/core/migrations/control-policy.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlPolicySubject } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n isPostgresEnumStorageEntry,\n type SqlStorage,\n storageTableAt,\n} from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { isPostgresSchema } from '../postgres-schema';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\n\n/**\n * Factory calls that create a whole, previously-absent top-level storage\n * object. Used to decide whether `tolerated` permits a call (it only allows\n * creating absent objects, never modifying existing ones).\n *\n * Deliberately an explicit, closed set rather than a `factoryName`\n * create/alter/drop classification: it answers exactly one yes/no question\n * and is fail-closed. Any call not listed here — including future or\n * extension-contributed factories — is treated as NOT object-creation, so it\n * is suppressed under `tolerated` rather than permissively emitted.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>([\n 'createTable',\n 'createEnumType',\n 'createSchema',\n]);\n\nfunction createsNewTopLevelObject(call: PostgresOpFactoryCall): boolean {\n return OBJECT_CREATION_FACTORIES.has(call.factoryName);\n}\n\nfunction ddlSchemaNameForNamespace(contract: Contract<SqlStorage>, namespaceId: string): string {\n const namespace = contract.storage.namespaces[namespaceId];\n return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;\n}\n\nfunction resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const table = storageTableAt(contract.storage, namespaceId, tableName);\n if (!table) continue;\n if (\n ddlSchemaName === undefined ||\n ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName\n ) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\nfunction resolveNamespaceIdForDdlSchema(\n contract: Contract<SqlStorage>,\n ddlSchemaName: string,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const ns = contract.storage.namespaces[namespaceId];\n if (isPostgresSchema(ns) && ns.ddlSchemaName(contract.storage) === ddlSchemaName) {\n return namespaceId;\n }\n if (namespaceId === ddlSchemaName) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\ninterface PostgresCallFields {\n readonly schemaName?: string;\n readonly tableName?: string;\n readonly columnName?: string;\n readonly typeName?: string;\n}\n\nfunction postgresCallFields(call: PostgresOpFactoryCall): PostgresCallFields {\n return {\n ...ifDefined('schemaName', 'schemaName' in call ? call.schemaName : undefined),\n ...ifDefined('tableName', 'tableName' in call ? call.tableName : undefined),\n ...ifDefined('columnName', 'columnName' in call ? call.columnName : undefined),\n ...ifDefined('typeName', 'typeName' in call ? call.typeName : undefined),\n };\n}\n\nexport function formatPostgresControlPolicySubjectLabel(\n factoryName: string,\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject?.table) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.table})`;\n }\n if (subject?.typeName) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.typeName})`;\n }\n return factoryName;\n}\n\nexport function resolvePostgresCallControlPolicySubject(\n call: PostgresOpFactoryCall,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const callFields = postgresCallFields(call);\n const createsNewObject = createsNewTopLevelObject(call);\n\n if (call.factoryName === 'createSchema' && callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n if (callFields.typeName && call.factoryName !== 'addColumn') {\n const namespaceId = callFields.schemaName\n ? resolveNamespaceIdForDdlSchema(contract, callFields.schemaName)\n : UNBOUND_NAMESPACE_ID;\n const ns = contract.storage.namespaces[namespaceId];\n const rawEnum = isPostgresSchema(ns) ? ns.entries.type[callFields.typeName] : undefined;\n const controlPolicy = isPostgresEnumStorageEntry(rawEnum) ? rawEnum.control : undefined;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', controlPolicy),\n typeName: callFields.typeName,\n createsNewObject,\n };\n }\n\n if (callFields.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const table = storageTableAt(contract.storage, namespaceId, callFields.tableName);\n const tableControlPolicy = table?.control;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\n table: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n createsNewObject,\n };\n }\n\n if (callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n\n/**\n * Issue kinds that describe the absence of a whole, top-level Postgres\n * object — the same kinds `createsNewTopLevelObject` recognises for calls.\n * Used by {@link resolvePostgresIssueCreationFactoryName} to decide whether\n * a `tolerated` subject permits the issue to flow into the planner\n * (create-if-absent) and to seed the suppressed-subject warning's\n * `factoryName` when the planner is skipped.\n */\nconst POSTGRES_ISSUE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n missing_schema: 'createSchema',\n missing_table: 'createTable',\n type_missing: 'createEnumType',\n});\n\nexport function resolvePostgresIssueCreationFactoryName(issue: SchemaIssue): string | undefined {\n return POSTGRES_ISSUE_CREATION_FACTORY[issue.kind];\n}\n\n/**\n * Resolve the control-policy subject coordinate for a single\n * {@link SchemaIssue}. Mirrors the resolution `resolvePostgresCallControlPolicySubject`\n * performs for a generated DDL call, but works *off the issue* — so the\n * planner can partition issues by effective policy before the diff engine\n * runs. `createsNewObject` is derived from the issue's kind: schema/table/\n * type-missing issues describe a brand-new top-level object; everything else\n * touches an existing object.\n *\n * An `extra_table` issue carries no contract namespace coordinate (the table\n * isn't in any contract namespace), so the subject's `namespaceId` falls\n * back to {@link UNBOUND_NAMESPACE_ID}; the call-side resolver does the same\n * for the `DropTableCall` it produces.\n */\nexport function resolvePostgresIssueControlPolicySubject(\n issue: SchemaIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const createsNewObject = POSTGRES_ISSUE_CREATION_FACTORY[issue.kind] !== undefined;\n\n if (issue.kind === 'missing_schema' && issue.namespaceId) {\n return { namespaceId: issue.namespaceId, createsNewObject };\n }\n\n if ('typeName' in issue && issue.typeName) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId ? issue.namespaceId : UNBOUND_NAMESPACE_ID;\n const ns = contract.storage.namespaces[namespaceId];\n const rawEnum = isPostgresSchema(ns) ? ns.entries.type[issue.typeName] : undefined;\n const controlPolicy = isPostgresEnumStorageEntry(rawEnum) ? rawEnum.control : undefined;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', controlPolicy),\n typeName: issue.typeName,\n createsNewObject,\n };\n }\n\n if ('table' in issue && issue.table) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId\n ? issue.namespaceId\n : resolveNamespaceIdForTable(contract, issue.table, undefined);\n const table = storageTableAt(contract.storage, namespaceId, issue.table);\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n table: issue.table,\n ...ifDefined('column', 'column' in issue ? issue.column : undefined),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the Postgres-flavoured\n * annotations slot on the schema IR. Defaults to the always-present\n * `public` schema when introspection did not populate the slot — a fresh\n * Postgres database always carries `public` (unless an operator dropped\n * it manually), so any verifier path that runs without an enriched\n * introspection still suppresses the redundant `CREATE SCHEMA \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and writes every\n * non-system schema into `annotations.pg.existingSchemas`. Tests that\n * want to assert against a richer initial state pass the slot\n * explicitly via the schema IR.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIR): readonly string[] {\n const annotations = (schema as { annotations?: { pg?: { existingSchemas?: unknown } } })\n .annotations;\n const slot = annotations?.pg?.existingSchemas;\n if (Array.isArray(slot)) {\n return slot.filter((s): s is string => typeof s === 'string');\n }\n return ['public'];\n}\n\n/**\n * Emits a `missing_schema` issue for every contract-declared Postgres\n * namespace whose live container does not yet exist.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue stamps `namespaceId` with the contract namespace\n * coordinate so the downstream `mapIssueToCall` re-resolves the DDL\n * schema name through the same polymorphic path — keeping the\n * coordinate, not the resolved name, as the issue's stable identity.\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIR;\n}): readonly SchemaIssue[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaIssue[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n issues.push({\n kind: 'missing_schema',\n namespaceId,\n message: `Schema \"${ddlName}\" is missing from database`,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerConflict,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n partitionCallsByControlPolicy,\n partitionIssuesByControlPolicy,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport type { Lowerer } from '@prisma-next/family-sql/control-adapter';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { createResolveExistingEnumValues } from './enum-planning';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(lowerer: Lowerer): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner(lowerer);\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | {\n readonly kind: 'success';\n readonly plan: TypeScriptRenderablePostgresMigration;\n readonly warnings?: readonly SqlPlannerConflict[];\n }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n readonly #lowerer: Lowerer | undefined;\n\n constructor(lowerer?: Lowerer) {\n this.#lowerer = lowerer;\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n this.#lowerer,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n // Input-side control-policy partition. `external` / `observed` subjects\n // — and non-creation issues for `tolerated` subjects — are dropped from\n // the planner's input entirely; the planner never observes them, never\n // diffs them, never generates DDL for them. Suppression warnings are\n // built directly from the suppressed partition (one per subject), so the\n // user-visible message survives even when the planner would have failed\n // to model the subject's live shape.\n const issuePartition = partitionIssuesByControlPolicy({\n issues: schemaIssues,\n contract: options.contract,\n resolveControlPolicySubject: (issue) =>\n resolvePostgresIssueControlPolicySubject(issue, options.contract),\n resolveCreationFactoryName: resolvePostgresIssueCreationFactoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n const result = planIssues({\n issues: issuePartition.plannable,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec hook ops are target-agnostic `OpFactoryCall`; Postgres planning\n // lifts them at this integration boundary (see field-event-planner JSDoc).\n const fieldEventPostgresCalls = blindCast<\n readonly PostgresOpFactoryCall[],\n 'Codec hook ops conform to PostgresOpFactoryCall at the app emitter boundary'\n >(fieldEventOps);\n const fieldEventPartition = partitionCallsByControlPolicy({\n calls: fieldEventPostgresCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n const calls = [...result.value.calls, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...fieldEventPartition.warnings,\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n this.#lowerer,\n ),\n ...(warnings.length > 0 ? { warnings: Object.freeze(warnings) } : {}),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage),\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n // Schema presence is a Postgres-specific concern (no equivalent in\n // SQLite / Mongo), so the issue emission lives in the target layer\n // rather than in the family verifier. Stitch it in here so a single\n // `SchemaIssue[]` flows through `planIssues` and the planner emits\n // CREATE SCHEMA in the dep bucket before any CreateTableCall.\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n if (namespaceIssues.length === 0) {\n return verifyResult.schema.issues;\n }\n return [...namespaceIssues, ...verifyResult.schema.issues];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,4BAAiD,IAAI,IAAY;CACrE;CACA;CACA;AACF,CAAC;AAED,SAAS,yBAAyB,MAAsC;CACtE,OAAO,0BAA0B,IAAI,KAAK,WAAW;AACvD;AAEA,SAAS,0BAA0B,UAAgC,aAA6B;CAC9F,MAAM,YAAY,SAAS,QAAQ,WAAW;CAC9C,OAAO,iBAAiB,SAAS,IAAI,UAAU,cAAc,SA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,QAAQ;EAClB,CAAC;EACD,IAAI,gBAAgB,WAAW,GAC7B,OAAO,aAAa,OAAO;EAE7B,OAAO,CAAC,GAAG,iBAAiB,GAAG,aAAa,OAAO,MAAM;CAC3D;AACF"}
package/dist/planner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createPostgresMigrationPlanner } from "./planner-CAYPJObw.mjs";
1
+ import { t as createPostgresMigrationPlanner } from "./planner-DSrPHeFC.mjs";
2
2
  export { createPostgresMigrationPlanner };
package/package.json CHANGED
@@ -1,32 +1,32 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.13.0-dev.7",
3
+ "version": "0.13.0-dev.9",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Postgres target pack for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/cli": "0.13.0-dev.7",
10
- "@prisma-next/contract": "0.13.0-dev.7",
11
- "@prisma-next/errors": "0.13.0-dev.7",
12
- "@prisma-next/family-sql": "0.13.0-dev.7",
13
- "@prisma-next/framework-components": "0.13.0-dev.7",
14
- "@prisma-next/migration-tools": "0.13.0-dev.7",
15
- "@prisma-next/ts-render": "0.13.0-dev.7",
16
- "@prisma-next/sql-contract": "0.13.0-dev.7",
17
- "@prisma-next/sql-errors": "0.13.0-dev.7",
18
- "@prisma-next/sql-operations": "0.13.0-dev.7",
19
- "@prisma-next/sql-relational-core": "0.13.0-dev.7",
20
- "@prisma-next/sql-schema-ir": "0.13.0-dev.7",
21
- "@prisma-next/utils": "0.13.0-dev.7",
9
+ "@prisma-next/cli": "0.13.0-dev.9",
10
+ "@prisma-next/contract": "0.13.0-dev.9",
11
+ "@prisma-next/errors": "0.13.0-dev.9",
12
+ "@prisma-next/family-sql": "0.13.0-dev.9",
13
+ "@prisma-next/framework-components": "0.13.0-dev.9",
14
+ "@prisma-next/migration-tools": "0.13.0-dev.9",
15
+ "@prisma-next/ts-render": "0.13.0-dev.9",
16
+ "@prisma-next/sql-contract": "0.13.0-dev.9",
17
+ "@prisma-next/sql-errors": "0.13.0-dev.9",
18
+ "@prisma-next/sql-operations": "0.13.0-dev.9",
19
+ "@prisma-next/sql-relational-core": "0.13.0-dev.9",
20
+ "@prisma-next/sql-schema-ir": "0.13.0-dev.9",
21
+ "@prisma-next/utils": "0.13.0-dev.9",
22
22
  "@standard-schema/spec": "^1.1.0",
23
23
  "arktype": "^2.2.0",
24
24
  "pathe": "^2.0.3"
25
25
  },
26
26
  "devDependencies": {
27
- "@prisma-next/test-utils": "0.13.0-dev.7",
28
- "@prisma-next/tsconfig": "0.13.0-dev.7",
29
- "@prisma-next/tsdown": "0.13.0-dev.7",
27
+ "@prisma-next/test-utils": "0.13.0-dev.9",
28
+ "@prisma-next/tsconfig": "0.13.0-dev.9",
29
+ "@prisma-next/tsdown": "0.13.0-dev.9",
30
30
  "tsdown": "0.22.1",
31
31
  "typescript": "5.9.3",
32
32
  "vitest": "4.1.8"
@@ -14,17 +14,25 @@ import { isPostgresSchema } from '../postgres-schema';
14
14
 
15
15
  /**
16
16
  * Codec-typed enum entry shape stored under
17
- * `schema.annotations.pg.storageTypes[(schemaName, nativeType)]`.
17
+ * `schema.annotations.pg.enumTypes[schemaName][nativeType]`.
18
18
  */
19
19
  interface PgStorageTypeEntry {
20
20
  readonly codecId?: string;
21
21
  readonly typeParams?: { readonly values?: unknown };
22
22
  }
23
23
 
24
+ /**
25
+ * Live enum types keyed by `(schemaName, nativeType)` as a nested map, so two
26
+ * schemas sharing a native enum name stay distinct without packing the pair
27
+ * into a string. This is the same `(namespace, entityName)` coordinate the
28
+ * contract side addresses entities by.
29
+ */
30
+ type PgEnumTypesMap = Readonly<Record<string, Readonly<Record<string, PgStorageTypeEntry>>>>;
31
+
24
32
  /** Postgres-specific subtree on family `SqlSchemaIR.annotations`. */
25
33
  export interface PostgresSchemaIrAnnotations {
26
34
  readonly schema?: string;
27
- readonly storageTypes?: Readonly<Record<string, PgStorageTypeEntry>>;
35
+ readonly enumTypes?: PgEnumTypesMap;
28
36
  }
29
37
 
30
38
  function readOptionalString(value: unknown): string | undefined {
@@ -50,20 +58,27 @@ function readPgStorageTypeEntry(value: unknown): PgStorageTypeEntry | undefined
50
58
  };
51
59
  }
52
60
 
53
- function readPgStorageTypesMap(
54
- value: unknown,
55
- ): Readonly<Record<string, PgStorageTypeEntry>> | undefined {
61
+ function readPgEnumTypesMap(value: unknown): PgEnumTypesMap | undefined {
56
62
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
57
63
  return undefined;
58
64
  }
59
- const entries: Record<string, PgStorageTypeEntry> = {};
60
- for (const [key, entryValue] of Object.entries(value)) {
61
- const entry = readPgStorageTypeEntry(entryValue);
62
- if (entry !== undefined) {
63
- entries[key] = entry;
65
+ const bySchema: Record<string, Record<string, PgStorageTypeEntry>> = {};
66
+ for (const [schemaName, byTypeRaw] of Object.entries(value)) {
67
+ if (byTypeRaw === null || typeof byTypeRaw !== 'object' || Array.isArray(byTypeRaw)) {
68
+ continue;
69
+ }
70
+ const byType: Record<string, PgStorageTypeEntry> = {};
71
+ for (const [nativeType, entryValue] of Object.entries(byTypeRaw)) {
72
+ const entry = readPgStorageTypeEntry(entryValue);
73
+ if (entry !== undefined) {
74
+ byType[nativeType] = entry;
75
+ }
76
+ }
77
+ if (Object.keys(byType).length > 0) {
78
+ bySchema[schemaName] = byType;
64
79
  }
65
80
  }
66
- return Object.keys(entries).length > 0 ? entries : undefined;
81
+ return Object.keys(bySchema).length > 0 ? bySchema : undefined;
67
82
  }
68
83
 
69
84
  /**
@@ -78,25 +93,13 @@ export function readPostgresSchemaIrAnnotations(schema: SqlSchemaIR): PostgresSc
78
93
  return {};
79
94
  }
80
95
  const schemaField = readOptionalString(Reflect.get(raw, 'schema'));
81
- const storageTypes = readPgStorageTypesMap(Reflect.get(raw, 'storageTypes'));
96
+ const enumTypes = readPgEnumTypesMap(Reflect.get(raw, 'enumTypes'));
82
97
  return {
83
98
  ...(schemaField !== undefined ? { schema: schemaField } : {}),
84
- ...(storageTypes !== undefined ? { storageTypes } : {}),
99
+ ...(enumTypes !== undefined ? { enumTypes } : {}),
85
100
  };
86
101
  }
87
102
 
88
- /**
89
- * Separator for `(schemaName, nativeType)` keys in introspected
90
- * `schema.annotations.pg.storageTypes`. NUL cannot appear in Postgres
91
- * identifiers, so the pair is unambiguous.
92
- */
93
- export const ENUM_STORAGE_KEY_SEP = '\u0000';
94
-
95
- /** Builds the schema-qualified storageTypes map key for a live Postgres enum. */
96
- export function enumStorageCompoundKey(schemaName: string, nativeType: string): string {
97
- return `${schemaName}${ENUM_STORAGE_KEY_SEP}${nativeType}`;
98
- }
99
-
100
103
  /**
101
104
  * Resolves the live-schema name a namespace's enums are introspected under,
102
105
  * for keying `readExistingEnumValues` lookups. The unbound namespace's
@@ -149,9 +152,10 @@ export type EnumDiff =
149
152
 
150
153
  /**
151
154
  * Reads existing enum values for `(schemaName, nativeType)` from the
152
- * Postgres-introspected `schema.annotations.pg.storageTypes` map.
155
+ * Postgres-introspected `schema.annotations.pg.enumTypes` map, addressed by
156
+ * the `(schema, nativeType)` coordinate.
153
157
  *
154
- * Schema IR's `storageTypes` slots are always codec-typed
158
+ * Schema IR's enum entries are always codec-typed
155
159
  * (`{codecId: PG_ENUM_CODEC_ID, typeParams.values}`): the introspector
156
160
  * writes that shape, and the Contract→Schema IR projector resolves
157
161
  * `PostgresEnumType` instances down to the same codec-typed triple before
@@ -165,8 +169,8 @@ export function readExistingEnumValues(
165
169
  schemaName: string,
166
170
  nativeType: string,
167
171
  ): readonly string[] | null {
168
- const storageTypes = readPostgresSchemaIrAnnotations(schema).storageTypes;
169
- const existing = storageTypes?.[enumStorageCompoundKey(schemaName, nativeType)];
172
+ const enumTypes = readPostgresSchemaIrAnnotations(schema).enumTypes;
173
+ const existing = enumTypes?.[schemaName]?.[nativeType];
170
174
  if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {
171
175
  return null;
172
176
  }
@@ -10,10 +10,7 @@ import type {
10
10
  import type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';
11
11
  import { ifDefined } from '@prisma-next/utils/defined';
12
12
  import { postgresTargetDescriptorMeta } from '../core/descriptor-meta';
13
- import {
14
- enumStorageCompoundKey,
15
- resolveDdlSchemaForNamespaceStorage,
16
- } from '../core/migrations/enum-planning';
13
+ import { resolveDdlSchemaForNamespaceStorage } from '../core/migrations/enum-planning';
17
14
  import { createPostgresMigrationPlanner } from '../core/migrations/planner';
18
15
  import { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';
19
16
  import type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';
@@ -80,18 +77,14 @@ const postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresP
80
77
  annotationNamespace: 'pg',
81
78
  ...ifDefined('expandNativeType', expander),
82
79
  renderDefault: postgresRenderDefault,
83
- // Schema-qualify enum annotation keys so the projected "from" IR's
84
- // `storageTypes` match `readExistingEnumValues` on the read side
85
- // (the contract-to-contract `migration plan` path). The DDL-schema
86
- // resolution + compound-key format stay here in the target layer;
87
- // the family projector treats the returned string as opaque.
88
- // `undefined` schema IR ⇒ the unbound coordinate resolves to the
89
- // default `public` landing schema, matching the read-side fallback.
90
- resolveEnumStorageKey: (storage, namespaceId, nativeType) =>
91
- enumStorageCompoundKey(
92
- resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),
93
- nativeType,
94
- ),
80
+ // Map each namespace to the live DDL schema its enums are stored
81
+ // under, so the projected "from" IR nests enums by the same schema
82
+ // `readExistingEnumValues` reads (the contract-to-contract `migration
83
+ // plan` path). `undefined` schema IR the unbound coordinate
84
+ // resolves to the default `public` landing schema, matching the
85
+ // read-side fallback.
86
+ resolveEnumNamespaceSchema: (storage, namespaceId) =>
87
+ resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),
95
88
  });
96
89
  },
97
90
  },
@@ -2,7 +2,6 @@ export {
2
2
  createResolveExistingEnumValues,
3
3
  determineEnumDiff,
4
4
  type EnumDiff,
5
- enumStorageCompoundKey,
6
5
  getDesiredEnumValues,
7
6
  type PostgresSchemaIrAnnotations,
8
7
  readExistingEnumValues,
@@ -1 +0,0 @@
1
- {"version":3,"file":"enum-planning-BCyvlFHk.mjs","names":[],"sources":["../src/core/migrations/enum-planning.ts"],"sourcesContent":["/**\n * Pure planning helpers for Postgres enum types: the diff/rebuild logic\n * that the verifier and planner use to walk `PostgresEnumType` instances\n * natively. Op builders live in `./operations/enums.ts`.\n */\n\nimport { arraysEqual } from '@prisma-next/family-sql/schema-verify';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { PostgresEnumStorageEntry, SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { PG_ENUM_CODEC_ID } from '../codec-ids';\nimport type { PostgresEnumType } from '../postgres-enum-type';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Codec-typed enum entry shape stored under\n * `schema.annotations.pg.storageTypes[(schemaName, nativeType)]`.\n */\ninterface PgStorageTypeEntry {\n readonly codecId?: string;\n readonly typeParams?: { readonly values?: unknown };\n}\n\n/** Postgres-specific subtree on family `SqlSchemaIR.annotations`. */\nexport interface PostgresSchemaIrAnnotations {\n readonly schema?: string;\n readonly storageTypes?: Readonly<Record<string, PgStorageTypeEntry>>;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction readPgStorageTypeEntry(value: unknown): PgStorageTypeEntry | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n const codecId = Reflect.get(value, 'codecId');\n const typeParamsRaw = Reflect.get(value, 'typeParams');\n const typeParams =\n typeParamsRaw !== undefined &&\n typeParamsRaw !== null &&\n typeof typeParamsRaw === 'object' &&\n !Array.isArray(typeParamsRaw)\n ? { values: Reflect.get(typeParamsRaw, 'values') }\n : undefined;\n return {\n ...(typeof codecId === 'string' ? { codecId } : {}),\n ...(typeParams !== undefined ? { typeParams } : {}),\n };\n}\n\nfunction readPgStorageTypesMap(\n value: unknown,\n): Readonly<Record<string, PgStorageTypeEntry>> | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n const entries: Record<string, PgStorageTypeEntry> = {};\n for (const [key, entryValue] of Object.entries(value)) {\n const entry = readPgStorageTypeEntry(entryValue);\n if (entry !== undefined) {\n entries[key] = entry;\n }\n }\n return Object.keys(entries).length > 0 ? entries : undefined;\n}\n\n/**\n * Reads the Postgres annotation envelope (`schema.annotations.pg`) from\n * family Schema IR. `SqlAnnotations` is an open target-pack extensibility\n * map (`Record<string, unknown>`); this accessor narrows the `pg` slot at\n * runtime so Postgres code can read introspection fields without casts.\n */\nexport function readPostgresSchemaIrAnnotations(schema: SqlSchemaIR): PostgresSchemaIrAnnotations {\n const raw = schema.annotations?.['pg'];\n if (raw === undefined || raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return {};\n }\n const schemaField = readOptionalString(Reflect.get(raw, 'schema'));\n const storageTypes = readPgStorageTypesMap(Reflect.get(raw, 'storageTypes'));\n return {\n ...(schemaField !== undefined ? { schema: schemaField } : {}),\n ...(storageTypes !== undefined ? { storageTypes } : {}),\n };\n}\n\n/**\n * Separator for `(schemaName, nativeType)` keys in introspected\n * `schema.annotations.pg.storageTypes`. NUL cannot appear in Postgres\n * identifiers, so the pair is unambiguous.\n */\nexport const ENUM_STORAGE_KEY_SEP = '\\u0000';\n\n/** Builds the schema-qualified storageTypes map key for a live Postgres enum. */\nexport function enumStorageCompoundKey(schemaName: string, nativeType: string): string {\n return `${schemaName}${ENUM_STORAGE_KEY_SEP}${nativeType}`;\n}\n\n/**\n * Resolves the live-schema name a namespace's enums are introspected under,\n * for keying `readExistingEnumValues` lookups. The unbound namespace's\n * `ddlSchemaName` is a planner-emit sentinel (`__unbound__`) that never names a\n * real schema, so for the unbound coordinate we read the *introspected* schema\n * recorded on `annotations.pg.schema` (the live `current_schema()` the adapter\n * walked) — that is the schema the enum's `storageTypes` entry is keyed under.\n * Named namespaces resolve to their own DDL schema, which matches the\n * per-schema introspection key directly.\n */\nexport function resolveDdlSchemaForNamespaceStorage(\n storage: SqlStorage,\n namespaceId: string,\n schemaIr?: SqlSchemaIR,\n): string {\n if (namespaceId === UNBOUND_NAMESPACE_ID) {\n return (schemaIr ? readPostgresSchemaIrAnnotations(schemaIr).schema : undefined) ?? 'public';\n }\n const namespace = storage.namespaces[namespaceId];\n if (namespace && isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/** Contract-scoped bridge for the family verifier's enum value resolver. */\nexport function createResolveExistingEnumValues(\n storage: SqlStorage,\n): (\n schema: SqlSchemaIR,\n enumType: PostgresEnumStorageEntry,\n namespaceId: string,\n) => readonly string[] | null {\n return (schema, enumType, namespaceId) =>\n readExistingEnumValues(\n schema,\n resolveDdlSchemaForNamespaceStorage(storage, namespaceId, schema),\n enumType.nativeType,\n );\n}\n\n/**\n * Categorisation of how an existing enum type's values relate to the\n * desired set in the contract.\n */\nexport type EnumDiff =\n | { readonly kind: 'unchanged' }\n | { readonly kind: 'add_values'; readonly values: readonly string[] }\n | { readonly kind: 'rebuild'; readonly removedValues: readonly string[] };\n\n/**\n * Reads existing enum values for `(schemaName, nativeType)` from the\n * Postgres-introspected `schema.annotations.pg.storageTypes` map.\n *\n * Schema IR's `storageTypes` slots are always codec-typed\n * (`{codecId: PG_ENUM_CODEC_ID, typeParams.values}`): the introspector\n * writes that shape, and the Contract→Schema IR projector resolves\n * `PostgresEnumType` instances down to the same codec-typed triple before\n * they ever land in Schema IR. There is no second on-disk shape to\n * accept here.\n *\n * Returns `null` when no enum entry exists for the given native type.\n */\nexport function readExistingEnumValues(\n schema: SqlSchemaIR,\n schemaName: string,\n nativeType: string,\n): readonly string[] | null {\n const storageTypes = readPostgresSchemaIrAnnotations(schema).storageTypes;\n const existing = storageTypes?.[enumStorageCompoundKey(schemaName, nativeType)];\n if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {\n return null;\n }\n const enumValues = existing.typeParams?.values;\n if (!Array.isArray(enumValues) || !enumValues.every((v) => typeof v === 'string')) {\n return null;\n }\n return enumValues;\n}\n\n/**\n * Determines what changes are needed to transform existing enum values to\n * desired values.\n *\n * Postgres enums can only have values added (not removed or reordered)\n * without a full type rebuild involving temp type creation and column\n * migration; `'rebuild'` covers the value-removal and reorder cases.\n */\nexport function determineEnumDiff(\n existing: readonly string[],\n desired: readonly string[],\n): EnumDiff {\n if (arraysEqual(existing, desired)) {\n return { kind: 'unchanged' };\n }\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\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 if (removedValues.length > 0 || orderMismatch) {\n return { kind: 'rebuild', removedValues };\n }\n return { kind: 'add_values', values: missingValues };\n}\n\n/**\n * Convenience accessor — returns the enum's desired values from a\n * `PostgresEnumType` IR instance.\n */\nexport function getDesiredEnumValues(typeInstance: PostgresEnumType): readonly string[] {\n return typeInstance.values;\n}\n"],"mappings":";;;;;;;;;;AA6BA,SAAS,mBAAmB,OAAoC;CAC9D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,uBAAuB,OAAgD;CAC9E,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE;CAEF,MAAM,UAAU,QAAQ,IAAI,OAAO,SAAS;CAC5C,MAAM,gBAAgB,QAAQ,IAAI,OAAO,YAAY;CACrD,MAAM,aACJ,kBAAkB,KAAA,KAClB,kBAAkB,QAClB,OAAO,kBAAkB,YACzB,CAAC,MAAM,QAAQ,aAAa,IACxB,EAAE,QAAQ,QAAQ,IAAI,eAAe,QAAQ,EAAE,IAC/C,KAAA;CACN,OAAO;EACL,GA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