@prisma-next/target-postgres 0.16.0-dev.32 → 0.16.0-dev.34

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 (87) hide show
  1. package/README.md +4 -0
  2. package/dist/{authoring-DnO1B0N9.mjs → authoring-DL-Y8A7_.mjs} +5 -5
  3. package/dist/{authoring-DnO1B0N9.mjs.map → authoring-DL-Y8A7_.mjs.map} +1 -1
  4. package/dist/codec-descriptor-C4SaWX0P.d.mts +36 -0
  5. package/dist/codec-descriptor-C4SaWX0P.d.mts.map +1 -0
  6. package/dist/codec-descriptor-cuAuPE0Y.mjs +142 -0
  7. package/dist/codec-descriptor-cuAuPE0Y.mjs.map +1 -0
  8. package/dist/codec-descriptor.d.mts +2 -0
  9. package/dist/codec-descriptor.mjs +2 -0
  10. package/dist/{codec-types-DdoPc2dy.d.mts → codec-types-Bstec0HR.d.mts} +9 -8
  11. package/dist/codec-types-Bstec0HR.d.mts.map +1 -0
  12. package/dist/codec-types.d.mts +1 -1
  13. package/dist/{codecs-Deand7sy.mjs → codecs-C-VA-quH.mjs} +228 -40
  14. package/dist/codecs-C-VA-quH.mjs.map +1 -0
  15. package/dist/{codecs-CGE5dh94.d.mts → codecs-Cd4TftwI.d.mts} +82 -29
  16. package/dist/codecs-Cd4TftwI.d.mts.map +1 -0
  17. package/dist/codecs.d.mts +4 -2
  18. package/dist/codecs.d.mts.map +1 -1
  19. package/dist/codecs.mjs +4 -2
  20. package/dist/codecs.mjs.map +1 -1
  21. package/dist/contract-free.mjs +2 -2
  22. package/dist/{control-policy-DEwdS3oK.mjs → control-policy-DMZVl4x7.mjs} +8 -8
  23. package/dist/{control-policy-DEwdS3oK.mjs.map → control-policy-DMZVl4x7.mjs.map} +1 -1
  24. package/dist/control.mjs +9 -9
  25. package/dist/{ddl-BQC6u-L9.mjs → ddl-Db1JOIMn.mjs} +2 -2
  26. package/dist/{ddl-BQC6u-L9.mjs.map → ddl-Db1JOIMn.mjs.map} +1 -1
  27. package/dist/{descriptor-meta-DGlJurgA.mjs → descriptor-meta-AnueS0OA.mjs} +4 -4
  28. package/dist/{descriptor-meta-DGlJurgA.mjs.map → descriptor-meta-AnueS0OA.mjs.map} +1 -1
  29. package/dist/{diff-database-schema-qRPwuYBH.mjs → diff-database-schema-CluGQkmh.mjs} +8 -8
  30. package/dist/{diff-database-schema-qRPwuYBH.mjs.map → diff-database-schema-CluGQkmh.mjs.map} +1 -1
  31. package/dist/diff-database-schema.mjs +1 -1
  32. package/dist/{errors-DBSNx7EJ.mjs → errors-l1usFTuz.mjs} +2 -2
  33. package/dist/{errors-DBSNx7EJ.mjs.map → errors-l1usFTuz.mjs.map} +1 -1
  34. package/dist/errors.d.mts +1 -1
  35. package/dist/errors.mjs +1 -1
  36. package/dist/issue-planner.mjs +1 -1
  37. package/dist/migration.mjs +2 -2
  38. package/dist/{op-factory-call-CIaPDDUc.mjs → op-factory-call-Cm13qr4w.mjs} +7 -7
  39. package/dist/{op-factory-call-CIaPDDUc.mjs.map → op-factory-call-Cm13qr4w.mjs.map} +1 -1
  40. package/dist/op-factory-call.mjs +1 -1
  41. package/dist/pack.d.mts +2 -2
  42. package/dist/pack.mjs +1 -1
  43. package/dist/{planner-BhnkIJX-.mjs → planner-CB0e-x6l.mjs} +9 -9
  44. package/dist/{planner-BhnkIJX-.mjs.map → planner-CB0e-x6l.mjs.map} +1 -1
  45. package/dist/{planner-ddl-builders-CVo3L7Nd.mjs → planner-ddl-builders-DX8DHY8D.mjs} +4 -4
  46. package/dist/{planner-ddl-builders-CVo3L7Nd.mjs.map → planner-ddl-builders-DX8DHY8D.mjs.map} +1 -1
  47. package/dist/planner-ddl-builders.mjs +1 -1
  48. package/dist/{planner-produced-postgres-migration-BE3EJIRK.mjs → planner-produced-postgres-migration-B0i-PVar.mjs} +3 -3
  49. package/dist/{planner-produced-postgres-migration-BE3EJIRK.mjs.map → planner-produced-postgres-migration-B0i-PVar.mjs.map} +1 -1
  50. package/dist/planner-produced-postgres-migration.mjs +1 -1
  51. package/dist/{planner-sql-checks-CmiQ6Nei.mjs → planner-sql-checks-D3Xsln1p.mjs} +3 -3
  52. package/dist/{planner-sql-checks-CmiQ6Nei.mjs.map → planner-sql-checks-D3Xsln1p.mjs.map} +1 -1
  53. package/dist/planner-sql-checks.mjs +1 -1
  54. package/dist/planner.mjs +2 -2
  55. package/dist/{postgres-contract-view-BeIEyZfD.mjs → postgres-contract-view-v-zxqBtj.mjs} +4 -4
  56. package/dist/{postgres-contract-view-BeIEyZfD.mjs.map → postgres-contract-view-v-zxqBtj.mjs.map} +1 -1
  57. package/dist/{postgres-migration--BzvpA92.mjs → postgres-migration-D_6w1hJj.mjs} +5 -5
  58. package/dist/{postgres-migration--BzvpA92.mjs.map → postgres-migration-D_6w1hJj.mjs.map} +1 -1
  59. package/dist/{postgres-native-enum-BwVNf0Ku.mjs → postgres-native-enum-DqjHPN11.mjs} +2 -2
  60. package/dist/{postgres-native-enum-BwVNf0Ku.mjs.map → postgres-native-enum-DqjHPN11.mjs.map} +1 -1
  61. package/dist/{postgres-role-schema-node-bg32e7I-.mjs → postgres-role-schema-node-DOkim7QI.mjs} +3 -3
  62. package/dist/{postgres-role-schema-node-bg32e7I-.mjs.map → postgres-role-schema-node-DOkim7QI.mjs.map} +1 -1
  63. package/dist/{postgres-schema-CTplQZDK.mjs → postgres-schema-DAhXnFac.mjs} +4 -4
  64. package/dist/{postgres-schema-CTplQZDK.mjs.map → postgres-schema-DAhXnFac.mjs.map} +1 -1
  65. package/dist/{postgres-table-schema-node-D6LvInCe.mjs → postgres-table-schema-node-DXzwiu16.mjs} +2 -2
  66. package/dist/{postgres-table-schema-node-D6LvInCe.mjs.map → postgres-table-schema-node-DXzwiu16.mjs.map} +1 -1
  67. package/dist/{render-ops-TcY9XEkz.mjs → render-ops-DIjVRr1-.mjs} +2 -2
  68. package/dist/{render-ops-TcY9XEkz.mjs.map → render-ops-DIjVRr1-.mjs.map} +1 -1
  69. package/dist/render-ops.mjs +1 -1
  70. package/dist/{resolve-ddl-schema-BAsJEKW8.mjs → resolve-ddl-schema-nTvL_9Nq.mjs} +2 -2
  71. package/dist/{resolve-ddl-schema-BAsJEKW8.mjs.map → resolve-ddl-schema-nTvL_9Nq.mjs.map} +1 -1
  72. package/dist/runtime.mjs +1 -1
  73. package/dist/schema-ir-annotations.mjs +1 -1
  74. package/dist/{sql-utils-B2lzkKfP.mjs → sql-utils-CuKSscKn.mjs} +2 -2
  75. package/dist/{sql-utils-B2lzkKfP.mjs.map → sql-utils-CuKSscKn.mjs.map} +1 -1
  76. package/dist/sql-utils.mjs +1 -1
  77. package/dist/types.mjs +4 -4
  78. package/package.json +21 -20
  79. package/src/core/codec-descriptor.ts +318 -0
  80. package/src/core/codec-type-map.ts +12 -14
  81. package/src/core/codecs.ts +232 -39
  82. package/src/core/registry.ts +4 -0
  83. package/src/exports/codec-descriptor.ts +11 -0
  84. package/src/exports/codecs.ts +4 -1
  85. package/dist/codec-types-DdoPc2dy.d.mts.map +0 -1
  86. package/dist/codecs-CGE5dh94.d.mts.map +0 -1
  87. package/dist/codecs-Deand7sy.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"control-policy-DEwdS3oK.mjs","names":[],"sources":["../src/core/schema-ir/node-storage-coordinate.ts","../src/core/migrations/column-ddl-rendering.ts","../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/control-policy.ts"],"sourcesContent":["import type { EntityCoordinate } from '@prisma-next/framework-components/ir';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { PostgresNativeEnumSchemaNode } from './postgres-native-enum-schema-node';\nimport { PostgresTableSchemaNode } from './postgres-table-schema-node';\nimport { postgresNodeEntityKind } from './schema-node-kinds';\n\n/**\n * The storage-`entries` coordinate `(entityKind, entityName)` a Postgres diff\n * node addresses — a table by its name, a native enum by its physical type\n * name. `undefined` for a node that is not a whole storage entity (a namespace,\n * a column, a policy). Lets ownership/subject resolution treat every entity kind\n * uniformly, the node self-describing its storage identity.\n */\nexport function postgresNodeStorageCoordinate(\n node: SqlSchemaIRNode,\n): Pick<EntityCoordinate, 'entityKind' | 'entityName'> | undefined {\n if (PostgresTableSchemaNode.is(node)) {\n const entityKind = postgresNodeEntityKind(node.nodeKind);\n return entityKind === undefined ? undefined : { entityKind, entityName: node.name };\n }\n if (PostgresNativeEnumSchemaNode.is(node)) {\n const entityKind = postgresNodeEntityKind(node.nodeKind);\n return entityKind === undefined ? undefined : { entityKind, entityName: node.typeName };\n }\n return undefined;\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn } from '@prisma-next/sql-relational-core/ast';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport type { SqlColumnDefaultIR, SqlColumnIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { InternalError } from '@prisma-next/utils/internal-error';\nimport { postgresDefaultToDdlColumnDefault } from './op-factory-call';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport { buildExpectedFormatType } from './planner-sql-checks';\n\n/**\n * Reconstructs the `StorageColumn`-shaped fields the DDL builder functions\n * (`buildColumnTypeSql`, `buildExpectedFormatType`, `resolveIdentityValue`)\n * expect, from a column node's own stamped codec identity (`codecRef` /\n * `codecBaseNativeType` / `codecNamedType`, Decision 5) — never the\n * contract. The builders were written against `StorageColumn` and are\n * unchanged here; only the shape feeding them moves from the contract to\n * the node. An empty `storageTypes` catalog is passed alongside: the\n * node's fields are already resolved past any `typeRef` indirection, so no\n * live lookup is needed, and passing a non-empty catalog would risk a\n * false `typeRef` hit against an unrelated storage type.\n */\nfunction columnLike(\n column: SqlColumnIR,\n): Pick<\n StorageColumn,\n 'nativeType' | 'codecId' | 'nullable' | 'many' | 'typeParams' | 'typeRef' | 'default'\n> {\n if (column.codecRef === undefined || column.codecBaseNativeType === undefined) {\n throw new InternalError(\n `columnLike: expected column \"${column.name}\" carries no codec identity — the expected tree must be derived via contractToSchemaIR for planning`,\n );\n }\n return {\n nativeType: column.codecBaseNativeType,\n codecId: column.codecRef.codecId,\n nullable: column.nullable,\n // `column.many` is unset on contract-derived columns (array-ness rides\n // on the `nativeType` `[]` suffix there instead) — `codecRef.many`\n // carries it. Hand-built/introspected columns set `column.many` directly.\n ...ifDefined('many', column.many ?? column.codecRef.many),\n ...ifDefined(\n 'typeParams',\n column.codecRef.typeParams !== undefined\n ? blindCast<\n Record<string, unknown>,\n 'CodecRef.typeParams is JsonValue-shaped; the DDL builders only ever read it as the Record the contract column originally carried'\n >(column.codecRef.typeParams)\n : undefined,\n ),\n ...(column.codecNamedType ? { typeRef: '<resolved>' } : {}),\n ...ifDefined('default', column.resolvedDefault),\n };\n}\n\n/**\n * Builds the `CREATE TABLE` / `ADD COLUMN` DDL column for an expected column\n * node, resolving type rendering from the node's codec identity against the\n * codec hooks the caller holds — the same builder the pre-`plan(start, end)`\n * op-path called, so the output is byte-identical.\n */\nexport function renderColumnDdl(\n name: string,\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): DdlColumn {\n const like = columnLike(column);\n const typeSql = buildColumnTypeSql(like, codecHooks, {});\n const ddlDefault = postgresDefaultToDdlColumnDefault(like.default);\n return contractFree.col(name, typeSql, {\n ...(!column.nullable ? { notNull: true } : {}),\n ...ifDefined('default', ddlDefault),\n ...ifDefined('codecRef', column.codecRef),\n });\n}\n\n/**\n * Builds the `ALTER COLUMN … TYPE` operands for an expected column node.\n */\nexport function renderColumnAlterType(\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): { readonly qualifiedTargetType: string; readonly formatTypeExpected: string } {\n const like = columnLike(column);\n return {\n qualifiedTargetType: buildColumnTypeSql(like, codecHooks, {}, false),\n formatTypeExpected: buildExpectedFormatType(like, codecHooks, {}),\n };\n}\n\n/**\n * Resolves the identity value (monoid neutral element) SQL literal used as\n * the temporary default when adding a NOT-NULL column with no contract\n * default (`notNullAddColumnCallStrategy`'s shared-temp-default backfill).\n * `null` when the column's type has no built-in/codec-provided identity\n * value.\n */\nexport function resolveColumnTemporaryDefault(\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): string | null {\n return resolveIdentityValue(columnLike(column), codecHooks, {});\n}\n\n/**\n * The column's `SET DEFAULT` clause SQL, resolved from a column-default\n * diff node. `''` when the node carries no resolved default.\n */\nexport function renderColumnDefaultSql(defaultNode: SqlColumnDefaultIR): string {\n if (defaultNode.resolved === undefined) return '';\n return buildColumnDefaultSql(defaultNode.resolved, {\n nativeType: defaultNode.nativeTypeContext ?? '',\n ...ifDefined('many', defaultNode.many),\n });\n}\n","/**\n * Migration strategies.\n *\n * Each strategy examines the node-typed diff-issue list, consumes issues it\n * handles, and returns the `PostgresOpFactoryCall[]` to address them. The\n * issue planner runs each strategy in order and routes whatever's left\n * through `mapNodeIssueToCall`.\n *\n * The full ordered list is exported as `postgresPlannerStrategies` and is\n * used unchanged by both `migration plan` and `db update` / `db init`. The\n * two journeys differ only in `policy.allowedOperationClasses`:\n *\n * - When `'data'` is in the policy, data-safe strategies (NOT NULL backfill,\n * nullability tightening, unsafe type changes) emit\n * `DataTransformCall` placeholders that the user fills in.\n * - When `'data'` is excluded, those strategies short-circuit so the\n * downstream strategies (codec-hook type ops and temp-default backfill)\n * and `mapNodeIssueToCall` defaults emit direct DDL instead.\n *\n * Structural decisions (type/nullability drift, DDL fragments) read the diff\n * node pair and resolve column DDL from the node's `codecRef` (`column-ddl-\n * rendering.ts`). The retained subsystems — codec type-operations\n * (`storageTypePlanCallStrategy`) and the NOT-NULL temp-default deferred DDL\n * (`notNullAddColumnCallStrategy`) — keep reading the contract + codec hooks\n * via `StrategyContext`, per the slice's scope (see `diff-database-schema.ts`\n * / the slice spec).\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport { resolveValueSetValues } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n type SqlStorage,\n StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport {\n RelationalSchemaNodeKind,\n type SqlColumnIR,\n type SqlSchemaIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { isPostgresSchema } from '../postgres-schema';\nimport {\n renderColumnAlterType,\n renderColumnDdl,\n resolveColumnTemporaryDefault,\n} from './column-ddl-rendering';\nimport { resolveNamespaceIdForDdlSchema } from './control-policy';\nimport { emissionSchemaName, issueNode, issueSchemaName, issueTableName } from './issue-planner';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddNotNullColumnDirectCall,\n AddNotNullColumnWithTempDefaultCall,\n AlterColumnTypeCall,\n DataTransformCall,\n DropCheckConstraintCall,\n DropNotNullCall,\n type PostgresOpFactoryCall,\n RawSqlCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { buildSchemaLookupMap, hasForeignKey, hasUniqueConstraint } from './planner-schema-lookup';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Look up a storage table by its explicit namespace coordinate. Returns\n * `undefined` when the namespace has no table by that name (or no such\n * namespace exists). Callers that get `undefined` MUST treat it as an\n * explicit conflict — never silently fall back to a global default\n * schema or a name-only walk, because that footgun would resolve a\n * stale or duplicate table name to whichever namespace the iteration\n * order surfaced first (a real data-loss hazard in multi-namespace\n * contracts where two namespaces can carry the same table name).\n */\nexport function tableAt(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const ns = storage.namespaces[namespaceId];\n if (ns === undefined) return undefined;\n return ns.entries.table?.[tableName];\n}\n\n/**\n * Resolve the DDL schema name for a namespace coordinate. Postgres-aware\n * namespaces dispatch to their polymorphic `ddlSchemaName` override —\n * named schemas return their own id; the unbound singleton returns\n * `UNBOUND_NAMESPACE_ID`. Legacy single-namespace contracts whose\n * `__unbound__` slot is the framework-default `SqlUnboundNamespace`\n * (rather than the Postgres-aware `PostgresUnboundSchema`) flow the\n * coordinate through unchanged so downstream `qualifyTableName`\n * resolves polymorphically.\n */\nexport function resolveDdlSchemaForNamespace(ctx: StrategyContext, namespaceId: string): string {\n const namespace = ctx.toContract.storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(ctx.toContract.storage);\n }\n return namespaceId;\n}\n\n/**\n * Recovers the contract namespace id for a DDL schema name embedded in a\n * diff-issue path (`path[1]`). The strategies need the CONTRACT column/table\n * (for codec-hook reads and eligibility probes the retained subsystems still\n * run) even though the issue itself only carries the resolved DDL schema —\n * this is the reverse of `resolveDdlSchemaForNamespace`.\n */\nfunction namespaceIdForDdlSchema(ctx: StrategyContext, ddlSchemaName: string): string {\n return resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);\n}\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/**\n * Context passed to each migration strategy.\n *\n * Strategies read the source (`fromContract`), target (`toContract`), current\n * database state (`schema`), operation policy (`policy`), and component list\n * (`frameworkComponents`) to make planning decisions. `fromContract` is null\n * when no prior contract is available (e.g. `db update`, where the current\n * DB state is approximated via `schema`).\n */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n readonly schema: SqlSchemaIR;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n// ============================================================================\n// Call strategies (for issue planner)\n// ============================================================================\n\n/**\n * Consumes node-typed diff issues (`SchemaDiffIssue`, from the one differ —\n * `buildPostgresPlanDiff`), reading the issue's node pair for structural\n * decisions and resolving column DDL from the node's `codecRef`. The\n * retained subsystems (codec type-operations, the NOT-NULL temp-default\n * backfill) keep reading the contract via `StrategyContext`.\n */\nexport type CallMigrationStrategy = (\n issues: readonly SchemaDiffIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaDiffIssue[];\n calls: readonly PostgresOpFactoryCall[];\n /**\n * `true` for strategies that emit cohesive sequential recipes whose\n * calls must stay contiguous and in the returned order — e.g.\n * `notNullBackfillCallStrategy` (addColumn → dataTransform → setNotNull).\n * Defaults to `false`, which lets `planIssues` hoist individual calls\n * into their DDL sequencing bucket.\n */\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\n/** A `not-equal` column issue whose node pair is narrowed to `SqlColumnIR`. */\nfunction columnNodePair(\n issue: SchemaDiffIssue,\n): { readonly expected: SqlColumnIR; readonly actual: SqlColumnIR } | undefined {\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) return undefined;\n if (issue.expected === undefined || issue.actual === undefined) return undefined;\n return {\n expected: blindCast<SqlColumnIR, 'a column diff node is always a SqlColumnIR'>(issue.expected),\n actual: blindCast<SqlColumnIR, 'a column diff node is always a SqlColumnIR'>(issue.actual),\n };\n}\n\nexport const notNullBackfillCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `notNullAddColumnCallStrategy`\n // (temp-default backfill) or `mapNodeIssueToCall` can take the issue.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-found') continue;\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) continue;\n const expected = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n if (expected.nullable !== false || expected.resolvedDefault !== undefined) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n const ddl = renderColumnDdl(expected.name, expected, ctx.codecHooks);\n const nullableSpec = contractFree.col(ddl.name, ddl.type, {\n ...(ddl.codecRef !== undefined ? { codecRef: ddl.codecRef } : {}),\n });\n calls.push(\n new AddColumnCall(schemaName, tableName, nullableSpec),\n new DataTransformCall(\n `backfill-${tableName}-${expected.name}`,\n `backfill-${tableName}-${expected.name}:check`,\n `backfill-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nconst SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n\n/**\n * Handles `not-equal` column issues whose TYPE differs. `fromContract` is\n * only supplied by `migration plan` — for reconciliation (`db update` /\n * `db init`, `fromContract === null`) this strategy never fires, mirroring\n * the legacy `typeChangeCallStrategy`'s requirement of a prior contract:\n * `mapNodeIssueToCall`'s in-place ALTER covers reconciliation directly.\n *\n * A single node issue can carry BOTH type and nullability drift (Postgres\n * alters in place, so the differ emits one `not-equal` column issue where\n * the legacy coordinate walk emitted two: `type_mismatch` +\n * `nullability_mismatch`). When this strategy consumes the issue for its\n * type portion, it also emits whatever nullability delta the same node pair\n * carries — using the same construction `nullableTighteningCallStrategy` /\n * the mapper's direct dispatch would have used — so the issue is never\n * partially handled.\n */\nexport const typeChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n if (ctx.fromContract === null) return { kind: 'no_match' };\n const dataAllowed = ctx.policy.allowedOperationClasses.includes('data');\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-equal') continue;\n const pair = columnNodePair(issue);\n if (pair === undefined) continue;\n const { expected, actual } = pair;\n if (!columnTypeChangedNativeOnly(expected, actual)) continue;\n\n const fromType = actual.nativeType;\n const toType = expected.nativeType;\n const isSafeWidening = SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n if (!isSafeWidening && !dataAllowed) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(\n expected,\n ctx.codecHooks,\n );\n const alterOpts = {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n };\n if (isSafeWidening) {\n calls.push(new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts));\n } else {\n calls.push(\n new DataTransformCall(\n `typechange-${tableName}-${expected.name}`,\n `typechange-${tableName}-${expected.name}:check`,\n `typechange-${tableName}-${expected.name}:run`,\n ),\n new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts),\n );\n }\n\n if (expected.nullable !== actual.nullable) {\n if (expected.nullable) {\n calls.push(new DropNotNullCall(schemaName, tableName, expected.name));\n } else if (dataAllowed) {\n calls.push(\n new DataTransformCall(\n `handle-nulls-${tableName}-${expected.name}`,\n `handle-nulls-${tableName}-${expected.name}:check`,\n `handle-nulls-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n } else {\n calls.push(new SetNotNullCall(schemaName, tableName, expected.name));\n }\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n/**\n * Whether the raw (unresolved) native type differs — the SAME comparison\n * `typeChangeCallStrategy` always used (`fromColumn.nativeType !==\n * toColumn.nativeType`), which for the widenable numeric/float types\n * `SAFE_WIDENINGS` lists is identical to the resolved comparison\n * `columnTypeChanged` (in `issue-planner.ts`) performs.\n */\nfunction columnTypeChangedNativeOnly(expected: SqlColumnIR, actual: SqlColumnIR): boolean {\n return expected.nativeType !== actual.nativeType;\n}\n\n/**\n * Handles `not-equal` column issues whose type did NOT change but\n * nullability tightened (contract requires NOT NULL, live column is\n * nullable). A type-changed issue's nullability delta (if any) is already\n * handled by `typeChangeCallStrategy`, which runs first — this strategy\n * only ever sees issues that strategy left behind.\n */\nexport const nullableTighteningCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `mapNodeIssueToCall` emits a direct\n // `SET NOT NULL` instead.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-equal') continue;\n const pair = columnNodePair(issue);\n if (pair === undefined) continue;\n const { expected, actual } = pair;\n if (columnTypeChangedNativeOnly(expected, actual)) continue; // typeChangeCallStrategy's concern\n if (expected.nullable !== false || actual.nullable !== true) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n calls.push(\n new DataTransformCall(\n `handle-nulls-${tableName}-${expected.name}`,\n `handle-nulls-${tableName}-${expected.name}:check`,\n `handle-nulls-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n/**\n * Collects every check constraint from a table in the contract storage.\n * Returns an empty array when the table has no checks or the table is absent.\n */\nfunction collectContractChecks(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): ReadonlyArray<{ name: string; column: string; permittedValues: readonly string[] }> {\n const ns = storage.namespaces[namespaceId];\n const tableRaw = ns !== undefined ? ns.entries.table?.[tableName] : undefined;\n if (!(tableRaw instanceof StorageTable)) return [];\n const checks = tableRaw.checks;\n if (!checks || checks.length === 0) return [];\n return checks.map((c) => ({\n name: c.name,\n column: c.column,\n permittedValues: resolveValueSetValues(\n c.valueSet,\n storage,\n `check \"${c.name}\" on \"${tableName}\"`,\n ),\n }));\n}\n\n/**\n * Compares two value arrays as unordered sets.\n */\nfunction checkValueSetsEqual(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n const bSet = new Set(b);\n return a.every((v) => bSet.has(v));\n}\n\n/**\n * Plans check-constraint migrations for `enumType`-authored columns.\n *\n * Walks every namespace's tables in the target contract (the check nodes'\n * resolved `permittedValues` are ultimately sourced from the same\n * contract-declared value sets, so walking the contract directly is the\n * simplest faithful port — the strategy's decisions never depend on which\n * ISSUES happen to be in the input list, only on the contract + live schema\n * shapes). For each table that carries `checks`, diffs the contract-expected\n * checks against the live schema's checks:\n *\n * - Check in contract, absent from live DB → `AddCheckConstraintCall`.\n * - Check in live DB, absent from contract → `DropCheckConstraintCall`.\n * - Check on both sides but value sets differ → `DropCheckConstraintCall`\n * then `AddCheckConstraintCall` (drop + recreate; a check predicate cannot\n * be altered in place).\n *\n * Consumes every `sql-check-constraint` issue on a table this walk handles\n * (not-found/not-expected/not-equal), leaving check issues on tables with\n * NO contract checks to `mapNodeIssueToCall`'s `not-expected` fallback.\n */\nexport const checkConstraintPlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const calls: PostgresOpFactoryCall[] = [];\n const handledIssueKeys = new Set<string>();\n\n for (const [namespaceId, ns] of Object.entries(ctx.toContract.storage.namespaces)) {\n for (const tableName of Object.keys(ns.entries.table ?? {})) {\n const contractChecks = collectContractChecks(ctx.toContract.storage, namespaceId, tableName);\n if (contractChecks.length === 0) continue;\n\n const schemaTable = ctx.schema.tables[tableName];\n const liveChecks = schemaTable?.checks ?? [];\n const ddlSchema = resolveDdlSchemaForNamespace(ctx, namespaceId);\n\n for (const contractCheck of contractChecks) {\n const liveCheck = liveChecks.find((c) => c.name === contractCheck.name);\n const issueKey = `${tableName} ${contractCheck.name}`;\n if (!liveCheck) {\n calls.push(\n new AddCheckConstraintCall(\n ddlSchema,\n tableName,\n contractCheck.name,\n contractCheck.column,\n contractCheck.permittedValues,\n ),\n );\n handledIssueKeys.add(issueKey);\n } else if (!checkValueSetsEqual(contractCheck.permittedValues, liveCheck.permittedValues)) {\n calls.push(\n new DropCheckConstraintCall(ddlSchema, tableName, contractCheck.name),\n new AddCheckConstraintCall(\n ddlSchema,\n tableName,\n contractCheck.name,\n contractCheck.column,\n contractCheck.permittedValues,\n ),\n );\n handledIssueKeys.add(issueKey);\n }\n // else: values match — no op needed, still consume the issue\n else {\n handledIssueKeys.add(issueKey);\n }\n }\n\n // Emit drops for checks that are live but not in the contract.\n for (const liveCheck of liveChecks) {\n const inContract = contractChecks.some((c) => c.name === liveCheck.name);\n if (!inContract) {\n const issueKey = `${tableName} ${liveCheck.name}`;\n calls.push(new DropCheckConstraintCall(ddlSchema, tableName, liveCheck.name));\n handledIssueKeys.add(issueKey);\n }\n }\n }\n }\n\n if (calls.length === 0 && handledIssueKeys.size === 0) return { kind: 'no_match' };\n\n const remaining = issues.filter((issue) => {\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.check) return true;\n const tableName = issueTableName(issue);\n if (tableName === undefined) return true;\n const checkName = blindCast<{ readonly name: string }, 'a check node always carries a name'>(\n node,\n ).name;\n return !handledIssueKeys.has(`${tableName} ${checkName}`);\n });\n\n return { kind: 'match', issues: remaining, calls };\n};\n\n/**\n * Dispatches codec-typed storage types through their codec's\n * `planTypeOperations` hook (the authoritative source for codec-driven DDL\n * such as custom type creation). Codec extension/type ops are not modeled as\n * diff nodes — this strategy drives entirely off `ctx.toContract.storage.types`\n * + codec hooks, consuming nothing from the node issue list (there is no\n * node-vocabulary equivalent of `type_missing` / `enum_values_changed`).\n */\nexport const storageTypePlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const storageTypes = ctx.toContract.storage.types ?? {};\n if (Object.keys(storageTypes).length === 0) return { kind: 'no_match' };\n\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n const codecInstance = typeInstance as StorageTypeInstance;\n const hook = ctx.codecHooks.get(codecInstance.codecId);\n if (!hook?.planTypeOperations) continue;\n const planResult = hook.planTypeOperations({\n typeName,\n typeInstance: codecInstance,\n contract: ctx.toContract,\n schema: ctx.schema,\n schemaName: ctx.schemaName,\n policy: ctx.policy,\n });\n if (!planResult) continue;\n for (const op of planResult.operations) {\n calls.push(\n new RawSqlCall({\n ...op,\n target: {\n id: op.target.id,\n details: buildTargetDetails('type', typeName, ctx.schemaName),\n },\n } as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),\n );\n }\n }\n\n if (calls.length === 0) return { kind: 'no_match' };\n return { kind: 'match', issues, calls };\n};\n\n/**\n * Handles `not-found` column issues for NOT NULL columns without a contract\n * default. Replaces the legacy `buildAddColumnItem` non-default branches.\n *\n * Two shapes:\n * - Shared-temp-default safe: emit a single atomic composite op (add\n * nullable → backfill identity value → `SET NOT NULL` → `DROP DEFAULT`).\n * The temp-default value is resolved from the column node's `codecRef`\n * (`resolveColumnTemporaryDefault`, wrapping `resolveIdentityValue`).\n * - Empty-table guarded: emit a hand-built op with a `tableIsEmptyCheck`\n * precheck so the failure message is \"table is not empty\" rather than the\n * raw PG NOT NULL violation.\n *\n * \"Normal\" not-found column cases (nullable or has a contract default) are\n * left for `mapNodeIssueToCall`'s default `AddColumnCall` emission.\n */\nexport const notNullAddColumnCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n const schemaLookups = buildSchemaLookupMap(ctx.schema);\n\n const mutableCodecHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableStorageTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-found') continue;\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) continue;\n const expected = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n if (expected.nullable !== false || expected.resolvedDefault !== undefined) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n\n const namespaceId = namespaceIdForDdlSchema(ctx, ddlSchemaName);\n const schemaName = namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, tableName);\n const column = contractTable?.columns[expected.name];\n if (!contractTable || !column) continue;\n\n const schemaTable = ctx.schema.tables[tableName];\n if (!schemaTable) continue;\n\n const temporaryDefault = resolveColumnTemporaryDefault(expected, ctx.codecHooks);\n const schemaLookup = schemaLookups.get(tableName);\n const canUseSharedTempDefault =\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table: contractTable,\n schemaTable,\n schemaLookup,\n columnName: expected.name,\n });\n\n matched.push(issue);\n\n if (canUseSharedTempDefault && temporaryDefault !== null) {\n calls.push(\n new AddNotNullColumnWithTempDefaultCall({\n schemaName,\n tableName,\n columnName: expected.name,\n column,\n codecHooks: mutableCodecHooks,\n storageTypes: mutableStorageTypes,\n temporaryDefault,\n }),\n );\n continue;\n }\n\n calls.push(\n new AddNotNullColumnDirectCall(\n schemaName,\n tableName,\n expected.name,\n renderColumnDdl(expected.name, expected, ctx.codecHooks),\n ),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n };\n};\n\n// ============================================================================\n// Strategy helpers\n// ============================================================================\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: ReturnType<typeof buildSchemaLookupMap> extends ReadonlyMap<\n string,\n infer V\n >\n ? V | undefined\n : never;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) return false;\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (!foreignKey.source.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) return false;\n }\n\n return true;\n}\n\n/**\n * Ordered list of Postgres planner strategies, shared by `migration plan`\n * and `db update` / `db init`. The issue planner runs each strategy in\n * order, letting it consume any issues it handles, and routes whatever's\n * left through `mapNodeIssueToCall`. Behavior diverges purely on\n * `policy.allowedOperationClasses`:\n *\n * - When `'data'` is allowed (`migration plan`), the data-safe strategies\n * (`notNullBackfillCallStrategy`, `typeChangeCallStrategy`,\n * `nullableTighteningCallStrategy`) consume their matching issues and emit\n * `DataTransformCall` placeholders or recipe ops.\n *\n * - When `'data'` is not allowed (`db update` / `db init`), the\n * placeholder-emitting strategies short-circuit to `no_match`, leaving\n * the issue for the downstream strategies (`storageTypePlanCallStrategy`,\n * `notNullAddColumnCallStrategy`) or the `mapNodeIssueToCall` default to\n * handle with direct DDL.\n *\n * Codec-typed storage type entries are dispatched through\n * `storageTypePlanCallStrategy`.\n */\nexport const postgresPlannerStrategies: readonly CallMigrationStrategy[] = [\n notNullBackfillCallStrategy,\n typeChangeCallStrategy,\n nullableTighteningCallStrategy,\n checkConstraintPlanCallStrategy,\n storageTypePlanCallStrategy,\n notNullAddColumnCallStrategy,\n];\n","/**\n * Postgres migration issue planner.\n *\n * Takes node-typed schema-diff issues (from the one differ — see\n * `buildPostgresPlanDiff` in `diff-database-schema.ts`) and emits migration\n * IR (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize\n * and produce specialized call sequences (e.g. NOT NULL backfill →\n * addColumn(nullable) + dataTransform + setNotNull); remaining issues flow\n * through `mapNodeIssueToCall` for the default case.\n *\n * Structural op-render (column type/default DDL) resolves the column node's\n * `codecRef` against the codec hooks the caller holds (`column-ddl-\n * rendering.ts`) — never re-derived from the contract. The retained\n * subsystems (codec type-operations, the NOT-NULL temp-default deferred DDL,\n * control-policy disposition) still read the contract via the strategy\n * context, per the slice's scope.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome, orderIssuesByDependencies } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport {\n RelationalSchemaNodeKind,\n type SqlColumnDefaultIR,\n type SqlColumnIR,\n type SqlForeignKeyIR,\n type SqlIndexIR,\n SqlSchemaIR,\n type SqlSchemaIRNode,\n type SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport type { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport type { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { quoteIdentifier } from '../sql-utils';\nimport {\n renderColumnAlterType,\n renderColumnDdl,\n renderColumnDefaultSql,\n} from './column-ddl-rendering';\nimport { resolveNamespaceIdForDdlSchema } from './control-policy';\nimport {\n AddColumnCall,\n AddForeignKeyCall,\n AddNativeEnumValueCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n CreateIndexCall,\n CreateNativeEnumTypeCall,\n CreateSchemaCall,\n CreateTableCall,\n DisableRowLevelSecurityCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNativeEnumTypeCall,\n DropNotNullCall,\n DropTableCall,\n EnableRowLevelSecurityCall,\n type PostgresOpFactoryCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport type { ForeignKeySpec } from './operations/shared';\nimport {\n type CallMigrationStrategy,\n postgresPlannerStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n/**\n * Deterministic name for the element-non-null CHECK constraint on a scalar-array\n * column. Distinct `_elem_not_null` suffix avoids collision with the enum\n * value-set `_check` constraints. Re-emitting the same schema produces the same\n * name, so `pg_get_constraintdef`-based verify sees no drift.\n */\nfunction elementNonNullCheckName(tableName: string, columnName: string): string {\n return `${tableName}_${columnName}_elem_not_null`;\n}\n\n/**\n * Predicate enforcing that a scalar-array column carries no NULL element. The\n * array column itself may be NULL (container nullability is the column's NOT NULL\n * clause); `array_position` over a NULL array yields NULL, which a CHECK treats\n * as satisfied, so a nullable array column is unaffected.\n */\nfunction elementNonNullCheckExpression(columnName: string): string {\n return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly PostgresOpFactoryCall[];\n}\n\n/**\n * Classifies calls into dependency order categories for correct DDL sequencing.\n */\ntype CallCategory =\n | 'dep'\n | 'drop'\n | 'dropType'\n | 'table'\n | 'rlsEnable'\n | 'rlsPolicy'\n | 'column'\n | 'alter'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\n/**\n * Classifies calls into DDL sequencing buckets. The order matches the\n * legacy walk-schema planner's emission order so `db init` and `db update`\n * produce byte-identical plans for the shared shape (deps → drops → tables\n * → columns → alters → PKs → uniques → indexes → FKs).\n *\n * `dropType` (DROP TYPE for a managed native enum) is its own bucket, ordered\n * after the general drop bucket: a type can only be dropped once every table\n * whose column uses it is gone. A column→enum edge would make this precise,\n * but `coalesceSubtreeIssues` removes the column issue under a whole-table\n * drop, so the edge never reaches the graph; the coarse bucket stands in until\n * that edge lands (the coordinate work is a later slice).\n */\nfunction classifyCall(call: PostgresOpFactoryCall): CallCategory {\n switch (call.factoryName) {\n case 'createExtension':\n case 'createSchema':\n case 'createNativeEnumType':\n case 'addNativeEnumValue':\n return 'dep';\n case 'dropNativeEnumType':\n return 'dropType';\n case 'dropTable':\n case 'dropColumn':\n case 'dropConstraint':\n case 'dropCheckConstraint':\n case 'dropIndex':\n case 'dropDefault':\n return 'drop';\n case 'addCheckConstraint':\n return 'unique'; // after uniques, before indexes\n case 'createTable':\n return 'table';\n case 'enableRowLevelSecurity':\n case 'disableRowLevelSecurity':\n return 'rlsEnable';\n case 'createRlsPolicy':\n return 'rlsPolicy';\n case 'dropRlsPolicy':\n return 'drop';\n case 'addColumn':\n return 'column';\n case 'alterColumnType':\n case 'setNotNull':\n case 'dropNotNull':\n case 'setDefault':\n return 'alter';\n case 'addPrimaryKey':\n return 'primaryKey';\n case 'addUnique':\n return 'unique';\n case 'createIndex':\n case 'renameIndex':\n return 'index';\n case 'addForeignKey':\n return 'foreignKey';\n case 'rawSql': {\n // Type ops lifted through `RawSqlCall` by `storageTypePlanCallStrategy`\n // to preserve the codec-emitted label and precheck/postcheck.\n // Classification falls back to inspecting the underlying op's target\n // details (`objectType: 'type'`).\n const op = (\n call as {\n op?: {\n target?: { details?: { objectType?: string } };\n };\n }\n ).op;\n const objectType = op?.target?.details?.objectType;\n if (objectType === 'type') return 'dep';\n return 'alter';\n }\n default:\n return 'alter';\n }\n}\n\n// When no policy is explicitly supplied (test-only path; production callers\n// always pass one), allow every class so strategies that gate on\n// `'data'` (data-safe placeholders) still fire — the test is treated as\n// trusted. Filtering of actual emitted calls only runs when a policy was\n// explicitly provided (see `policyProvided` below).\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return new SqlSchemaIR({ tables: {} });\n}\n\nfunction conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'alterColumnType':\n return 'typeMismatch';\n case 'setNotNull':\n case 'dropNotNull':\n return 'nullabilityConflict';\n case 'addForeignKey':\n case 'dropConstraint':\n return 'foreignKeyConflict';\n case 'createIndex':\n case 'renameIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['location'] | undefined {\n // Most Postgres call classes expose `tableName`/`columnName`/`indexName`/\n // `constraintName` as readonly fields. We avoid `toOp()` here because a\n // `DataTransformCall` intentionally throws from `toOp`.\n const anyCall = call as unknown as {\n tableName?: string;\n columnName?: string;\n indexName?: string;\n newIndexName?: string;\n constraintName?: string;\n typeName?: string;\n };\n const location: {\n entityKind?: string;\n entityName?: string;\n column?: string;\n index?: string;\n constraint?: string;\n } = {};\n if (anyCall.tableName) {\n location.entityKind = 'table';\n location.entityName = anyCall.tableName;\n } else if (anyCall.typeName) {\n location.entityKind = 'native_enum';\n location.entityName = anyCall.typeName;\n }\n if (anyCall.columnName) location.column = anyCall.columnName;\n // A rename call carries old/new index names; the new name is the index's\n // contract-side identity, so it is the conflict location.\n if (anyCall.indexName) location.index = anyCall.indexName;\n else if (anyCall.newIndexName) location.index = anyCall.newIndexName;\n if (anyCall.constraintName) location.constraint = anyCall.constraintName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: PostgresOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\n// ============================================================================\n// Node-based issue planner\n// ============================================================================\n//\n// Consumes node-typed `SchemaDiffIssue`s (from the one differ —\n// `buildPostgresPlanDiff`) and reads the diff node each issue carries\n// (`issue.expected` / `issue.actual`). Column DDL (type/default SQL) resolves\n// from the column node's `codecRef` against the codec hooks the caller holds\n// (`column-ddl-rendering.ts`), never the contract. The retained subsystems —\n// codec type-operations, field-lifecycle hooks, the NOT-NULL temp-default\n// deferred DDL, control-policy disposition — keep the contract via the\n// strategy context, per the slice's scope.\n\n/** The diff node an issue concerns — expected when present, else the actual (extra) node. */\nexport function issueNode(issue: SchemaDiffIssue): SqlSchemaIRNode | undefined {\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n return blindCast<\n SqlSchemaIRNode,\n 'every node in a Postgres schema diff tree is a SqlSchemaIRNode; nodeKind is its required discriminant'\n >(node);\n}\n\n/** DDL schema segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */\nexport function issueSchemaName(issue: SchemaDiffIssue): string | undefined {\n return issue.path[1];\n}\n\n/** Table segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */\nexport function issueTableName(issue: SchemaDiffIssue): string | undefined {\n return issue.path[2];\n}\n\n/** Column name embedded in a column/default issue path segment (`column:<name>`). */\nexport function issueColumnName(issue: SchemaDiffIssue): string | undefined {\n const segment = issue.path[3];\n if (segment === undefined || !segment.startsWith('column:')) return undefined;\n return segment.slice('column:'.length);\n}\n\n/**\n * The DDL schema name to use when EMITTING an op against `ddlSchemaName` (the\n * diff tree's resolved physical schema, `issueSchemaName(issue)`). The\n * unbound namespace's diff-tree identity resolves to `public` (a concrete\n * physical default the differ needs in order to compare its tree against\n * introspection — `resolveDdlSchemaForNamespaceStorage`), but DDL EMISSION\n * must stay unqualified so the live connection's `search_path` resolves it\n * at runtime (`boundSchema`). Recovers the logical namespace id via the\n * contract and substitutes the unbound sentinel back in when it resolves\n * there; every other namespace's `ddlSchemaName` already agrees between the\n * two resolution paths, so it passes through unchanged.\n */\nexport function emissionSchemaName(ctx: StrategyContext, ddlSchemaName: string): string {\n const namespaceId = resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);\n return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;\n}\n\n/**\n * Whether a column node is a scalar-array (`many: true`) column. The family\n * converter (`contractToSchemaIR`'s `convertColumn`) never stamps `many` on\n * the derived node — array-ness is folded into the `[]` suffix on\n * `nativeType` instead — so the node-derived check reads the suffix; `.many`\n * is still checked first for nodes a caller stamps directly (e.g. hand-built\n * test fixtures, or an adapter that populates it at introspection).\n */\nfunction isManyColumn(column: SqlColumnIR): boolean {\n return column.many === true || column.nativeType.endsWith('[]');\n}\n\n/** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */\nexport function columnTypeChanged(expected: SqlColumnIR, actual: SqlColumnIR): boolean {\n if (expected.resolvedNativeType !== undefined && actual.resolvedNativeType !== undefined) {\n return expected.resolvedNativeType !== actual.resolvedNativeType;\n }\n return (\n expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many)\n );\n}\n\n// ----------------------------------------------------------------------------\n// Subtree coalescing (the planner's responsibility per the differ's contract)\n// ----------------------------------------------------------------------------\n\n/**\n * The generic differ is total: a missing/extra table (or column) emits an\n * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`\n * and `AddColumn`/`DropColumn` already account for the whole subtree, so the\n * nested issues are redundant — coalescing drops any issue whose path is a\n * strict descendant of a `not-found`/`not-expected` issue's path. Run over the\n * relational subset ONLY (policy issues and synthesized namespace issues are\n * handled on their own paths, never coalesced against tables).\n */\nexport function coalesceSubtreeIssues<TNode extends DiffableNode = DiffableNode>(\n issues: readonly SchemaDiffIssue<TNode>[],\n): readonly SchemaDiffIssue<TNode>[] {\n const collapsingPaths = issues\n .filter((issue) => issueOutcome(issue) !== 'not-equal')\n .map((issue) => issue.path);\n if (collapsingPaths.length === 0) return issues;\n return issues.filter(\n (issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)),\n );\n}\n\nfunction isStrictDescendantPath(path: readonly string[], ancestor: readonly string[]): boolean {\n if (path.length <= ancestor.length) return false;\n for (let i = 0; i < ancestor.length; i += 1) {\n if (path[i] !== ancestor[i]) return false;\n }\n return true;\n}\n\n// ----------------------------------------------------------------------------\n// Node → call construction\n// ----------------------------------------------------------------------------\n\nfunction fkSpecFromNode(fk: SqlForeignKeyIR, tableName: string): ForeignKeySpec {\n const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;\n return {\n name,\n columns: [...fk.columns],\n references: {\n // The raw target namespace coordinate, matching the retired coordinate\n // path's `references.schema: fk.target.namespaceId` (the FK node stamps\n // it verbatim). The op renderer qualifies the REFERENCES clause from it.\n schema: fk.referencedSchema ?? '',\n table: fk.referencedTable,\n columns: [...fk.referencedColumns],\n },\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n };\n}\n\n/**\n * Builds the `CreateTable` + child `CreateIndex` / `AddForeignKey` / `AddUnique`\n * calls for a newly-expected table, reading only the table node's children. The\n * PK and element-non-null CHECKs go inline as table constraints; indexes\n * (declared + FK-backing, already merged and ordered at derivation) and the\n * FK / unique constraints are separate calls (re-bucketed downstream). Every\n * column's DDL is resolved from its `codecRef` via `renderColumnDdl`.\n */\nfunction buildCreateTableCallsFromNode(\n schemaName: string,\n ddlSchemaName: string,\n table: PostgresTableSchemaNode,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): PostgresOpFactoryCall[] {\n const ddlColumns = Object.values(table.columns).map((c) =>\n renderColumnDdl(c.name, c, codecHooks),\n );\n const primaryKeyConstraints: DdlTableConstraint[] = table.primaryKey\n ? [\n contractFree.primaryKey([...table.primaryKey.columns], {\n ...ifDefined('name', table.primaryKey.name),\n }),\n ]\n : [];\n const elementNonNullChecks: DdlTableConstraint[] = Object.values(table.columns)\n .filter((c) => isManyColumn(c))\n .map((c) =>\n contractFree.checkExpression(\n elementNonNullCheckName(table.name, c.name),\n elementNonNullCheckExpression(c.name),\n ),\n );\n const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];\n const calls: PostgresOpFactoryCall[] = [\n new CreateTableCall(\n schemaName,\n table.name,\n ddlColumns,\n allTableConstraints.length > 0 ? allTableConstraints : undefined,\n ),\n ];\n for (const index of table.indexes) {\n calls.push(createIndexCallFromNode(index, schemaName, table.name));\n }\n for (const fk of table.foreignKeys) {\n calls.push(new AddForeignKeyCall(schemaName, table.name, fkSpecFromNode(fk, table.name)));\n }\n for (const unique of table.uniques) {\n const constraintName = unique.name ?? `${table.name}_${unique.columns.join('_')}_key`;\n calls.push(new AddUniqueCall(schemaName, table.name, constraintName, [...unique.columns]));\n }\n // Marker-driven: a newly-created table that is RLS-controlled enables RLS\n // as part of its creation bundle. The policy set never decides this. The\n // resolved schema (not the emission sentinel) binds into the op's\n // relrowsecurity checks.\n if (table.rlsEnabled) {\n calls.push(new EnableRowLevelSecurityCall(ddlSchemaName, table.name));\n }\n return calls;\n}\n\nfunction nodeConflict(kind: SqlPlannerConflict['kind'], message: string): SqlPlannerConflict {\n return issueConflict(kind, message);\n}\n\n/**\n * True when `actualMembers` (the live database's ordered members) is a\n * strict, order-preserving prefix of `expectedMembers` (the contract's) —\n * the database already carries every contract member, in declaration\n * order, and the contract declares at least one member the database still\n * lacks. Any other relationship — a renamed value, a removed value, a\n * reordering, or the database holding members the contract lacks — is not\n * a suffix append.\n */\nfunction isNativeEnumSuffixAppend(\n actualMembers: readonly string[],\n expectedMembers: readonly string[],\n): boolean {\n if (actualMembers.length >= expectedMembers.length) return false;\n return actualMembers.every((member, index) => member === expectedMembers[index]);\n}\n\n/** Operator-worded refusal for a native-enum member change beyond a suffix append (design ruling — tests match this verbatim). */\nfunction nativeEnumMemberChangeRefusal(options: {\n readonly ddlSchemaName: string;\n readonly typeName: string;\n readonly expectedMembers: readonly string[];\n readonly actualMembers: readonly string[];\n}): string {\n return (\n `Native enum type \"${options.ddlSchemaName}\".\"${options.typeName}\" changed beyond appending new values ` +\n `(contract declares [${options.expectedMembers.join(', ')}], database has [${options.actualMembers.join(', ')}]). ` +\n \"Prisma Next does not modify a native enum's existing values (rename, removal, reorder) — \" +\n 'see https://pris.ly/d/postgres-native-enums. Author the change manually with `migration new`.'\n );\n}\n\n/**\n * Managed native-enum issue -> op lowering. A missing declared type creates\n * it; an unclaimed live type drops it (ownership-scoped upstream by\n * `retainUnownedExtras`, destructiveness gated by the operation-class\n * policy); a paired member-value mismatch lowers to one `ALTER TYPE ... ADD\n * VALUE` per appended member when the database's members are a strict,\n * order-preserving prefix of the contract's — any other change (rename,\n * removal, reorder, or the database holding members the contract lacks) is\n * refused with a NAMED diagnostic, never a silent no-op and never a\n * drop-and-recreate.\n */\nfunction mapNativeEnumNodeIssue(\n issue: SchemaDiffIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const ddlSchemaName = issueSchemaName(issue);\n if (ddlSchemaName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Enum issue has no schema in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n if (issueOutcome(issue) === 'not-found') {\n const expected = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-found native-enum issue always carries the expected PostgresNativeEnumSchemaNode'\n >(issue.expected);\n return ok([new CreateNativeEnumTypeCall(schemaName, expected.typeName, expected.members)]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const actual = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-expected native-enum issue always carries the actual PostgresNativeEnumSchemaNode'\n >(issue.actual);\n return ok([new DropNativeEnumTypeCall(schemaName, actual.typeName)]);\n }\n const expected = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-equal native-enum issue carries both sides; the expected node names the type'\n >(issue.expected);\n const actual = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-equal native-enum issue carries both sides'\n >(issue.actual);\n if (isNativeEnumSuffixAppend(actual.members, expected.members)) {\n const appendedValues = expected.members.slice(actual.members.length);\n return ok(\n appendedValues.map(\n (value) => new AddNativeEnumValueCall(schemaName, expected.typeName, value),\n ),\n );\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n nativeEnumMemberChangeRefusal({\n ddlSchemaName,\n typeName: expected.typeName,\n expectedMembers: expected.members,\n actualMembers: actual.members,\n }),\n ),\n );\n}\n\nfunction mapTableNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n // The diff tree's RESOLVED physical schema. Enablement ops bind it into\n // their `pg_class`/`pg_namespace` checks (the emission sentinel would\n // never match a live nspname), mirroring the schema the retired\n // policy-half enable resolved via `resolveDdlSchemaForNamespaceStorage`.\n ddlSchemaName: string,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const table = blindCast<\n PostgresTableSchemaNode,\n 'a not-found table issue always carries the expected PostgresTableSchemaNode'\n >(issue.expected);\n return ok(buildCreateTableCallsFromNode(schemaName, ddlSchemaName, table, codecHooks));\n }\n if (issueOutcome(issue) === 'not-expected') {\n const table = blindCast<\n PostgresTableSchemaNode,\n 'a not-expected table issue always carries the actual PostgresTableSchemaNode'\n >(issue.actual);\n return ok([new DropTableCall(schemaName, table.name)]);\n }\n // A paired table `not-equal` means enablement drift TODAY, because\n // `isEqualTo` compares only name + `rlsEnabled`. Key on the actual\n // expected-vs-actual `rlsEnabled` delta rather than assuming it: emit ENABLE\n // when it flipped on, DISABLE when it flipped off, and fail loud when\n // `rlsEnabled` matches on both sides — that means a second table attribute\n // drifted into `isEqualTo` and this mapper does not yet handle it. The\n // expected side is authoritative (marker-driven, never the policy set).\n const expected = blindCast<\n PostgresTableSchemaNode,\n 'a not-equal table issue always carries the expected PostgresTableSchemaNode'\n >(issue.expected);\n const actual = blindCast<\n PostgresTableSchemaNode,\n 'a not-equal table issue always carries the actual PostgresTableSchemaNode'\n >(issue.actual);\n if (expected.rlsEnabled && !actual.rlsEnabled) {\n return ok([new EnableRowLevelSecurityCall(ddlSchemaName, expected.name)]);\n }\n if (!expected.rlsEnabled && actual.rlsEnabled) {\n return ok([new DisableRowLevelSecurityCall(ddlSchemaName, expected.name)]);\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `unhandled table-attribute drift on \"${expected.name}\": table not-equal with no rlsEnabled delta (a second table attribute drifted)`,\n ),\n );\n}\n\nfunction mapColumnNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const column = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n return ok([\n new AddColumnCall(schemaName, tableName, renderColumnDdl(column.name, column, codecHooks)),\n ]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const column = blindCast<\n SqlColumnIR,\n 'a not-expected column issue always carries the actual column node'\n >(issue.actual);\n return ok([new DropColumnCall(schemaName, tableName, column.name)]);\n }\n // not-equal: Postgres alters in place — type drift and/or nullability drift.\n const expected = blindCast<\n SqlColumnIR,\n 'a not-equal column issue always carries the expected column node'\n >(issue.expected);\n const actual = blindCast<\n SqlColumnIR,\n 'a not-equal column issue always carries the actual column node'\n >(issue.actual);\n const calls: PostgresOpFactoryCall[] = [];\n if (columnTypeChanged(expected, actual)) {\n const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, codecHooks);\n calls.push(\n new AlterColumnTypeCall(schemaName, tableName, expected.name, {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n }),\n );\n }\n if (expected.nullable !== actual.nullable) {\n calls.push(\n expected.nullable\n ? new DropNotNullCall(schemaName, tableName, expected.name)\n : new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n return ok(calls);\n}\n\nfunction mapColumnDefaultNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n columnName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-expected') {\n return ok([new DropDefaultCall(schemaName, tableName, columnName)]);\n }\n // not-found (SET DEFAULT, additive) or not-equal (SET DEFAULT, widening).\n if (issue.expected === undefined) return ok([]);\n const defaultNode = blindCast<\n SqlColumnDefaultIR,\n 'a not-found/not-equal column-default issue always carries the expected default node'\n >(issue.expected);\n const defaultSql = renderColumnDefaultSql(defaultNode);\n if (!defaultSql) return ok([]);\n return ok([\n new SetDefaultCall(\n schemaName,\n tableName,\n columnName,\n defaultSql,\n issueOutcome(issue) === 'not-equal' ? 'widening' : 'additive',\n ),\n ]);\n}\n\nfunction mapPrimaryKeyNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const pk = blindCast<\n { readonly columns: readonly string[]; readonly name?: string },\n 'a not-found primary-key issue always carries the expected PrimaryKey node'\n >(issue.expected);\n const constraintName = pk.name ?? `${tableName}_pkey`;\n return ok([new AddPrimaryKeyCall(schemaName, tableName, constraintName, [...pk.columns])]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const pk = blindCast<\n { readonly name?: string },\n 'a not-expected primary-key issue always carries the actual PrimaryKey node'\n >(issue.actual);\n return ok([\n new DropConstraintCall(schemaName, tableName, pk.name ?? `${tableName}_pkey`, 'primaryKey'),\n ]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\nfunction mapForeignKeyNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const fk = blindCast<\n SqlForeignKeyIR,\n 'a not-found foreign-key issue always carries the expected foreign-key node'\n >(issue.expected);\n return ok([new AddForeignKeyCall(schemaName, tableName, fkSpecFromNode(fk, tableName))]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const fk = blindCast<\n SqlForeignKeyIR,\n 'a not-expected foreign-key issue always carries the actual foreign-key node'\n >(issue.actual);\n const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;\n return ok([new DropConstraintCall(schemaName, tableName, name, 'foreignKey')]);\n }\n return notOk(nodeConflict('foreignKeyConflict', issue.path.join('/')));\n}\n\nfunction mapUniqueNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const unique = blindCast<\n SqlUniqueIR,\n 'a not-found unique issue always carries the expected unique node'\n >(issue.expected);\n const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n return ok([new AddUniqueCall(schemaName, tableName, name, [...unique.columns])]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const unique = blindCast<\n SqlUniqueIR,\n 'a not-expected unique issue always carries the actual unique node'\n >(issue.actual);\n const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n return ok([new DropConstraintCall(schemaName, tableName, name, 'unique')]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\n/**\n * The CreateIndexCall for a name-identified index node: the node's own name\n * verbatim, its element list (column tuple or opaque expression), and the\n * unique/type/options/where attributes carried through.\n */\nexport function createIndexCallFromNode(\n index: SqlIndexIR,\n schemaName: string,\n tableName: string,\n): CreateIndexCall {\n const extras: {\n type?: string;\n options?: Record<string, unknown>;\n where?: string;\n unique?: boolean;\n } = {};\n if (index.type !== undefined) extras.type = index.type;\n if (index.options !== undefined) extras.options = index.options;\n if (index.where !== undefined) extras.where = index.where;\n if (index.unique) extras.unique = true;\n return new CreateIndexCall(\n schemaName,\n tableName,\n index.name,\n index.columns !== undefined\n ? { columns: [...index.columns] }\n : { expression: index.expression ?? '' },\n extras,\n );\n}\n\nfunction mapIndexNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const index = blindCast<\n SqlIndexIR,\n 'a not-found index issue always carries the expected index node'\n >(issue.expected);\n return ok([createIndexCallFromNode(index, schemaName, tableName)]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const index = blindCast<\n SqlIndexIR,\n 'a not-expected index issue always carries the actual index node'\n >(issue.actual);\n return ok([new DropIndexCall(schemaName, tableName, index.name)]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\nfunction mapCheckNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n // check_removed (extra live check not in contract) is the only check drift\n // the default mapper handles directly; check_missing / check_mismatch are\n // consumed by `checkConstraintPlanCallStrategy` (drop+recreate), so reaching\n // here for them means the strategy did not run — a conflict.\n if (issueOutcome(issue) === 'not-expected') {\n const check = blindCast<\n { readonly name: string },\n 'a not-expected check issue always carries the actual check node'\n >(issue.actual);\n return ok([new DropCheckConstraintCall(schemaName, tableName, check.name)]);\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Check constraint drift on \"${tableName}\" — handled by checkConstraintPlanCallStrategy: ${issue.path.join('/')}`,\n ),\n );\n}\n\n/**\n * Maps one node-typed diff issue to its migration call(s), dispatching on the\n * node's `nodeKind` and the issue's presence-derived `issueOutcome`, reading\n * nodes and resolving column DDL from `codecRef` via `column-ddl-rendering.ts`.\n */\nexport function mapNodeIssueToCall(\n issue: SchemaDiffIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const node = issueNode(issue);\n if (node === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Issue carries neither an expected nor an actual node: ${issue.path.join('/')}`,\n ),\n );\n }\n if (node.nodeKind === PostgresSchemaNodeKind.namespace) {\n if (issueOutcome(issue) !== 'not-found') {\n return notOk(\n nodeConflict('unsupportedOperation', `Unexpected namespace drift: ${issue.path.join('/')}`),\n );\n }\n const namespace = blindCast<\n PostgresNamespaceSchemaNode,\n 'a namespace-presence issue always carries a PostgresNamespaceSchemaNode'\n >(issue.expected);\n return ok([new CreateSchemaCall(namespace.schemaName)]);\n }\n\n if (node.nodeKind === PostgresSchemaNodeKind.nativeEnum) {\n return mapNativeEnumNodeIssue(issue, ctx);\n }\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Issue has no schema/table in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n switch (node.nodeKind) {\n case PostgresSchemaNodeKind.table:\n return mapTableNodeIssue(issue, schemaName, ddlSchemaName, ctx.codecHooks);\n case RelationalSchemaNodeKind.column:\n return mapColumnNodeIssue(issue, schemaName, tableName, ctx.codecHooks);\n case RelationalSchemaNodeKind.columnDefault: {\n const columnName = issueColumnName(issue);\n if (columnName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Default issue has no column in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n return mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName);\n }\n case RelationalSchemaNodeKind.primaryKey:\n return mapPrimaryKeyNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.foreignKey:\n return mapForeignKeyNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.unique:\n return mapUniqueNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.index:\n return mapIndexNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.check:\n return mapCheckNodeIssue(issue, schemaName, tableName);\n default:\n return notOk(nodeConflict('unsupportedOperation', `Unhandled node kind: ${node.nodeKind}`));\n }\n}\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaDiffIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n /**\n * Current database schema IR. Strategies read this to detect whether a\n * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-\n * default safety, extension dependency checks). Defaults to an empty schema\n * when omitted so the planner can still run over \"fresh DB\" contract\n * snapshots.\n */\n readonly schema?: SqlSchemaIR;\n /**\n * Operation-class policy. `planIssues` filters calls whose `operationClass`\n * is not in `policy.allowedOperationClasses` and surfaces them as conflicts\n * instead of emitting disallowed DDL. Defaults to additive-only.\n */\n readonly policy?: MigrationOperationPolicy;\n /**\n * Framework components participating in this composition. Available to\n * future strategies that may consult component metadata at plan time.\n */\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\n/**\n * Runs the ordered strategy list over the node-typed diff issues, maps\n * leftover issues via {@link mapNodeIssueToCall}, applies operation-class\n * policy gating, and buckets calls into the fixed DDL emission order (dep →\n * drop → table → column → recipe → alter → primaryKey → unique → index →\n * foreignKey).\n */\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\n const policyProvided = options.policy !== undefined;\n const policy = options.policy ?? DEFAULT_POLICY;\n const schema = options.schema ?? emptySchemaIR();\n const frameworkComponents = options.frameworkComponents ?? [];\n\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n schemaName: options.schemaName,\n codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? postgresPlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: PostgresOpFactoryCall[] = [];\n const bucketablePatternCalls: PostgresOpFactoryCall[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n if (result.recipe) {\n recipeCalls.push(...result.calls);\n } else {\n bucketablePatternCalls.push(...result.calls);\n }\n }\n }\n\n // Dependency-graph order: a topological sort over the issues' `dependsOn`\n // cross-links and containment edges (the ordering law drives edge direction\n // by presence), path-tiebroken for determinism. `classifyCall` bucketing\n // downstream fixes the coarse cross-entity DDL sequence; this settles the\n // order within each bucket (notably the teardown order among drops).\n const sorted = orderIssuesByDependencies(remaining);\n\n const defaultCalls: PostgresOpFactoryCall[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapNodeIssueToCall(issue, context);\n if (result.ok) {\n defaultCalls.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n const allowed = policy.allowedOperationClasses;\n let gatedDefault = defaultCalls;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketablePatternCalls;\n if (policyProvided) {\n const keepIfAllowed = (bucket: PostgresOpFactoryCall[]) => (call: PostgresOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n bucket.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedDefaultBucket: PostgresOpFactoryCall[] = [];\n const gatedRecipeBucket: PostgresOpFactoryCall[] = [];\n const gatedBucketableBucket: PostgresOpFactoryCall[] = [];\n defaultCalls.forEach(keepIfAllowed(gatedDefaultBucket));\n recipeCalls.forEach(keepIfAllowed(gatedRecipeBucket));\n bucketablePatternCalls.forEach(keepIfAllowed(gatedBucketableBucket));\n gatedDefault = gatedDefaultBucket;\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n const combinedBucketable = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) =>\n combinedBucketable.filter((c) => classifyCall(c) === cat);\n\n const calls: PostgresOpFactoryCall[] = [\n ...byCategory('dep'),\n ...byCategory('drop'),\n // DROP TYPE after every table drop — a managed enum type can only go once\n // no live column still uses it.\n ...byCategory('dropType'),\n ...byCategory('table'),\n ...byCategory('column'),\n ...gatedRecipe,\n ...byCategory('alter'),\n ...byCategory('primaryKey'),\n ...byCategory('unique'),\n ...byCategory('index'),\n ...byCategory('foreignKey'),\n // Enablement changes run after all relational DDL (the table must exist)\n // and before the policy calls the planner appends after `planIssues` —\n // the same position the retired imperative enable-on-first-policy used.\n ...byCategory('rlsEnable'),\n ];\n\n return ok({ calls });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type {\n ControlPolicySubject,\n SqlPlannerConflict,\n SuppressionRecord,\n} from '@prisma-next/family-sql/control';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome } 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 { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type PostgresRole, ROLE_DEFAULT_CONTROL_POLICY } from '../postgres-role';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { postgresNodeStorageCoordinate } from '../schema-ir/node-storage-coordinate';\nimport type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { issueColumnName } from './issue-planner';\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 *\n * Lists the creation factories that actually reach the call-side resolver\n * (`resolvePostgresCallControlPolicySubject`) — today only RLS policy\n * creation, from `planPostgresSchemaDiff`. Every other whole-object create\n * (table, schema, native enum, and RLS enablement) is constructed inside\n * `planIssues` and graded on the node side by\n * `resolvePostgresNodeIssueCreationFactoryName`, so none of them are listed\n * here.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>(['createRlsPolicy']);\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\n/**\n * Resolve the namespace a declared storage entity lives in by walking every\n * namespace for one whose `entries` map actually contains the coordinate —\n * a table by its name, a native enum by its physical type name (see\n * {@link postgresNodeStorageCoordinate}). When `ddlSchemaName` is given, the\n * match must also land in that DDL schema (disambiguates same-named entities\n * declared under different namespaces); when omitted, the first namespace\n * that declares the entity wins. Falls back to {@link UNBOUND_NAMESPACE_ID}\n * when no namespace declares it — e.g. an extra/dropped entity the contract\n * doesn't claim at all.\n */\nfunction resolveNamespaceIdForEntity(\n contract: Contract<SqlStorage>,\n coordinate: { readonly entityKind: string; readonly entityName: string },\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const entity = entityAt(contract.storage, { namespaceId, ...coordinate });\n if (!entity) 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 resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n return resolveNamespaceIdForEntity(\n contract,\n { entityKind: 'table', entityName: tableName },\n ddlSchemaName,\n );\n}\n\nexport function 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\nfunction formatSuppressionSubjectLabel(\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject === undefined) return 'unknown';\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n if (subject.entityKind !== undefined && subject.entityName !== undefined) {\n return `${subject.entityKind} \"${ddlSchema}.${subject.entityName}\"`;\n }\n return `namespace \"${ddlSchema}\"`;\n}\n\nfunction postgresSuppressionSummary(\n subjectLabel: string,\n subject: ControlPolicySubject | undefined,\n policy: string,\n): string {\n const namespace = subject?.namespaceId ?? 'unknown';\n const declared = subject?.explicitNodeControlPolicy;\n if (policy === 'external' && declared === 'managed') {\n return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control 'external' but declared 'managed'`;\n }\n const declaredSuffix = declared ? ` but declared '${declared}'` : '';\n return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control '${policy}'${declaredSuffix}`;\n}\n\n/**\n * Render one family {@link SuppressionRecord} into a target `SqlPlannerConflict`.\n * The family decides *that* a subject is suppressed and hands over the raw\n * coordinate + policy; the label, message, and location are rendered here,\n * driven entirely by the subject's own `(entityKind, entityName)` coordinate\n * — no target-owned table-vs-enum vocabulary.\n */\nexport function renderPostgresSuppression(\n record: SuppressionRecord,\n contract: Contract<SqlStorage>,\n): SqlPlannerConflict {\n const subject = record.subject;\n const subjectLabel = formatSuppressionSubjectLabel(subject, contract);\n return {\n kind: 'controlPolicySuppressedCall',\n summary: postgresSuppressionSummary(subjectLabel, subject, record.policy),\n location: {\n ...ifDefined('namespaceId', subject?.namespaceId),\n ...ifDefined('entityKind', subject?.entityKind),\n ...ifDefined('entityName', subject?.entityName),\n ...ifDefined('column', subject?.column),\n },\n meta: {\n controlPolicy: record.policy,\n ...ifDefined('factoryName', record.factoryName),\n ...ifDefined('declaredControlPolicy', subject?.explicitNodeControlPolicy),\n },\n };\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 entityKind: 'table',\n entityName: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\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 * Node kinds whose *absence* is the creation of a whole, top-level Postgres\n * object: a namespace, a table, or a native enum. Used by\n * {@link resolvePostgresNodeIssueCreationFactoryName} to decide whether a\n * `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. RLS policy creation is not\n * listed here — policy issues never reach this issue-based partition (they\n * are routed to `planPostgresSchemaDiff` and gated via the call-based\n * {@link resolvePostgresCallControlPolicySubject} instead).\n */\nconst POSTGRES_NODE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n [PostgresSchemaNodeKind.namespace]: 'createSchema',\n [PostgresSchemaNodeKind.table]: 'createTable',\n [PostgresSchemaNodeKind.nativeEnum]: 'createNativeEnumType',\n});\n\n/**\n * A table `not-equal` issue whose `rlsEnabled` flips OFF→ON (expected on,\n * actual off) is enablement toward `ENABLE ROW LEVEL SECURITY`. It is\n * creation-class on the node side because `isEnablementCreationIssue` and\n * {@link resolvePostgresNodeIssueCreationFactoryName} treat this OFF→ON delta\n * as a creation: enabling RLS establishes the fail-closed guard the declared\n * policy set attaches to, the same grant `tolerated` extends to creating the\n * policies themselves. The opposite direction (`DISABLE`) is a modification\n * and stays managed-only. Keying on the actual delta (not just the expected\n * bit) keeps this correct if a second table attribute ever joins\n * `isEqualTo`: a not-equal with no `rlsEnabled` delta is not enablement, so\n * it is not admitted as creation-class here.\n */\nfunction isEnablementCreationIssue(issue: SchemaDiffIssue<SqlSchemaDiffNode>): boolean {\n if (issueOutcome(issue) !== 'not-equal') return false;\n const { expected, actual } = issue;\n return (\n expected !== undefined &&\n actual !== undefined &&\n PostgresTableSchemaNode.is(expected) &&\n PostgresTableSchemaNode.is(actual) &&\n expected.rlsEnabled === true &&\n actual.rlsEnabled === false\n );\n}\n\nexport function resolvePostgresNodeIssueCreationFactoryName(\n issue: SchemaDiffIssue<SqlSchemaDiffNode>,\n): string | undefined {\n if (isEnablementCreationIssue(issue)) {\n return 'enableRowLevelSecurity';\n }\n if (issueOutcome(issue) !== 'not-found') return undefined;\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n return POSTGRES_NODE_CREATION_FACTORY[node.nodeKind];\n}\n\n/**\n * Resolves the control-policy subject for a node-typed {@link SchemaDiffIssue}\n * (the issue-side mirror of `resolvePostgresCallControlPolicySubject`).\n * Storage entities resolve off their node coordinate; a sub-entity issue\n * resolves off the enclosing table read from the issue path; an unclaimed\n * extra falls back to the unbound coordinate. A role always resolves\n * `'external'` — roles are referenced, never owned.\n */\nexport function resolvePostgresNodeIssueControlPolicySubject(\n issue: SchemaDiffIssue<SqlSchemaDiffNode>,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n\n if (node.nodeKind === PostgresSchemaNodeKind.namespace) {\n const namespaceNode = blindCast<\n PostgresNamespaceSchemaNode,\n 'a postgres-namespace diff node is always a PostgresNamespaceSchemaNode'\n >(node);\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, namespaceNode.schemaName),\n createsNewObject: issueOutcome(issue) === 'not-found',\n };\n }\n\n if (node.nodeKind === PostgresSchemaNodeKind.role) {\n const roleName = issue.path[1];\n const roleEntity =\n roleName === undefined\n ? undefined\n : entityAt<PostgresRole>(contract.storage, {\n namespaceId: UNBOUND_NAMESPACE_ID,\n entityKind: 'role',\n entityName: roleName,\n });\n return {\n namespaceId: UNBOUND_NAMESPACE_ID,\n explicitNodeControlPolicy: roleEntity?.control ?? ROLE_DEFAULT_CONTROL_POLICY,\n createsNewObject: false,\n };\n }\n\n const coordinate = postgresNodeStorageCoordinate(node);\n if (coordinate !== undefined) {\n const namespaceId = resolveNamespaceIdForEntity(contract, coordinate, issue.path[1]);\n const entityControl = entityAt<{ readonly control?: ControlPolicy }>(contract.storage, {\n namespaceId,\n ...coordinate,\n })?.control;\n return {\n namespaceId,\n ...coordinate,\n ...ifDefined('column', issueColumnName(issue)),\n ...ifDefined('explicitNodeControlPolicy', entityControl),\n createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,\n };\n }\n\n const tableName = issue.path[2];\n if (tableName === undefined) return undefined;\n const ddlSchemaName = issue.path[1];\n const namespaceId = resolveNamespaceIdForTable(contract, tableName, ddlSchemaName);\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\n\n return {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n ...ifDefined('column', issueColumnName(issue)),\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,8BACd,MACiE;CACjE,IAAI,wBAAwB,GAAG,IAAI,GAAG;EACpC,MAAM,aAAa,uBAAuB,KAAK,QAAQ;EACvD,OAAO,eAAe,KAAA,IAAY,KAAA,IAAY;GAAE;GAAY,YAAY,KAAK;EAAK;CACpF;CACA,IAAI,6BAA6B,GAAG,IAAI,GAAG;EACzC,MAAM,aAAa,uBAAuB,KAAK,QAAQ;EACvD,OAAO,eAAe,KAAA,IAAY,KAAA,IAAY;GAAE;GAAY,YAAY,KAAK;EAAS;CACxF;AAEF;;;;;;;;;;;;;;;ACAA,SAAS,WACP,QAIA;CACA,IAAI,OAAO,aAAa,KAAA,KAAa,OAAO,wBAAwB,KAAA,GAClE,MAAM,IAAI,cACR,gCAAgC,OAAO,KAAK,oGAC9C;CAEF,OAAO;EACL,YAAY,OAAO;EACnB,SAAS,OAAO,SAAS;EACzB,UAAU,OAAO;EAIjB,GAAG,UAAU,QAAQ,OAAO,QAAQ,OAAO,SAAS,IAAI;EACxD,GAAG,UACD,cACA,OAAO,SAAS,eAAe,KAAA,IAC3B,UAGE,OAAO,SAAS,UAAU,IAC5B,KAAA,CACN;EACA,GAAI,OAAO,iBAAiB,EAAE,SAAS,aAAa,IAAI,CAAC;EACzD,GAAG,UAAU,WAAW,OAAO,eAAe;CAChD;AACF;;;;;;;AAQA,SAAgB,gBACd,MACA,QACA,YACW;CACX,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAM,UAAU,mBAAmB,MAAM,YAAY,CAAC,CAAC;CACvD,MAAM,aAAa,kCAAkC,KAAK,OAAO;CACjE,OAAO,aAAa,IAAI,MAAM,SAAS;E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AAK,EAAE;EACnF,MAAM,gBAAgB,SAA+C,SAAS,SAAS;GACrF;GACA,GAAG;EACL,CAAC,CAAC,EAAE;EACJ,OAAO;GACL;GACA,GAAG;GACH,GAAG,UAAU,UAAU,gBAAgB,KAAK,CAAC;GAC7C,GAAG,UAAU,6BAA6B,aAAa;GACvD,kBAAkB,4CAA4C,KAAK,MAAM,KAAA;EAC3E;CACF;CAEA,MAAM,YAAY,MAAM,KAAK;CAC7B,IAAI,cAAc,KAAA,GAAW,OAAO,KAAA;CACpC,MAAM,gBAAgB,MAAM,KAAK;CACjC,MAAM,cAAc,2BAA2B,UAAU,WAAW,aAAa;CACjF,MAAM,QAAQ,SAAuB,SAAS,SAAS;EACrD;EACA,YAAY;EACZ,YAAY;CACd,CAAC;CAED,OAAO;EACL;EACA,YAAY;EACZ,YAAY;EACZ,GAAG,UAAU,UAAU,gBAAgB,KAAK,CAAC;EAC7C,GAAG,UAAU,6BAA6B,OAAO,OAAO;EACxD,kBAAkB,4CAA4C,KAAK,MAAM,KAAA;CAC3E;AACF"}
