@prisma-next/target-postgres 0.14.0-dev.35 → 0.14.0-dev.36

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 (31) hide show
  1. package/dist/control.mjs +2 -2
  2. package/dist/{default-normalizer-CzV8-QSu.mjs → default-normalizer-Dug8Fez9.mjs} +69 -8
  3. package/dist/default-normalizer-Dug8Fez9.mjs.map +1 -0
  4. package/dist/default-normalizer.d.mts.map +1 -1
  5. package/dist/default-normalizer.mjs +1 -1
  6. package/dist/{issue-planner-D5H1VuVP.mjs → issue-planner-C-CwZd8D.mjs} +26 -3
  7. package/dist/issue-planner-C-CwZd8D.mjs.map +1 -0
  8. package/dist/issue-planner.d.mts.map +1 -1
  9. package/dist/issue-planner.mjs +1 -1
  10. package/dist/migration.d.mts +2 -2
  11. package/dist/migration.mjs +4 -4
  12. package/dist/{op-factory-call-DIdBDwmO.mjs → op-factory-call-DArx_1HM.mjs} +3 -1
  13. package/dist/op-factory-call-DArx_1HM.mjs.map +1 -0
  14. package/dist/op-factory-call-DPJR7tJc.d.mts.map +1 -1
  15. package/dist/op-factory-call.mjs +1 -1
  16. package/dist/{planner-D3Pl8LXU.mjs → planner-D9Qkrrib.mjs} +5 -5
  17. package/dist/{planner-D3Pl8LXU.mjs.map → planner-D9Qkrrib.mjs.map} +1 -1
  18. package/dist/{planner-produced-postgres-migration-Bbv8RYKJ.mjs → planner-produced-postgres-migration-7FFowaSF.mjs} +2 -2
  19. package/dist/{planner-produced-postgres-migration-Bbv8RYKJ.mjs.map → planner-produced-postgres-migration-7FFowaSF.mjs.map} +1 -1
  20. package/dist/planner-produced-postgres-migration.mjs +1 -1
  21. package/dist/planner.mjs +1 -1
  22. package/dist/{postgres-migration-DEefginX.mjs → postgres-migration-DezzqbS6.mjs} +2 -2
  23. package/dist/{postgres-migration-DEefginX.mjs.map → postgres-migration-DezzqbS6.mjs.map} +1 -1
  24. package/package.json +19 -19
  25. package/src/core/default-normalizer.ts +69 -7
  26. package/src/core/migrations/issue-planner.ts +35 -2
  27. package/src/core/migrations/op-factory-call.ts +3 -0
  28. package/src/exports/migration.ts +1 -0
  29. package/dist/default-normalizer-CzV8-QSu.mjs.map +0 -1
  30. package/dist/issue-planner-D5H1VuVP.mjs.map +0 -1
  31. package/dist/op-factory-call-DIdBDwmO.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"planner-D3Pl8LXU.mjs","names":["#lowerer"],"sources":["../src/core/migrations/contract-to-postgres-schema-ir.ts","../src/core/migrations/control-policy.ts","../src/core/migrations/diff-postgres-schema.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR } from '@prisma-next/family-sql/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { PostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\nimport { resolveDdlSchemaForNamespaceStorage } from '../schema-ir/postgres-schema-ir-annotations';\nimport { PostgresTableIR } from '../schema-ir/postgres-table-ir';\n\nexport function contractToPostgresSchemaIR(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresSchemaIR {\n const sqlIr = contractToSchemaIR(contract, options);\n const ownedSchemas =\n contract === null\n ? []\n : Object.values(contract.storage.namespaces)\n .filter((ns) => isPostgresSchema(ns))\n .map((ns) => resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id));\n\n // Build a map of tableName → PostgresRlsPolicy[], resolving the DDL schema\n // name once per namespace (not per policy).\n const policiesByTable = new Map<string, PostgresRlsPolicy[]>();\n if (contract !== null) {\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n const resolvedSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n for (const policy of Object.values(ns.policy)) {\n const resolved =\n resolvedSchema === policy.namespaceId\n ? policy\n : new PostgresRlsPolicy({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId: resolvedSchema,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(resolved);\n policiesByTable.set(policy.tableName, list);\n }\n }\n }\n\n // Attach policies to each table from the relational projection. A policy that\n // references a table absent from the schema IR is a malformed contract — the\n // loop below throws rather than fabricating a stub table.\n const tables: Record<string, PostgresTableIR> = {};\n for (const [tableName, sqlTable] of Object.entries(sqlIr.tables)) {\n tables[tableName] = new PostgresTableIR({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys: sqlTable.foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...(sqlTable.primaryKey !== undefined ? { primaryKey: sqlTable.primaryKey } : {}),\n ...(sqlTable.annotations !== undefined ? { annotations: sqlTable.annotations } : {}),\n ...(sqlTable.checks !== undefined ? { checks: sqlTable.checks } : {}),\n rlsPolicies: policiesByTable.get(tableName) ?? [],\n });\n }\n for (const [tableName, policies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = policies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-schema-ir: policy \"${policyName}\" references table \"${tableName}\" not present in the schema`,\n );\n }\n }\n\n return new PostgresSchemaIR({\n tables,\n roles:\n contract === null\n ? []\n : Object.values(contract.storage.namespaces).flatMap((ns) =>\n isPostgresSchema(ns) ? Object.values(ns.role) : [],\n ),\n pgSchemaName: 'public',\n pgVersion: '',\n existingSchemas: ownedSchemas,\n nativeEnumTypeNames: [],\n });\n}\n","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 { entityAt, UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTable } 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 'createSchema',\n 'createRlsPolicy',\n 'enableRowLevelSecurity',\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 = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\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}\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 };\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 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.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const tableControlPolicy = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: callFields.tableName,\n })?.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 missing_rls_policy: 'createRlsPolicy',\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 ('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 = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: issue.table,\n });\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 { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas } from '@prisma-next/framework-components/control';\nimport { isPostgresRlsPolicy, type PostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { ensurePostgresSchemaIR, type PostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\n\n// Renders a display-only reference string for the diff message. If policy\n// rendering grows, route it through the adapter's SQL renderer so the message\n// can't diverge from the emitted policy SQL.\nfunction renderPostgresPolicyReference(policy: PostgresRlsPolicy): string {\n return `policy \"${policy.name}\" on \"${policy.namespaceId}\".\"${policy.tableName}\"`;\n}\n\n/**\n * Computes schema drift between two derived schema IRs.\n *\n * 1. Runs the framework total diff.\n * 2. Filters to policy-subject issues only — this is transitional: the generic\n * differ walks the whole tree, but the legacy relational verifier still owns\n * table/column drift, so non-policy issues are dropped here.\n * 3. Remaps the message to a human-readable policy reference.\n *\n * Ownership filtering (dropping `extra` issues in namespaces a contract doesn't\n * own) is the caller's responsibility — use `filterIssuesByOwnership`.\n */\nexport function diffPostgresSchema(\n expected: PostgresSchemaIR,\n actual: PostgresSchemaIR,\n): readonly SchemaDiffIssue[] {\n const safeActual = ensurePostgresSchemaIR(actual);\n const issues = diffSchemas(expected, safeActual);\n\n return issues\n .filter((i) => isPostgresRlsPolicy(i.expected ?? i.actual))\n .map((i) => {\n const policy = i.expected ?? i.actual;\n if (!isPostgresRlsPolicy(policy)) return i;\n return { ...i, message: `${i.outcome}: ${renderPostgresPolicyReference(policy)}` };\n });\n}\n\n/**\n * Filters `extra` policy issues to those in owned namespaces. Call after\n * `diffPostgresSchema` with the union of namespace ids from the expected IR's\n * policies and its `existingSchemas`.\n */\nexport function filterIssuesByOwnership(\n issues: readonly SchemaDiffIssue[],\n ownedSchemaNames: ReadonlySet<string>,\n): readonly SchemaDiffIssue[] {\n return issues.filter(\n (i) =>\n i.outcome !== 'extra' ||\n (isPostgresRlsPolicy(i.actual) && ownedSchemaNames.has(i.actual.namespaceId)),\n );\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';\nimport { isPostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\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 a `PostgresSchemaIR`.\n * Defaults to the always-present `public` schema when the schema IR is not a\n * `PostgresSchemaIR` — a fresh Postgres database always carries `public`\n * (unless an operator dropped it manually), so any verifier path that runs\n * without an enriched introspection still suppresses the redundant\n * `CREATE SCHEMA \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and sets `existingSchemas`\n * on the returned `PostgresSchemaIR`. Tests that want to assert against a\n * richer initial state construct a `PostgresSchemaIR` explicitly.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIR): readonly string[] {\n if (isPostgresSchemaIR(schema)) {\n return schema.existingSchemas;\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 { ExecuteRequestLowerer } 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 type { PostgresContract } from '../postgres-schema';\nimport { assertPostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { assertPostgresSchemaIR, ensurePostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\nimport { resolveDdlSchemaForNamespaceStorage } from '../schema-ir/postgres-schema-ir-annotations';\nimport { contractToPostgresSchemaIR } from './contract-to-postgres-schema-ir';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { diffPostgresSchema, filterIssuesByOwnership } from './diff-postgres-schema';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport {\n CreatePostgresRlsPolicyCall,\n DropPostgresRlsPolicyCall,\n EnableRowLevelSecurityCall,\n} 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(\n lowerer: ExecuteRequestLowerer,\n): 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: ExecuteRequestLowerer | undefined;\n\n constructor(lowerer?: ExecuteRequestLowerer) {\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 const schemaDiffCalls = this.planPostgresSchemaDiff(options);\n const schemaDiffPartition = partitionCallsByControlPolicy({\n calls: schemaDiffCalls,\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\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, ...schemaDiffPartition.kept, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...schemaDiffPartition.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 planPostgresSchemaDiff(\n options: PlannerOptionsWithComponents,\n ): readonly PostgresOpFactoryCall[] {\n assertPostgresSchemaIR(options.schema);\n const expected = contractToPostgresSchemaIR(\n blindCast<PostgresContract, 'planPostgresSchemaDiff is only called with a postgres contract'>(\n options.contract,\n ),\n { annotationNamespace: 'pg' },\n );\n const actual = ensurePostgresSchemaIR(options.schema);\n const rawIssues = diffPostgresSchema(expected, actual);\n const ownedSchemaNames = new Set([\n ...expected.rlsPolicies.map((p) => p.namespaceId),\n ...expected.existingSchemas,\n ]);\n const filteredDiffIssues = filterIssuesByOwnership(rawIssues, ownedSchemaNames);\n\n const allowsDestructive = options.policy.allowedOperationClasses.includes('destructive');\n const calls: PostgresOpFactoryCall[] = [];\n const seenEnableTables = new Set<string>();\n\n for (const issue of filteredDiffIssues) {\n // 'mismatch' is unreachable for content-addressed policies: the wire name\n // encodes the body hash, so two policies sharing a local key (same name)\n // are always equal and isEqualTo never returns false.\n if (issue.outcome === 'missing') {\n assertPostgresRlsPolicy(issue.expected);\n // issue.expected.namespaceId is the DDL schema name (resolved during projection);\n // this re-resolution is a no-op as long as PostgresSchema.ddlSchemaName() returns this.id.\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n issue.expected.namespaceId,\n options.schema,\n );\n const tableKey = `${schemaForTable}.${issue.expected.tableName}`;\n if (!seenEnableTables.has(tableKey)) {\n seenEnableTables.add(tableKey);\n calls.push(new EnableRowLevelSecurityCall(schemaForTable, issue.expected.tableName));\n }\n calls.push(\n new CreatePostgresRlsPolicyCall(schemaForTable, issue.expected.tableName, issue.expected),\n );\n } else if (issue.outcome === 'extra' && allowsDestructive) {\n assertPostgresRlsPolicy(issue.actual);\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n issue.actual.namespaceId,\n options.schema,\n );\n calls.push(\n new DropPostgresRlsPolicyCall(schemaForTable, issue.actual.tableName, issue.actual.name),\n );\n }\n }\n\n return calls;\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 };\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 // Schema drift is handled separately via diffPostgresSchema → planPostgresSchemaDiff.\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":";;;;;;;;;;;;;;;AAUA,SAAgB,2BACd,UACA,SACkB;CAClB,MAAM,QAAQ,mBAAmB,UAAU,OAAO;CAClD,MAAM,eACJ,aAAa,OACT,CAAC,IACD,OAA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AQ,SAAS,SACjB,MAAM,OAAO,aACb,QAAQ,MACV;GACA,MAAM,KACJ,IAAI,0BAA0B,gBAAgB,MAAM,OAAO,WAAW,MAAM,OAAO,IAAI,CACzF;EACF;EAGF,OAAO;CACT;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;EAU7E,MAAM,eAAe,gBAAgB;GARnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,IAAI;GAC9B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;EAE0B,CAAC;EAOlD,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-D9Qkrrib.mjs","names":["#lowerer"],"sources":["../src/core/migrations/contract-to-postgres-schema-ir.ts","../src/core/migrations/control-policy.ts","../src/core/migrations/diff-postgres-schema.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR } from '@prisma-next/family-sql/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { PostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\nimport { resolveDdlSchemaForNamespaceStorage } from '../schema-ir/postgres-schema-ir-annotations';\nimport { PostgresTableIR } from '../schema-ir/postgres-table-ir';\n\nexport function contractToPostgresSchemaIR(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresSchemaIR {\n const sqlIr = contractToSchemaIR(contract, options);\n const ownedSchemas =\n contract === null\n ? []\n : Object.values(contract.storage.namespaces)\n .filter((ns) => isPostgresSchema(ns))\n .map((ns) => resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id));\n\n // Build a map of tableName → PostgresRlsPolicy[], resolving the DDL schema\n // name once per namespace (not per policy).\n const policiesByTable = new Map<string, PostgresRlsPolicy[]>();\n if (contract !== null) {\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n const resolvedSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n for (const policy of Object.values(ns.policy)) {\n const resolved =\n resolvedSchema === policy.namespaceId\n ? policy\n : new PostgresRlsPolicy({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId: resolvedSchema,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(resolved);\n policiesByTable.set(policy.tableName, list);\n }\n }\n }\n\n // Attach policies to each table from the relational projection. A policy that\n // references a table absent from the schema IR is a malformed contract — the\n // loop below throws rather than fabricating a stub table.\n const tables: Record<string, PostgresTableIR> = {};\n for (const [tableName, sqlTable] of Object.entries(sqlIr.tables)) {\n tables[tableName] = new PostgresTableIR({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys: sqlTable.foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...(sqlTable.primaryKey !== undefined ? { primaryKey: sqlTable.primaryKey } : {}),\n ...(sqlTable.annotations !== undefined ? { annotations: sqlTable.annotations } : {}),\n ...(sqlTable.checks !== undefined ? { checks: sqlTable.checks } : {}),\n rlsPolicies: policiesByTable.get(tableName) ?? [],\n });\n }\n for (const [tableName, policies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = policies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-schema-ir: policy \"${policyName}\" references table \"${tableName}\" not present in the schema`,\n );\n }\n }\n\n return new PostgresSchemaIR({\n tables,\n roles:\n contract === null\n ? []\n : Object.values(contract.storage.namespaces).flatMap((ns) =>\n isPostgresSchema(ns) ? Object.values(ns.role) : [],\n ),\n pgSchemaName: 'public',\n pgVersion: '',\n existingSchemas: ownedSchemas,\n nativeEnumTypeNames: [],\n });\n}\n","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 { entityAt, UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTable } 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 'createSchema',\n 'createRlsPolicy',\n 'enableRowLevelSecurity',\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 = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\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}\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 };\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 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.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const tableControlPolicy = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: callFields.tableName,\n })?.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 missing_rls_policy: 'createRlsPolicy',\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 ('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 = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: issue.table,\n });\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 { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas } from '@prisma-next/framework-components/control';\nimport { isPostgresRlsPolicy, type PostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { ensurePostgresSchemaIR, type PostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\n\n// Renders a display-only reference string for the diff message. If policy\n// rendering grows, route it through the adapter's SQL renderer so the message\n// can't diverge from the emitted policy SQL.\nfunction renderPostgresPolicyReference(policy: PostgresRlsPolicy): string {\n return `policy \"${policy.name}\" on \"${policy.namespaceId}\".\"${policy.tableName}\"`;\n}\n\n/**\n * Computes schema drift between two derived schema IRs.\n *\n * 1. Runs the framework total diff.\n * 2. Filters to policy-subject issues only — this is transitional: the generic\n * differ walks the whole tree, but the legacy relational verifier still owns\n * table/column drift, so non-policy issues are dropped here.\n * 3. Remaps the message to a human-readable policy reference.\n *\n * Ownership filtering (dropping `extra` issues in namespaces a contract doesn't\n * own) is the caller's responsibility — use `filterIssuesByOwnership`.\n */\nexport function diffPostgresSchema(\n expected: PostgresSchemaIR,\n actual: PostgresSchemaIR,\n): readonly SchemaDiffIssue[] {\n const safeActual = ensurePostgresSchemaIR(actual);\n const issues = diffSchemas(expected, safeActual);\n\n return issues\n .filter((i) => isPostgresRlsPolicy(i.expected ?? i.actual))\n .map((i) => {\n const policy = i.expected ?? i.actual;\n if (!isPostgresRlsPolicy(policy)) return i;\n return { ...i, message: `${i.outcome}: ${renderPostgresPolicyReference(policy)}` };\n });\n}\n\n/**\n * Filters `extra` policy issues to those in owned namespaces. Call after\n * `diffPostgresSchema` with the union of namespace ids from the expected IR's\n * policies and its `existingSchemas`.\n */\nexport function filterIssuesByOwnership(\n issues: readonly SchemaDiffIssue[],\n ownedSchemaNames: ReadonlySet<string>,\n): readonly SchemaDiffIssue[] {\n return issues.filter(\n (i) =>\n i.outcome !== 'extra' ||\n (isPostgresRlsPolicy(i.actual) && ownedSchemaNames.has(i.actual.namespaceId)),\n );\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';\nimport { isPostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\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 a `PostgresSchemaIR`.\n * Defaults to the always-present `public` schema when the schema IR is not a\n * `PostgresSchemaIR` — a fresh Postgres database always carries `public`\n * (unless an operator dropped it manually), so any verifier path that runs\n * without an enriched introspection still suppresses the redundant\n * `CREATE SCHEMA \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and sets `existingSchemas`\n * on the returned `PostgresSchemaIR`. Tests that want to assert against a\n * richer initial state construct a `PostgresSchemaIR` explicitly.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIR): readonly string[] {\n if (isPostgresSchemaIR(schema)) {\n return schema.existingSchemas;\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 { ExecuteRequestLowerer } 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 type { PostgresContract } from '../postgres-schema';\nimport { assertPostgresRlsPolicy } from '../schema-ir/postgres-rls-policy';\nimport { assertPostgresSchemaIR, ensurePostgresSchemaIR } from '../schema-ir/postgres-schema-ir';\nimport { resolveDdlSchemaForNamespaceStorage } from '../schema-ir/postgres-schema-ir-annotations';\nimport { contractToPostgresSchemaIR } from './contract-to-postgres-schema-ir';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { diffPostgresSchema, filterIssuesByOwnership } from './diff-postgres-schema';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport {\n CreatePostgresRlsPolicyCall,\n DropPostgresRlsPolicyCall,\n EnableRowLevelSecurityCall,\n} 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(\n lowerer: ExecuteRequestLowerer,\n): 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: ExecuteRequestLowerer | undefined;\n\n constructor(lowerer?: ExecuteRequestLowerer) {\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 const schemaDiffCalls = this.planPostgresSchemaDiff(options);\n const schemaDiffPartition = partitionCallsByControlPolicy({\n calls: schemaDiffCalls,\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\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, ...schemaDiffPartition.kept, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...schemaDiffPartition.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 planPostgresSchemaDiff(\n options: PlannerOptionsWithComponents,\n ): readonly PostgresOpFactoryCall[] {\n assertPostgresSchemaIR(options.schema);\n const expected = contractToPostgresSchemaIR(\n blindCast<PostgresContract, 'planPostgresSchemaDiff is only called with a postgres contract'>(\n options.contract,\n ),\n { annotationNamespace: 'pg' },\n );\n const actual = ensurePostgresSchemaIR(options.schema);\n const rawIssues = diffPostgresSchema(expected, actual);\n const ownedSchemaNames = new Set([\n ...expected.rlsPolicies.map((p) => p.namespaceId),\n ...expected.existingSchemas,\n ]);\n const filteredDiffIssues = filterIssuesByOwnership(rawIssues, ownedSchemaNames);\n\n const allowsDestructive = options.policy.allowedOperationClasses.includes('destructive');\n const calls: PostgresOpFactoryCall[] = [];\n const seenEnableTables = new Set<string>();\n\n for (const issue of filteredDiffIssues) {\n // 'mismatch' is unreachable for content-addressed policies: the wire name\n // encodes the body hash, so two policies sharing a local key (same name)\n // are always equal and isEqualTo never returns false.\n if (issue.outcome === 'missing') {\n assertPostgresRlsPolicy(issue.expected);\n // issue.expected.namespaceId is the DDL schema name (resolved during projection);\n // this re-resolution is a no-op as long as PostgresSchema.ddlSchemaName() returns this.id.\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n issue.expected.namespaceId,\n options.schema,\n );\n const tableKey = `${schemaForTable}.${issue.expected.tableName}`;\n if (!seenEnableTables.has(tableKey)) {\n seenEnableTables.add(tableKey);\n calls.push(new EnableRowLevelSecurityCall(schemaForTable, issue.expected.tableName));\n }\n calls.push(\n new CreatePostgresRlsPolicyCall(schemaForTable, issue.expected.tableName, issue.expected),\n );\n } else if (issue.outcome === 'extra' && allowsDestructive) {\n assertPostgresRlsPolicy(issue.actual);\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n issue.actual.namespaceId,\n options.schema,\n );\n calls.push(\n new DropPostgresRlsPolicyCall(schemaForTable, issue.actual.tableName, issue.actual.name),\n );\n }\n }\n\n return calls;\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 };\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 // Schema drift is handled separately via diffPostgresSchema → planPostgresSchemaDiff.\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":";;;;;;;;;;;;;;;AAUA,SAAgB,2BACd,UACA,SACkB;CAClB,MAAM,QAAQ,mBAAmB,UAAU,OAAO;CAClD,MAAM,eACJ,aAAa,OACT,CAAC,IACD,OAAO,OAAO,SAAS,QAAQ,UAAU,CAAC,CACvC,QAAQ,OAAO,iBAAiB,EAAE,CAAC,CAAC,CACpC,KAAK,OAAO,oCAAoC,SAAS,SAAS,GAAG,EAAE,CAAC;CAIjF,MAAM,kCAAkB,IAAI,IAAiC;CAC7D,IAAI,aAAa,MACf,KAAK,MAAM,MAAM,OAAO,OAAO,SAAS,QAAQ,UAAU,GAAG;EAC3D,IAAI,CAAC,iBAAiB,EAAE,GAAG;EAC3B,MAAM,iBAAiB,oCAAoC,SAAS,SAAS,GAAG,EAAE;EAClF,KAAK,MAAM,UAAU,OAAO,OAAO,GAAG,MAAM,GAAG;GAC7C,MAAM,WACJ,mBAAmB,OAAO,cACtB,SACA,IAAI,kBAAkB;IACpB,MAAM,OAAO;IACb,QAAQ,OAAO;IACf,WAAW,OAAO;IAClB,aAAa;IACb,WAAW,OAAO;IAClB,OAAO,CAAC,GAAG,OAAO,KAAK;IACvB,GAAG,UAAU,SAAS,OAAO,KAAK;IAClC,GAAG,UAAU,aAAa,OAAO,SAAS;IAC1C,YAAY,OAAO;GACrB,CAAC;GACP,M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AgB,WAAW,GAC7B,OAAO,aAAa,OAAO;EAE7B,OAAO,CAAC,GAAG,iBAAiB,GAAG,aAAa,OAAO,MAAM;CAC3D;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as PostgresMigration } from "./postgres-migration-DEefginX.mjs";
1
+ import { t as PostgresMigration } from "./postgres-migration-DezzqbS6.mjs";
2
2
  import { t as renderOps } from "./render-ops-BREh1kHe.mjs";
3
3
  import { t as renderCallsToTypeScript } from "./render-typescript-7yqILcwr.mjs";
4
4
  //#region src/core/migrations/planner-produced-postgres-migration.ts
@@ -40,4 +40,4 @@ var TypeScriptRenderablePostgresMigration = class extends PostgresMigration {
40
40
  //#endregion
41
41
  export { TypeScriptRenderablePostgresMigration as t };
42
42
 
43
- //# sourceMappingURL=planner-produced-postgres-migration-Bbv8RYKJ.mjs.map
43
+ //# sourceMappingURL=planner-produced-postgres-migration-7FFowaSF.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-produced-postgres-migration-Bbv8RYKJ.mjs","names":["#calls","#meta","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"sourcesContent":["/**\n * Planner-produced Postgres migration.\n *\n * Returned by `PostgresMigrationPlanner.plan(...)` and `emptyMigration(...)`.\n * Holds the migration IR (`PostgresOpFactoryCall[]`) alongside\n * `MigrationMeta` and exposes both the runtime-ops view (`get operations`)\n * and the TypeScript authoring view (`renderTypeScript()`). Satisfies\n * `MigrationPlanWithAuthoringSurface` so the CLI can uniformly serialize any\n * planner result back to `migration.ts`.\n *\n * Extends the family-level `SqlMigration` alias rather than the target-local\n * migration base directly — mirrors Mongo's `PlannerProducedMongoMigration`\n * shape and keeps CLI wiring one step removed from target internals.\n *\n * Placeholder-bearing plans: `renderTypeScript()` always succeeds and embeds\n * `() => placeholder(\"slot\")` at each stub. `operations`, in contrast, is\n * _not safe to enumerate_ on a stub-bearing plan — `DataTransformCall.toOp()`\n * throws `PN-MIG-2001` because a planner-stubbed closure cannot be lowered\n * to a runtime op. Callers that know a plan may carry stubs must render to\n * `migration.ts`, let the user fill the slots, and re-load the edited\n * migration before enumerating ops. The walk-schema planner does not emit\n * `DataTransformCall`s today, so this asymmetry is invisible until the\n * issue-planner integration lands in Phase 2.\n */\n\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport { PostgresMigration } from './postgres-migration';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\nexport class TypeScriptRenderablePostgresMigration\n extends PostgresMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache:\n | readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[]\n | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from the planner options so the runner keys the marker row by\n * the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, { from: this.#meta.from, to: this.#meta.to });\n }\n}\n"],"mappings":";;;;AAqCA,IAAa,wCAAb,cACU,kBAEV;CACE;CACA;CACA;CACA;CACA;CAOA,YACE,OACA,MACA,SACA,SACA;EACA,MAAM;EACN,KAAKA,SAAS;EACd,KAAKC,QAAQ;EACb,KAAKC,WAAW;EAChB,KAAKC,WAAW;CAClB;CAEA,IAAa,aAGT;EACF,KAAKC,qBAAqB,UAAU,KAAKJ,QAAQ,KAAKG,QAAQ;EAC9D,OAAO,KAAKC;CACd;CAEA,WAAmC;EACjC,OAAO,KAAKH;CACd;;;;;;CAOA,IAAI,UAAkB;EACpB,OAAO,KAAKC;CACd;CAEA,mBAA2B;EACzB,OAAO,wBAAwB,KAAKF,QAAQ;GAAE,MAAM,KAAKC,MAAM;GAAM,IAAI,KAAKA,MAAM;EAAG,CAAC;CAC1F;AACF"}
1
+ {"version":3,"file":"planner-produced-postgres-migration-7FFowaSF.mjs","names":["#calls","#meta","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"sourcesContent":["/**\n * Planner-produced Postgres migration.\n *\n * Returned by `PostgresMigrationPlanner.plan(...)` and `emptyMigration(...)`.\n * Holds the migration IR (`PostgresOpFactoryCall[]`) alongside\n * `MigrationMeta` and exposes both the runtime-ops view (`get operations`)\n * and the TypeScript authoring view (`renderTypeScript()`). Satisfies\n * `MigrationPlanWithAuthoringSurface` so the CLI can uniformly serialize any\n * planner result back to `migration.ts`.\n *\n * Extends the family-level `SqlMigration` alias rather than the target-local\n * migration base directly — mirrors Mongo's `PlannerProducedMongoMigration`\n * shape and keeps CLI wiring one step removed from target internals.\n *\n * Placeholder-bearing plans: `renderTypeScript()` always succeeds and embeds\n * `() => placeholder(\"slot\")` at each stub. `operations`, in contrast, is\n * _not safe to enumerate_ on a stub-bearing plan — `DataTransformCall.toOp()`\n * throws `PN-MIG-2001` because a planner-stubbed closure cannot be lowered\n * to a runtime op. Callers that know a plan may carry stubs must render to\n * `migration.ts`, let the user fill the slots, and re-load the edited\n * migration before enumerating ops. The walk-schema planner does not emit\n * `DataTransformCall`s today, so this asymmetry is invisible until the\n * issue-planner integration lands in Phase 2.\n */\n\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport { PostgresMigration } from './postgres-migration';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\nexport class TypeScriptRenderablePostgresMigration\n extends PostgresMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache:\n | readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[]\n | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from the planner options so the runner keys the marker row by\n * the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, { from: this.#meta.from, to: this.#meta.to });\n }\n}\n"],"mappings":";;;;AAqCA,IAAa,wCAAb,cACU,kBAEV;CACE;CACA;CACA;CACA;CACA;CAOA,YACE,OACA,MACA,SACA,SACA;EACA,MAAM;EACN,KAAKA,SAAS;EACd,KAAKC,QAAQ;EACb,KAAKC,WAAW;EAChB,KAAKC,WAAW;CAClB;CAEA,IAAa,aAGT;EACF,KAAKC,qBAAqB,UAAU,KAAKJ,QAAQ,KAAKG,QAAQ;EAC9D,OAAO,KAAKC;CACd;CAEA,WAAmC;EACjC,OAAO,KAAKH;CACd;;;;;;CAOA,IAAI,UAAkB;EACpB,OAAO,KAAKC;CACd;CAEA,mBAA2B;EACzB,OAAO,wBAAwB,KAAKF,QAAQ;GAAE,MAAM,KAAKC,MAAM;GAAM,IAAI,KAAKA,MAAM;EAAG,CAAC;CAC1F;AACF"}
@@ -1,2 +1,2 @@
1
- import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-Bbv8RYKJ.mjs";
1
+ import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-7FFowaSF.mjs";
2
2
  export { TypeScriptRenderablePostgresMigration };
package/dist/planner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as contractToPostgresSchemaIR, n as diffPostgresSchema, r as filterIssuesByOwnership, t as createPostgresMigrationPlanner } from "./planner-D3Pl8LXU.mjs";
1
+ import { i as contractToPostgresSchemaIR, n as diffPostgresSchema, r as filterIssuesByOwnership, t as createPostgresMigrationPlanner } from "./planner-D9Qkrrib.mjs";
2
2
  export { contractToPostgresSchemaIR, createPostgresMigrationPlanner, diffPostgresSchema, filterIssuesByOwnership };
@@ -1,4 +1,4 @@
1
- import { A as installExtension, E as SetNotNullCall, S as DropTableCall, T as SetDefaultCall, _ as DropConstraintCall, b as DropNotNullCall, c as AlterColumnTypeCall, f as CreateSchemaCall, g as DropColumnCall, h as DropCheckConstraintCall, n as AddColumnCall, o as AddPrimaryKeyCall, p as CreateTableCall, r as AddForeignKeyCall, s as AddUniqueCall, t as AddCheckConstraintCall, u as CreateIndexCall, v as DropDefaultCall, y as DropIndexCall } from "./op-factory-call-DIdBDwmO.mjs";
1
+ import { A as installExtension, E as SetNotNullCall, S as DropTableCall, T as SetDefaultCall, _ as DropConstraintCall, b as DropNotNullCall, c as AlterColumnTypeCall, f as CreateSchemaCall, g as DropColumnCall, h as DropCheckConstraintCall, n as AddColumnCall, o as AddPrimaryKeyCall, p as CreateTableCall, r as AddForeignKeyCall, s as AddUniqueCall, t as AddCheckConstraintCall, u as CreateIndexCall, v as DropDefaultCall, y as DropIndexCall } from "./op-factory-call-DArx_1HM.mjs";
2
2
  import { t as errorPostgresMigrationStackMissing } from "./errors-CUk87ByX.mjs";
3
3
  import { t as PostgresContractView } from "./postgres-contract-view-D12LEXT5.mjs";
4
4
  import { t as dataTransform } from "./data-transform-BOWpliq8.mjs";
@@ -161,4 +161,4 @@ var PostgresMigration = class extends Migration {
161
161
  //#endregion
162
162
  export { PostgresMigration as t };
163
163
 
164
- //# sourceMappingURL=postgres-migration-DEefginX.mjs.map
164
+ //# sourceMappingURL=postgres-migration-DezzqbS6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-migration-DEefginX.mjs","names":["SqlMigration","#endView","#startView"],"sources":["../src/core/migrations/postgres-migration.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationContractViews } from '@prisma-next/migration-tools/migration';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { errorPostgresMigrationStackMissing } from '../errors';\nimport { PostgresContractView } from '../postgres-contract-view';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateSchemaCall,\n CreateTableCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { type DataTransformOptions, dataTransform } from './operations/data-transform';\nimport { installExtension } from './operations/dependencies';\nimport type { CreateIndexExtras } from './operations/indexes';\nimport type { ForeignKeySpec } from './operations/shared';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for Postgres migrations.\n *\n * Fixes the `SqlMigration` generic to `PostgresPlanTargetDetails` and the\n * abstract `targetId` to the Postgres target-id string literal, so both\n * user-authored migrations and renderer-generated scaffolds (the output of\n * `renderCallsToTypeScript`) can extend `PostgresMigration` directly without\n * redeclaring target-local identity.\n *\n * Mirrors `MongoMigration` in `@prisma-next/family-mongo`: the renderer\n * emits `extends Migration` against a facade re-export of this class\n * from `@prisma-next/postgres/migration`, keeping the authoring surface\n * target-scoped rather than family-scoped.\n *\n * The constructor materializes a single Postgres `SqlControlAdapter` from\n * `stack.adapter.create(stack)` and stores it; the protected `dataTransform`\n * instance method forwards to the free `dataTransform` factory with that\n * stored adapter, so user migrations can write `this.dataTransform(...)`\n * without threading the adapter through every call.\n *\n * Every method requires an explicit `schema`. Postgres migrations name their\n * schema deliberately — there is no default and no `search_path`-relative\n * option. A migration that left the schema unspecified would resolve against\n * whatever `search_path` the connection happened to carry, and that ambiguity\n * is an antipattern in a migration. (The unbound/unspecified namespace concept\n * remains for SQLite, which has no schemas, and for Mongo's connection `db`.)\n */\nexport abstract class PostgresMigration<\n Start extends Contract<SqlStorage> = Contract<SqlStorage>,\n End extends Contract<SqlStorage> = Contract<SqlStorage>,\n> extends SqlMigration<PostgresPlanTargetDetails, 'postgres', Start, End> {\n readonly targetId = 'postgres' as const;\n\n /**\n * Materialized Postgres control adapter, created once per migration\n * instance from the injected stack. `undefined` only when the migration\n * was instantiated without a stack (test fixtures); `dataTransform`\n * throws in that case to surface the misuse.\n */\n protected readonly controlAdapter: SqlControlAdapter<'postgres'> | undefined;\n\n #endView = new MigrationContractViews<PostgresContractView<End>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<End>(json),\n );\n #startView = new MigrationContractViews<PostgresContractView<Start>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<Start>(json),\n );\n\n constructor(stack?: ControlStack<'sql', 'postgres'>) {\n super(stack);\n // The descriptor `create()` is typed as the wider `ControlAdapterInstance`;\n // the Postgres descriptor concretely returns a `SqlControlAdapter<'postgres'>`,\n // so the cast holds for any Postgres-target stack assembled at runtime.\n this.controlAdapter = stack?.adapter\n ? (stack.adapter.create(stack) as SqlControlAdapter<'postgres'>)\n : undefined;\n }\n\n /**\n * The typed, schema-qualified Postgres view over this migration's end-state\n * contract — `this.endContract.namespace.<schema>.table.<name>`, etc. Throws\n * if no `endContractJson` was provided.\n */\n get endContract(): PostgresContractView<End> {\n return this.#endView.endContract;\n }\n\n /**\n * The typed Postgres view over this migration's start-state contract, or\n * `null` for a baseline migration (no `startContractJson`).\n */\n get startContract(): PostgresContractView<Start> | null {\n return this.#startView.startContract;\n }\n\n /**\n * Instance-method wrapper around the free `dataTransform` factory that\n * supplies the stored control adapter. Authors call this from inside\n * `get operations()`; the adapter argument is hidden from the call site.\n */\n protected dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n ): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return dataTransform(contract, name, options, this.controlAdapter);\n }\n\n /**\n * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createTable(options: {\n readonly schema: string;\n readonly table: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapter);\n }\n\n /**\n * Emit a `CREATE SCHEMA` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapter);\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected addPrimaryKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addUnique(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapter,\n );\n }\n\n protected addCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly column: string;\n readonly values: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapter);\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly kind?: 'foreignKey' | 'unique' | 'primaryKey';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapter);\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropTableCall(options.schema, options.table).toOp(this.controlAdapter);\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected alterColumnType(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly options: AlterColumnTypeOptions;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapter);\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected setDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly defaultSql: string;\n readonly operationClass?: 'additive' | 'widening';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapter);\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected createIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n readonly columns: readonly string[];\n readonly extras?: CreateIndexExtras;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapter);\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapter,\n );\n }\n\n protected installExtension(options: {\n readonly extensionName: string;\n readonly invariantId: string;\n readonly id: string;\n readonly label?: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return installExtension(options, this.controlAdapter);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,IAAsB,oBAAtB,cAGUA,UAAgE;CACxE,WAAoB;;;;;;;CAQpB;CAEA,WAAW,IAAI,uBACb,MACA,sBACC,SAAS,qBAAqB,SAAc,IAAI,CACnD;CACA,aAAa,IAAI,uBACf,MACA,sBACC,SAAS,qBAAqB,SAAgB,IAAI,CACrD;CAEA,YAAY,OAAyC;EACnD,MAAM,KAAK;EAIX,KAAK,iBAAiB,OAAO,UACxB,MAAM,QAAQ,OAAO,KAAK,IAC3B,KAAA;CACN;;;;;;CAOA,IAAI,cAAyC;EAC3C,OAAO,KAAKC,SAAS;CACvB;;;;;CAMA,IAAI,gBAAoD;EACtD,OAAO,KAAKC,WAAW;CACzB;;;;;;CAOA,cACE,UACA,MACA,SAC+D;EAC/D,IAAI,CAAC,KAAK,g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AAqB,SAM6C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,eACT,QAAQ,QACR,QAAQ,OACR,QAAQ,QACR,QAAQ,YACR,QAAQ,cACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,YAAsB,SAI4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBAAgB,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC,KACxE,KAAK,cACP;CACF;CAEA,YAAsB,SAM4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBACT,QAAQ,QACR,QAAQ,OACR,QAAQ,OACR,QAAQ,SACR,QAAQ,MACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,UAAoB,SAI8C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,cAAc,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC,CAAC,KACrE,KAAK,cACP;CACF;CAEA,iBAA2B,SAKuC;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,iBAAiB,SAAS,KAAK,cAAc;CACtD;AACF"}
1
+ {"version":3,"file":"postgres-migration-DezzqbS6.mjs","names":["SqlMigration","#endView","#startView"],"sources":["../src/core/migrations/postgres-migration.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationContractViews } from '@prisma-next/migration-tools/migration';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { errorPostgresMigrationStackMissing } from '../errors';\nimport { PostgresContractView } from '../postgres-contract-view';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateSchemaCall,\n CreateTableCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { type DataTransformOptions, dataTransform } from './operations/data-transform';\nimport { installExtension } from './operations/dependencies';\nimport type { CreateIndexExtras } from './operations/indexes';\nimport type { ForeignKeySpec } from './operations/shared';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for Postgres migrations.\n *\n * Fixes the `SqlMigration` generic to `PostgresPlanTargetDetails` and the\n * abstract `targetId` to the Postgres target-id string literal, so both\n * user-authored migrations and renderer-generated scaffolds (the output of\n * `renderCallsToTypeScript`) can extend `PostgresMigration` directly without\n * redeclaring target-local identity.\n *\n * Mirrors `MongoMigration` in `@prisma-next/family-mongo`: the renderer\n * emits `extends Migration` against a facade re-export of this class\n * from `@prisma-next/postgres/migration`, keeping the authoring surface\n * target-scoped rather than family-scoped.\n *\n * The constructor materializes a single Postgres `SqlControlAdapter` from\n * `stack.adapter.create(stack)` and stores it; the protected `dataTransform`\n * instance method forwards to the free `dataTransform` factory with that\n * stored adapter, so user migrations can write `this.dataTransform(...)`\n * without threading the adapter through every call.\n *\n * Every method requires an explicit `schema`. Postgres migrations name their\n * schema deliberately — there is no default and no `search_path`-relative\n * option. A migration that left the schema unspecified would resolve against\n * whatever `search_path` the connection happened to carry, and that ambiguity\n * is an antipattern in a migration. (The unbound/unspecified namespace concept\n * remains for SQLite, which has no schemas, and for Mongo's connection `db`.)\n */\nexport abstract class PostgresMigration<\n Start extends Contract<SqlStorage> = Contract<SqlStorage>,\n End extends Contract<SqlStorage> = Contract<SqlStorage>,\n> extends SqlMigration<PostgresPlanTargetDetails, 'postgres', Start, End> {\n readonly targetId = 'postgres' as const;\n\n /**\n * Materialized Postgres control adapter, created once per migration\n * instance from the injected stack. `undefined` only when the migration\n * was instantiated without a stack (test fixtures); `dataTransform`\n * throws in that case to surface the misuse.\n */\n protected readonly controlAdapter: SqlControlAdapter<'postgres'> | undefined;\n\n #endView = new MigrationContractViews<PostgresContractView<End>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<End>(json),\n );\n #startView = new MigrationContractViews<PostgresContractView<Start>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<Start>(json),\n );\n\n constructor(stack?: ControlStack<'sql', 'postgres'>) {\n super(stack);\n // The descriptor `create()` is typed as the wider `ControlAdapterInstance`;\n // the Postgres descriptor concretely returns a `SqlControlAdapter<'postgres'>`,\n // so the cast holds for any Postgres-target stack assembled at runtime.\n this.controlAdapter = stack?.adapter\n ? (stack.adapter.create(stack) as SqlControlAdapter<'postgres'>)\n : undefined;\n }\n\n /**\n * The typed, schema-qualified Postgres view over this migration's end-state\n * contract — `this.endContract.namespace.<schema>.table.<name>`, etc. Throws\n * if no `endContractJson` was provided.\n */\n get endContract(): PostgresContractView<End> {\n return this.#endView.endContract;\n }\n\n /**\n * The typed Postgres view over this migration's start-state contract, or\n * `null` for a baseline migration (no `startContractJson`).\n */\n get startContract(): PostgresContractView<Start> | null {\n return this.#startView.startContract;\n }\n\n /**\n * Instance-method wrapper around the free `dataTransform` factory that\n * supplies the stored control adapter. Authors call this from inside\n * `get operations()`; the adapter argument is hidden from the call site.\n */\n protected dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n ): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return dataTransform(contract, name, options, this.controlAdapter);\n }\n\n /**\n * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createTable(options: {\n readonly schema: string;\n readonly table: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapter);\n }\n\n /**\n * Emit a `CREATE SCHEMA` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapter);\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected addPrimaryKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addUnique(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapter,\n );\n }\n\n protected addCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly column: string;\n readonly values: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapter);\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly kind?: 'foreignKey' | 'unique' | 'primaryKey';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapter);\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropTableCall(options.schema, options.table).toOp(this.controlAdapter);\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected alterColumnType(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly options: AlterColumnTypeOptions;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapter);\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected setDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly defaultSql: string;\n readonly operationClass?: 'additive' | 'widening';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapter);\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected createIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n readonly columns: readonly string[];\n readonly extras?: CreateIndexExtras;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapter);\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapter,\n );\n }\n\n protected installExtension(options: {\n readonly extensionName: string;\n readonly invariantId: string;\n readonly id: string;\n readonly label?: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return installExtension(options, this.controlAdapter);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,IAAsB,oBAAtB,cAGUA,UAAgE;CACxE,WAAoB;;;;;;;CAQpB;CAEA,WAAW,IAAI,uBACb,MACA,sBACC,SAAS,qBAAqB,SAAc,IAAI,CACnD;CACA,aAAa,IAAI,uBACf,MACA,sBACC,SAAS,qBAAqB,SAAgB,IAAI,CACrD;CAEA,YAAY,OAAyC;EACnD,MAAM,KAAK;EAIX,KAAK,iBAAiB,OAAO,UACxB,MAAM,QAAQ,OAAO,KAAK,IAC3B,KAAA;CACN;;;;;;CAOA,IAAI,cAAyC;EAC3C,OAAO,KAAKC,SAAS;CACvB;;;;;CAMA,IAAI,gBAAoD;EACtD,OAAO,KAAKC,WAAW;CACz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,OAAO,QAAQ,MAAM,CAAC,CAAC,KACxE,KAAK,cACP;CACF;CAEA,WAAqB,SAM6C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,eACT,QAAQ,QACR,QAAQ,OACR,QAAQ,QACR,QAAQ,YACR,QAAQ,cACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,YAAsB,SAI4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBAAgB,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC,KACxE,KAAK,cACP;CACF;CAEA,YAAsB,SAM4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBACT,QAAQ,QACR,QAAQ,OACR,QAAQ,OACR,QAAQ,SACR,QAAQ,MACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,UAAoB,SAI8C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,cAAc,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC,CAAC,KACrE,KAAK,cACP;CACF;CAEA,iBAA2B,SAKuC;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,iBAAiB,SAAS,KAAK,cAAc;CACtD;AACF"}
package/package.json CHANGED
@@ -1,34 +1,34 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.14.0-dev.35",
3
+ "version": "0.14.0-dev.36",
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.14.0-dev.35",
10
- "@prisma-next/contract": "0.14.0-dev.35",
11
- "@prisma-next/errors": "0.14.0-dev.35",
12
- "@prisma-next/family-sql": "0.14.0-dev.35",
13
- "@prisma-next/framework-components": "0.14.0-dev.35",
14
- "@prisma-next/migration-tools": "0.14.0-dev.35",
15
- "@prisma-next/ts-render": "0.14.0-dev.35",
16
- "@prisma-next/sql-contract": "0.14.0-dev.35",
17
- "@prisma-next/sql-errors": "0.14.0-dev.35",
18
- "@prisma-next/sql-operations": "0.14.0-dev.35",
19
- "@prisma-next/sql-relational-core": "0.14.0-dev.35",
20
- "@prisma-next/sql-schema-ir": "0.14.0-dev.35",
21
- "@prisma-next/utils": "0.14.0-dev.35",
9
+ "@prisma-next/cli": "0.14.0-dev.36",
10
+ "@prisma-next/contract": "0.14.0-dev.36",
11
+ "@prisma-next/errors": "0.14.0-dev.36",
12
+ "@prisma-next/family-sql": "0.14.0-dev.36",
13
+ "@prisma-next/framework-components": "0.14.0-dev.36",
14
+ "@prisma-next/migration-tools": "0.14.0-dev.36",
15
+ "@prisma-next/ts-render": "0.14.0-dev.36",
16
+ "@prisma-next/sql-contract": "0.14.0-dev.36",
17
+ "@prisma-next/sql-errors": "0.14.0-dev.36",
18
+ "@prisma-next/sql-operations": "0.14.0-dev.36",
19
+ "@prisma-next/sql-relational-core": "0.14.0-dev.36",
20
+ "@prisma-next/sql-schema-ir": "0.14.0-dev.36",
21
+ "@prisma-next/utils": "0.14.0-dev.36",
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/psl-parser": "0.14.0-dev.35",
28
- "@prisma-next/sql-contract-psl": "0.14.0-dev.35",
29
- "@prisma-next/test-utils": "0.14.0-dev.35",
30
- "@prisma-next/tsconfig": "0.14.0-dev.35",
31
- "@prisma-next/tsdown": "0.14.0-dev.35",
27
+ "@prisma-next/psl-parser": "0.14.0-dev.36",
28
+ "@prisma-next/sql-contract-psl": "0.14.0-dev.36",
29
+ "@prisma-next/test-utils": "0.14.0-dev.36",
30
+ "@prisma-next/tsconfig": "0.14.0-dev.36",
31
+ "@prisma-next/tsdown": "0.14.0-dev.36",
32
32
  "tsdown": "0.22.1",
33
33
  "typescript": "5.9.3",
34
34
  "vitest": "4.1.8"
@@ -58,6 +58,63 @@ function canonicalizeTimestampDefault(expr: string): string | undefined {
58
58
  return undefined;
59
59
  }
60
60
 
61
+ type ArrayElementToken = { readonly value: string; readonly quoted: boolean };
62
+
63
+ /**
64
+ * Splits a Postgres array literal body (without the enclosing braces) into its
65
+ * element tokens, honouring quoting. A comma only separates elements when it is
66
+ * outside double quotes; inside a quoted element a doubled quote (`""`) or a
67
+ * backslash-escaped quote (`\"`) is a literal quote, and a backslash escapes the
68
+ * next character. Returns undefined if the body is malformed (e.g. an unbalanced
69
+ * quote).
70
+ */
71
+ function splitArrayElements(inner: string): readonly ArrayElementToken[] | undefined {
72
+ const tokens: ArrayElementToken[] = [];
73
+ let current = '';
74
+ let inQuotes = false;
75
+ let quoted = false;
76
+
77
+ for (let i = 0; i < inner.length; i++) {
78
+ const char = inner[i];
79
+ if (inQuotes) {
80
+ if (char === '\\') {
81
+ const next = inner[i + 1];
82
+ if (next === undefined) return undefined;
83
+ current += next;
84
+ i++;
85
+ continue;
86
+ }
87
+ if (char === '"') {
88
+ if (inner[i + 1] === '"') {
89
+ current += '"';
90
+ i++;
91
+ continue;
92
+ }
93
+ inQuotes = false;
94
+ continue;
95
+ }
96
+ current += char;
97
+ continue;
98
+ }
99
+ if (char === '"') {
100
+ inQuotes = true;
101
+ quoted = true;
102
+ continue;
103
+ }
104
+ if (char === ',') {
105
+ tokens.push({ value: current, quoted });
106
+ current = '';
107
+ quoted = false;
108
+ continue;
109
+ }
110
+ current += char;
111
+ }
112
+
113
+ if (inQuotes) return undefined;
114
+ tokens.push({ value: current, quoted });
115
+ return tokens;
116
+ }
117
+
61
118
  /**
62
119
  * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.
63
120
  * Returns undefined if the body cannot be reliably parsed.
@@ -65,14 +122,23 @@ function canonicalizeTimestampDefault(expr: string): string | undefined {
65
122
  * Handles:
66
123
  * - `{}` → `[]`
67
124
  * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion
125
+ * - quoted elements that contain commas, doubled/escaped quotes, and the literal
126
+ * strings `NULL`/`true`/`false` (a quoted token is always a string)
68
127
  */
69
128
  function parseArrayLiteralBody(body: string): readonly JsonValue[] | undefined {
70
129
  const inner = body.slice(1, -1).trim();
71
130
  if (inner === '') return [];
72
- const elements = inner.split(',');
131
+ const tokens = splitArrayElements(inner);
132
+ if (tokens === undefined) return undefined;
73
133
  const result: JsonValue[] = [];
74
- for (const rawEl of elements) {
75
- const el = rawEl.trim();
134
+ for (const token of tokens) {
135
+ if (token.quoted) {
136
+ // A quoted token is always a string — `"NULL"`, `"true"`, `"1"` are the
137
+ // literal text, never the keyword/number.
138
+ result.push(token.value);
139
+ continue;
140
+ }
141
+ const el = token.value.trim();
76
142
  if (el.toUpperCase() === 'NULL') {
77
143
  result.push(null);
78
144
  continue;
@@ -89,10 +155,6 @@ function parseArrayLiteralBody(body: string): readonly JsonValue[] | undefined {
89
155
  result.push(Number(el));
90
156
  continue;
91
157
  }
92
- if (el.startsWith('"') && el.endsWith('"')) {
93
- result.push(el.slice(1, -1).replace(/""/g, '"'));
94
- continue;
95
- }
96
158
  return undefined;
97
159
  }
98
160
  return result;
@@ -31,6 +31,7 @@ import { blindCast } from '@prisma-next/utils/casts';
31
31
  import { ifDefined } from '@prisma-next/utils/defined';
32
32
  import type { Result } from '@prisma-next/utils/result';
33
33
  import { notOk, ok } from '@prisma-next/utils/result';
34
+ import { quoteIdentifier } from '../sql-utils';
34
35
  import {
35
36
  AddColumnCall,
36
37
  AddForeignKeyCall,
@@ -67,6 +68,26 @@ import { resolveColumnTypeMetadata } from './planner-type-resolution';
67
68
 
68
69
  export type { CallMigrationStrategy, StrategyContext };
69
70
 
71
+ /**
72
+ * Deterministic name for the element-non-null CHECK constraint on a scalar-array
73
+ * column. Distinct `_elem_not_null` suffix avoids collision with the enum
74
+ * value-set `_check` constraints. Re-emitting the same schema produces the same
75
+ * name, so `pg_get_constraintdef`-based verify sees no drift.
76
+ */
77
+ function elementNonNullCheckName(tableName: string, columnName: string): string {
78
+ return `${tableName}_${columnName}_elem_not_null`;
79
+ }
80
+
81
+ /**
82
+ * Predicate enforcing that a scalar-array column carries no NULL element. The
83
+ * array column itself may be NULL (container nullability is the column's NOT NULL
84
+ * clause); `array_position` over a NULL array yields NULL, which a CHECK treats
85
+ * as satisfied, so a nullable array column is unaffected.
86
+ */
87
+ function elementNonNullCheckExpression(columnName: string): string {
88
+ return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;
89
+ }
90
+
70
91
  // ============================================================================
71
92
  // Issue kind ordering (dependency order)
72
93
  // ============================================================================
@@ -254,16 +275,28 @@ function mapIssueToCall(
254
275
  );
255
276
  }
256
277
  const schemaForTable = tableSchema(issue);
278
+ const missingTableName = issue.table;
257
279
  const ddlColumns: DdlColumn[] = Object.entries(contractTable.columns).map(([name, column]) =>
258
280
  toDdlColumn(name, column, codecHooks, storageTypes),
259
281
  );
260
- const ddlConstraints: DdlTableConstraint[] | undefined = contractTable.primaryKey
282
+ const primaryKeyConstraints: DdlTableConstraint[] = contractTable.primaryKey
261
283
  ? [
262
284
  contractFree.primaryKey(contractTable.primaryKey.columns, {
263
285
  ...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } : {}),
264
286
  }),
265
287
  ]
266
- : undefined;
288
+ : [];
289
+ const elementNonNullChecks: DdlTableConstraint[] = Object.entries(contractTable.columns)
290
+ .filter(([, column]) => column.many === true)
291
+ .map(([columnName]) =>
292
+ contractFree.checkExpression(
293
+ elementNonNullCheckName(missingTableName, columnName),
294
+ elementNonNullCheckExpression(columnName),
295
+ ),
296
+ );
297
+ const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];
298
+ const ddlConstraints: DdlTableConstraint[] | undefined =
299
+ allTableConstraints.length > 0 ? allTableConstraints : undefined;
267
300
  const calls: PostgresOpFactoryCall[] = [
268
301
  new CreateTableCall(schemaForTable, issue.table, ddlColumns, ddlConstraints),
269
302
  ];
@@ -168,6 +168,8 @@ function renderDdlConstraintAsTsCall(constraint: DdlTableConstraint): string {
168
168
  const nameOpt = constraint.name ? `, { name: ${jsonToTsSource(constraint.name)} }` : '';
169
169
  return `unique(${jsonToTsSource(constraint.columns)}${nameOpt})`;
170
170
  }
171
+ case 'check-expression':
172
+ return `checkExpression(${jsonToTsSource(constraint.name)}, ${jsonToTsSource(constraint.expression)})`;
171
173
  }
172
174
  }
173
175
 
@@ -182,6 +184,7 @@ function constraintImportSymbols(constraints: readonly DdlTableConstraint[] | un
182
184
  if (c.kind === 'primary-key') symbols.add('primaryKey');
183
185
  else if (c.kind === 'foreign-key') symbols.add('foreignKey');
184
186
  else if (c.kind === 'unique') symbols.add('unique');
187
+ else if (c.kind === 'check-expression') symbols.add('checkExpression');
185
188
  }
186
189
  return [...symbols];
187
190
  }
@@ -10,6 +10,7 @@ export { MigrationCLI } from '@prisma-next/cli/migration-cli';
10
10
  // directly. The planner emits an import from this same module.
11
11
  export { placeholder } from '@prisma-next/errors/migration';
12
12
  export {
13
+ checkExpression,
13
14
  col,
14
15
  fn,
15
16
  foreignKey,