1
+ {"version":3,"file":"control-policy-DMZVl4x7.mjs","names":[],"sources":["../src/core/schema-ir/node-storage-coordinate.ts","../src/core/migrations/column-ddl-rendering.ts","../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/control-policy.ts"],"sourcesContent":["import type { EntityCoordinate } from '@prisma-next/framework-components/ir';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { PostgresNativeEnumSchemaNode } from './postgres-native-enum-schema-node';\nimport { PostgresTableSchemaNode } from './postgres-table-schema-node';\nimport { postgresNodeEntityKind } from './schema-node-kinds';\n\n/**\n * The storage-`entries` coordinate `(entityKind, entityName)` a Postgres diff\n * node addresses — a table by its name, a native enum by its physical type\n * name. `undefined` for a node that is not a whole storage entity (a namespace,\n * a column, a policy). Lets ownership/subject resolution treat every entity kind\n * uniformly, the node self-describing its storage identity.\n */\nexport function postgresNodeStorageCoordinate(\n node: SqlSchemaIRNode,\n): Pick<EntityCoordinate, 'entityKind' | 'entityName'> | undefined {\n if (PostgresTableSchemaNode.is(node)) {\n const entityKind = postgresNodeEntityKind(node.nodeKind);\n return entityKind === undefined ? undefined : { entityKind, entityName: node.name };\n }\n if (PostgresNativeEnumSchemaNode.is(node)) {\n const entityKind = postgresNodeEntityKind(node.nodeKind);\n return entityKind === undefined ? undefined : { entityKind, entityName: node.typeName };\n }\n return undefined;\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn } from '@prisma-next/sql-relational-core/ast';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport type { SqlColumnDefaultIR, SqlColumnIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { InternalError } from '@prisma-next/utils/internal-error';\nimport { postgresDefaultToDdlColumnDefault } from './op-factory-call';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport { buildExpectedFormatType } from './planner-sql-checks';\n\n/**\n * Reconstructs the `StorageColumn`-shaped fields the DDL builder functions\n * (`buildColumnTypeSql`, `buildExpectedFormatType`, `resolveIdentityValue`)\n * expect, from a column node's own stamped codec identity (`codecRef` /\n * `codecBaseNativeType` / `codecNamedType`, Decision 5) — never the\n * contract. The builders were written against `StorageColumn` and are\n * unchanged here; only the shape feeding them moves from the contract to\n * the node. An empty `storageTypes` catalog is passed alongside: the\n * node's fields are already resolved past any `typeRef` indirection, so no\n * live lookup is needed, and passing a non-empty catalog would risk a\n * false `typeRef` hit against an unrelated storage type.\n */\nfunction columnLike(\n column: SqlColumnIR,\n): Pick<\n StorageColumn,\n 'nativeType' | 'codecId' | 'nullable' | 'many' | 'typeParams' | 'typeRef' | 'default'\n> {\n if (column.codecRef === undefined || column.codecBaseNativeType === undefined) {\n throw new InternalError(\n `columnLike: expected column \"${column.name}\" carries no codec identity — the expected tree must be derived via contractToSchemaIR for planning`,\n );\n }\n return {\n nativeType: column.codecBaseNativeType,\n codecId: column.codecRef.codecId,\n nullable: column.nullable,\n // `column.many` is unset on contract-derived columns (array-ness rides\n // on the `nativeType` `[]` suffix there instead) — `codecRef.many`\n // carries it. Hand-built/introspected columns set `column.many` directly.\n ...ifDefined('many', column.many ?? column.codecRef.many),\n ...ifDefined(\n 'typeParams',\n column.codecRef.typeParams !== undefined\n ? blindCast<\n Record<string, unknown>,\n 'CodecRef.typeParams is JsonValue-shaped; the DDL builders only ever read it as the Record the contract column originally carried'\n >(column.codecRef.typeParams)\n : undefined,\n ),\n ...(column.codecNamedType ? { typeRef: '<resolved>' } : {}),\n ...ifDefined('default', column.resolvedDefault),\n };\n}\n\n/**\n * Builds the `CREATE TABLE` / `ADD COLUMN` DDL column for an expected column\n * node, resolving type rendering from the node's codec identity against the\n * codec hooks the caller holds — the same builder the pre-`plan(start, end)`\n * op-path called, so the output is byte-identical.\n */\nexport function renderColumnDdl(\n name: string,\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): DdlColumn {\n const like = columnLike(column);\n const typeSql = buildColumnTypeSql(like, codecHooks, {});\n const ddlDefault = postgresDefaultToDdlColumnDefault(like.default);\n return contractFree.col(name, typeSql, {\n ...(!column.nullable ? { notNull: true } : {}),\n ...ifDefined('default', ddlDefault),\n ...ifDefined('codecRef', column.codecRef),\n });\n}\n\n/**\n * Builds the `ALTER COLUMN … TYPE` operands for an expected column node.\n */\nexport function renderColumnAlterType(\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): { readonly qualifiedTargetType: string; readonly formatTypeExpected: string } {\n const like = columnLike(column);\n return {\n qualifiedTargetType: buildColumnTypeSql(like, codecHooks, {}, false),\n formatTypeExpected: buildExpectedFormatType(like, codecHooks, {}),\n };\n}\n\n/**\n * Resolves the identity value (monoid neutral element) SQL literal used as\n * the temporary default when adding a NOT-NULL column with no contract\n * default (`notNullAddColumnCallStrategy`'s shared-temp-default backfill).\n * `null` when the column's type has no built-in/codec-provided identity\n * value.\n */\nexport function resolveColumnTemporaryDefault(\n column: SqlColumnIR,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): string | null {\n return resolveIdentityValue(columnLike(column), codecHooks, {});\n}\n\n/**\n * The column's `SET DEFAULT` clause SQL, resolved from a column-default\n * diff node. `''` when the node carries no resolved default.\n */\nexport function renderColumnDefaultSql(defaultNode: SqlColumnDefaultIR): string {\n if (defaultNode.resolved === undefined) return '';\n return buildColumnDefaultSql(defaultNode.resolved, {\n nativeType: defaultNode.nativeTypeContext ?? '',\n ...ifDefined('many', defaultNode.many),\n });\n}\n","/**\n * Migration strategies.\n *\n * Each strategy examines the node-typed diff-issue list, consumes issues it\n * handles, and returns the `PostgresOpFactoryCall[]` to address them. The\n * issue planner runs each strategy in order and routes whatever's left\n * through `mapNodeIssueToCall`.\n *\n * The full ordered list is exported as `postgresPlannerStrategies` and is\n * used unchanged by both `migration plan` and `db update` / `db init`. The\n * two journeys differ only in `policy.allowedOperationClasses`:\n *\n * - When `'data'` is in the policy, data-safe strategies (NOT NULL backfill,\n * nullability tightening, unsafe type changes) emit\n * `DataTransformCall` placeholders that the user fills in.\n * - When `'data'` is excluded, those strategies short-circuit so the\n * downstream strategies (codec-hook type ops and temp-default backfill)\n * and `mapNodeIssueToCall` defaults emit direct DDL instead.\n *\n * Structural decisions (type/nullability drift, DDL fragments) read the diff\n * node pair and resolve column DDL from the node's `codecRef` (`column-ddl-\n * rendering.ts`). The retained subsystems — codec type-operations\n * (`storageTypePlanCallStrategy`) and the NOT-NULL temp-default deferred DDL\n * (`notNullAddColumnCallStrategy`) — keep reading the contract + codec hooks\n * via `StrategyContext`, per the slice's scope (see `diff-database-schema.ts`\n * / the slice spec).\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport { resolveValueSetValues } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n type SqlStorage,\n StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport {\n RelationalSchemaNodeKind,\n type SqlColumnIR,\n type SqlSchemaIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { isPostgresSchema } from '../postgres-schema';\nimport {\n renderColumnAlterType,\n renderColumnDdl,\n resolveColumnTemporaryDefault,\n} from './column-ddl-rendering';\nimport { resolveNamespaceIdForDdlSchema } from './control-policy';\nimport { emissionSchemaName, issueNode, issueSchemaName, issueTableName } from './issue-planner';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddNotNullColumnDirectCall,\n AddNotNullColumnWithTempDefaultCall,\n AlterColumnTypeCall,\n DataTransformCall,\n DropCheckConstraintCall,\n DropNotNullCall,\n type PostgresOpFactoryCall,\n RawSqlCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { buildSchemaLookupMap, hasForeignKey, hasUniqueConstraint } from './planner-schema-lookup';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Look up a storage table by its explicit namespace coordinate. Returns\n * `undefined` when the namespace has no table by that name (or no such\n * namespace exists). Callers that get `undefined` MUST treat it as an\n * explicit conflict — never silently fall back to a global default\n * schema or a name-only walk, because that footgun would resolve a\n * stale or duplicate table name to whichever namespace the iteration\n * order surfaced first (a real data-loss hazard in multi-namespace\n * contracts where two namespaces can carry the same table name).\n */\nexport function tableAt(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const ns = storage.namespaces[namespaceId];\n if (ns === undefined) return undefined;\n return ns.entries.table?.[tableName];\n}\n\n/**\n * Resolve the DDL schema name for a namespace coordinate. Postgres-aware\n * namespaces dispatch to their polymorphic `ddlSchemaName` override —\n * named schemas return their own id; the unbound singleton returns\n * `UNBOUND_NAMESPACE_ID`. Legacy single-namespace contracts whose\n * `__unbound__` slot is the framework-default `SqlUnboundNamespace`\n * (rather than the Postgres-aware `PostgresUnboundSchema`) flow the\n * coordinate through unchanged so downstream `qualifyTableName`\n * resolves polymorphically.\n */\nexport function resolveDdlSchemaForNamespace(ctx: StrategyContext, namespaceId: string): string {\n const namespace = ctx.toContract.storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(ctx.toContract.storage);\n }\n return namespaceId;\n}\n\n/**\n * Recovers the contract namespace id for a DDL schema name embedded in a\n * diff-issue path (`path[1]`). The strategies need the CONTRACT column/table\n * (for codec-hook reads and eligibility probes the retained subsystems still\n * run) even though the issue itself only carries the resolved DDL schema —\n * this is the reverse of `resolveDdlSchemaForNamespace`.\n */\nfunction namespaceIdForDdlSchema(ctx: StrategyContext, ddlSchemaName: string): string {\n return resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);\n}\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/**\n * Context passed to each migration strategy.\n *\n * Strategies read the source (`fromContract`), target (`toContract`), current\n * database state (`schema`), operation policy (`policy`), and component list\n * (`frameworkComponents`) to make planning decisions. `fromContract` is null\n * when no prior contract is available (e.g. `db update`, where the current\n * DB state is approximated via `schema`).\n */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n readonly schema: SqlSchemaIR;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n// ============================================================================\n// Call strategies (for issue planner)\n// ============================================================================\n\n/**\n * Consumes node-typed diff issues (`SchemaDiffIssue`, from the one differ —\n * `buildPostgresPlanDiff`), reading the issue's node pair for structural\n * decisions and resolving column DDL from the node's `codecRef`. The\n * retained subsystems (codec type-operations, the NOT-NULL temp-default\n * backfill) keep reading the contract via `StrategyContext`.\n */\nexport type CallMigrationStrategy = (\n issues: readonly SchemaDiffIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaDiffIssue[];\n calls: readonly PostgresOpFactoryCall[];\n /**\n * `true` for strategies that emit cohesive sequential recipes whose\n * calls must stay contiguous and in the returned order — e.g.\n * `notNullBackfillCallStrategy` (addColumn → dataTransform → setNotNull).\n * Defaults to `false`, which lets `planIssues` hoist individual calls\n * into their DDL sequencing bucket.\n */\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\n/** A `not-equal` column issue whose node pair is narrowed to `SqlColumnIR`. */\nfunction columnNodePair(\n issue: SchemaDiffIssue,\n): { readonly expected: SqlColumnIR; readonly actual: SqlColumnIR } | undefined {\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) return undefined;\n if (issue.expected === undefined || issue.actual === undefined) return undefined;\n return {\n expected: blindCast<SqlColumnIR, 'a column diff node is always a SqlColumnIR'>(issue.expected),\n actual: blindCast<SqlColumnIR, 'a column diff node is always a SqlColumnIR'>(issue.actual),\n };\n}\n\nexport const notNullBackfillCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `notNullAddColumnCallStrategy`\n // (temp-default backfill) or `mapNodeIssueToCall` can take the issue.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-found') continue;\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) continue;\n const expected = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n if (expected.nullable !== false || expected.resolvedDefault !== undefined) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n const ddl = renderColumnDdl(expected.name, expected, ctx.codecHooks);\n const nullableSpec = contractFree.col(ddl.name, ddl.type, {\n ...(ddl.codecRef !== undefined ? { codecRef: ddl.codecRef } : {}),\n });\n calls.push(\n new AddColumnCall(schemaName, tableName, nullableSpec),\n new DataTransformCall(\n `backfill-${tableName}-${expected.name}`,\n `backfill-${tableName}-${expected.name}:check`,\n `backfill-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nconst SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n\n/**\n * Handles `not-equal` column issues whose TYPE differs. `fromContract` is\n * only supplied by `migration plan` — for reconciliation (`db update` /\n * `db init`, `fromContract === null`) this strategy never fires, mirroring\n * the legacy `typeChangeCallStrategy`'s requirement of a prior contract:\n * `mapNodeIssueToCall`'s in-place ALTER covers reconciliation directly.\n *\n * A single node issue can carry BOTH type and nullability drift (Postgres\n * alters in place, so the differ emits one `not-equal` column issue where\n * the legacy coordinate walk emitted two: `type_mismatch` +\n * `nullability_mismatch`). When this strategy consumes the issue for its\n * type portion, it also emits whatever nullability delta the same node pair\n * carries — using the same construction `nullableTighteningCallStrategy` /\n * the mapper's direct dispatch would have used — so the issue is never\n * partially handled.\n */\nexport const typeChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n if (ctx.fromContract === null) return { kind: 'no_match' };\n const dataAllowed = ctx.policy.allowedOperationClasses.includes('data');\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-equal') continue;\n const pair = columnNodePair(issue);\n if (pair === undefined) continue;\n const { expected, actual } = pair;\n if (!columnTypeChangedNativeOnly(expected, actual)) continue;\n\n const fromType = actual.nativeType;\n const toType = expected.nativeType;\n const isSafeWidening = SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n if (!isSafeWidening && !dataAllowed) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(\n expected,\n ctx.codecHooks,\n );\n const alterOpts = {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n };\n if (isSafeWidening) {\n calls.push(new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts));\n } else {\n calls.push(\n new DataTransformCall(\n `typechange-${tableName}-${expected.name}`,\n `typechange-${tableName}-${expected.name}:check`,\n `typechange-${tableName}-${expected.name}:run`,\n ),\n new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts),\n );\n }\n\n if (expected.nullable !== actual.nullable) {\n if (expected.nullable) {\n calls.push(new DropNotNullCall(schemaName, tableName, expected.name));\n } else if (dataAllowed) {\n calls.push(\n new DataTransformCall(\n `handle-nulls-${tableName}-${expected.name}`,\n `handle-nulls-${tableName}-${expected.name}:check`,\n `handle-nulls-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n } else {\n calls.push(new SetNotNullCall(schemaName, tableName, expected.name));\n }\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n/**\n * Whether the raw (unresolved) native type differs — the SAME comparison\n * `typeChangeCallStrategy` always used (`fromColumn.nativeType !==\n * toColumn.nativeType`), which for the widenable numeric/float types\n * `SAFE_WIDENINGS` lists is identical to the resolved comparison\n * `columnTypeChanged` (in `issue-planner.ts`) performs.\n */\nfunction columnTypeChangedNativeOnly(expected: SqlColumnIR, actual: SqlColumnIR): boolean {\n return expected.nativeType !== actual.nativeType;\n}\n\n/**\n * Handles `not-equal` column issues whose type did NOT change but\n * nullability tightened (contract requires NOT NULL, live column is\n * nullable). A type-changed issue's nullability delta (if any) is already\n * handled by `typeChangeCallStrategy`, which runs first — this strategy\n * only ever sees issues that strategy left behind.\n */\nexport const nullableTighteningCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `mapNodeIssueToCall` emits a direct\n // `SET NOT NULL` instead.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-equal') continue;\n const pair = columnNodePair(issue);\n if (pair === undefined) continue;\n const { expected, actual } = pair;\n if (columnTypeChangedNativeOnly(expected, actual)) continue; // typeChangeCallStrategy's concern\n if (expected.nullable !== false || actual.nullable !== true) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n matched.push(issue);\n calls.push(\n new DataTransformCall(\n `handle-nulls-${tableName}-${expected.name}`,\n `handle-nulls-${tableName}-${expected.name}:check`,\n `handle-nulls-${tableName}-${expected.name}:run`,\n ),\n new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n/**\n * Collects every check constraint from a table in the contract storage.\n * Returns an empty array when the table has no checks or the table is absent.\n */\nfunction collectContractChecks(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): ReadonlyArray<{ name: string; column: string; permittedValues: readonly string[] }> {\n const ns = storage.namespaces[namespaceId];\n const tableRaw = ns !== undefined ? ns.entries.table?.[tableName] : undefined;\n if (!(tableRaw instanceof StorageTable)) return [];\n const checks = tableRaw.checks;\n if (!checks || checks.length === 0) return [];\n return checks.map((c) => ({\n name: c.name,\n column: c.column,\n permittedValues: resolveValueSetValues(\n c.valueSet,\n storage,\n `check \"${c.name}\" on \"${tableName}\"`,\n ),\n }));\n}\n\n/**\n * Compares two value arrays as unordered sets.\n */\nfunction checkValueSetsEqual(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n const bSet = new Set(b);\n return a.every((v) => bSet.has(v));\n}\n\n/**\n * Plans check-constraint migrations for `enumType`-authored columns.\n *\n * Walks every namespace's tables in the target contract (the check nodes'\n * resolved `permittedValues` are ultimately sourced from the same\n * contract-declared value sets, so walking the contract directly is the\n * simplest faithful port — the strategy's decisions never depend on which\n * ISSUES happen to be in the input list, only on the contract + live schema\n * shapes). For each table that carries `checks`, diffs the contract-expected\n * checks against the live schema's checks:\n *\n * - Check in contract, absent from live DB → `AddCheckConstraintCall`.\n * - Check in live DB, absent from contract → `DropCheckConstraintCall`.\n * - Check on both sides but value sets differ → `DropCheckConstraintCall`\n * then `AddCheckConstraintCall` (drop + recreate; a check predicate cannot\n * be altered in place).\n *\n * Consumes every `sql-check-constraint` issue on a table this walk handles\n * (not-found/not-expected/not-equal), leaving check issues on tables with\n * NO contract checks to `mapNodeIssueToCall`'s `not-expected` fallback.\n */\nexport const checkConstraintPlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const calls: PostgresOpFactoryCall[] = [];\n const handledIssueKeys = new Set<string>();\n\n for (const [namespaceId, ns] of Object.entries(ctx.toContract.storage.namespaces)) {\n for (const tableName of Object.keys(ns.entries.table ?? {})) {\n const contractChecks = collectContractChecks(ctx.toContract.storage, namespaceId, tableName);\n if (contractChecks.length === 0) continue;\n\n const schemaTable = ctx.schema.tables[tableName];\n const liveChecks = schemaTable?.checks ?? [];\n const ddlSchema = resolveDdlSchemaForNamespace(ctx, namespaceId);\n\n for (const contractCheck of contractChecks) {\n const liveCheck = liveChecks.find((c) => c.name === contractCheck.name);\n const issueKey = `${tableName} ${contractCheck.name}`;\n if (!liveCheck) {\n calls.push(\n new AddCheckConstraintCall(\n ddlSchema,\n tableName,\n contractCheck.name,\n contractCheck.column,\n contractCheck.permittedValues,\n ),\n );\n handledIssueKeys.add(issueKey);\n } else if (!checkValueSetsEqual(contractCheck.permittedValues, liveCheck.permittedValues)) {\n calls.push(\n new DropCheckConstraintCall(ddlSchema, tableName, contractCheck.name),\n new AddCheckConstraintCall(\n ddlSchema,\n tableName,\n contractCheck.name,\n contractCheck.column,\n contractCheck.permittedValues,\n ),\n );\n handledIssueKeys.add(issueKey);\n }\n // else: values match — no op needed, still consume the issue\n else {\n handledIssueKeys.add(issueKey);\n }\n }\n\n // Emit drops for checks that are live but not in the contract.\n for (const liveCheck of liveChecks) {\n const inContract = contractChecks.some((c) => c.name === liveCheck.name);\n if (!inContract) {\n const issueKey = `${tableName} ${liveCheck.name}`;\n calls.push(new DropCheckConstraintCall(ddlSchema, tableName, liveCheck.name));\n handledIssueKeys.add(issueKey);\n }\n }\n }\n }\n\n if (calls.length === 0 && handledIssueKeys.size === 0) return { kind: 'no_match' };\n\n const remaining = issues.filter((issue) => {\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.check) return true;\n const tableName = issueTableName(issue);\n if (tableName === undefined) return true;\n const checkName = blindCast<{ readonly name: string }, 'a check node always carries a name'>(\n node,\n ).name;\n return !handledIssueKeys.has(`${tableName} ${checkName}`);\n });\n\n return { kind: 'match', issues: remaining, calls };\n};\n\n/**\n * Dispatches codec-typed storage types through their codec's\n * `planTypeOperations` hook (the authoritative source for codec-driven DDL\n * such as custom type creation). Codec extension/type ops are not modeled as\n * diff nodes — this strategy drives entirely off `ctx.toContract.storage.types`\n * + codec hooks, consuming nothing from the node issue list (there is no\n * node-vocabulary equivalent of `type_missing` / `enum_values_changed`).\n */\nexport const storageTypePlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const storageTypes = ctx.toContract.storage.types ?? {};\n if (Object.keys(storageTypes).length === 0) return { kind: 'no_match' };\n\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n const codecInstance = typeInstance as StorageTypeInstance;\n const hook = ctx.codecHooks.get(codecInstance.codecId);\n if (!hook?.planTypeOperations) continue;\n const planResult = hook.planTypeOperations({\n typeName,\n typeInstance: codecInstance,\n contract: ctx.toContract,\n schema: ctx.schema,\n schemaName: ctx.schemaName,\n policy: ctx.policy,\n });\n if (!planResult) continue;\n for (const op of planResult.operations) {\n calls.push(\n new RawSqlCall({\n ...op,\n target: {\n id: op.target.id,\n details: buildTargetDetails('type', typeName, ctx.schemaName),\n },\n } as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),\n );\n }\n }\n\n if (calls.length === 0) return { kind: 'no_match' };\n return { kind: 'match', issues, calls };\n};\n\n/**\n * Handles `not-found` column issues for NOT NULL columns without a contract\n * default. Replaces the legacy `buildAddColumnItem` non-default branches.\n *\n * Two shapes:\n * - Shared-temp-default safe: emit a single atomic composite op (add\n * nullable → backfill identity value → `SET NOT NULL` → `DROP DEFAULT`).\n * The temp-default value is resolved from the column node's `codecRef`\n * (`resolveColumnTemporaryDefault`, wrapping `resolveIdentityValue`).\n * - Empty-table guarded: emit a hand-built op with a `tableIsEmptyCheck`\n * precheck so the failure message is \"table is not empty\" rather than the\n * raw PG NOT NULL violation.\n *\n * \"Normal\" not-found column cases (nullable or has a contract default) are\n * left for `mapNodeIssueToCall`'s default `AddColumnCall` emission.\n */\nexport const notNullAddColumnCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const matched: SchemaDiffIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n const schemaLookups = buildSchemaLookupMap(ctx.schema);\n\n const mutableCodecHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableStorageTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n\n for (const issue of issues) {\n if (issueOutcome(issue) !== 'not-found') continue;\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== RelationalSchemaNodeKind.column) continue;\n const expected = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n if (expected.nullable !== false || expected.resolvedDefault !== undefined) continue;\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) continue;\n\n const namespaceId = namespaceIdForDdlSchema(ctx, ddlSchemaName);\n const schemaName = namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, tableName);\n const column = contractTable?.columns[expected.name];\n if (!contractTable || !column) continue;\n\n const schemaTable = ctx.schema.tables[tableName];\n if (!schemaTable) continue;\n\n const temporaryDefault = resolveColumnTemporaryDefault(expected, ctx.codecHooks);\n const schemaLookup = schemaLookups.get(tableName);\n const canUseSharedTempDefault =\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table: contractTable,\n schemaTable,\n schemaLookup,\n columnName: expected.name,\n });\n\n matched.push(issue);\n\n if (canUseSharedTempDefault && temporaryDefault !== null) {\n calls.push(\n new AddNotNullColumnWithTempDefaultCall({\n schemaName,\n tableName,\n columnName: expected.name,\n column,\n codecHooks: mutableCodecHooks,\n storageTypes: mutableStorageTypes,\n temporaryDefault,\n }),\n );\n continue;\n }\n\n calls.push(\n new AddNotNullColumnDirectCall(\n schemaName,\n tableName,\n expected.name,\n renderColumnDdl(expected.name, expected, ctx.codecHooks),\n ),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n };\n};\n\n// ============================================================================\n// Strategy helpers\n// ============================================================================\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: ReturnType<typeof buildSchemaLookupMap> extends ReadonlyMap<\n string,\n infer V\n >\n ? V | undefined\n : never;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) return false;\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (!foreignKey.source.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) return false;\n }\n\n return true;\n}\n\n/**\n * Ordered list of Postgres planner strategies, shared by `migration plan`\n * and `db update` / `db init`. The issue planner runs each strategy in\n * order, letting it consume any issues it handles, and routes whatever's\n * left through `mapNodeIssueToCall`. Behavior diverges purely on\n * `policy.allowedOperationClasses`:\n *\n * - When `'data'` is allowed (`migration plan`), the data-safe strategies\n * (`notNullBackfillCallStrategy`, `typeChangeCallStrategy`,\n * `nullableTighteningCallStrategy`) consume their matching issues and emit\n * `DataTransformCall` placeholders or recipe ops.\n *\n * - When `'data'` is not allowed (`db update` / `db init`), the\n * placeholder-emitting strategies short-circuit to `no_match`, leaving\n * the issue for the downstream strategies (`storageTypePlanCallStrategy`,\n * `notNullAddColumnCallStrategy`) or the `mapNodeIssueToCall` default to\n * handle with direct DDL.\n *\n * Codec-typed storage type entries are dispatched through\n * `storageTypePlanCallStrategy`.\n */\nexport const postgresPlannerStrategies: readonly CallMigrationStrategy[] = [\n notNullBackfillCallStrategy,\n typeChangeCallStrategy,\n nullableTighteningCallStrategy,\n checkConstraintPlanCallStrategy,\n storageTypePlanCallStrategy,\n notNullAddColumnCallStrategy,\n];\n","/**\n * Postgres migration issue planner.\n *\n * Takes node-typed schema-diff issues (from the one differ — see\n * `buildPostgresPlanDiff` in `diff-database-schema.ts`) and emits migration\n * IR (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize\n * and produce specialized call sequences (e.g. NOT NULL backfill →\n * addColumn(nullable) + dataTransform + setNotNull); remaining issues flow\n * through `mapNodeIssueToCall` for the default case.\n *\n * Structural op-render (column type/default DDL) resolves the column node's\n * `codecRef` against the codec hooks the caller holds (`column-ddl-\n * rendering.ts`) — never re-derived from the contract. The retained\n * subsystems (codec type-operations, the NOT-NULL temp-default deferred DDL,\n * control-policy disposition) still read the contract via the strategy\n * context, per the slice's scope.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome, orderIssuesByDependencies } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport * as contractFree from '@prisma-next/sql-relational-core/contract-free';\nimport {\n RelationalSchemaNodeKind,\n type SqlColumnDefaultIR,\n type SqlColumnIR,\n type SqlForeignKeyIR,\n type SqlIndexIR,\n SqlSchemaIR,\n type SqlSchemaIRNode,\n type SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport type { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport type { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { quoteIdentifier } from '../sql-utils';\nimport {\n renderColumnAlterType,\n renderColumnDdl,\n renderColumnDefaultSql,\n} from './column-ddl-rendering';\nimport { resolveNamespaceIdForDdlSchema } from './control-policy';\nimport {\n AddColumnCall,\n AddForeignKeyCall,\n AddNativeEnumValueCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n CreateIndexCall,\n CreateNativeEnumTypeCall,\n CreateSchemaCall,\n CreateTableCall,\n DisableRowLevelSecurityCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNativeEnumTypeCall,\n DropNotNullCall,\n DropTableCall,\n EnableRowLevelSecurityCall,\n type PostgresOpFactoryCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport type { ForeignKeySpec } from './operations/shared';\nimport {\n type CallMigrationStrategy,\n postgresPlannerStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n/**\n * Deterministic name for the element-non-null CHECK constraint on a scalar-array\n * column. Distinct `_elem_not_null` suffix avoids collision with the enum\n * value-set `_check` constraints. Re-emitting the same schema produces the same\n * name, so `pg_get_constraintdef`-based verify sees no drift.\n */\nfunction elementNonNullCheckName(tableName: string, columnName: string): string {\n return `${tableName}_${columnName}_elem_not_null`;\n}\n\n/**\n * Predicate enforcing that a scalar-array column carries no NULL element. The\n * array column itself may be NULL (container nullability is the column's NOT NULL\n * clause); `array_position` over a NULL array yields NULL, which a CHECK treats\n * as satisfied, so a nullable array column is unaffected.\n */\nfunction elementNonNullCheckExpression(columnName: string): string {\n return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly PostgresOpFactoryCall[];\n}\n\n/**\n * Classifies calls into dependency order categories for correct DDL sequencing.\n */\ntype CallCategory =\n | 'dep'\n | 'drop'\n | 'dropType'\n | 'table'\n | 'rlsEnable'\n | 'rlsPolicy'\n | 'column'\n | 'alter'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\n/**\n * Classifies calls into DDL sequencing buckets. The order matches the\n * legacy walk-schema planner's emission order so `db init` and `db update`\n * produce byte-identical plans for the shared shape (deps → drops → tables\n * → columns → alters → PKs → uniques → indexes → FKs).\n *\n * `dropType` (DROP TYPE for a managed native enum) is its own bucket, ordered\n * after the general drop bucket: a type can only be dropped once every table\n * whose column uses it is gone. A column→enum edge would make this precise,\n * but `coalesceSubtreeIssues` removes the column issue under a whole-table\n * drop, so the edge never reaches the graph; the coarse bucket stands in until\n * that edge lands (the coordinate work is a later slice).\n */\nfunction classifyCall(call: PostgresOpFactoryCall): CallCategory {\n switch (call.factoryName) {\n case 'createExtension':\n case 'createSchema':\n case 'createNativeEnumType':\n case 'addNativeEnumValue':\n return 'dep';\n case 'dropNativeEnumType':\n return 'dropType';\n case 'dropTable':\n case 'dropColumn':\n case 'dropConstraint':\n case 'dropCheckConstraint':\n case 'dropIndex':\n case 'dropDefault':\n return 'drop';\n case 'addCheckConstraint':\n return 'unique'; // after uniques, before indexes\n case 'createTable':\n return 'table';\n case 'enableRowLevelSecurity':\n case 'disableRowLevelSecurity':\n return 'rlsEnable';\n case 'createRlsPolicy':\n return 'rlsPolicy';\n case 'dropRlsPolicy':\n return 'drop';\n case 'addColumn':\n return 'column';\n case 'alterColumnType':\n case 'setNotNull':\n case 'dropNotNull':\n case 'setDefault':\n return 'alter';\n case 'addPrimaryKey':\n return 'primaryKey';\n case 'addUnique':\n return 'unique';\n case 'createIndex':\n case 'renameIndex':\n return 'index';\n case 'addForeignKey':\n return 'foreignKey';\n case 'rawSql': {\n // Type ops lifted through `RawSqlCall` by `storageTypePlanCallStrategy`\n // to preserve the codec-emitted label and precheck/postcheck.\n // Classification falls back to inspecting the underlying op's target\n // details (`objectType: 'type'`).\n const op = (\n call as {\n op?: {\n target?: { details?: { objectType?: string } };\n };\n }\n ).op;\n const objectType = op?.target?.details?.objectType;\n if (objectType === 'type') return 'dep';\n return 'alter';\n }\n default:\n return 'alter';\n }\n}\n\n// When no policy is explicitly supplied (test-only path; production callers\n// always pass one), allow every class so strategies that gate on\n// `'data'` (data-safe placeholders) still fire — the test is treated as\n// trusted. Filtering of actual emitted calls only runs when a policy was\n// explicitly provided (see `policyProvided` below).\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return new SqlSchemaIR({ tables: {} });\n}\n\nfunction conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'alterColumnType':\n return 'typeMismatch';\n case 'setNotNull':\n case 'dropNotNull':\n return 'nullabilityConflict';\n case 'addForeignKey':\n case 'dropConstraint':\n return 'foreignKeyConflict';\n case 'createIndex':\n case 'renameIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['location'] | undefined {\n // Most Postgres call classes expose `tableName`/`columnName`/`indexName`/\n // `constraintName` as readonly fields. We avoid `toOp()` here because a\n // `DataTransformCall` intentionally throws from `toOp`.\n const anyCall = call as unknown as {\n tableName?: string;\n columnName?: string;\n indexName?: string;\n newIndexName?: string;\n constraintName?: string;\n typeName?: string;\n };\n const location: {\n entityKind?: string;\n entityName?: string;\n column?: string;\n index?: string;\n constraint?: string;\n } = {};\n if (anyCall.tableName) {\n location.entityKind = 'table';\n location.entityName = anyCall.tableName;\n } else if (anyCall.typeName) {\n location.entityKind = 'native_enum';\n location.entityName = anyCall.typeName;\n }\n if (anyCall.columnName) location.column = anyCall.columnName;\n // A rename call carries old/new index names; the new name is the index's\n // contract-side identity, so it is the conflict location.\n if (anyCall.indexName) location.index = anyCall.indexName;\n else if (anyCall.newIndexName) location.index = anyCall.newIndexName;\n if (anyCall.constraintName) location.constraint = anyCall.constraintName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: PostgresOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\n// ============================================================================\n// Node-based issue planner\n// ============================================================================\n//\n// Consumes node-typed `SchemaDiffIssue`s (from the one differ —\n// `buildPostgresPlanDiff`) and reads the diff node each issue carries\n// (`issue.expected` / `issue.actual`). Column DDL (type/default SQL) resolves\n// from the column node's `codecRef` against the codec hooks the caller holds\n// (`column-ddl-rendering.ts`), never the contract. The retained subsystems —\n// codec type-operations, field-lifecycle hooks, the NOT-NULL temp-default\n// deferred DDL, control-policy disposition — keep the contract via the\n// strategy context, per the slice's scope.\n\n/** The diff node an issue concerns — expected when present, else the actual (extra) node. */\nexport function issueNode(issue: SchemaDiffIssue): SqlSchemaIRNode | undefined {\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n return blindCast<\n SqlSchemaIRNode,\n 'every node in a Postgres schema diff tree is a SqlSchemaIRNode; nodeKind is its required discriminant'\n >(node);\n}\n\n/** DDL schema segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */\nexport function issueSchemaName(issue: SchemaDiffIssue): string | undefined {\n return issue.path[1];\n}\n\n/** Table segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */\nexport function issueTableName(issue: SchemaDiffIssue): string | undefined {\n return issue.path[2];\n}\n\n/** Column name embedded in a column/default issue path segment (`column:<name>`). */\nexport function issueColumnName(issue: SchemaDiffIssue): string | undefined {\n const segment = issue.path[3];\n if (segment === undefined || !segment.startsWith('column:')) return undefined;\n return segment.slice('column:'.length);\n}\n\n/**\n * The DDL schema name to use when EMITTING an op against `ddlSchemaName` (the\n * diff tree's resolved physical schema, `issueSchemaName(issue)`). The\n * unbound namespace's diff-tree identity resolves to `public` (a concrete\n * physical default the differ needs in order to compare its tree against\n * introspection — `resolveDdlSchemaForNamespaceStorage`), but DDL EMISSION\n * must stay unqualified so the live connection's `search_path` resolves it\n * at runtime (`boundSchema`). Recovers the logical namespace id via the\n * contract and substitutes the unbound sentinel back in when it resolves\n * there; every other namespace's `ddlSchemaName` already agrees between the\n * two resolution paths, so it passes through unchanged.\n */\nexport function emissionSchemaName(ctx: StrategyContext, ddlSchemaName: string): string {\n const namespaceId = resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);\n return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;\n}\n\n/**\n * Whether a column node is a scalar-array (`many: true`) column. The family\n * converter (`contractToSchemaIR`'s `convertColumn`) never stamps `many` on\n * the derived node — array-ness is folded into the `[]` suffix on\n * `nativeType` instead — so the node-derived check reads the suffix; `.many`\n * is still checked first for nodes a caller stamps directly (e.g. hand-built\n * test fixtures, or an adapter that populates it at introspection).\n */\nfunction isManyColumn(column: SqlColumnIR): boolean {\n return column.many === true || column.nativeType.endsWith('[]');\n}\n\n/** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */\nexport function columnTypeChanged(expected: SqlColumnIR, actual: SqlColumnIR): boolean {\n if (expected.resolvedNativeType !== undefined && actual.resolvedNativeType !== undefined) {\n return expected.resolvedNativeType !== actual.resolvedNativeType;\n }\n return (\n expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many)\n );\n}\n\n// ----------------------------------------------------------------------------\n// Subtree coalescing (the planner's responsibility per the differ's contract)\n// ----------------------------------------------------------------------------\n\n/**\n * The generic differ is total: a missing/extra table (or column) emits an\n * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`\n * and `AddColumn`/`DropColumn` already account for the whole subtree, so the\n * nested issues are redundant — coalescing drops any issue whose path is a\n * strict descendant of a `not-found`/`not-expected` issue's path. Run over the\n * relational subset ONLY (policy issues and synthesized namespace issues are\n * handled on their own paths, never coalesced against tables).\n */\nexport function coalesceSubtreeIssues<TNode extends DiffableNode = DiffableNode>(\n issues: readonly SchemaDiffIssue<TNode>[],\n): readonly SchemaDiffIssue<TNode>[] {\n const collapsingPaths = issues\n .filter((issue) => issueOutcome(issue) !== 'not-equal')\n .map((issue) => issue.path);\n if (collapsingPaths.length === 0) return issues;\n return issues.filter(\n (issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)),\n );\n}\n\nfunction isStrictDescendantPath(path: readonly string[], ancestor: readonly string[]): boolean {\n if (path.length <= ancestor.length) return false;\n for (let i = 0; i < ancestor.length; i += 1) {\n if (path[i] !== ancestor[i]) return false;\n }\n return true;\n}\n\n// ----------------------------------------------------------------------------\n// Node → call construction\n// ----------------------------------------------------------------------------\n\nfunction fkSpecFromNode(fk: SqlForeignKeyIR, tableName: string): ForeignKeySpec {\n const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;\n return {\n name,\n columns: [...fk.columns],\n references: {\n // The raw target namespace coordinate, matching the retired coordinate\n // path's `references.schema: fk.target.namespaceId` (the FK node stamps\n // it verbatim). The op renderer qualifies the REFERENCES clause from it.\n schema: fk.referencedSchema ?? '',\n table: fk.referencedTable,\n columns: [...fk.referencedColumns],\n },\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n };\n}\n\n/**\n * Builds the `CreateTable` + child `CreateIndex` / `AddForeignKey` / `AddUnique`\n * calls for a newly-expected table, reading only the table node's children. The\n * PK and element-non-null CHECKs go inline as table constraints; indexes\n * (declared + FK-backing, already merged and ordered at derivation) and the\n * FK / unique constraints are separate calls (re-bucketed downstream). Every\n * column's DDL is resolved from its `codecRef` via `renderColumnDdl`.\n */\nfunction buildCreateTableCallsFromNode(\n schemaName: string,\n ddlSchemaName: string,\n table: PostgresTableSchemaNode,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): PostgresOpFactoryCall[] {\n const ddlColumns = Object.values(table.columns).map((c) =>\n renderColumnDdl(c.name, c, codecHooks),\n );\n const primaryKeyConstraints: DdlTableConstraint[] = table.primaryKey\n ? [\n contractFree.primaryKey([...table.primaryKey.columns], {\n ...ifDefined('name', table.primaryKey.name),\n }),\n ]\n : [];\n const elementNonNullChecks: DdlTableConstraint[] = Object.values(table.columns)\n .filter((c) => isManyColumn(c))\n .map((c) =>\n contractFree.checkExpression(\n elementNonNullCheckName(table.name, c.name),\n elementNonNullCheckExpression(c.name),\n ),\n );\n const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];\n const calls: PostgresOpFactoryCall[] = [\n new CreateTableCall(\n schemaName,\n table.name,\n ddlColumns,\n allTableConstraints.length > 0 ? allTableConstraints : undefined,\n ),\n ];\n for (const index of table.indexes) {\n calls.push(createIndexCallFromNode(index, schemaName, table.name));\n }\n for (const fk of table.foreignKeys) {\n calls.push(new AddForeignKeyCall(schemaName, table.name, fkSpecFromNode(fk, table.name)));\n }\n for (const unique of table.uniques) {\n const constraintName = unique.name ?? `${table.name}_${unique.columns.join('_')}_key`;\n calls.push(new AddUniqueCall(schemaName, table.name, constraintName, [...unique.columns]));\n }\n // Marker-driven: a newly-created table that is RLS-controlled enables RLS\n // as part of its creation bundle. The policy set never decides this. The\n // resolved schema (not the emission sentinel) binds into the op's\n // relrowsecurity checks.\n if (table.rlsEnabled) {\n calls.push(new EnableRowLevelSecurityCall(ddlSchemaName, table.name));\n }\n return calls;\n}\n\nfunction nodeConflict(kind: SqlPlannerConflict['kind'], message: string): SqlPlannerConflict {\n return issueConflict(kind, message);\n}\n\n/**\n * True when `actualMembers` (the live database's ordered members) is a\n * strict, order-preserving prefix of `expectedMembers` (the contract's) —\n * the database already carries every contract member, in declaration\n * order, and the contract declares at least one member the database still\n * lacks. Any other relationship — a renamed value, a removed value, a\n * reordering, or the database holding members the contract lacks — is not\n * a suffix append.\n */\nfunction isNativeEnumSuffixAppend(\n actualMembers: readonly string[],\n expectedMembers: readonly string[],\n): boolean {\n if (actualMembers.length >= expectedMembers.length) return false;\n return actualMembers.every((member, index) => member === expectedMembers[index]);\n}\n\n/** Operator-worded refusal for a native-enum member change beyond a suffix append (design ruling — tests match this verbatim). */\nfunction nativeEnumMemberChangeRefusal(options: {\n readonly ddlSchemaName: string;\n readonly typeName: string;\n readonly expectedMembers: readonly string[];\n readonly actualMembers: readonly string[];\n}): string {\n return (\n `Native enum type \"${options.ddlSchemaName}\".\"${options.typeName}\" changed beyond appending new values ` +\n `(contract declares [${options.expectedMembers.join(', ')}], database has [${options.actualMembers.join(', ')}]). ` +\n \"Prisma Next does not modify a native enum's existing values (rename, removal, reorder) — \" +\n 'see https://pris.ly/d/postgres-native-enums. Author the change manually with `migration new`.'\n );\n}\n\n/**\n * Managed native-enum issue -> op lowering. A missing declared type creates\n * it; an unclaimed live type drops it (ownership-scoped upstream by\n * `retainUnownedExtras`, destructiveness gated by the operation-class\n * policy); a paired member-value mismatch lowers to one `ALTER TYPE ... ADD\n * VALUE` per appended member when the database's members are a strict,\n * order-preserving prefix of the contract's — any other change (rename,\n * removal, reorder, or the database holding members the contract lacks) is\n * refused with a NAMED diagnostic, never a silent no-op and never a\n * drop-and-recreate.\n */\nfunction mapNativeEnumNodeIssue(\n issue: SchemaDiffIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const ddlSchemaName = issueSchemaName(issue);\n if (ddlSchemaName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Enum issue has no schema in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n if (issueOutcome(issue) === 'not-found') {\n const expected = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-found native-enum issue always carries the expected PostgresNativeEnumSchemaNode'\n >(issue.expected);\n return ok([new CreateNativeEnumTypeCall(schemaName, expected.typeName, expected.members)]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const actual = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-expected native-enum issue always carries the actual PostgresNativeEnumSchemaNode'\n >(issue.actual);\n return ok([new DropNativeEnumTypeCall(schemaName, actual.typeName)]);\n }\n const expected = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-equal native-enum issue carries both sides; the expected node names the type'\n >(issue.expected);\n const actual = blindCast<\n PostgresNativeEnumSchemaNode,\n 'a not-equal native-enum issue carries both sides'\n >(issue.actual);\n if (isNativeEnumSuffixAppend(actual.members, expected.members)) {\n const appendedValues = expected.members.slice(actual.members.length);\n return ok(\n appendedValues.map(\n (value) => new AddNativeEnumValueCall(schemaName, expected.typeName, value),\n ),\n );\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n nativeEnumMemberChangeRefusal({\n ddlSchemaName,\n typeName: expected.typeName,\n expectedMembers: expected.members,\n actualMembers: actual.members,\n }),\n ),\n );\n}\n\nfunction mapTableNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n // The diff tree's RESOLVED physical schema. Enablement ops bind it into\n // their `pg_class`/`pg_namespace` checks (the emission sentinel would\n // never match a live nspname), mirroring the schema the retired\n // policy-half enable resolved via `resolveDdlSchemaForNamespaceStorage`.\n ddlSchemaName: string,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const table = blindCast<\n PostgresTableSchemaNode,\n 'a not-found table issue always carries the expected PostgresTableSchemaNode'\n >(issue.expected);\n return ok(buildCreateTableCallsFromNode(schemaName, ddlSchemaName, table, codecHooks));\n }\n if (issueOutcome(issue) === 'not-expected') {\n const table = blindCast<\n PostgresTableSchemaNode,\n 'a not-expected table issue always carries the actual PostgresTableSchemaNode'\n >(issue.actual);\n return ok([new DropTableCall(schemaName, table.name)]);\n }\n // A paired table `not-equal` means enablement drift TODAY, because\n // `isEqualTo` compares only name + `rlsEnabled`. Key on the actual\n // expected-vs-actual `rlsEnabled` delta rather than assuming it: emit ENABLE\n // when it flipped on, DISABLE when it flipped off, and fail loud when\n // `rlsEnabled` matches on both sides — that means a second table attribute\n // drifted into `isEqualTo` and this mapper does not yet handle it. The\n // expected side is authoritative (marker-driven, never the policy set).\n const expected = blindCast<\n PostgresTableSchemaNode,\n 'a not-equal table issue always carries the expected PostgresTableSchemaNode'\n >(issue.expected);\n const actual = blindCast<\n PostgresTableSchemaNode,\n 'a not-equal table issue always carries the actual PostgresTableSchemaNode'\n >(issue.actual);\n if (expected.rlsEnabled && !actual.rlsEnabled) {\n return ok([new EnableRowLevelSecurityCall(ddlSchemaName, expected.name)]);\n }\n if (!expected.rlsEnabled && actual.rlsEnabled) {\n return ok([new DisableRowLevelSecurityCall(ddlSchemaName, expected.name)]);\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `unhandled table-attribute drift on \"${expected.name}\": table not-equal with no rlsEnabled delta (a second table attribute drifted)`,\n ),\n );\n}\n\nfunction mapColumnNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const column = blindCast<\n SqlColumnIR,\n 'a not-found column issue always carries the expected column node'\n >(issue.expected);\n return ok([\n new AddColumnCall(schemaName, tableName, renderColumnDdl(column.name, column, codecHooks)),\n ]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const column = blindCast<\n SqlColumnIR,\n 'a not-expected column issue always carries the actual column node'\n >(issue.actual);\n return ok([new DropColumnCall(schemaName, tableName, column.name)]);\n }\n // not-equal: Postgres alters in place — type drift and/or nullability drift.\n const expected = blindCast<\n SqlColumnIR,\n 'a not-equal column issue always carries the expected column node'\n >(issue.expected);\n const actual = blindCast<\n SqlColumnIR,\n 'a not-equal column issue always carries the actual column node'\n >(issue.actual);\n const calls: PostgresOpFactoryCall[] = [];\n if (columnTypeChanged(expected, actual)) {\n const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, codecHooks);\n calls.push(\n new AlterColumnTypeCall(schemaName, tableName, expected.name, {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n }),\n );\n }\n if (expected.nullable !== actual.nullable) {\n calls.push(\n expected.nullable\n ? new DropNotNullCall(schemaName, tableName, expected.name)\n : new SetNotNullCall(schemaName, tableName, expected.name),\n );\n }\n return ok(calls);\n}\n\nfunction mapColumnDefaultNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n columnName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-expected') {\n return ok([new DropDefaultCall(schemaName, tableName, columnName)]);\n }\n // not-found (SET DEFAULT, additive) or not-equal (SET DEFAULT, widening).\n if (issue.expected === undefined) return ok([]);\n const defaultNode = blindCast<\n SqlColumnDefaultIR,\n 'a not-found/not-equal column-default issue always carries the expected default node'\n >(issue.expected);\n const defaultSql = renderColumnDefaultSql(defaultNode);\n if (!defaultSql) return ok([]);\n return ok([\n new SetDefaultCall(\n schemaName,\n tableName,\n columnName,\n defaultSql,\n issueOutcome(issue) === 'not-equal' ? 'widening' : 'additive',\n ),\n ]);\n}\n\nfunction mapPrimaryKeyNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const pk = blindCast<\n { readonly columns: readonly string[]; readonly name?: string },\n 'a not-found primary-key issue always carries the expected PrimaryKey node'\n >(issue.expected);\n const constraintName = pk.name ?? `${tableName}_pkey`;\n return ok([new AddPrimaryKeyCall(schemaName, tableName, constraintName, [...pk.columns])]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const pk = blindCast<\n { readonly name?: string },\n 'a not-expected primary-key issue always carries the actual PrimaryKey node'\n >(issue.actual);\n return ok([\n new DropConstraintCall(schemaName, tableName, pk.name ?? `${tableName}_pkey`, 'primaryKey'),\n ]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\nfunction mapForeignKeyNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const fk = blindCast<\n SqlForeignKeyIR,\n 'a not-found foreign-key issue always carries the expected foreign-key node'\n >(issue.expected);\n return ok([new AddForeignKeyCall(schemaName, tableName, fkSpecFromNode(fk, tableName))]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const fk = blindCast<\n SqlForeignKeyIR,\n 'a not-expected foreign-key issue always carries the actual foreign-key node'\n >(issue.actual);\n const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;\n return ok([new DropConstraintCall(schemaName, tableName, name, 'foreignKey')]);\n }\n return notOk(nodeConflict('foreignKeyConflict', issue.path.join('/')));\n}\n\nfunction mapUniqueNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const unique = blindCast<\n SqlUniqueIR,\n 'a not-found unique issue always carries the expected unique node'\n >(issue.expected);\n const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n return ok([new AddUniqueCall(schemaName, tableName, name, [...unique.columns])]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const unique = blindCast<\n SqlUniqueIR,\n 'a not-expected unique issue always carries the actual unique node'\n >(issue.actual);\n const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n return ok([new DropConstraintCall(schemaName, tableName, name, 'unique')]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\n/**\n * The CreateIndexCall for a name-identified index node: the node's own name\n * verbatim, its element list (column tuple or opaque expression), and the\n * unique/type/options/where attributes carried through.\n */\nexport function createIndexCallFromNode(\n index: SqlIndexIR,\n schemaName: string,\n tableName: string,\n): CreateIndexCall {\n const extras: {\n type?: string;\n options?: Record<string, unknown>;\n where?: string;\n unique?: boolean;\n } = {};\n if (index.type !== undefined) extras.type = index.type;\n if (index.options !== undefined) extras.options = index.options;\n if (index.where !== undefined) extras.where = index.where;\n if (index.unique) extras.unique = true;\n return new CreateIndexCall(\n schemaName,\n tableName,\n index.name,\n index.columns !== undefined\n ? { columns: [...index.columns] }\n : { expression: index.expression ?? '' },\n extras,\n );\n}\n\nfunction mapIndexNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n if (issueOutcome(issue) === 'not-found') {\n const index = blindCast<\n SqlIndexIR,\n 'a not-found index issue always carries the expected index node'\n >(issue.expected);\n return ok([createIndexCallFromNode(index, schemaName, tableName)]);\n }\n if (issueOutcome(issue) === 'not-expected') {\n const index = blindCast<\n SqlIndexIR,\n 'a not-expected index issue always carries the actual index node'\n >(issue.actual);\n return ok([new DropIndexCall(schemaName, tableName, index.name)]);\n }\n return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));\n}\n\nfunction mapCheckNodeIssue(\n issue: SchemaDiffIssue,\n schemaName: string,\n tableName: string,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n // check_removed (extra live check not in contract) is the only check drift\n // the default mapper handles directly; check_missing / check_mismatch are\n // consumed by `checkConstraintPlanCallStrategy` (drop+recreate), so reaching\n // here for them means the strategy did not run — a conflict.\n if (issueOutcome(issue) === 'not-expected') {\n const check = blindCast<\n { readonly name: string },\n 'a not-expected check issue always carries the actual check node'\n >(issue.actual);\n return ok([new DropCheckConstraintCall(schemaName, tableName, check.name)]);\n }\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Check constraint drift on \"${tableName}\" — handled by checkConstraintPlanCallStrategy: ${issue.path.join('/')}`,\n ),\n );\n}\n\n/**\n * Maps one node-typed diff issue to its migration call(s), dispatching on the\n * node's `nodeKind` and the issue's presence-derived `issueOutcome`, reading\n * nodes and resolving column DDL from `codecRef` via `column-ddl-rendering.ts`.\n */\nexport function mapNodeIssueToCall(\n issue: SchemaDiffIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const node = issueNode(issue);\n if (node === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Issue carries neither an expected nor an actual node: ${issue.path.join('/')}`,\n ),\n );\n }\n if (node.nodeKind === PostgresSchemaNodeKind.namespace) {\n if (issueOutcome(issue) !== 'not-found') {\n return notOk(\n nodeConflict('unsupportedOperation', `Unexpected namespace drift: ${issue.path.join('/')}`),\n );\n }\n const namespace = blindCast<\n PostgresNamespaceSchemaNode,\n 'a namespace-presence issue always carries a PostgresNamespaceSchemaNode'\n >(issue.expected);\n return ok([new CreateSchemaCall(namespace.schemaName)]);\n }\n\n if (node.nodeKind === PostgresSchemaNodeKind.nativeEnum) {\n return mapNativeEnumNodeIssue(issue, ctx);\n }\n\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Issue has no schema/table in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n const schemaName = emissionSchemaName(ctx, ddlSchemaName);\n\n switch (node.nodeKind) {\n case PostgresSchemaNodeKind.table:\n return mapTableNodeIssue(issue, schemaName, ddlSchemaName, ctx.codecHooks);\n case RelationalSchemaNodeKind.column:\n return mapColumnNodeIssue(issue, schemaName, tableName, ctx.codecHooks);\n case RelationalSchemaNodeKind.columnDefault: {\n const columnName = issueColumnName(issue);\n if (columnName === undefined) {\n return notOk(\n nodeConflict(\n 'unsupportedOperation',\n `Default issue has no column in its path: ${issue.path.join('/')}`,\n ),\n );\n }\n return mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName);\n }\n case RelationalSchemaNodeKind.primaryKey:\n return mapPrimaryKeyNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.foreignKey:\n return mapForeignKeyNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.unique:\n return mapUniqueNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.index:\n return mapIndexNodeIssue(issue, schemaName, tableName);\n case RelationalSchemaNodeKind.check:\n return mapCheckNodeIssue(issue, schemaName, tableName);\n default:\n return notOk(nodeConflict('unsupportedOperation', `Unhandled node kind: ${node.nodeKind}`));\n }\n}\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaDiffIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n /**\n * Current database schema IR. Strategies read this to detect whether a\n * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-\n * default safety, extension dependency checks). Defaults to an empty schema\n * when omitted so the planner can still run over \"fresh DB\" contract\n * snapshots.\n */\n readonly schema?: SqlSchemaIR;\n /**\n * Operation-class policy. `planIssues` filters calls whose `operationClass`\n * is not in `policy.allowedOperationClasses` and surfaces them as conflicts\n * instead of emitting disallowed DDL. Defaults to additive-only.\n */\n readonly policy?: MigrationOperationPolicy;\n /**\n * Framework components participating in this composition. Available to\n * future strategies that may consult component metadata at plan time.\n */\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\n/**\n * Runs the ordered strategy list over the node-typed diff issues, maps\n * leftover issues via {@link mapNodeIssueToCall}, applies operation-class\n * policy gating, and buckets calls into the fixed DDL emission order (dep →\n * drop → table → column → recipe → alter → primaryKey → unique → index →\n * foreignKey).\n */\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\n const policyProvided = options.policy !== undefined;\n const policy = options.policy ?? DEFAULT_POLICY;\n const schema = options.schema ?? emptySchemaIR();\n const frameworkComponents = options.frameworkComponents ?? [];\n\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n schemaName: options.schemaName,\n codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? postgresPlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: PostgresOpFactoryCall[] = [];\n const bucketablePatternCalls: PostgresOpFactoryCall[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n if (result.recipe) {\n recipeCalls.push(...result.calls);\n } else {\n bucketablePatternCalls.push(...result.calls);\n }\n }\n }\n\n // Dependency-graph order: a topological sort over the issues' `dependsOn`\n // cross-links and containment edges (the ordering law drives edge direction\n // by presence), path-tiebroken for determinism. `classifyCall` bucketing\n // downstream fixes the coarse cross-entity DDL sequence; this settles the\n // order within each bucket (notably the teardown order among drops).\n const sorted = orderIssuesByDependencies(remaining);\n\n const defaultCalls: PostgresOpFactoryCall[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapNodeIssueToCall(issue, context);\n if (result.ok) {\n defaultCalls.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n const allowed = policy.allowedOperationClasses;\n let gatedDefault = defaultCalls;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketablePatternCalls;\n if (policyProvided) {\n const keepIfAllowed = (bucket: PostgresOpFactoryCall[]) => (call: PostgresOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n bucket.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedDefaultBucket: PostgresOpFactoryCall[] = [];\n const gatedRecipeBucket: PostgresOpFactoryCall[] = [];\n const gatedBucketableBucket: PostgresOpFactoryCall[] = [];\n defaultCalls.forEach(keepIfAllowed(gatedDefaultBucket));\n recipeCalls.forEach(keepIfAllowed(gatedRecipeBucket));\n bucketablePatternCalls.forEach(keepIfAllowed(gatedBucketableBucket));\n gatedDefault = gatedDefaultBucket;\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n const combinedBucketable = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) =>\n combinedBucketable.filter((c) => classifyCall(c) === cat);\n\n const calls: PostgresOpFactoryCall[] = [\n ...byCategory('dep'),\n ...byCategory('drop'),\n // DROP TYPE after every table drop — a managed enum type can only go once\n // no live column still uses it.\n ...byCategory('dropType'),\n ...byCategory('table'),\n ...byCategory('column'),\n ...gatedRecipe,\n ...byCategory('alter'),\n ...byCategory('primaryKey'),\n ...byCategory('unique'),\n ...byCategory('index'),\n ...byCategory('foreignKey'),\n // Enablement changes run after all relational DDL (the table must exist)\n // and before the policy calls the planner appends after `planIssues` —\n // the same position the retired imperative enable-on-first-policy used.\n ...byCategory('rlsEnable'),\n ];\n\n return ok({ calls });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type {\n ControlPolicySubject,\n SqlPlannerConflict,\n SuppressionRecord,\n} from '@prisma-next/family-sql/control';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { issueOutcome } 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 { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type PostgresRole, ROLE_DEFAULT_CONTROL_POLICY } from '../postgres-role';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { postgresNodeStorageCoordinate } from '../schema-ir/node-storage-coordinate';\nimport type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { issueColumnName } from './issue-planner';\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 *\n * Lists the creation factories that actually reach the call-side resolver\n * (`resolvePostgresCallControlPolicySubject`) — today only RLS policy\n * creation, from `planPostgresSchemaDiff`. Every other whole-object create\n * (table, schema, native enum, and RLS enablement) is constructed inside\n * `planIssues` and graded on the node side by\n * `resolvePostgresNodeIssueCreationFactoryName`, so none of them are listed\n * here.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>(['createRlsPolicy']);\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\n/**\n * Resolve the namespace a declared storage entity lives in by walking every\n * namespace for one whose `entries` map actually contains the coordinate —\n * a table by its name, a native enum by its physical type name (see\n * {@link postgresNodeStorageCoordinate}). When `ddlSchemaName` is given, the\n * match must also land in that DDL schema (disambiguates same-named entities\n * declared under different namespaces); when omitted, the first namespace\n * that declares the entity wins. Falls back to {@link UNBOUND_NAMESPACE_ID}\n * when no namespace declares it — e.g. an extra/dropped entity the contract\n * doesn't claim at all.\n */\nfunction resolveNamespaceIdForEntity(\n contract: Contract<SqlStorage>,\n coordinate: { readonly entityKind: string; readonly entityName: string },\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const entity = entityAt(contract.storage, { namespaceId, ...coordinate });\n if (!entity) 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 resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n return resolveNamespaceIdForEntity(\n contract,\n { entityKind: 'table', entityName: tableName },\n ddlSchemaName,\n );\n}\n\nexport function 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\nfunction formatSuppressionSubjectLabel(\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject === undefined) return 'unknown';\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n if (subject.entityKind !== undefined && subject.entityName !== undefined) {\n return `${subject.entityKind} \"${ddlSchema}.${subject.entityName}\"`;\n }\n return `namespace \"${ddlSchema}\"`;\n}\n\nfunction postgresSuppressionSummary(\n subjectLabel: string,\n subject: ControlPolicySubject | undefined,\n policy: string,\n): string {\n const namespace = subject?.namespaceId ?? 'unknown';\n const declared = subject?.explicitNodeControlPolicy;\n if (policy === 'external' && declared === 'managed') {\n return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control 'external' but declared 'managed'`;\n }\n const declaredSuffix = declared ? ` but declared '${declared}'` : '';\n return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control '${policy}'${declaredSuffix}`;\n}\n\n/**\n * Render one family {@link SuppressionRecord} into a target `SqlPlannerConflict`.\n * The family decides *that* a subject is suppressed and hands over the raw\n * coordinate + policy; the label, message, and location are rendered here,\n * driven entirely by the subject's own `(entityKind, entityName)` coordinate\n * — no target-owned table-vs-enum vocabulary.\n */\nexport function renderPostgresSuppression(\n record: SuppressionRecord,\n contract: Contract<SqlStorage>,\n): SqlPlannerConflict {\n const subject = record.subject;\n const subjectLabel = formatSuppressionSubjectLabel(subject, contract);\n return {\n kind: 'controlPolicySuppressedCall',\n summary: postgresSuppressionSummary(subjectLabel, subject, record.policy),\n location: {\n ...ifDefined('namespaceId', subject?.namespaceId),\n ...ifDefined('entityKind', subject?.entityKind),\n ...ifDefined('entityName', subject?.entityName),\n ...ifDefined('column', subject?.column),\n },\n meta: {\n controlPolicy: record.policy,\n ...ifDefined('factoryName', record.factoryName),\n ...ifDefined('declaredControlPolicy', subject?.explicitNodeControlPolicy),\n },\n };\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 entityKind: 'table',\n entityName: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\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 * Node kinds whose *absence* is the creation of a whole, top-level Postgres\n * object: a namespace, a table, or a native enum. Used by\n * {@link resolvePostgresNodeIssueCreationFactoryName} to decide whether a\n * `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. RLS policy creation is not\n * listed here — policy issues never reach this issue-based partition (they\n * are routed to `planPostgresSchemaDiff` and gated via the call-based\n * {@link resolvePostgresCallControlPolicySubject} instead).\n */\nconst POSTGRES_NODE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n [PostgresSchemaNodeKind.namespace]: 'createSchema',\n [PostgresSchemaNodeKind.table]: 'createTable',\n [PostgresSchemaNodeKind.nativeEnum]: 'createNativeEnumType',\n});\n\n/**\n * A table `not-equal` issue whose `rlsEnabled` flips OFF→ON (expected on,\n * actual off) is enablement toward `ENABLE ROW LEVEL SECURITY`. It is\n * creation-class on the node side because `isEnablementCreationIssue` and\n * {@link resolvePostgresNodeIssueCreationFactoryName} treat this OFF→ON delta\n * as a creation: enabling RLS establishes the fail-closed guard the declared\n * policy set attaches to, the same grant `tolerated` extends to creating the\n * policies themselves. The opposite direction (`DISABLE`) is a modification\n * and stays managed-only. Keying on the actual delta (not just the expected\n * bit) keeps this correct if a second table attribute ever joins\n * `isEqualTo`: a not-equal with no `rlsEnabled` delta is not enablement, so\n * it is not admitted as creation-class here.\n */\nfunction isEnablementCreationIssue(issue: SchemaDiffIssue<SqlSchemaDiffNode>): boolean {\n if (issueOutcome(issue) !== 'not-equal') return false;\n const { expected, actual } = issue;\n return (\n expected !== undefined &&\n actual !== undefined &&\n PostgresTableSchemaNode.is(expected) &&\n PostgresTableSchemaNode.is(actual) &&\n expected.rlsEnabled === true &&\n actual.rlsEnabled === false\n );\n}\n\nexport function resolvePostgresNodeIssueCreationFactoryName(\n issue: SchemaDiffIssue<SqlSchemaDiffNode>,\n): string | undefined {\n if (isEnablementCreationIssue(issue)) {\n return 'enableRowLevelSecurity';\n }\n if (issueOutcome(issue) !== 'not-found') return undefined;\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n return POSTGRES_NODE_CREATION_FACTORY[node.nodeKind];\n}\n\n/**\n * Resolves the control-policy subject for a node-typed {@link SchemaDiffIssue}\n * (the issue-side mirror of `resolvePostgresCallControlPolicySubject`).\n * Storage entities resolve off their node coordinate; a sub-entity issue\n * resolves off the enclosing table read from the issue path; an unclaimed\n * extra falls back to the unbound coordinate. A role always resolves\n * `'external'` — roles are referenced, never owned.\n */\nexport function resolvePostgresNodeIssueControlPolicySubject(\n issue: SchemaDiffIssue<SqlSchemaDiffNode>,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const node = issue.expected ?? issue.actual;\n if (node === undefined) return undefined;\n\n if (node.nodeKind === PostgresSchemaNodeKind.namespace) {\n const namespaceNode = blindCast<\n PostgresNamespaceSchemaNode,\n 'a postgres-namespace diff node is always a PostgresNamespaceSchemaNode'\n >(node);\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, namespaceNode.schemaName),\n createsNewObject: issueOutcome(issue) === 'not-found',\n };\n }\n\n if (node.nodeKind === PostgresSchemaNodeKind.role) {\n const roleName = issue.path[1];\n const roleEntity =\n roleName === undefined\n ? undefined\n : entityAt<PostgresRole>(contract.storage, {\n namespaceId: UNBOUND_NAMESPACE_ID,\n entityKind: 'role',\n entityName: roleName,\n });\n return {\n namespaceId: UNBOUND_NAMESPACE_ID,\n explicitNodeControlPolicy: roleEntity?.control ?? ROLE_DEFAULT_CONTROL_POLICY,\n createsNewObject: false,\n };\n }\n\n const coordinate = postgresNodeStorageCoordinate(node);\n if (coordinate !== undefined) {\n const namespaceId = resolveNamespaceIdForEntity(contract, coordinate, issue.path[1]);\n const entityControl = entityAt<{ readonly control?: ControlPolicy }>(contract.storage, {\n namespaceId,\n ...coordinate,\n })?.control;\n return {\n namespaceId,\n ...coordinate,\n ...ifDefined('column', issueColumnName(issue)),\n ...ifDefined('explicitNodeControlPolicy', entityControl),\n createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,\n };\n }\n\n const tableName = issue.path[2];\n if (tableName === undefined) return undefined;\n const ddlSchemaName = issue.path[1];\n const namespaceId = resolveNamespaceIdForTable(contract, tableName, ddlSchemaName);\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\n\n return {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n ...ifDefined('column', issueColumnName(issue)),\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== undefined,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,8BACd,MACiE;CACjE,IAAI,wBAAwB,GAAG,IAAI,GAAG;EACpC,MAAM,aAAa,uBAAuB,KAAK,QAAQ;EACvD,OAAO,eAAe,KAAA,IAAY,KAAA,IAAY;GAAE;GAAY,YAAY,KAAK;EAAK;CACpF;CACA,IAAI,6BAA6B,GAAG,IAAI,GAAG;EACzC,MAAM,aAAa,uBAAuB,KAAK,QAAQ;EACvD,OAAO,eAAe,KAAA,IAAY,KAAA,IAAY;GAAE;GAAY,YAAY,KAAK;EAAS;CACxF;AAEF;;;;;;;;;;;;;;;ACAA,SAAS,WACP,QAIA;CACA,IAAI,OAAO,aAAa,KAAA,KAAa,OAAO,wBAAwB,KAAA,GAClE,MAAM,IAAI,cACR,gCAAgC,OAAO,KAAK,oGAC9C;CAEF,OAAO;EACL,YAAY,OAAO;EACnB,SAAS,OAAO,SAAS;EACzB,UAAU,OAAO;EAIjB,GAAG,UAAU,QAAQ,OAAO,QAAQ,OAAO,SAAS,IAAI;EACxD,GAAG,UACD,cACA,OAAO,SAAS,eAAe,KAAA,IAC3B,UAGE,OAAO,SAAS,UAAU,IAC5B,KAAA,CACN;EACA,GAAI,OAAO,iBAAiB,EAAE,SAAS,aAAa,IAAI,CAAC;EACzD,GAAG,UAAU,WAAW,OAAO,eAAe;CAChD;AACF;;;;;;;AAQA,SAAgB,gBACd,MACA,QACA,YACW;CACX,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAM,UAAU,mBAAmB,MAAM,YAAY,CAAC,CAAC;CACvD,MAAM,aAAa,kCAAkC,KAAK,OAAO;CACjE,OAAO,aAAa,IAAI,MAAM,SAAS;EACrC,GAAI,CAAC,OAAO,WAAW,EAAE,SAAS,KAAK,IAAI,CAAC;EAC5C,GAAG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