@prisma-next/target-postgres 0.14.0-dev.55 → 0.14.0-dev.56

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 (117) hide show
  1. package/dist/{authoring-BBIGcFZM.mjs → authoring-WkqG_MkU.mjs} +38 -6
  2. package/dist/authoring-WkqG_MkU.mjs.map +1 -0
  3. package/dist/contract-free.d.mts +27 -2
  4. package/dist/contract-free.d.mts.map +1 -1
  5. package/dist/contract-free.mjs +3 -3
  6. package/dist/{control-policy-DievMCOV.mjs → control-policy-BtOZBVxL.mjs} +38 -13
  7. package/dist/control-policy-BtOZBVxL.mjs.map +1 -0
  8. package/dist/control.mjs +6 -6
  9. package/dist/{ddl-D5j4JiAB.mjs → ddl-B-krEXY1.mjs} +18 -4
  10. package/dist/{ddl-D5j4JiAB.mjs.map → ddl-B-krEXY1.mjs.map} +1 -1
  11. package/dist/ddl.d.mts +2 -2
  12. package/dist/ddl.mjs +2 -2
  13. package/dist/{descriptor-meta-C-tyS25s.mjs → descriptor-meta-BOcKPaLE.mjs} +4 -3
  14. package/dist/descriptor-meta-BOcKPaLE.mjs.map +1 -0
  15. package/dist/{diff-database-schema-ff3ioNtK.mjs → diff-database-schema-CWb-jeLy.mjs} +19 -11
  16. package/dist/diff-database-schema-CWb-jeLy.mjs.map +1 -0
  17. package/dist/diff-database-schema.d.mts +1 -1
  18. package/dist/diff-database-schema.d.mts.map +1 -1
  19. package/dist/diff-database-schema.mjs +1 -1
  20. package/dist/issue-planner.d.mts +1 -1
  21. package/dist/issue-planner.d.mts.map +1 -1
  22. package/dist/issue-planner.mjs +1 -1
  23. package/dist/migration.d.mts +2 -2
  24. package/dist/migration.mjs +2 -2
  25. package/dist/{nodes-Dh__NS58.mjs → nodes-B815pj_X.mjs} +34 -2
  26. package/dist/{nodes-Dh__NS58.mjs.map → nodes-B815pj_X.mjs.map} +1 -1
  27. package/dist/{nodes-CSkPX3rI.d.mts → nodes-BtQyZha6.d.mts} +29 -3
  28. package/dist/nodes-BtQyZha6.d.mts.map +1 -0
  29. package/dist/{op-factory-call-Dt-Jx5JS.d.mts → op-factory-call-D6_7-7Vc.d.mts} +24 -2
  30. package/dist/{op-factory-call-Dt-Jx5JS.d.mts.map → op-factory-call-D6_7-7Vc.d.mts.map} +1 -1
  31. package/dist/{op-factory-call-DZWTTjKM.mjs → op-factory-call-DxNNKUeZ.mjs} +99 -4
  32. package/dist/op-factory-call-DxNNKUeZ.mjs.map +1 -0
  33. package/dist/op-factory-call.d.mts +1 -1
  34. package/dist/op-factory-call.mjs +1 -1
  35. package/dist/pack.d.mts +29 -2
  36. package/dist/pack.d.mts.map +1 -1
  37. package/dist/pack.mjs +1 -1
  38. package/dist/{planner-DWQYPxP8.mjs → planner-BryLk0Ie.mjs} +80 -24
  39. package/dist/planner-BryLk0Ie.mjs.map +1 -0
  40. package/dist/{planner-produced-postgres-migration-Ch1L8RiV.mjs → planner-produced-postgres-migration-BLJH1zIc.mjs} +2 -2
  41. package/dist/{planner-produced-postgres-migration-Ch1L8RiV.mjs.map → planner-produced-postgres-migration-BLJH1zIc.mjs.map} +1 -1
  42. package/dist/{planner-produced-postgres-migration-C0a7I1-e.d.mts → planner-produced-postgres-migration-CGifB6VH.d.mts} +2 -2
  43. package/dist/{planner-produced-postgres-migration-C0a7I1-e.d.mts.map → planner-produced-postgres-migration-CGifB6VH.d.mts.map} +1 -1
  44. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  45. package/dist/planner-produced-postgres-migration.mjs +1 -1
  46. package/dist/{planner-sql-checks-D8Q5ck4o.mjs → planner-sql-checks-AXoxB1Jl.mjs} +2 -2
  47. package/dist/{planner-sql-checks-D8Q5ck4o.mjs.map → planner-sql-checks-AXoxB1Jl.mjs.map} +1 -1
  48. package/dist/planner-sql-checks.mjs +1 -1
  49. package/dist/planner.d.mts +23 -6
  50. package/dist/planner.d.mts.map +1 -1
  51. package/dist/planner.mjs +2 -2
  52. package/dist/{postgres-contract-view-C-By7rOB.mjs → postgres-contract-view-Dg-N7KA7.mjs} +4 -3
  53. package/dist/postgres-contract-view-Dg-N7KA7.mjs.map +1 -0
  54. package/dist/{postgres-database-schema-node-UpzA0Ug5.d.mts → postgres-database-schema-node-CfdTY-Qs.d.mts} +18 -3
  55. package/dist/postgres-database-schema-node-CfdTY-Qs.d.mts.map +1 -0
  56. package/dist/{postgres-migration-D3XACWKM.mjs → postgres-migration-BahMHTbj.mjs} +3 -3
  57. package/dist/{postgres-migration-D3XACWKM.mjs.map → postgres-migration-BahMHTbj.mjs.map} +1 -1
  58. package/dist/{postgres-migration-DFaxuRyI.d.mts → postgres-migration-cyBe2Ee0.d.mts} +2 -2
  59. package/dist/{postgres-migration-DFaxuRyI.d.mts.map → postgres-migration-cyBe2Ee0.d.mts.map} +1 -1
  60. package/dist/{postgres-table-schema-node-BZWWEo7B.mjs → postgres-role-schema-node-BiSTCTNg.mjs} +4 -69
  61. package/dist/postgres-role-schema-node-BiSTCTNg.mjs.map +1 -0
  62. package/dist/{postgres-schema-9vFZLwGo.d.mts → postgres-schema-CU4gF6QZ.d.mts} +30 -2
  63. package/dist/postgres-schema-CU4gF6QZ.d.mts.map +1 -0
  64. package/dist/{postgres-schema-DcG72fcT.mjs → postgres-schema-DTLA_aRi.mjs} +41 -2
  65. package/dist/postgres-schema-DTLA_aRi.mjs.map +1 -0
  66. package/dist/postgres-table-schema-node-9FCtCUz2.mjs +153 -0
  67. package/dist/postgres-table-schema-node-9FCtCUz2.mjs.map +1 -0
  68. package/dist/{resolve-ddl-schema-BOtCoeKV.mjs → resolve-ddl-schema-Ca88Tg6W.mjs} +2 -2
  69. package/dist/{resolve-ddl-schema-BOtCoeKV.mjs.map → resolve-ddl-schema-Ca88Tg6W.mjs.map} +1 -1
  70. package/dist/rls-canonicalize.d.mts +19 -1
  71. package/dist/rls-canonicalize.d.mts.map +1 -0
  72. package/dist/rls-canonicalize.mjs +2 -2
  73. package/dist/runtime.d.mts.map +1 -1
  74. package/dist/runtime.mjs +1 -1
  75. package/dist/schema-ir-annotations.mjs +1 -1
  76. package/dist/types.d.mts +3 -3
  77. package/dist/types.mjs +4 -3
  78. package/dist/{canonicalize-Bn3BM1Cn.mjs → wire-name-rHHtr1h0.mjs} +31 -2
  79. package/dist/wire-name-rHHtr1h0.mjs.map +1 -0
  80. package/package.json +20 -20
  81. package/src/contract-free/ddl.ts +26 -0
  82. package/src/core/authoring.ts +44 -1
  83. package/src/core/ddl/nodes.ts +48 -1
  84. package/src/core/descriptor-meta.ts +2 -0
  85. package/src/core/entity-kinds.ts +11 -0
  86. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +9 -0
  87. package/src/core/migrations/control-policy.ts +31 -1
  88. package/src/core/migrations/diff-database-schema.ts +1 -0
  89. package/src/core/migrations/issue-planner.ts +49 -4
  90. package/src/core/migrations/op-factory-call.ts +81 -1
  91. package/src/core/migrations/operations/rls.ts +82 -1
  92. package/src/core/migrations/planner.ts +110 -26
  93. package/src/core/postgres-contract-serializer.ts +7 -1
  94. package/src/core/postgres-rls-enablement.ts +34 -0
  95. package/src/core/postgres-schema.ts +19 -3
  96. package/src/core/postgres-validators.ts +6 -0
  97. package/src/core/rls/wire-name.ts +33 -0
  98. package/src/core/schema-ir/postgres-table-schema-node.ts +25 -3
  99. package/src/exports/contract-free.ts +4 -0
  100. package/src/exports/ddl.ts +2 -0
  101. package/src/exports/rls-canonicalize.ts +1 -0
  102. package/src/exports/types.ts +4 -0
  103. package/dist/authoring-BBIGcFZM.mjs.map +0 -1
  104. package/dist/canonicalize-Bn3BM1Cn.mjs.map +0 -1
  105. package/dist/control-policy-DievMCOV.mjs.map +0 -1
  106. package/dist/descriptor-meta-C-tyS25s.mjs.map +0 -1
  107. package/dist/diff-database-schema-ff3ioNtK.mjs.map +0 -1
  108. package/dist/nodes-CSkPX3rI.d.mts.map +0 -1
  109. package/dist/op-factory-call-DZWTTjKM.mjs.map +0 -1
  110. package/dist/planner-DWQYPxP8.mjs.map +0 -1
  111. package/dist/postgres-contract-view-C-By7rOB.mjs.map +0 -1
  112. package/dist/postgres-database-schema-node-UpzA0Ug5.d.mts.map +0 -1
  113. package/dist/postgres-schema-9vFZLwGo.d.mts.map +0 -1
  114. package/dist/postgres-schema-DcG72fcT.mjs.map +0 -1
  115. package/dist/postgres-table-schema-node-BZWWEo7B.mjs.map +0 -1
  116. package/dist/schema-node-kinds-ClScchhi.mjs +0 -76
  117. package/dist/schema-node-kinds-ClScchhi.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"op-factory-call-DZWTTjKM.mjs","names":["contractFreeDdl.alterTable","contractFreeDdl.dropDefaultAction","contractFreeDdl.addColumnAction","contractFreeDdl.alterTable","contractFreeDdl.addColumnAction","contractFreeDdl.dropDefaultAction","exhaustive","contractFreeDdl.createTable","contractFreeDdl.alterTable","contractFreeDdl.addColumnAction","contractFreeDdl.createSchema"],"sources":["../src/core/migrations/bound-schema.ts","../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/operations/constraints.ts","../src/core/migrations/operations/dependencies.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/rls.ts","../src/core/migrations/operations/tables.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/op-factory-call.ts"],"sourcesContent":["import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\n\n/**\n * Maps a planner schema name to the contract-free DDL builder's optional\n * `schema` field: the unbound sentinel becomes `undefined` (the builder omits\n * the schema qualifier), every other name passes through.\n */\nexport function boundSchema(schemaName: string): string | undefined {\n return schemaName === UNBOUND_NAMESPACE_ID ? undefined : schemaName;\n}\n","import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { OperationClass, PostgresPlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\n/**\n * Literal-args shape for a foreign key definition. `references.schema`\n * carries the target table's namespace (schema) coordinate so the rendered\n * DDL qualifies the REFERENCES clause correctly for cross-schema FKs.\n */\nexport interface ForeignKeySpec {\n readonly name: string;\n readonly columns: readonly string[];\n readonly references: {\n readonly schema: string;\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n}\n\nexport function step(description: string, sql: string, params?: readonly unknown[]) {\n return { description, sql, ...ifDefined('params', params) };\n}\n\nexport function targetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): { readonly id: 'postgres'; readonly details: PostgresPlanTargetDetails } {\n return {\n id: 'postgres',\n details: { schema, objectType, name, ...ifDefined('table', table) },\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type { DdlColumn } from '@prisma-next/sql-relational-core/ast';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport {\n columnDefaultAst,\n columnExistsAst,\n columnNullabilityAst,\n columnTypeAst,\n noNullValuesAst,\n tableIsEmptyAst,\n} from '../../../contract-free/checks';\nimport * as contractFreeDdl from '../../../contract-free/ddl';\nimport { quoteIdentifier } from '../../sql-utils';\nimport { boundSchema } from '../bound-schema';\nimport { qualifyTableName } from '../planner-sql-checks';\nimport { type Op, step, targetDetails } from './shared';\n\ntype CheckStep = { sql: string; params?: readonly unknown[] };\n\nasync function columnExistsSteps(\n lowerer: ExecuteRequestLowerer,\n options: { schema: string; table: string; column: string },\n): Promise<{ present: CheckStep; absent: CheckStep }> {\n const checks = columnExistsAst(options);\n const present = await lowerer.lowerToExecuteRequest(checks.columnPresent());\n const absent = await lowerer.lowerToExecuteRequest(checks.columnAbsent());\n return { present, absent };\n}\n\nexport async function dropColumn(\n schemaName: string,\n tableName: string,\n columnName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { present, absent } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column \"${columnName}\" from \"${tableName}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `drop column \"${columnName}\"`,\n `ALTER TABLE ${qualified} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [step(`verify column \"${columnName}\" does not exist`, absent.sql, absent.params)],\n };\n}\n\n/**\n * `qualifiedTargetType` is the new column type as it appears in the\n * `ALTER COLUMN TYPE` clause (schema-qualified for user-defined types, raw\n * native name for built-ins). `formatTypeExpected` is the unqualified\n * `format_type` form used in the postcheck. `rawTargetTypeForLabel` is the\n * string appearing in the human-readable label (typically `toType` when\n * explicit, else the column's native type).\n */\nexport async function alterColumnType(\n schemaName: string,\n tableName: string,\n columnName: string,\n options: {\n readonly qualifiedTargetType: string;\n readonly formatTypeExpected: string;\n readonly rawTargetTypeForLabel: string;\n readonly using?: string;\n },\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const usingClause = options.using\n ? ` USING ${options.using}`\n : ` USING ${quoteIdentifier(columnName)}::${options.qualifiedTargetType}`;\n const { present } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n const typeCheck = await lowerer.lowerToExecuteRequest(\n columnTypeAst({\n schema: schemaName,\n table: tableName,\n column: columnName,\n expectedType: options.formatTypeExpected,\n }),\n );\n return {\n id: `alterType.${tableName}.${columnName}`,\n label: `Alter type of \"${tableName}\".\"${columnName}\" to ${options.rawTargetTypeForLabel}`,\n operationClass: 'destructive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `alter type of \"${columnName}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} TYPE ${options.qualifiedTargetType}${usingClause}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" has type \"${options.formatTypeExpected}\"`,\n typeCheck.sql,\n typeCheck.params,\n ),\n ],\n meta: { warning: 'TABLE_REWRITE' },\n };\n}\n\nexport async function setNotNull(\n schemaName: string,\n tableName: string,\n columnName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { present } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n const noNulls = await lowerer.lowerToExecuteRequest(\n noNullValuesAst({ schema: schemaName, table: tableName, column: columnName }),\n );\n const notNullable = await lowerer.lowerToExecuteRequest(\n columnNullabilityAst({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n );\n return {\n id: `alterNullability.setNotNull.${tableName}.${columnName}`,\n label: `Set NOT NULL on \"${tableName}\".\"${columnName}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [\n step(`ensure column \"${columnName}\" exists`, present.sql, present.params),\n step(`ensure no NULL values in \"${columnName}\"`, noNulls.sql, noNulls.params),\n ],\n execute: [\n step(\n `set NOT NULL on \"${columnName}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`,\n ),\n ],\n postcheck: [\n step(`verify column \"${columnName}\" is NOT NULL`, notNullable.sql, notNullable.params),\n ],\n };\n}\n\nexport async function dropNotNull(\n schemaName: string,\n tableName: string,\n columnName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { present } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n const nullable = await lowerer.lowerToExecuteRequest(\n columnNullabilityAst({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: true,\n }),\n );\n return {\n id: `alterNullability.dropNotNull.${tableName}.${columnName}`,\n label: `Drop NOT NULL on \"${tableName}\".\"${columnName}\"`,\n operationClass: 'widening',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `drop NOT NULL on \"${columnName}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`,\n ),\n ],\n postcheck: [step(`verify column \"${columnName}\" is nullable`, nullable.sql, nullable.params)],\n };\n}\n\n/**\n * `defaultSql` is the full `DEFAULT …` clause as produced by\n * `buildColumnDefaultSql` — e.g. `\"DEFAULT 42\"`,\n * `\"DEFAULT (CURRENT_TIMESTAMP)\"`, or `\"DEFAULT nextval('seq'::regclass)\"`.\n *\n * `operationClass` defaults to `'additive'` (setting a default on a column\n * that currently has none). The reconciliation planner passes `'widening'`\n * when the column already has a different default — policy enforcement\n * treats that as a widening change rather than an additive one.\n */\nexport async function setDefault(\n schemaName: string,\n tableName: string,\n columnName: string,\n defaultSql: string,\n lowerer: ExecuteRequestLowerer,\n operationClass: 'additive' | 'widening' = 'additive',\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { present } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n const hasDefault = await lowerer.lowerToExecuteRequest(\n columnDefaultAst({ schema: schemaName, table: tableName, column: columnName }).defaultPresent(),\n );\n return {\n id: `setDefault.${tableName}.${columnName}`,\n label: `Set default on \"${tableName}\".\"${columnName}\"`,\n operationClass,\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `set default on \"${columnName}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} SET ${defaultSql}`,\n ),\n ],\n postcheck: [\n step(`verify column \"${columnName}\" has a default`, hasDefault.sql, hasDefault.params),\n ],\n };\n}\n\nexport async function dropDefault(\n schemaName: string,\n tableName: string,\n columnName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const { present } = await columnExistsSteps(lowerer, {\n schema: schemaName,\n table: tableName,\n column: columnName,\n });\n const dropDefaultExec = await lowerer.lowerToExecuteRequest(\n contractFreeDdl.alterTable({\n ...ifDefined('schema', boundSchema(schemaName)),\n table: tableName,\n actions: [contractFreeDdl.dropDefaultAction(columnName)],\n }),\n );\n const noDefault = await lowerer.lowerToExecuteRequest(\n columnDefaultAst({ schema: schemaName, table: tableName, column: columnName }).defaultAbsent(),\n );\n return {\n id: `dropDefault.${tableName}.${columnName}`,\n label: `Drop default on \"${tableName}\".\"${columnName}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" exists`, present.sql, present.params)],\n execute: [step(`drop default on \"${columnName}\"`, dropDefaultExec.sql)],\n postcheck: [\n step(`verify column \"${columnName}\" has no default`, noDefault.sql, noDefault.params),\n ],\n };\n}\n\n/**\n * Builds the op for adding a NOT NULL column (no contract default) to a\n * non-empty table. Prechecks assert the column is absent and the table is\n * empty; the execute step lowers the typed `AddColumn` DDL node through the\n * adapter; postchecks assert the column exists and is NOT NULL.\n */\nexport async function addNotNullColumnDirect(\n schemaName: string,\n tableName: string,\n column: DdlColumn,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const columnName = column.name;\n const addColumn = await lowerer.lowerToExecuteRequest(\n contractFreeDdl.alterTable({\n ...ifDefined('schema', boundSchema(schemaName)),\n table: tableName,\n actions: [contractFreeDdl.addColumnAction(column)],\n }),\n );\n const absent = await lowerer.lowerToExecuteRequest(\n columnExistsAst({ schema: schemaName, table: tableName, column: columnName }).columnAbsent(),\n );\n const tableEmpty = await lowerer.lowerToExecuteRequest(tableIsEmptyAst(schemaName, tableName));\n const present = await lowerer.lowerToExecuteRequest(\n columnExistsAst({ schema: schemaName, table: tableName, column: columnName }).columnPresent(),\n );\n const notNullable = await lowerer.lowerToExecuteRequest(\n columnNullabilityAst({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n );\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n operationClass: 'additive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [\n step(`ensure column \"${columnName}\" is missing`, absent.sql, absent.params),\n step(\n `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n tableEmpty.sql,\n tableEmpty.params,\n ),\n ],\n execute: [step(`add column \"${columnName}\"`, addColumn.sql)],\n postcheck: [\n step(`verify column \"${columnName}\" exists`, present.sql, present.params),\n step(`verify column \"${columnName}\" is NOT NULL`, notNullable.sql, notNullable.params),\n ],\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport { REFERENTIAL_ACTION_SQL } from '@prisma-next/sql-contract/referential-action-sql';\nimport { constraintExistsAst } from '../../../contract-free/checks';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { qualifyTableName } from '../planner-sql-checks';\nimport { type ForeignKeySpec, type Op, step, targetDetails } from './shared';\n\nasync function constraintCheckSteps(\n lowerer: ExecuteRequestLowerer,\n options: { constraintName: string; schema: string; table: string },\n): Promise<{\n absent: { sql: string; params?: readonly unknown[] };\n present: { sql: string; params?: readonly unknown[] };\n}> {\n const checks = constraintExistsAst(options);\n const absent = await lowerer.lowerToExecuteRequest(checks.constraintAbsent());\n const present = await lowerer.lowerToExecuteRequest(checks.constraintPresent());\n return { absent, present };\n}\n\nfunction renderForeignKeySql(schemaName: string, tableName: string, fk: ForeignKeySpec): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fk.name)}\nFOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(fk.references.schema, fk.references.table)} (${fk.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (fk.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[fk.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(fk.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (fk.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[fk.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(fk.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n return sql;\n}\n\nexport async function addPrimaryKey(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const columnList = columns.map(quoteIdentifier).join(', ');\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `primaryKey.${tableName}.${constraintName}`,\n label: `Add primary key on \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('primaryKey', constraintName, schemaName, tableName),\n precheck: [\n step(`ensure primary key \"${constraintName}\" does not exist`, absent.sql, absent.params),\n ],\n execute: [\n step(\n `add primary key \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteIdentifier(constraintName)} PRIMARY KEY (${columnList})`,\n ),\n ],\n postcheck: [step(`verify primary key \"${constraintName}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function addUnique(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const columnList = columns.map(quoteIdentifier).join(', ');\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint on \"${tableName}\" (${columns.join(', ')})`,\n operationClass: 'additive',\n target: targetDetails('unique', constraintName, schemaName, tableName),\n precheck: [\n step(`ensure constraint \"${constraintName}\" does not exist`, absent.sql, absent.params),\n ],\n execute: [\n step(\n `add unique constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteIdentifier(constraintName)} UNIQUE (${columnList})`,\n ),\n ],\n postcheck: [step(`verify constraint \"${constraintName}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function addForeignKey(\n schemaName: string,\n tableName: string,\n fk: ForeignKeySpec,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName: fk.name,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `foreignKey.${tableName}.${fk.name}`,\n label: `Add foreign key \"${fk.name}\" on \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('foreignKey', fk.name, schemaName, tableName),\n precheck: [step(`ensure FK \"${fk.name}\" does not exist`, absent.sql, absent.params)],\n execute: [step(`add FK \"${fk.name}\"`, renderForeignKeySql(schemaName, tableName, fk))],\n postcheck: [step(`verify FK \"${fk.name}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function addCheckConstraint(\n schemaName: string,\n tableName: string,\n constraintName: string,\n column: string,\n values: readonly string[],\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const valueList = values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `checkConstraint.${tableName}.${constraintName}`,\n label: `Add check constraint \"${constraintName}\" on \"${tableName}\".\"${column}\"`,\n operationClass: 'additive',\n target: targetDetails('checkConstraint', constraintName, schemaName, tableName),\n precheck: [\n step(`ensure constraint \"${constraintName}\" does not exist`, absent.sql, absent.params),\n ],\n execute: [\n step(\n `add check constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteIdentifier(constraintName)} CHECK (${quoteIdentifier(column)} IN (${valueList}))`,\n ),\n ],\n postcheck: [step(`verify constraint \"${constraintName}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function dropCheckConstraint(\n schemaName: string,\n tableName: string,\n constraintName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `dropCheckConstraint.${tableName}.${constraintName}`,\n label: `Drop check constraint \"${constraintName}\" on \"${tableName}\"`,\n operationClass: 'destructive',\n target: targetDetails('checkConstraint', constraintName, schemaName, tableName),\n precheck: [step(`ensure constraint \"${constraintName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `drop check constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} DROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n ),\n ],\n postcheck: [\n step(`verify constraint \"${constraintName}\" does not exist`, absent.sql, absent.params),\n ],\n };\n}\n\n/**\n * `kind` feeds the operation's `target.details.objectType`. Descriptor-flow\n * does not carry kind information in its drop-constraint descriptor, so the\n * default is `'unique'`. The reconciliation planner passes the correct kind\n * (`'foreignKey'`, `'primaryKey'`, or `'unique'`) based on the diff issue\n * that produced the drop.\n */\nexport async function dropConstraint(\n schemaName: string,\n tableName: string,\n constraintName: string,\n lowerer: ExecuteRequestLowerer,\n kind: 'foreignKey' | 'unique' | 'primaryKey' = 'unique',\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const { absent, present } = await constraintCheckSteps(lowerer, {\n constraintName,\n schema: schemaName,\n table: tableName,\n });\n return {\n id: `dropConstraint.${tableName}.${constraintName}`,\n label: `Drop constraint \"${constraintName}\" on \"${tableName}\"`,\n operationClass: 'destructive',\n target: targetDetails(kind, constraintName, schemaName, tableName),\n precheck: [step(`ensure constraint \"${constraintName}\" exists`, present.sql, present.params)],\n execute: [\n step(\n `drop constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} DROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n ),\n ],\n postcheck: [\n step(`verify constraint \"${constraintName}\" does not exist`, absent.sql, absent.params),\n ],\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport { extensionExistsAst } from '../../../contract-free/checks';\nimport { DEFAULT_NAMESPACE_ID } from '../../namespace-ids';\nimport { quoteIdentifier } from '../../sql-utils';\nimport { type Op, step } from './shared';\n\nexport function createExtension(extensionName: string): Op {\n return {\n id: `extension.${extensionName}`,\n label: `Create extension \"${extensionName}\"`,\n operationClass: 'additive',\n target: { id: 'postgres' },\n precheck: [],\n execute: [\n step(\n `Create extension \"${extensionName}\"`,\n `CREATE EXTENSION IF NOT EXISTS ${quoteIdentifier(extensionName)}`,\n ),\n ],\n postcheck: [],\n };\n}\n\n/**\n * Install a Postgres extension as the baseline op for an extension-pack\n * contract space. Layered on top of {@link createExtension}: stamps an\n * `invariantId` (required so the per-space marker records the install),\n * scopes the op `id` under a caller-chosen namespace (e.g. `pgvector.`),\n * and emits pre- and postcheck SQL probing `pg_extension`. The richer\n * shape lets the runner's idempotency probe skip the install on re-run\n * (postcheck-pre-satisfied) without firing the precheck.\n *\n * Use this for hand-rolled baseline migrations in contract-space\n * extension packages (e.g. `extension-pgvector`, `extension-paradedb`);\n * use the bare {@link createExtension} for planner-emitted ops where the\n * caller already controls idempotency through the surrounding plan.\n */\nexport async function installExtension(\n options: {\n readonly extensionName: string;\n readonly invariantId: string;\n readonly id: string;\n readonly label?: string;\n },\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const { extensionName, invariantId, id } = options;\n const label = options.label ?? `Enable extension \"${extensionName}\"`;\n const checks = extensionExistsAst(extensionName);\n const absent = await lowerer.lowerToExecuteRequest(checks.extensionAbsent());\n const present = await lowerer.lowerToExecuteRequest(checks.extensionPresent());\n return {\n id,\n label,\n operationClass: 'additive',\n invariantId,\n target: {\n id: 'postgres',\n details: { schema: DEFAULT_NAMESPACE_ID, objectType: 'dependency', name: extensionName },\n },\n precheck: [\n step(`verify extension \"${extensionName}\" is not already enabled`, absent.sql, absent.params),\n ],\n execute: [\n step(\n `create extension \"${extensionName}\"`,\n `CREATE EXTENSION IF NOT EXISTS ${extensionName}`,\n ),\n ],\n postcheck: [\n step(`confirm extension \"${extensionName}\" is enabled`, present.sql, present.params),\n ],\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport { indexExistsAst } from '../../../contract-free/checks';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { qualifyTableName } from '../planner-sql-checks';\nimport { type Op, step, targetDetails } from './shared';\n\ntype CheckStep = { sql: string; params?: readonly unknown[] };\n\nasync function indexExistsSteps(\n lowerer: ExecuteRequestLowerer,\n schemaName: string,\n indexName: string,\n): Promise<{ present: CheckStep; absent: CheckStep }> {\n const checks = indexExistsAst(schemaName, indexName);\n const present = await lowerer.lowerToExecuteRequest(checks.indexPresent());\n const absent = await lowerer.lowerToExecuteRequest(checks.indexAbsent());\n return { present, absent };\n}\n\nexport interface CreateIndexExtras {\n readonly type?: string;\n readonly options?: Record<string, unknown>;\n}\n\nfunction renderIndexOptionValue(key: string, value: unknown): string {\n if (typeof value === 'string') return `'${escapeLiteral(value)}'`;\n if (typeof value === 'number' && Number.isFinite(value)) return String(value);\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n throw new Error(\n `Index option \"${key}\" must be a string, finite number, or boolean; got ${typeof value}`,\n );\n}\n\nfunction renderIndexOptions(options: Record<string, unknown>): string {\n return Object.entries(options)\n .map(([key, value]) => `${quoteIdentifier(key)} = ${renderIndexOptionValue(key, value)}`)\n .join(', ');\n}\n\nexport async function createIndex(\n schemaName: string,\n tableName: string,\n indexName: string,\n columns: readonly string[],\n lowerer: ExecuteRequestLowerer,\n extras?: CreateIndexExtras,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const columnList = columns.map(quoteIdentifier).join(', ');\n const using = extras?.type ? ` USING ${quoteIdentifier(extras.type)}` : '';\n const options = extras?.options;\n const withClause =\n options && Object.keys(options).length > 0 ? ` WITH (${renderIndexOptions(options)})` : '';\n const { present, absent } = await indexExistsSteps(lowerer, schemaName, indexName);\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index \"${indexName}\" on \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('index', indexName, schemaName, tableName),\n precheck: [step(`ensure index \"${indexName}\" does not exist`, absent.sql, absent.params)],\n execute: [\n step(\n `create index \"${indexName}\"`,\n `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualified}${using} (${columnList})${withClause}`,\n ),\n ],\n postcheck: [step(`verify index \"${indexName}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function dropIndex(\n schemaName: string,\n tableName: string,\n indexName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const { present, absent } = await indexExistsSteps(lowerer, schemaName, indexName);\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index \"${indexName}\"`,\n operationClass: 'destructive',\n target: targetDetails('index', indexName, schemaName, tableName),\n precheck: [step(`ensure index \"${indexName}\" exists`, present.sql, present.params)],\n execute: [\n step(`drop index \"${indexName}\"`, `DROP INDEX ${qualifyTableName(schemaName, indexName)}`),\n ],\n postcheck: [step(`verify index \"${indexName}\" does not exist`, absent.sql, absent.params)],\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { rlsEnabledAst, rlsPolicyExistsAst } from '../../../contract-free/checks';\nimport { createPolicy, dropPolicy } from '../../../contract-free/ddl';\nimport type { PostgresRlsPolicy } from '../../postgres-rls-policy';\nimport { qualifyTableName } from '../planner-sql-checks';\nimport { type Op, step, targetDetails } from './shared';\n\nconst PLAIN_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\nfunction validateRoleName(role: string): string {\n if (!PLAIN_IDENTIFIER.test(role)) {\n throw new Error(\n `Invalid role name ${JSON.stringify(role)}: role names must be plain SQL identifiers matching ^[A-Za-z_][A-Za-z0-9_$]*$`,\n );\n }\n return role;\n}\n\nexport async function createRlsPolicy(\n schemaName: string,\n tableName: string,\n policy: PostgresRlsPolicy,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const validatedRoles = policy.roles.map(validateRoleName);\n const ddlNode = createPolicy({\n schema: schemaName,\n table: tableName,\n name: policy.name,\n permissive: policy.permissive,\n operation: policy.operation,\n roles: validatedRoles,\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n });\n const checks = rlsPolicyExistsAst({\n schema: schemaName,\n table: tableName,\n policyName: policy.name,\n });\n const absent = await lowerer.lowerToExecuteRequest(checks.policyAbsent());\n const execute = await lowerer.lowerToExecuteRequest(ddlNode);\n const present = await lowerer.lowerToExecuteRequest(checks.policyPresent());\n return {\n id: `rlsPolicy.${schemaName}.${tableName}.${policy.name}`,\n label: `Create RLS policy \"${policy.name}\" on \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('rlsPolicy', policy.name, schemaName, tableName),\n precheck: [\n step(`ensure RLS policy \"${policy.name}\" does not exist`, absent.sql, absent.params),\n ],\n execute: [step(`create RLS policy \"${policy.name}\"`, execute.sql, execute.params)],\n postcheck: [step(`verify RLS policy \"${policy.name}\" exists`, present.sql, present.params)],\n };\n}\n\nexport async function dropRlsPolicy(\n schemaName: string,\n tableName: string,\n policyName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const ddlNode = dropPolicy({ schema: schemaName, table: tableName, name: policyName });\n const checks = rlsPolicyExistsAst({ schema: schemaName, table: tableName, policyName });\n const present = await lowerer.lowerToExecuteRequest(checks.policyPresent());\n const execute = await lowerer.lowerToExecuteRequest(ddlNode);\n const absent = await lowerer.lowerToExecuteRequest(checks.policyAbsent());\n return {\n id: `rlsPolicy.${schemaName}.${tableName}.${policyName}.drop`,\n label: `Drop RLS policy \"${policyName}\" on \"${tableName}\"`,\n operationClass: 'destructive',\n target: targetDetails('rlsPolicy', policyName, schemaName, tableName),\n precheck: [step(`ensure RLS policy \"${policyName}\" exists`, present.sql, present.params)],\n execute: [step(`drop RLS policy \"${policyName}\"`, execute.sql, execute.params)],\n postcheck: [step(`verify RLS policy \"${policyName}\" is absent`, absent.sql, absent.params)],\n };\n}\n\nexport async function enableRowLevelSecurity(\n schemaName: string,\n tableName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const checks = rlsEnabledAst(schemaName, tableName);\n const disabled = await lowerer.lowerToExecuteRequest(checks.rlsDisabled());\n const enabled = await lowerer.lowerToExecuteRequest(checks.rlsEnabled());\n return {\n id: `rowLevelSecurity.${schemaName}.${tableName}`,\n label: `Enable row-level security on \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('rowLevelSecurity', tableName, schemaName),\n precheck: [\n step(`check RLS is not already enabled on \"${tableName}\"`, disabled.sql, disabled.params),\n ],\n execute: [\n step(\n `enable row-level security on \"${tableName}\"`,\n `ALTER TABLE ${qualifyTableName(schemaName, tableName)} ENABLE ROW LEVEL SECURITY`,\n ),\n ],\n postcheck: [\n step(`verify row-level security is enabled on \"${tableName}\"`, enabled.sql, enabled.params),\n ],\n };\n}\n","import type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport { tableExistsAst } from '../../../contract-free/checks';\nimport { qualifyTableName } from '../planner-sql-checks';\nimport { type Op, step, targetDetails } from './shared';\n\nexport async function dropTable(\n schemaName: string,\n tableName: string,\n lowerer: ExecuteRequestLowerer,\n): Promise<Op> {\n const qualified = qualifyTableName(schemaName, tableName);\n const checks = tableExistsAst(schemaName, tableName);\n const present = await lowerer.lowerToExecuteRequest(checks.tablePresent());\n const absent = await lowerer.lowerToExecuteRequest(checks.tableAbsent());\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table \"${tableName}\"`,\n operationClass: 'destructive',\n target: targetDetails('table', tableName, schemaName),\n precheck: [step(`ensure table \"${tableName}\" exists`, present.sql, present.params)],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${qualified}`)],\n postcheck: [step(`verify table \"${tableName}\" does not exist`, absent.sql, absent.params)],\n };\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey'\n | 'checkConstraint'\n | 'rlsPolicy'\n | 'rowLevelSecurity';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\nexport function buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...ifDefined('table', table),\n };\n}\n","import type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { FunctionColumnDefault } from '@prisma-next/sql-relational-core/ast';\nimport { col } from '@prisma-next/sql-relational-core/contract-free';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport {\n columnDefaultAst,\n columnExistsAst,\n columnNullabilityAst,\n} from '../../contract-free/checks';\nimport * as contractFreeDdl from '../../contract-free/ddl';\nimport { boundSchema } from './bound-schema';\nimport { step } from './operations/shared';\nimport { buildColumnTypeSql } from './planner-ddl-builders';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport async function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n readonly lowerer: ExecuteRequestLowerer;\n}): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n const {\n schema,\n tableName,\n columnName,\n column,\n codecHooks,\n storageTypes,\n temporaryDefault,\n lowerer,\n } = options;\n\n // The recipe handles NOT NULL columns that carry no contract default, so the\n // temporary backfill value is the only default. It is a pre-rendered SQL\n // fragment (e.g. `''`, `0`, `'{}'::jsonb`), carried verbatim as a\n // `FunctionColumnDefault` so the adapter emits it as a `DEFAULT (...)` clause.\n const ddlColumn = col(columnName, buildColumnTypeSql(column, codecHooks, storageTypes), {\n notNull: true,\n default: new FunctionColumnDefault(temporaryDefault),\n });\n const addColumn = await lowerer.lowerToExecuteRequest(\n contractFreeDdl.alterTable({\n ...ifDefined('schema', boundSchema(schema)),\n table: tableName,\n actions: [contractFreeDdl.addColumnAction(ddlColumn)],\n }),\n );\n const dropTempDefault = await lowerer.lowerToExecuteRequest(\n contractFreeDdl.alterTable({\n ...ifDefined('schema', boundSchema(schema)),\n table: tableName,\n actions: [contractFreeDdl.dropDefaultAction(columnName)],\n }),\n );\n\n const absent = await lowerer.lowerToExecuteRequest(\n columnExistsAst({ schema, table: tableName, column: columnName }).columnAbsent(),\n );\n const present = await lowerer.lowerToExecuteRequest(\n columnExistsAst({ schema, table: tableName, column: columnName }).columnPresent(),\n );\n const notNullable = await lowerer.lowerToExecuteRequest(\n columnNullabilityAst({ schema, table: tableName, column: columnName, nullable: false }),\n );\n const noDefault = await lowerer.lowerToExecuteRequest(\n columnDefaultAst({ schema, table: tableName, column: columnName }).noDefault(),\n );\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [step(`ensure column \"${columnName}\" is missing`, absent.sql, absent.params)],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: addColumn.sql,\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: dropTempDefault.sql,\n },\n ],\n postcheck: [\n step(`verify column \"${columnName}\" exists`, present.sql, present.params),\n step(`verify column \"${columnName}\" is NOT NULL`, notNullable.sql, notNullable.params),\n step(\n `verify column \"${columnName}\" has no default after temporary default removal`,\n noDefault.sql,\n noDefault.params,\n ),\n ],\n };\n}\n","/**\n * Postgres migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `PostgresOpFactoryCallNode` abstract base.\n *\n * Every call class carries the literal arguments its backing factory would\n * receive, computes a human-readable `label` in its constructor, and\n * implements two polymorphic hooks:\n *\n * - `toOp()` — converts the IR node to a runtime\n * `SqlMigrationPlanOperation` by delegating to the matching pure factory\n * under `operations/`. `DataTransformCall.toOp()` always throws\n * `PN-MIG-2001` because a planner-generated data transform is an\n * unfilled authoring stub by construction.\n * - `renderTypeScript()` / `importRequirements()` — inherited from\n * `TsExpression`. Used by `renderCallsToTypeScript` to emit the call as\n * a TypeScript expression inside the scaffolded `migration.ts`.\n *\n * The abstract base and all concrete classes are package-private. External\n * consumers see only the framework-level `OpFactoryCall` interface and the\n * `PostgresOpFactoryCall` union.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer, Lowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n OpFactoryCall as FrameworkOpFactoryCall,\n MigrationOperationClass,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type {\n AnyDdlColumnDefault,\n DdlColumn,\n DdlTableConstraint,\n} from '@prisma-next/sql-relational-core/ast';\nimport { FunctionColumnDefault, LiteralColumnDefault } from '@prisma-next/sql-relational-core/ast';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { columnExistsAst, tableExistsAst } from '../../contract-free/checks';\nimport * as contractFreeDdl from '../../contract-free/ddl';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\nimport type { PostgresColumnDefault } from '../types';\nimport { boundSchema } from './bound-schema';\nimport {\n addNotNullColumnDirect,\n alterColumnType,\n dropColumn,\n dropDefault,\n dropNotNull,\n setDefault,\n setNotNull,\n} from './operations/columns';\nimport {\n addCheckConstraint,\n addForeignKey,\n addPrimaryKey,\n addUnique,\n dropCheckConstraint,\n dropConstraint,\n} from './operations/constraints';\nimport { createExtension } from './operations/dependencies';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport { createRlsPolicy, dropRlsPolicy, enableRowLevelSecurity } from './operations/rls';\nimport type { ForeignKeySpec } from './operations/shared';\nimport { step, targetDetails } from './operations/shared';\nimport { dropTable } from './operations/tables';\nimport { buildAddNotNullColumnWithTemporaryDefaultOperation } from './planner-recipes';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\n// Single module specifier emitted in user-edited `migration.ts` imports. The\n// Postgres migration facade re-exports both the `*Call` factory names\n// (createTable / addColumn / …) and the contract-free DDL builders\n// (col / lit / fn / primaryKey / foreignKey / unique) from\n// sql-relational-core/contract-free. We emit imports against the facade,\n// not against the underlying sql-relational-core subpath, because user\n// projects depend on `@prisma-next/postgres` (a runtime dep of every\n// init-scaffolded project) — they do not depend on the internal\n// `@prisma-next/sql-relational-core` package, so an emitted\n// `import … from '@prisma-next/sql-relational-core/contract-free'` fails\n// ESM resolution at runtime in user migrations even though pnpm has the\n// transitive package on disk.\nconst POSTGRES_MIGRATION_FACADE = '@prisma-next/postgres/migration';\n\nabstract class PostgresOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(lowerer?: Lowerer): Op | Promise<Op>;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport function postgresDefaultToDdlColumnDefault(\n columnDefault: PostgresColumnDefault | undefined,\n): DdlColumn['default'] {\n if (!columnDefault) return undefined;\n switch (columnDefault.kind) {\n case 'literal':\n return new LiteralColumnDefault(columnDefault.value);\n case 'function':\n if (columnDefault.expression === 'autoincrement()') return undefined;\n return new FunctionColumnDefault(columnDefault.expression);\n case 'sequence':\n return new FunctionColumnDefault(\n `nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`,\n );\n default: {\n const exhaustive: never = columnDefault;\n throw new Error(\n `postgresDefaultToDdlColumnDefault: unhandled kind \"${blindCast<{ kind: string }, 'exhaustiveness: surface the unhandled default kind'>(exhaustive).kind}\"`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// TypeScript rendering helpers for DdlColumn / DdlTableConstraint\n// ---------------------------------------------------------------------------\n\nfunction renderDdlColumnDefault(def: AnyDdlColumnDefault | undefined): string {\n if (!def) return '';\n if (def.kind === 'literal') {\n return `lit(${jsonToTsSource(def.value)})`;\n }\n return `fn(${jsonToTsSource(def.expression)})`;\n}\n\nfunction renderDdlColumnAsTsCall(col: DdlColumn): string {\n const opts: string[] = [];\n if (col.notNull) opts.push('notNull: true');\n if (col.primaryKey) opts.push('primaryKey: true');\n if (col.default) opts.push(`default: ${renderDdlColumnDefault(col.default)}`);\n if (col.codecRef) opts.push(`codecRef: ${jsonToTsSource(col.codecRef)}`);\n const optsStr = opts.length > 0 ? `, { ${opts.join(', ')} }` : '';\n return `col(${jsonToTsSource(col.name)}, ${jsonToTsSource(col.type)}${optsStr})`;\n}\n\nfunction renderDdlConstraintAsTsCall(constraint: DdlTableConstraint): string {\n switch (constraint.kind) {\n case 'primary-key': {\n const nameOpt = constraint.name ? `, { name: ${jsonToTsSource(constraint.name)} }` : '';\n return `primaryKey(${jsonToTsSource(constraint.columns)}${nameOpt})`;\n }\n case 'foreign-key': {\n const opts: string[] = [];\n if (constraint.name) opts.push(`name: ${jsonToTsSource(constraint.name)}`);\n if (constraint.onDelete) opts.push(`onDelete: ${jsonToTsSource(constraint.onDelete)}`);\n if (constraint.onUpdate) opts.push(`onUpdate: ${jsonToTsSource(constraint.onUpdate)}`);\n const optsStr = opts.length > 0 ? `, { ${opts.join(', ')} }` : '';\n return `foreignKey(${jsonToTsSource(constraint.columns)}, ${jsonToTsSource(constraint.refTable)}, ${jsonToTsSource(constraint.refColumns)}${optsStr})`;\n }\n case 'unique': {\n const nameOpt = constraint.name ? `, { name: ${jsonToTsSource(constraint.name)} }` : '';\n return `unique(${jsonToTsSource(constraint.columns)}${nameOpt})`;\n }\n case 'check-expression':\n return `checkExpression(${jsonToTsSource(constraint.name)}, ${jsonToTsSource(constraint.expression)})`;\n }\n}\n\nfunction needsColOrConstraintImport(columns: readonly DdlColumn[]): boolean {\n return columns.length > 0;\n}\n\nfunction constraintImportSymbols(constraints: readonly DdlTableConstraint[] | undefined): string[] {\n if (!constraints || constraints.length === 0) return [];\n const symbols = new Set<string>();\n for (const c of constraints) {\n if (c.kind === 'primary-key') symbols.add('primaryKey');\n else if (c.kind === 'foreign-key') symbols.add('foreignKey');\n else if (c.kind === 'unique') symbols.add('unique');\n else if (c.kind === 'check-expression') symbols.add('checkExpression');\n }\n return [...symbols];\n}\n\nfunction defaultImportSymbols(columns: readonly DdlColumn[]): string[] {\n const symbols = new Set<string>();\n for (const col of columns) {\n if (col.default?.kind === 'literal') symbols.add('lit');\n else if (col.default?.kind === 'function') symbols.add('fn');\n }\n return [...symbols];\n}\n\nexport class CreateTableCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columns: readonly DdlColumn[];\n readonly constraints: readonly DdlTableConstraint[] | undefined;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columns: readonly DdlColumn[],\n constraints?: readonly DdlTableConstraint[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columns = Object.freeze([...columns]);\n this.constraints = constraints ? Object.freeze([...constraints]) : undefined;\n this.label = `Create table \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `CreateTableCall.toOp: a DDL lowerer is required on the Postgres planner path (table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n const ddlNode = contractFreeDdl.createTable({\n ...ifDefined('schema', boundSchema(this.schemaName)),\n table: this.tableName,\n columns: this.columns,\n ...ifDefined('constraints', this.constraints),\n });\n const statement = await lowerer.lowerToExecuteRequest(ddlNode);\n const schemaName = this.schemaName;\n const tableName = this.tableName;\n const checks = tableExistsAst(schemaName, tableName);\n const absent = await lowerer.lowerToExecuteRequest(checks.tableAbsent());\n const present = await lowerer.lowerToExecuteRequest(checks.tablePresent());\n return {\n id: `table.${tableName}`,\n label: `Create table \"${tableName}\"`,\n summary: `Creates table \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('table', tableName, schemaName),\n precheck: [step(`ensure table \"${tableName}\" does not exist`, absent.sql, absent.params)],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: statement.sql,\n params: statement.params ?? [],\n },\n ],\n postcheck: [step(`verify table \"${tableName}\" exists`, present.sql, present.params)],\n };\n }\n\n renderTypeScript(): string {\n const columnsList = this.columns.map(renderDdlColumnAsTsCall).join(', ');\n const constraintsList = this.constraints\n ? this.constraints.map(renderDdlConstraintAsTsCall).join(', ')\n : undefined;\n\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`columns: [${columnsList}]`);\n if (constraintsList) opts.push(`constraints: [${constraintsList}]`);\n\n return `this.createTable({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n const req: ImportRequirement[] = [];\n if (needsColOrConstraintImport(this.columns)) {\n req.push({ moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: 'col' });\n for (const sym of defaultImportSymbols(this.columns)) {\n req.push({ moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: sym });\n }\n }\n for (const sym of constraintImportSymbols(this.constraints)) {\n req.push({ moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: sym });\n }\n return req;\n }\n}\n\nexport class DropTableCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.label = `Drop table \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropTableCall.toOp: a lowerer is required on the Postgres planner path (table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropTable(this.schemaName, this.tableName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n return `this.dropTable({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly column: DdlColumn;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, column: DdlColumn) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.column = column;\n this.label = `Add column \"${column.name}\" to \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddColumnCall.toOp: a DDL lowerer is required on the Postgres planner path (column \"${this.column.name}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n const ddlNode = contractFreeDdl.alterTable({\n ...ifDefined('schema', boundSchema(this.schemaName)),\n table: this.tableName,\n actions: [contractFreeDdl.addColumnAction(this.column)],\n });\n const statement = await lowerer.lowerToExecuteRequest(ddlNode);\n const schemaName = this.schemaName;\n const tableName = this.tableName;\n const columnName = this.column.name;\n const colChecks = columnExistsAst({ schema: schemaName, table: tableName, column: columnName });\n const absent = await lowerer.lowerToExecuteRequest(colChecks.columnAbsent());\n const present = await lowerer.lowerToExecuteRequest(colChecks.columnPresent());\n return {\n id: `column.${schemaName}.${tableName}.${columnName}`,\n label: `Add column \"${columnName}\" to \"${tableName}\"`,\n operationClass: 'additive',\n target: targetDetails('column', columnName, schemaName, tableName),\n precheck: [step(`ensure column \"${columnName}\" is missing`, absent.sql, absent.params)],\n execute: [step(`add column \"${columnName}\"`, statement.sql)],\n postcheck: [step(`verify column \"${columnName}\" exists`, present.sql, present.params)],\n };\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${renderDdlColumnAsTsCall(this.column)}`);\n return `this.addColumn({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n const req: ImportRequirement[] = [\n { moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: 'col' },\n ];\n for (const sym of defaultImportSymbols([this.column])) {\n req.push({ moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: sym });\n }\n return req;\n }\n}\n\nexport class DropColumnCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column \"${columnName}\" from \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropColumnCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropColumn(this.schemaName, this.tableName, this.columnName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n return `this.dropColumn({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport interface AlterColumnTypeOptions {\n readonly qualifiedTargetType: string;\n readonly formatTypeExpected: string;\n readonly rawTargetTypeForLabel: string;\n readonly using?: string;\n}\n\nexport class AlterColumnTypeCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'alterColumnType' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly options: AlterColumnTypeOptions;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columnName: string,\n options: AlterColumnTypeOptions,\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.options = options;\n this.label = `Alter type of \"${tableName}\".\"${columnName}\" to ${options.rawTargetTypeForLabel}`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AlterColumnTypeCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return alterColumnType(this.schemaName, this.tableName, this.columnName, this.options, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n opts.push(`options: ${jsonToTsSource(this.options)}`);\n return `this.alterColumnType({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class SetNotNullCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'setNotNull' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Set NOT NULL on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `SetNotNullCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return setNotNull(this.schemaName, this.tableName, this.columnName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n return `this.setNotNull({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class DropNotNullCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropNotNull' as const;\n readonly operationClass = 'widening' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop NOT NULL on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropNotNullCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropNotNull(this.schemaName, this.tableName, this.columnName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n return `this.dropNotNull({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class SetDefaultCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'setDefault' as const;\n readonly operationClass: 'additive' | 'widening';\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly defaultSql: string;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n columnName: string,\n defaultSql: string,\n operationClass: 'additive' | 'widening' = 'additive',\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.defaultSql = defaultSql;\n this.operationClass = operationClass;\n this.label = `Set default on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `SetDefaultCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return setDefault(\n this.schemaName,\n this.tableName,\n this.columnName,\n this.defaultSql,\n lowerer,\n this.operationClass,\n );\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n opts.push(`defaultSql: ${jsonToTsSource(this.defaultSql)}`);\n if (this.operationClass !== 'additive') {\n opts.push(`operationClass: ${jsonToTsSource(this.operationClass)}`);\n }\n return `this.setDefault({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class DropDefaultCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropDefault' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop default on \"${tableName}\".\"${columnName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropDefaultCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropDefault(this.schemaName, this.tableName, this.columnName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`column: ${jsonToTsSource(this.columnName)}`);\n return `this.dropDefault({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// NOT NULL column additions (planner-internal; no authored surface)\n// ============================================================================\n\n/**\n * Planner-internal call for adding a NOT NULL column (no contract default) to\n * a table that must be empty at migration time. Carries the typed `DdlColumn`\n * and lowers it to an ADD COLUMN execute step via the adapter at `toOp` time.\n *\n * No authored `PostgresMigration` method: this call is only emitted by the\n * planner, never hand-written by migration authors.\n */\nexport class AddNotNullColumnDirectCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: DdlColumn;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, columnName: string, column: DdlColumn) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.columnName = columnName;\n this.column = column;\n this.label = `Add column ${columnName} to ${tableName}`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddNotNullColumnDirectCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return addNotNullColumnDirect(this.schemaName, this.tableName, this.column, lowerer);\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource({ id: `column.${this.tableName}.${this.columnName}`, label: this.label, operationClass: 'additive' })})`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n/**\n * Planner-internal call for adding a NOT NULL column (no contract default)\n * using a temporary default value for non-empty tables. Carries all parameters\n * needed for `buildAddNotNullColumnWithTemporaryDefaultOperation`; both the\n * typed ADD COLUMN execute step and the pre/postchecks are lowered via the\n * adapter at `toOp` time.\n *\n * No authored `PostgresMigration` method: this call is only emitted by the\n * planner, never hand-written by migration authors.\n */\nexport class AddNotNullColumnWithTempDefaultCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n readonly label: string;\n\n constructor(options: {\n readonly schemaName: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n }) {\n super();\n this.schemaName = options.schemaName;\n this.tableName = options.tableName;\n this.columnName = options.columnName;\n this.column = options.column;\n this.codecHooks = options.codecHooks;\n this.storageTypes = options.storageTypes;\n this.temporaryDefault = options.temporaryDefault;\n this.label = `Add column ${options.columnName} to ${options.tableName}`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddNotNullColumnWithTempDefaultCall.toOp: a lowerer is required on the Postgres planner path (column \"${this.columnName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema: this.schemaName,\n tableName: this.tableName,\n columnName: this.columnName,\n column: this.column,\n codecHooks: this.codecHooks,\n storageTypes: this.storageTypes,\n temporaryDefault: this.temporaryDefault,\n lowerer,\n });\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource({ id: `column.${this.tableName}.${this.columnName}`, label: this.label, operationClass: 'additive' })})`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// Constraints\n// ============================================================================\n\nfunction constraintCallOptions(\n schemaName: string,\n tableName: string,\n constraintName: string,\n): string {\n const opts: string[] = [];\n if (schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(tableName)}`);\n opts.push(`constraint: ${jsonToTsSource(constraintName)}`);\n return opts.join(', ');\n}\n\nexport class AddPrimaryKeyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addPrimaryKey' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.columns = columns;\n this.label = `Add primary key on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddPrimaryKeyCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.constraintName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return addPrimaryKey(\n this.schemaName,\n this.tableName,\n this.constraintName,\n this.columns,\n lowerer,\n );\n }\n\n renderTypeScript(): string {\n return `this.addPrimaryKey({ ${constraintCallOptions(this.schemaName, this.tableName, this.constraintName)}, columns: ${jsonToTsSource(this.columns)} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class AddUniqueCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addUnique' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n columns: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.columns = columns;\n this.label = `Add unique constraint on \"${tableName}\" (${columns.join(', ')})`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddUniqueCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.constraintName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return addUnique(this.schemaName, this.tableName, this.constraintName, this.columns, lowerer);\n }\n\n renderTypeScript(): string {\n return `this.addUnique({ ${constraintCallOptions(this.schemaName, this.tableName, this.constraintName)}, columns: ${jsonToTsSource(this.columns)} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class AddForeignKeyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addForeignKey' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly fk: ForeignKeySpec;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, fk: ForeignKeySpec) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.fk = fk;\n this.label = `Add foreign key \"${fk.name}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddForeignKeyCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.fk.name}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return addForeignKey(this.schemaName, this.tableName, this.fk, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`foreignKey: ${jsonToTsSource(this.fk)}`);\n return `this.addForeignKey({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class DropConstraintCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropConstraint' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly kind: 'foreignKey' | 'unique' | 'primaryKey';\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n kind: 'foreignKey' | 'unique' | 'primaryKey' = 'unique',\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.kind = kind;\n this.label = `Drop constraint \"${constraintName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropConstraintCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.constraintName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropConstraint(this.schemaName, this.tableName, this.constraintName, lowerer, this.kind);\n }\n\n renderTypeScript(): string {\n const opts = [constraintCallOptions(this.schemaName, this.tableName, this.constraintName)];\n if (this.kind !== 'unique') {\n opts.push(`kind: ${jsonToTsSource(this.kind)}`);\n }\n return `this.dropConstraint({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class AddCheckConstraintCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'addCheckConstraint' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly column: string;\n readonly values: readonly string[];\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n constraintName: string,\n column: string,\n values: readonly string[],\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.column = column;\n this.values = values;\n this.label = `Add check constraint \"${constraintName}\" on \"${tableName}\".\"${column}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `AddCheckConstraintCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.constraintName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return addCheckConstraint(\n this.schemaName,\n this.tableName,\n this.constraintName,\n this.column,\n this.values,\n lowerer,\n );\n }\n\n renderTypeScript(): string {\n return `this.addCheckConstraint({ ${constraintCallOptions(this.schemaName, this.tableName, this.constraintName)}, column: ${jsonToTsSource(this.column)}, values: ${jsonToTsSource(this.values)} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class DropCheckConstraintCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropCheckConstraint' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly constraintName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, constraintName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.constraintName = constraintName;\n this.label = `Drop check constraint \"${constraintName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropCheckConstraintCall.toOp: a lowerer is required on the Postgres planner path (constraint \"${this.constraintName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropCheckConstraint(this.schemaName, this.tableName, this.constraintName, lowerer);\n }\n\n renderTypeScript(): string {\n return `this.dropCheckConstraint({ ${constraintCallOptions(this.schemaName, this.tableName, this.constraintName)} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// Indexes\n// ============================================================================\n\nexport class CreateIndexCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n // Named indexType (not typeName): `locationForCall` in issue-planner.ts reads\n // a call's `typeName` as a CREATE TYPE target location, which an index is not.\n readonly indexType: string | undefined;\n readonly options: Record<string, unknown> | undefined;\n readonly label: string;\n\n constructor(\n schemaName: string,\n tableName: string,\n indexName: string,\n columns: readonly string[],\n extras?: { readonly type?: string; readonly options?: Record<string, unknown> },\n ) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.indexType = extras?.type;\n this.options = extras?.options;\n this.label = `Create index \"${indexName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `CreateIndexCall.toOp: a lowerer is required on the Postgres planner path (index \"${this.indexName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n const extras: { type?: string; options?: Record<string, unknown> } = {};\n if (this.indexType !== undefined) extras.type = this.indexType;\n if (this.options !== undefined) extras.options = this.options;\n return createIndex(\n this.schemaName,\n this.tableName,\n this.indexName,\n this.columns,\n lowerer,\n extras,\n );\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`index: ${jsonToTsSource(this.indexName)}`);\n opts.push(`columns: ${jsonToTsSource(this.columns)}`);\n if (this.indexType !== undefined || this.options !== undefined) {\n const extrasParts: string[] = [];\n if (this.indexType !== undefined) extrasParts.push(`type: ${jsonToTsSource(this.indexType)}`);\n if (this.options !== undefined) extrasParts.push(`options: ${jsonToTsSource(this.options)}`);\n opts.push(`extras: { ${extrasParts.join(', ')} }`);\n }\n return `this.createIndex({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\nexport class DropIndexCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, indexName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index \"${indexName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropIndexCall.toOp: a lowerer is required on the Postgres planner path (index \"${this.indexName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropIndex(this.schemaName, this.tableName, this.indexName, lowerer);\n }\n\n renderTypeScript(): string {\n const opts: string[] = [];\n if (this.schemaName !== UNBOUND_NAMESPACE_ID) {\n opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);\n }\n opts.push(`table: ${jsonToTsSource(this.tableName)}`);\n opts.push(`index: ${jsonToTsSource(this.indexName)}`);\n return `this.dropIndex({ ${opts.join(', ')} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation.\n *\n * Wraps an already-materialized `SqlMigrationPlanOperation` — typically one\n * produced by a SQL-family method or a codec control hook — so the planner\n * can carry it alongside IR nodes without reverse-engineering it into a\n * structured call class. Doubles as the user-facing escape hatch for raw\n * migrations: authors can pass a full op shape to `rawSql({...})`.\n *\n * `toOp()` returns the stored op unchanged. `renderTypeScript()` emits\n * `rawSql({...})` with the op serialized as a JSON literal — round-tripping\n * requires every field on the op to be JSON-serializable (no closures).\n */\nexport class RawSqlCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Database dependencies (structured DDL)\n// ============================================================================\n\nexport class CreateExtensionCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createExtension' as const;\n readonly operationClass = 'additive' as const;\n readonly extensionName: string;\n readonly label: string;\n\n constructor(extensionName: string) {\n super();\n this.extensionName = extensionName;\n this.label = `Create extension \"${extensionName}\"`;\n this.freeze();\n }\n\n toOp(): Op {\n return createExtension(this.extensionName);\n }\n\n renderTypeScript(): string {\n return `createExtension(${jsonToTsSource(this.extensionName)})`;\n }\n}\n\nexport class CreateSchemaCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createSchema' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly label: string;\n\n constructor(schemaName: string) {\n super();\n this.schemaName = schemaName;\n this.label = `Create schema \"${schemaName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `CreateSchemaCall.toOp: a DDL lowerer is required on the Postgres planner path (schema \"${this.schemaName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n const ddlNode = contractFreeDdl.createSchema({ schema: this.schemaName, ifNotExists: true });\n const statement = await lowerer.lowerToExecuteRequest(ddlNode);\n const schemaName = this.schemaName;\n return {\n id: `schema.${schemaName}`,\n label: `Create schema \"${schemaName}\"`,\n operationClass: 'additive',\n target: { id: 'postgres' },\n precheck: [],\n execute: [\n {\n description: `Create schema \"${schemaName}\"`,\n sql: statement.sql,\n params: statement.params ?? [],\n },\n ],\n postcheck: [],\n };\n }\n\n renderTypeScript(): string {\n return `this.createSchema({ schema: ${jsonToTsSource(this.schemaName)} })`;\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [];\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. `checkSlot` and `runSlot` name\n * the unfilled authoring slots that the rendered `migration.ts` will expose\n * to the user via `placeholder(\"…\")` calls. `toOp()` always throws\n * `PN-MIG-2001`: the planner cannot lower a stubbed transform to a runtime\n * op — the user must fill the rendered `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly checkSlot: string;\n readonly runSlot: string;\n\n constructor(\n label: string,\n checkSlot: string,\n runSlot: string,\n operationClass: MigrationOperationClass = 'data',\n ) {\n super();\n this.label = label;\n this.checkSlot = checkSlot;\n this.runSlot = runSlot;\n this.operationClass = operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n return [\n `this.dataTransform(endContract, ${jsonToTsSource(this.label)}, {`,\n ` check: () => placeholder(${jsonToTsSource(this.checkSlot)}),`,\n ` run: () => placeholder(${jsonToTsSource(this.runSlot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: POSTGRES_MIGRATION_FACADE, symbol: 'placeholder' },\n {\n moduleSpecifier: './end-contract.json',\n symbol: 'endContract',\n kind: 'default',\n attributes: { type: 'json' },\n },\n ];\n }\n}\n\nexport class CreatePostgresRlsPolicyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'createRlsPolicy' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly policy: PostgresRlsPolicy;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, policy: PostgresRlsPolicy) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.policy = policy;\n this.label = `Create RLS policy \"${policy.name}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `CreatePostgresRlsPolicyCall.toOp: a lowerer is required on the Postgres planner path (policy \"${this.policy.name}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return createRlsPolicy(this.schemaName, this.tableName, this.policy, lowerer);\n }\n\n renderTypeScript(): string {\n return `createRlsPolicy(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.policy)})`;\n }\n}\n\nexport class DropPostgresRlsPolicyCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'dropRlsPolicy' as const;\n readonly operationClass = 'destructive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly policyName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string, policyName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.policyName = policyName;\n this.label = `Drop RLS policy \"${policyName}\" on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `DropPostgresRlsPolicyCall.toOp: a lowerer is required on the Postgres planner path (policy \"${this.policyName}\" on table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return dropRlsPolicy(this.schemaName, this.tableName, this.policyName, lowerer);\n }\n\n renderTypeScript(): string {\n return `dropRlsPolicy(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.policyName)})`;\n }\n}\n\nexport class EnableRowLevelSecurityCall extends PostgresOpFactoryCallNode {\n readonly factoryName = 'enableRowLevelSecurity' as const;\n readonly operationClass = 'additive' as const;\n readonly schemaName: string;\n readonly tableName: string;\n readonly label: string;\n\n constructor(schemaName: string, tableName: string) {\n super();\n this.schemaName = schemaName;\n this.tableName = tableName;\n this.label = `Enable row-level security on \"${tableName}\"`;\n this.freeze();\n }\n\n async toOp(lowerer?: ExecuteRequestLowerer): Promise<Op> {\n if (lowerer === undefined) {\n throw new Error(\n `EnableRowLevelSecurityCall.toOp: a lowerer is required on the Postgres planner path (table \"${this.tableName}\"). Pass the control adapter to createPostgresMigrationPlanner.`,\n );\n }\n return enableRowLevelSecurity(this.schemaName, this.tableName, lowerer);\n }\n\n renderTypeScript(): string {\n return `enableRowLevelSecurity(${jsonToTsSource(this.schemaName)}, ${jsonToTsSource(this.tableName)})`;\n }\n}\n\nexport type PostgresOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | AddColumnCall\n | DropColumnCall\n | AlterColumnTypeCall\n | SetNotNullCall\n | DropNotNullCall\n | SetDefaultCall\n | DropDefaultCall\n | AddNotNullColumnDirectCall\n | AddNotNullColumnWithTempDefaultCall\n | AddPrimaryKeyCall\n | AddForeignKeyCall\n | AddUniqueCall\n | AddCheckConstraintCall\n | DropCheckConstraintCall\n | CreateIndexCall\n | DropIndexCall\n | DropConstraintCall\n | RawSqlCall\n | CreateExtensionCall\n | CreateSchemaCall\n | CreatePostgresRlsPolicyCall\n | DropPostgresRlsPolicyCall\n | EnableRowLevelSecurityCall\n | DataTransformCall;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,SAAgB,YAAY,YAAwC;CAClE,OAAO,eAAe,uBAAuB,KAAA,IAAY;AAC3D;;;ACeA,SAAgB,KAAK,aAAqB,KAAa,QAA6B;CAClF,OAAO;EAAE;EAAa;EAAK,GAAG,UAAU,UAAU,MAAM;CAAE;AAC5D;AAEA,SAAgB,cACd,YACA,MACA,QACA,OAC0E;CAC1E,OAAO;EACL,IAAI;EACJ,SAAS;GAAE;GAAQ;GAAY;GAAM,GAAG,UAAU,SAAS,KAAK;EAAE;CAC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,GACd,MAAM,IAAI,MACR,+FAA+F,KAAK,WAAW,cAAc,KAAK,UAAU,gEAC9I;EAEF,OAAO,cAAc,KAAK,YAAY,KAAK,WAAW,KAAK,YAAY,OAAO;CAChF;CAEA,mBAA2B;EACzB,OAAO,iBAAiB,eAAe,KAAK,UAAU,EAAE,IAAI,eAAe,KAAK,SAAS,EAAE,IAAI,eAAe,KAAK,UAAU,EAAE;CACjI;AACF;AAEA,IAAa,6BAAb,cAAgD,0BAA0B;CACxE,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CAEA,YAAY,YAAoB,WAAmB;EACjD,MAAM;EACN,KAAK,aAAa;EAClB,KAAK,YAAY;EACjB,KAAK,QAAQ,iCAAiC,UAAU;EACxD,KAAK,OAAO;CACd;CAEA,MAAM,KAAK,SAA8C;EACvD,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MACR,+FAA+F,KAAK,UAAU,gEAChH;EAEF,OAAO,uBAAuB,KAAK,YAAY,KAAK,WAAW,OAAO;CACxE;CAEA,mBAA2B;EACzB,OAAO,0BAA0B,eAAe,KAAK,UAAU,EAAE,IAAI,eAAe,KAAK,SAAS,EAAE;CACtG;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-DWQYPxP8.mjs","names":["#lowerer"],"sources":["../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { DEFAULT_NAMESPACE_ID } from '../namespace-ids';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the database-root schema\n * node. `existingSchemas` is database-level, so it lives on the\n * `PostgresDatabaseSchemaNode` root — not on the per-schema namespace nodes.\n *\n * Defaults to the always-present `public` schema when the node is not the\n * database root — a fresh Postgres database always carries `public` (unless an\n * operator dropped it manually), so any verifier path that runs without an\n * enriched introspection still suppresses the redundant `CREATE SCHEMA\n * \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and sets `existingSchemas`\n * on the returned root. Tests that want to assert against a richer initial\n * state construct a `PostgresDatabaseSchemaNode` explicitly.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIRNode): readonly string[] {\n if (PostgresDatabaseSchemaNode.is(schema)) {\n return schema.existingSchemas;\n }\n return [DEFAULT_NAMESPACE_ID];\n}\n\n/**\n * Emits a `postgres-namespace` `not-found` diff issue for every\n * contract-declared Postgres namespace whose live container does not yet\n * exist. The planner prepends these (node-typed, synthesized) to the\n * relational diff issues so a multi-schema plan emits `CREATE SCHEMA`\n * before the tables that need it — a planner-only concern (verify already\n * rejects via the `not-found` table issues a missing schema already\n * produces), so this is not part of the shared diff.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue's path is `['database', ddlName]` — an ancestor of\n * every table path under that schema, so it must never be run through\n * `coalesceSubtreeIssues` alongside the table diff (it would swallow the\n * table-level `not-found` issues that drive `CREATE TABLE`); the planner\n * adds these AFTER coalescing the relational issues, and they are not\n * subject to sibling-space ownership scoping (mirrors the retired\n * coordinate walk, which prepended namespace issues after that filter).\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n}): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaDiffIssue<SqlSchemaDiffNode>[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n const namespace = new PostgresNamespaceSchemaNode({\n schemaName: ddlName,\n tables: {},\n nativeEnumTypeNames: [],\n });\n issues.push({\n path: ['database', ddlName],\n reason: 'not-found',\n message: `Schema \"${ddlName}\" is missing from database`,\n expected: namespace,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerConflict,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n partitionCallsByControlPolicy,\n partitionIssuesByControlPolicy,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaDiffIssue,\n SchemaOwnership,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresSchemaNodeKind, type SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolveNamespaceIdForDdlSchema,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresNodeIssueControlPolicySubject,\n resolvePostgresNodeIssueCreationFactoryName,\n} from './control-policy';\nimport { buildPostgresPlanDiff } from './diff-database-schema';\nimport {\n coalesceSubtreeIssues,\n issueNode,\n issueSchemaName,\n issueTableName,\n planIssues,\n} from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport {\n CreatePostgresRlsPolicyCall,\n DropPostgresRlsPolicyCall,\n EnableRowLevelSecurityCall,\n} from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(\n lowerer: ExecuteRequestLowerer,\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner(lowerer);\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | {\n readonly kind: 'success';\n readonly plan: TypeScriptRenderablePostgresMigration;\n readonly warnings?: readonly SqlPlannerConflict[];\n }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` diffs the target contract against the live schema via the one\n * differ (`buildPostgresPlanDiff`, producing node-typed `SchemaDiffIssue[]`)\n * and delegates to `planIssues` with the unified `postgresPlannerStrategies`\n * list: NOT-NULL backfill, type-change, nullable-tightening, codec-hook\n * storage types, component-declared dependency installs, and\n * shared-temp-default / empty-table-guarded NOT-NULL add-column. The same\n * strategy list runs for `migration plan`, `db update`, and `db init`;\n * behavior diverges purely on `policy.allowedOperationClasses` (the\n * data-safe strategies short-circuit when `'data'` is excluded). The issue\n * planner applies operation-class policy gates and emits a single\n * `PostgresOpFactoryCall[]` that drives both the runtime-ops view (via\n * `renderOps`) and the `renderTypeScript()` authoring surface. RLS policy\n * drift (the structural half of the same one-differ tree) is handled\n * separately via `planPostgresSchemaDiff`.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n\n constructor(lowerer?: ExecuteRequestLowerer) {\n this.#lowerer = lowerer;\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n /**\n * Ownership oracle over the contract-space composition — see\n * {@link SqlMigrationPlannerPlanOptions.ownership}.\n */\n readonly ownership?: SchemaOwnership;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n this.#lowerer,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n // The one combined tree diff drives the whole plan: relational findings\n // become structural DDL via `planIssues`, policy findings become RLS ops\n // via `planPostgresSchemaDiff`. Verify runs its own full-tree node diff\n // (`diffSchema`) over the same schema and rejects on a\n // surviving failure.\n PostgresDatabaseSchemaNode.assert(options.schema);\n const { issues: rawIssues } = buildPostgresPlanDiff({\n contract: options.contract,\n actualSchema: options.schema,\n frameworkComponents: options.frameworkComponents,\n });\n const policyDiffIssues = rawIssues.filter((issue) => isPolicyDiffIssue(issue));\n const relationalDiffIssues = rawIssues.filter((issue) => !isPolicyDiffIssue(issue));\n\n // The generic differ is total and un-gated: strict-mode extras filtering\n // (dropping `not-expected` findings outside strict mode, mirroring the\n // retired coordinate walk's `if (strict) { ...extra_* } }` guards),\n // subtree coalescing (a missing/extra table also emits an issue for\n // every child under it — redundant once the table-level Create/Drop call\n // already accounts for the whole subtree), and ownership are all post-diff\n // planner steps.\n //\n // Ownership: a live extra is only this plan's to drop when no contract\n // space owns it. The differ ran against THIS space's contract, so a table\n // a sibling space owns surfaces here as `not-expected`; the planner asks\n // the ownership oracle (the passive aggregate) whether any space declares\n // it and, if so, leaves it alone — it is a sibling's table, not an orphan.\n // A table no space owns stays a genuine extra to drop under a destructive\n // policy. Ownership lives in the aggregate; the planner only asks. Absent\n // oracle (single-space, none handed) keeps every extra. Coalescing MUST\n // run before this so a sibling-owned table's child issues have already\n // collapsed into the one table-level issue that carries the table name.\n const strict =\n options.policy.allowedOperationClasses.includes('widening') ||\n options.policy.allowedOperationClasses.includes('destructive');\n const coalesced = coalesceSubtreeIssues(relationalDiffIssues);\n const owned = retainUnownedExtras(coalesced, options.ownership, options.contract);\n const gated = strict ? owned : owned.filter((issue) => issue.reason !== 'not-expected');\n\n // Namespace presence (`CREATE SCHEMA`) is a planner-only op-generation\n // concern stitched in here rather than inside the shared diff — verify\n // never needs it (a missing schema already surfaces as a `not-found`\n // table in the relational findings). These synthesized issues are added\n // AFTER coalescing/scoping (never coalesced against the table diff —\n // their path is an ancestor of every table path under that schema, so\n // running them through the same coalesce would swallow the table-level\n // `not-found` issues that drive `CREATE TABLE`) and are NOT subject to\n // sibling-space scoping, matching the retired coordinate walk exactly.\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n const schemaIssues = [...namespaceIssues, ...gated];\n\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n // The strategy layer reads the live schema by bare table name for existence\n // checks (shared-temp-default safety, FK/unique probes), so it takes one\n // per-schema namespace node — never the whole tree root, and never a flat\n // merge of every namespace (which would collide same-named tables across\n // schemas). Probing more than one namespace at once is future work.\n const relationalSchema = relationalNamespaceNode(options.schema, schemaName);\n\n // Input-side control-policy partition. `external` / `observed` subjects\n // — and non-creation issues for `tolerated` subjects — are dropped from\n // the planner's input entirely; the planner never observes them, never\n // diffs them, never generates DDL for them. Suppression warnings are\n // built directly from the suppressed partition (one per subject), so the\n // user-visible message survives even when the planner would have failed\n // to model the subject's live shape.\n const issuePartition = partitionIssuesByControlPolicy({\n issues: schemaIssues,\n contract: options.contract,\n resolveControlPolicySubject: (issue) =>\n resolvePostgresNodeIssueControlPolicySubject(issue, options.contract),\n resolveCreationFactoryName: resolvePostgresNodeIssueCreationFactoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n const result = planIssues({\n issues: issuePartition.plannable,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapNodeIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n ...ifDefined('schema', relationalSchema),\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n const schemaDiffCalls = this.planPostgresSchemaDiff(options, policyDiffIssues);\n const schemaDiffPartition = partitionCallsByControlPolicy({\n calls: schemaDiffCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec hook ops are target-agnostic `OpFactoryCall`; Postgres planning\n // lifts them at this integration boundary (see field-event-planner JSDoc).\n const fieldEventPostgresCalls = blindCast<\n readonly PostgresOpFactoryCall[],\n 'Codec hook ops conform to PostgresOpFactoryCall at the app emitter boundary'\n >(fieldEventOps);\n const fieldEventPartition = partitionCallsByControlPolicy({\n calls: fieldEventPostgresCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n const calls = [...result.value.calls, ...schemaDiffPartition.kept, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...schemaDiffPartition.warnings,\n ...fieldEventPartition.warnings,\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n this.#lowerer,\n ),\n ...(warnings.length > 0 ? { warnings: Object.freeze(warnings) } : {}),\n });\n }\n\n /**\n * Maps the RLS policy presence findings of the one combined tree diff\n * (`buildPostgresPlanDiff`, already ownership-filtered) into `ENABLE RLS`\n * / `CREATE POLICY` / `DROP POLICY` ops. It does not re-diff — it consumes\n * exactly the policy-node subset of the shared diff's issues.\n */\n private planPostgresSchemaDiff(\n options: PlannerOptionsWithComponents,\n filteredDiffIssues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ): readonly PostgresOpFactoryCall[] {\n const allowsDestructive = options.policy.allowedOperationClasses.includes('destructive');\n const calls: PostgresOpFactoryCall[] = [];\n const seenEnableTables = new Set<string>();\n\n for (const issue of filteredDiffIssues) {\n // 'not-equal' is unreachable for content-addressed policies: the wire name\n // encodes the body hash, so two policies sharing a local key (same name)\n // are always equal and isEqualTo never returns false.\n if (issue.reason === 'not-found') {\n const expected = issue.expected;\n PostgresPolicySchemaNode.assert(expected);\n // expected.namespaceId is the DDL schema name (resolved during projection);\n // this re-resolution is a no-op as long as PostgresSchema.ddlSchemaName() returns this.id.\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n expected.namespaceId,\n );\n const tableKey = `${schemaForTable}.${expected.tableName}`;\n if (!seenEnableTables.has(tableKey)) {\n seenEnableTables.add(tableKey);\n calls.push(new EnableRowLevelSecurityCall(schemaForTable, expected.tableName));\n }\n calls.push(\n new CreatePostgresRlsPolicyCall(\n schemaForTable,\n expected.tableName,\n policyNodeToContractPolicy(expected),\n ),\n );\n } else if (issue.reason === 'not-expected' && allowsDestructive) {\n const actual = issue.actual;\n PostgresPolicySchemaNode.assert(actual);\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n actual.namespaceId,\n );\n calls.push(new DropPostgresRlsPolicyCall(schemaForTable, actual.tableName, actual.name));\n }\n }\n\n return calls;\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n}\n\n/**\n * A diff issue whose node is an RLS policy — the structural half of the one\n * combined tree diff, routed to `planPostgresSchemaDiff` instead of\n * `planIssues`.\n */\nfunction isPolicyDiffIssue(issue: SchemaDiffIssue<SqlSchemaDiffNode>): boolean {\n const node = issue.expected ?? issue.actual;\n return node !== undefined && PostgresPolicySchemaNode.is(node);\n}\n\n/**\n * Drops a `not-expected` issue when it is a whole extra TABLE that some\n * contract space owns, asking the ownership oracle per node.\n *\n * The consultation applies ONLY to table-level extras — a live table this\n * space's contract lacks — identified by asking the issue's own node\n * (`nodeKind === table`), never by counting path segments. `declaresEntity`\n * answers over the whole composition (self included), keyed on the schema-IR\n * entity coordinate so a genuine orphan in one namespace is never conflated\n * with a same-named table a sibling space declares in another, or with a\n * same-named non-table entity (an enum, an RLS policy) a sibling declares in\n * the SAME namespace: a positive answer means another space owns THIS table\n * in THIS namespace (a table this space owned would be in its expected tree,\n * never an extra) — leave it. A negative answer means no space owns it — a\n * genuine orphan to drop. `entityKind` is the literal `'table'` here: this\n * function only ever asks about a node already confirmed to be\n * `PostgresSchemaNodeKind.table` (checked just above), and the diff tree's\n * `nodeKind` vocabulary (`'postgres-table'`) is distinct from the storage\n * `entries` vocabulary `elementCoordinates` walks (`'table'`) — the literal\n * is that storage-entries spelling, not the node kind.\n *\n * The issue path carries the *resolved DDL schema* (e.g. `public`), but a\n * contract space's own declared namespace id can be the unbound sentinel\n * (`__unbound__`) that resolves to that schema — the two spellings would\n * never string-match. `resolveNamespaceIdForDdlSchema` recovers the raw\n * namespace id THIS space's own contract would use for that DDL schema, so\n * a table this space's own unbound namespace declares (and any sibling\n * whose own unbound namespace resolves the same way) is compared on the\n * same coordinate the aggregate's `elementCoordinates` walk yields.\n *\n * A DEEPER extra (an extra column/constraint on a table this space DOES own —\n * only the child drifted, so the table is in the expected tree) is this\n * space's own drift and is always kept for dropping; asking the oracle there\n * would wrongly suppress it, because the owned table answers `true`. Shallower\n * issues (namespace/root) are never ownership-scoped here. No oracle ⇒ every\n * extra is kept (single-space plan).\n */\nfunction retainUnownedExtras(\n issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ownership: SchemaOwnership | undefined,\n contract: Contract<SqlStorage>,\n): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n if (ownership === undefined) return issues;\n return issues.filter((issue) => {\n if (issue.reason !== 'not-expected') return true;\n const node = issueNode(issue);\n if (node === undefined || node.nodeKind !== PostgresSchemaNodeKind.table) return true;\n const ddlSchemaName = issueSchemaName(issue);\n const tableName = issueTableName(issue);\n if (ddlSchemaName === undefined || tableName === undefined) return true;\n const namespaceId = resolveNamespaceIdForDdlSchema(contract, ddlSchemaName);\n return !ownership.declaresEntity({ namespaceId, entityKind: 'table', entityName: tableName });\n });\n}\n\n/**\n * Returns the one namespace node the relational strategy layer probes for\n * live-table existence and reads codec-hook context off — the namespace\n * matching the planner's resolved schema name, or the first namespace when\n * none matches. `undefined` when the tree has no namespaces, so the strategy\n * context uses its empty-schema default.\n *\n * The relational strategies key tables by bare name, so they can only probe one\n * namespace at a time; probing across every namespace at once is future work.\n *\n * Returns the real `PostgresNamespaceSchemaNode` reference rather than a\n * projection: `storageTypePlanCallStrategy` hands this same value to codec\n * `planTypeOperations` hooks as `schema`, and hooks read the Postgres-specific\n * `nativeEnumTypeNames` field off it (via `PostgresNamespaceSchemaNode.is`) to\n * decide whether a native enum type already exists — a projection that only\n * copies `tables` would silently drop that signal. `StrategyContext.schema`'s\n * declared type (`SqlSchemaIR`, shared with SQLite's flat shape) doesn't\n * capture this, so the return is `blindCast` the same way `namespaceSchemaNodes`\n * in the family's relational walk already treats a namespace node as a\n * structurally-`SqlSchemaIR`-shaped value.\n */\nfunction relationalNamespaceNode(\n schema: PostgresDatabaseSchemaNode,\n schemaName: string,\n): SqlSchemaIR | undefined {\n const namespaceNodes = Object.values(schema.namespaces);\n const namespaceNode =\n namespaceNodes.find((node) => node.schemaName === schemaName) ?? namespaceNodes[0];\n if (namespaceNode === undefined) return undefined;\n return blindCast<\n SqlSchemaIR,\n 'PostgresNamespaceSchemaNode carries tables (+ nativeEnumTypeNames, read by codec hooks via PostgresNamespaceSchemaNode.is) structurally compatible with the SqlSchemaIR shape the strategy layer declares'\n >(namespaceNode);\n}\n\n/**\n * Rebuilds the `PostgresRlsPolicy` contract entity `CreatePostgresRlsPolicyCall`\n * carries (its `renderTypeScript`/`createRlsPolicy` paths serialize the whole\n * entity, `namespaceId` included). This reconstructs rather than looking the\n * original up in the contract on purpose: the diff node's `namespaceId` is the\n * *resolved DDL schema* (set when the expected tree was built), which is the\n * value the emitted op must carry; the contract-stored entity holds the raw,\n * pre-resolution coordinate, so a lookup would change the migration output.\n */\nfunction policyNodeToContractPolicy(node: PostgresPolicySchemaNode): PostgresRlsPolicy {\n return new PostgresRlsPolicy({\n name: node.name,\n prefix: node.prefix,\n tableName: node.tableName,\n namespaceId: node.namespaceId,\n operation: node.operation,\n roles: [...node.roles],\n ...ifDefined('using', node.using),\n ...ifDefined('withCheck', node.withCheck),\n permissive: node.permissive,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,qBAAqB,SAAqB,aAA6B;CAC9E,MAAM,YAAY,QAAQ,WAAW;CACrC,IAAI,iBAAiB,SAAS,GAC5B,OAAO,UAAU,cAAc,OAAO;CAExC,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAS,0BAA0B,QAA4C;CAC7E,IAAI,2BAA2B,GAAG,MAAM,GACtC,OAAO,OAAO;CAEhB,OAAO,CAAC,oBAAoB;AAC9B;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,gCAAgC,OAGE;CAChD,MAAM,EAAE,UAAU,WAAW;CAC7B,MAAM,WAAW,IAAI,IAAI,0BAA0B,MAAM,CAAC;CAC1D,MAAM,SAA+C,CAAC;CACtD,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,UAAU,CAAC,CAAC,KAAK;CACnE,KAAK,MAAM,eAAe,cAAc;EACtC,IAAI,gBAAgB,sBAAsB;EAC1C,MAAM,UAAU,qBAAqB,SAAS,SAAS,WAAW;EAClE,IAAI,YAAY,sBAAsB;EACtC,IAAI,SAAS,IAAI,OAAO,GAAG;EAC3B,MAAM,YAAY,IAAI,4BAA4B;GAChD,YAAY;GACZ,QAAQ,CAAC;GACT,qBAAqB,CAAC;EACxB,CAAC;EACD,OAAO,KAAK;GACV,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rB,GAAG,UAAU,SAAS,KAAK,KAAK;EAChC,GAAG,UAAU,aAAa,KAAK,SAAS;EACxC,YAAY,KAAK;CACnB,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-contract-view-C-By7rOB.mjs","names":[],"sources":["../src/core/postgres-contract-serializer.ts","../src/core/postgres-contract-view.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n SqlContractSerializerBase,\n type SqlEntityHydrationFactory,\n} from '@prisma-next/family-sql/ir';\nimport {\n type AuthoringEntityContext,\n type AuthoringEntityTypeFactoryOutput,\n type AuthoringEntityTypeNamespace,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport {\n type AnyEntityKindDescriptor,\n type Namespace,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type { SqlNamespaceInput, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { postgresAuthoringEntityTypes } from './authoring';\nimport { PG_INT_CODEC_ID, PG_TEXT_CODEC_ID } from './codec-ids';\nimport { nativeEnumEntityKind, policyEntityKind, roleEntityKind } from './entity-kinds';\nimport { PostgresSchema } from './postgres-schema';\n\nconst POSTGRES_AUTHORING_CTX: AuthoringEntityContext = {\n family: 'sql',\n target: 'postgres',\n enumInferenceCodecs: { text: PG_TEXT_CODEC_ID, int: PG_INT_CODEC_ID },\n};\n\nfunction isAuthoringEntityTypeFactoryOutput(\n output: unknown,\n): output is AuthoringEntityTypeFactoryOutput<unknown, unknown> {\n return (\n typeof output === 'object' &&\n output !== null &&\n 'factory' in output &&\n typeof output.factory === 'function'\n );\n}\n\n/**\n * Walks a pack's entity-type namespace tree and emits hydration factories\n * keyed by the descriptor's `discriminator`. Used for `storage.types`\n * (codec-triple hydration). Namespace entries hydration dispatches by\n * entries key, not discriminator — handled by `hydrateNamespaceEntities`.\n */\nfunction collectStorageTypesHydrators(\n namespace: AuthoringEntityTypeNamespace,\n): ReadonlyMap<string, SqlEntityHydrationFactory> {\n const registry = new Map<string, SqlEntityHydrationFactory>();\n const walk = (node: AuthoringEntityTypeNamespace): void => {\n for (const value of Object.values(node)) {\n if (isAuthoringEntityTypeDescriptor(value)) {\n if (isAuthoringEntityTypeFactoryOutput(value.output)) {\n const { factory } = value.output;\n registry.set(value.discriminator, (raw) => factory(raw, POSTGRES_AUTHORING_CTX));\n }\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n walk(value);\n }\n }\n };\n walk(namespace);\n return registry;\n}\n\nexport class PostgresContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor(extraPackEntityKinds: readonly AnyEntityKindDescriptor[] = []) {\n const storageTypesHydrators = collectStorageTypesHydrators(postgresAuthoringEntityTypes);\n super(storageTypesHydrators, [\n policyEntityKind,\n roleEntityKind,\n nativeEnumEntityKind,\n ...extraPackEntityKinds,\n ]);\n }\n\n protected override hydrateSqlNamespaceEntry(\n nsId: string,\n raw: Record<string, unknown>,\n ): Namespace | SqlNamespaceInput {\n const hydrated = blindCast<\n SqlNamespaceInput,\n 'raw is always plain JSON, so super.hydrateSqlNamespaceEntry returns SqlNamespaceInput'\n >(super.hydrateSqlNamespaceEntry(nsId, raw));\n const { id, entries } = hydrated;\n\n const allSlotsEmpty = Object.values(entries).every(\n (slot) => slot === undefined || Object.keys(slot).length === 0,\n );\n if (id === UNBOUND_NAMESPACE_ID && allSlotsEmpty) {\n return PostgresSchema.unbound;\n }\n const valueSetSlot = entries['valueSet'];\n const hasValueSets = valueSetSlot !== undefined && Object.keys(valueSetSlot).length > 0;\n return new PostgresSchema({\n id,\n entries: {\n ...entries,\n table: entries['table'] ?? {},\n ...(hasValueSets ? { valueSet: valueSetSlot } : {}),\n },\n });\n }\n\n override serializeContract(contract: Contract<SqlStorage>): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n // Each namespace serializes to its id, its schema-kind tag, and the\n // base's generic entries walk — every enumerable kind on\n // `PostgresSchema.entries`, including `native_enum`.\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n const isUnboundSlot = ns.id === UNBOUND_NAMESPACE_ID;\n namespacesJson[nsId] = {\n id: ns.id,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n entries: this.serializeNamespaceEntries(ns.entries),\n };\n }\n const storageOut: Record<string, unknown> = {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n };\n if (storage.types !== undefined) {\n const typesOut: Record<string, JsonObject> = {};\n for (const [name, entry] of Object.entries(storage.types)) {\n typesOut[name] = this.serializeJsonObject(entry);\n }\n storageOut['types'] = typesOut;\n }\n return blindCast<\n JsonObject,\n 'contract minus storage plus a JSON-shaped storageOut is a JsonObject'\n >({\n ...rest,\n storage: storageOut,\n });\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n buildSqlSchemaQualifiedView,\n type SqlSchemaQualifiedView,\n} from '@prisma-next/sql-contract/contract-view';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { PostgresContractSerializer } from './postgres-contract-serializer';\n\n/**\n * A schema-qualified Postgres contract view: the deserialized contract\n * intersected with a single `namespace` member holding every schema by id. It is\n * substitutable for `Contract` (carries `storage`, `domain`, …) and reaches each\n * schema's entities through `view.namespace.<schema>`:\n *\n * ```ts\n * const view = PostgresContractView.fromJson<Contract>(contractJson);\n * view.namespace.public.table.users // typed table leaf in the public schema\n * view.namespace.auth.table.users // the auth schema's own users table\n * view.namespace.public.entries.policy.X // pack-contributed kind (RLS / #771 path)\n * view.namespace.__unbound__.table.X // default schema, keyed by its raw id\n * view.storage // the full contract is still present\n * ```\n *\n * This mirrors the runtime `db.enums.<ns>` keying exactly (the default schema\n * keeps its literal `__unbound__` id). Schema names are NOT promoted to the\n * contract root, so there is no collision with contract envelope fields — a\n * schema named `storage` is `view.namespace.storage`, while `view.storage`\n * stays the contract's `storage`.\n */\nexport type PostgresContractView<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> =\n SqlSchemaQualifiedView<TContract>;\n\nexport const PostgresContractView = {\n /** Wrap an already-deserialized Postgres contract in a schema-qualified view. */\n from<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n ): PostgresContractView<TContract> {\n return buildSqlSchemaQualifiedView(contract);\n },\n\n /** Deserialize a Postgres contract JSON envelope and wrap it in a view. */\n fromJson<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>(\n json: unknown,\n ): PostgresContractView<TContract> {\n const contract = new PostgresContractSerializer().deserializeContract<TContract>(json);\n return buildSqlSchemaQualifiedView(contract);\n },\n};\n"],"mappings":";;;;;;;;;AAwBA,MAAM,yBAAiD;CACrD,QAAQ;CACR,QAAQ;CACR,qBAAqB;EAAE,MAAM;EAAkB,KAAK;CAAgB;AACtE;AAEA,SAAS,mCACP,QAC8D;CAC9D,OACE,OAAO,WAAW,YAClB,WAAW,QACX,aAAa,UACb,OAAO,OAAO,YAAY;AAE9B;;;;;;;AAQA,SAAS,6BACP,WACgD;CAChD,MAAM,2BAAW,IAAI,IAAuC;CAC5D,MAAM,QAAQ,SAA6C;EACzD,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,GAAG;GACvC,IAAI,gCAAgC,KAAK,GAAG;IAC1C,IAAI,mCAAmC,MAAM,MAAM,GAAG;KACpD,MAAM,EAAE,YAAY,MAAM;KAC1B,SAAS,IAAI,MAAM,gBAAgB,QAAQ,QAAQ,KAAK,sBAAsB,CAAC;IACjF;IACA;GACF;GACA,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,KAAK,KAAK;EAEd;CACF;CACA,KAAK,SAAS;CACd,OAAO;AACT;AAEA,IAAa,6BAAb,cAAgD,0BAAgD;CAC9F,YAAY,uBAA2D,CAAC,GAAG;EACzE,MAAM,wBAAwB,6BAA6B,4BAA4B;EACvF,MAAM,uBAAuB;GAC3B;GACA;GACA;GACA,GAAG;EACL,CAAC;CACH;CA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EjC,OAAO,4BADU,IAAI,2BAA2B,CAAC,CAAC,oBAA+B,IACvC,CAAC;CAC7C;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-database-schema-node-UpzA0Ug5.d.mts","names":[],"sources":["../src/core/schema-ir/postgres-policy-schema-node.ts","../src/core/schema-ir/postgres-table-schema-node.ts","../src/core/schema-ir/postgres-namespace-schema-node.ts","../src/core/schema-ir/postgres-role-schema-node.ts","../src/core/schema-ir/postgres-database-schema-node.ts"],"mappings":";;;;;UAOiB,6BAAA;;WAEN,IAAA;EAFmC;EAAA,SAInC,MAAA;EAK6B;EAAA,SAH7B,SAAA;EAFA;EAAA,SAIA,WAAA;EAAA,SACA,SAAA,EAAW,kBAAkB;EAA7B;EAAA,SAEA,KAAA;EAAA;EAAA,SAEA,KAAA;EAEA;EAAA,SAAA,SAAA;EAEU;EAAA,SAAV,UAAA;AAAA;;;;;;;;;;;;cAcE,wBAAA,SAAiC,eAAA,YAA2B,YAAA;EAAA,SACrD,QAAA;EAAA,SAET,IAAA;EAAA,SACA,MAAA;EAAA,SACA,SAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA,EAAW,kBAAA;EAAA,SACX,KAAA;EAAA,SACQ,KAAA;EAAA,SACA,SAAA;EAAA,SACR,UAAA;cAEG,KAAA,EAAO,6BAAA;EAAA,IAcf,EAAA;EAIJ,QAAA,aAAqB,YAAA;EAIrB,SAAA,CAAU,KAAA,EAAO,YAAA;EAAA,OASV,EAAA,CAAG,IAAA,EAAM,eAAA,GAAkB,IAAA,IAAQ,wBAAA;EAAA,OAInC,MAAA,CAAO,IAAA,EAAM,eAAA,uBAAsC,IAAA,IAAQ,wBAAA;AAAA;;;UCrEnD,4BAAA,SAAqC,eAAe;EAAA,SAC1D,QAAA,YAAoB,wBAAA;AAAA;;;;;;;;;;;;;;;ADMV;AAcrB;;;cCCa,uBAAA,SAAgC,eAAA,YAA2B,YAAA;EAAA,SACpD,QAAA;EAAA,SAET,IAAA;EAAA,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AAA;;;UCrEvC,2BAAA;EAAA,SACN,IAAA;;AHAX;;;WGKW,WAAW;AAAA;;;;;;;;;;;cAaT,sBAAA,SAA+B,eAAA,YAA2B,YAAA;EAAA,SACnD,QAAA;EAAA,SAET,IAAA;EAAA,SACA,WAAA;cAEG,KAAA,EAAO,2BAAA;EAAA,IAOf,EAAA;EAIJ,QAAA,aAAqB,YAAA;EAIrB,SAAA,CAAU,KAAA,EAAO,YAAA;EAAA,OASV,EAAA,CAAG,IAAA,EAAM,eAAA,GAAkB,IAAA,IAAQ,sBAAA;EAAA,OAInC,MAAA,CAAO,IAAA,EAAM,eAAA,WAA0B,IAAA,IAAQ,sBAAA;AAAA;;;UCpDvC,+BAAA;EAAA,SACN,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,2BAAA;EAAA,SACpC,KAAA,WAAgB,sBAAA;EAAA,SAChB,eAAA;EAAA,SACA,SAAA;AAAA;;;;;;;;;;cAYE,0BAAA,SAAmC,eAAA,YAA2B,YAAA;EAAA,SACvD,QAAA;EAAA,SAET,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,2BAAA;EAAA,SACpC,KAAA,WAAgB,sBAAA;EAAA,SAChB,eAAA;EAAA,SACA,SAAA;cAEG,KAAA,EAAO,+BAAA;EAAA,IASf,EAAA;EAIJ,SAAA,CAAU,KAAA,EAAO,YAAA;EAIjB,QAAA,aAAqB,YAAA;EAAA,OAId,EAAA,CAAG,IAAA,EAAM,eAAA,GAAkB,IAAA,IAAQ,0BAAA;EAAA,OAInC,MAAA,CAAO,IAAA,EAAM,eAAA,WAA0B,IAAA,IAAQ,0BAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-schema-9vFZLwGo.d.mts","names":[],"sources":["../src/core/postgres-role.ts","../src/core/postgres-native-enum.ts","../src/core/postgres-schema.ts"],"mappings":";;;;;;;UAGiB,iBAAA;EAAA,SACN,IAAA;;;;;WAKA,WAAW;AAAA;;;AAAA;AAgBtB;;;;;;;;;;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A,SAAe,YAAA;EDpFV;;;;;EC6F1B,SAAA;EDpF2B;;;;;AAEe;EC4F1C,YAAA,CAAa,SAAA;;;AA5Gf;;;;EAsHE,eAAA,CAAgB,IAAA;EAtHsB;;;AAA+B;AAEvE;;;;EAgIE,mBAAA;EA/H2B;;;;;;;EA0I3B,sBAAA,IAA0B,MAAA;EAxIK;;;;;;;EAmJ/B,WAAA,CAAY,SAAA,UAAmB,KAAA,YAAiB,mBAAA;EApJhC;;;;;;;;AACiD;AAGnE;;EAmKE,aAAA,CAAc,QAAA,EAAU,UAAA;AAAA;;;;;;;;;;;;;AAjKiC;AAiB3D;;;;;;cAwKa,qBAAA,SAA8B,cAAA;EAAA,gBACzB,QAAA,EAAU,qBAAA;cAEd,KAAA,GAAQ,mBAAA;EAIX,SAAA;EAIA,YAAA,CAAa,SAAA;EAIb,mBAAA;EAIA,sBAAA,IAA0B,MAAA;EAI1B,WAAA,CAAY,SAAA,UAAmB,KAAA,YAAiB,mBAAA;AAAA;;;;;;;;;;iBAmB3C,gBAAA,CAAiB,EAAA,YAAc,EAAA,IAAM,cAAc;;;;;;;;;;;;;;;iBAkBnD,uBAAA,CAAwB,KAAA,EAAO,iBAAA,GAAoB,cAAc"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-schema-DcG72fcT.mjs","names":[],"sources":["../src/core/postgres-rls-policy.ts","../src/core/postgres-role.ts","../src/core/postgres-validators.ts","../src/core/ast/table-source.ts","../src/core/entity-kinds.ts","../src/core/postgres-schema.ts"],"sourcesContent":["import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport type RlsPolicyOperation = 'select' | 'insert' | 'update' | 'delete' | 'all';\n\nexport interface PostgresRlsPolicyInput {\n /** Full wire name: `<prefix>_<8hex>`. Stored as-is; hashing is not this class's job. */\n readonly name: string;\n /** User-supplied prefix (the part before the `_<8hex>` suffix). */\n readonly prefix: string;\n /** Name of the table this policy attaches to, by name within the same schema. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). Policies are schema-scoped. */\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n /** Sorted role names rendered in `TO <roles>`. Plain strings in this slice. */\n readonly roles: readonly string[];\n /** USING predicate SQL string, if present. */\n readonly using?: string;\n /** WITH CHECK predicate SQL string, if present. */\n readonly withCheck?: string;\n /** `true` = `AS PERMISSIVE`, `false` = `AS RESTRICTIVE`. */\n readonly permissive: boolean;\n}\n\n/**\n * Postgres contract-IR class for a row-level security policy (`CREATE POLICY … ON …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresPolicySchemaNode` for that role.\n *\n * Target-only concept — no SQL-family abstract. Extends `SqlNode` directly.\n * Frozen at construction via `freezeNode(this)`. The `kind: 'policy'`\n * discriminant is enumerable (overrides SqlNode's non-enumerable `'sql'`) so it\n * survives JSON serialization and enables dispatch. The literal matches the\n * entries key (one-string rule: node.kind === entries key === entity kind).\n */\nexport class PostgresRlsPolicy extends SqlNode {\n override readonly kind = 'policy' as const;\n readonly name: string;\n readonly prefix: string;\n readonly tableName: string;\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n declare readonly using?: string;\n declare readonly withCheck?: string;\n readonly permissive: boolean;\n\n constructor(input: PostgresRlsPolicyInput) {\n super();\n this.name = input.name;\n this.prefix = input.prefix;\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n this.operation = input.operation;\n this.roles = Object.freeze([...input.roles]);\n if (input.using !== undefined) this.using = input.using;\n if (input.withCheck !== undefined) this.withCheck = input.withCheck;\n this.permissive = input.permissive;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport interface PostgresRoleInput {\n readonly name: string;\n /**\n * Namespace coordinate. Roles are cluster-scoped; pass `UNBOUND_NAMESPACE_ID`\n * from `@prisma-next/framework-components/ir`.\n */\n readonly namespaceId: string;\n}\n\n/**\n * Postgres contract-IR class for a database role (`CREATE ROLE …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresRoleSchemaNode` for that role.\n *\n * Roles are cluster-scoped, so their namespace coordinate is always\n * `UNBOUND_NAMESPACE_ID`. Target-only concept — no SQL-family abstract.\n * Extends `SqlNode` directly, frozen at construction via `freezeNode(this)`.\n * The `kind: 'role'` discriminant is enumerable so it survives JSON.\n * Matches the entries key (one-string rule).\n */\nexport class PostgresRole extends SqlNode {\n override readonly kind = 'role' as const;\n readonly name: string;\n readonly namespaceId: string;\n\n constructor(input: PostgresRoleInput) {\n super();\n this.name = input.name;\n this.namespaceId = input.namespaceId;\n freezeNode(this);\n }\n}\n","import { type } from 'arktype';\n\nexport const PostgresRoleSchema = type({\n kind: \"'role'\",\n name: 'string',\n namespaceId: 'string',\n});\n\nexport const PostgresRlsPolicySchema = type({\n kind: \"'policy'\",\n name: 'string',\n prefix: 'string',\n tableName: 'string',\n namespaceId: 'string',\n operation: \"'select' | 'insert' | 'update' | 'delete' | 'all'\",\n roles: type.string.array().readonly(),\n 'using?': 'string',\n 'withCheck?': 'string',\n permissive: 'boolean',\n});\n\nexport const PostgresNativeEnumSchema = type({\n kind: \"'postgres-enum'\",\n typeName: 'string',\n members: type.string.array().readonly(),\n 'control?': \"'managed' | 'tolerated' | 'external' | 'observed'\",\n});\n","import {\n type AnyFromSource,\n type AstRewriter,\n TableSource,\n} from '@prisma-next/sql-relational-core/ast';\n\nexport class PostgresTableSource extends TableSource {\n readonly schema: string | undefined;\n\n constructor(options: {\n readonly name: string;\n readonly schema?: string;\n readonly alias?: string;\n }) {\n super(options.name, options.alias);\n this.schema = options.schema;\n this.freeze();\n }\n\n override rewrite(rewriter: AstRewriter): AnyFromSource {\n return rewriter.tableSource ? rewriter.tableSource(this) : this;\n }\n}\n","import type { EntityKindDescriptor } from '@prisma-next/framework-components/ir';\nimport { PostgresNativeEnum, type PostgresNativeEnumInput } from './postgres-native-enum';\nimport { PostgresRlsPolicy, type PostgresRlsPolicyInput } from './postgres-rls-policy';\nimport { PostgresRole, type PostgresRoleInput } from './postgres-role';\nimport {\n PostgresNativeEnumSchema,\n PostgresRlsPolicySchema,\n PostgresRoleSchema,\n} from './postgres-validators';\n\nexport const policyEntityKind: EntityKindDescriptor<PostgresRlsPolicyInput, PostgresRlsPolicy> = {\n kind: 'policy',\n schema: PostgresRlsPolicySchema,\n construct: (input) => new PostgresRlsPolicy(input),\n};\n\nexport const roleEntityKind: EntityKindDescriptor<PostgresRoleInput, PostgresRole> = {\n kind: 'role',\n schema: PostgresRoleSchema,\n construct: (input) => new PostgresRole(input),\n};\n\nexport const nativeEnumEntityKind: EntityKindDescriptor<\n PostgresNativeEnumInput,\n PostgresNativeEnum\n> = {\n kind: 'native_enum',\n schema: PostgresNativeEnumSchema,\n construct: (input) => new PostgresNativeEnum(input),\n};\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n hydrateNamespaceEntities,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { composeSqlEntityKinds } from '@prisma-next/sql-contract/entity-kinds';\nimport {\n SqlNamespaceBase,\n type SqlNamespaceEntries,\n type SqlNamespaceInput,\n type SqlStorage,\n type StorageTable,\n type StorageValueSet,\n} from '@prisma-next/sql-contract/types';\n\nimport { type CfExpr, cfExpr } from '@prisma-next/sql-relational-core/contract-free';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresTableSource } from './ast/table-source';\nimport { PG_TEXT_CODEC_ID } from './codec-ids';\nimport { nativeEnumEntityKind, policyEntityKind, roleEntityKind } from './entity-kinds';\nimport type { PostgresNativeEnum } from './postgres-native-enum';\nimport type { PostgresRlsPolicy } from './postgres-rls-policy';\nimport type { PostgresRole } from './postgres-role';\nimport { escapeLiteral } from './sql-utils';\n\nexport type PostgresContract = Contract<SqlStorage> & { readonly target: 'postgres' };\n\nexport type PostgresNamespaceEntries = SqlNamespaceEntries & {\n readonly policy?: Readonly<Record<string, PostgresRlsPolicy>>;\n readonly role?: Readonly<Record<string, PostgresRole>>;\n readonly native_enum?: Readonly<Record<string, PostgresNativeEnum>>;\n};\n\nexport interface PostgresSchemaInput {\n readonly id: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\n/**\n * Postgres target `Namespace` concretion — a Postgres schema (`CREATE\n * SCHEMA …`). Each Postgres `SqlStorage` carries a\n * `namespaces: Record<NamespaceId, PostgresSchema>` map populated by\n * the Postgres PSL interpreter from `namespace { … }` AST buckets.\n *\n * `entries` holds entity-kind maps (`table`, `valueSet`). Qualifier\n * emission is the rendering seam: DDL / SQL emission asks the namespace\n * for its qualifier (`\"<schema>\"`) or for a qualified table name\n * (`\"<schema>\".\"<table>\"`) and consumes the result polymorphically.\n * The unbound singleton below overrides these methods to elide the\n * prefix entirely — call sites stay polymorphic and never branch on\n * `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class PostgresSchema extends SqlNamespaceBase {\n /**\n * Stable singleton reference for the late-bound slot. Materialised\n * lazily below the singleton subclass declaration so the static\n * initialiser sees the subclass before assigning. Consumers always\n * reach for `PostgresSchema.unbound` (or `PostgresUnboundSchema.instance`\n * — same identity).\n */\n static unbound: PostgresUnboundSchema;\n\n declare readonly kind: 'schema';\n readonly id: string;\n readonly entries: PostgresNamespaceEntries;\n\n constructor(input: PostgresSchemaInput) {\n super();\n this.id = input.id;\n\n const dispatched = hydrateNamespaceEntities(\n input.entries,\n composeSqlEntityKinds([policyEntityKind, roleEntityKind, nativeEnumEntityKind]),\n 'carry',\n );\n\n // Drop an empty valueSet so presence signals non-emptiness.\n const valueSetRaw = dispatched['valueSet'];\n const withPresence =\n valueSetRaw !== undefined && Object.keys(valueSetRaw).length === 0\n ? { ...dispatched, valueSet: undefined }\n : dispatched;\n\n const entriesInput: Record<string, Readonly<Record<string, unknown>> | undefined> = {\n ...withPresence,\n };\n\n this.entries = Object.freeze(\n blindCast<\n PostgresNamespaceEntries,\n 'composeSqlEntityKinds([policyEntityKind, roleEntityKind, nativeEnumEntityKind]) supplies table→StorageTable, valueSet→StorageValueSet, policy→PostgresRlsPolicy, role→PostgresRole, native_enum→PostgresNativeEnum descriptors'\n >(entriesInput),\n );\n Object.defineProperty(this, 'kind', {\n value: 'schema',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n get table(): Readonly<Record<string, StorageTable>> {\n return this.entries.table ?? Object.freeze({});\n }\n\n get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined {\n return this.entries.valueSet;\n }\n\n get policy(): Readonly<Record<string, PostgresRlsPolicy>> {\n return this.entries.policy ?? Object.freeze({});\n }\n\n get role(): Readonly<Record<string, PostgresRole>> {\n return this.entries.role ?? Object.freeze({});\n }\n\n /**\n * The bare schema qualifier as it would appear in a rendered SQL\n * fragment (already quoted). The unbound-schema singleton overrides\n * this to return `''`.\n */\n qualifier(): string {\n return `\"${this.id}\"`;\n }\n\n /**\n * Qualify a table name with the schema prefix\n * (`\"<schema>\".\"<table>\"`). The unbound-schema singleton overrides\n * this to emit just `\"<table>\"` so the resolved DDL is unqualified\n * and `search_path` decides where the object lands at runtime.\n */\n qualifyTable(tableName: string): string {\n return `\"${this.id}\".\"${tableName}\"`;\n }\n\n /**\n * Render a SQL string-literal containing the qualified-name form\n * suitable for `to_regclass(...)` arguments (e.g. `'\"public\".\"user\"'`).\n * The unbound singleton overrides this to elide the schema prefix\n * (`'\"user\"'`) so `search_path` resolves the object at runtime.\n */\n regclassLiteral(name: string): string {\n return `'${escapeLiteral(this.qualifyTable(name))}'`;\n }\n\n /**\n * Render a SQL expression that evaluates to this namespace's schema\n * name at runtime, ready to drop into a `WHERE table_schema = …` /\n * `WHERE n.nspname = …` clause. Named schemas emit a quoted SQL\n * literal (`'public'`); the unbound singleton overrides this to emit\n * `current_schema()` so catalog queries match whichever schema the\n * connection's `search_path` resolved at runtime.\n */\n schemaSqlExpression(): string {\n return `'${escapeLiteral(this.id)}'`;\n }\n\n /**\n * Typed-AST counterpart of {@link schemaSqlExpression}: the expression a\n * builder-built catalog check compares `n.nspname` / `table_schema`\n * against. Named schemas bind the schema name as a text parameter; the\n * unbound singleton overrides this to the opaque `current_schema()`\n * expression so the live connection's `search_path` decides at runtime.\n */\n schemaFilterExpression(): CfExpr {\n return cfExpr.param(this.id, PG_TEXT_CODEC_ID);\n }\n\n /**\n * Typed-AST counterpart of {@link qualifyTable}: the FROM source a\n * builder-built check uses to address a user table in this namespace.\n * Named schemas qualify (`\"schema\".\"table\"`); the unbound singleton\n * overrides this to leave the table unqualified so `search_path`\n * resolves it at runtime.\n */\n tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n schema: this.id,\n ...ifDefined('alias', alias),\n });\n }\n\n /**\n * The bare schema name a DDL planner should target when emitting\n * statements that need to identify this namespace in the live\n * database (e.g. `CREATE TABLE \"<ddlSchemaName>\".\"<table>\" …`,\n * catalog filters, planner conflict lookups). Named schemas resolve\n * to their own id. The `PostgresUnboundSchema` singleton inherits\n * this and returns `UNBOUND_NAMESPACE_ID` — callers that dispatch\n * through `qualifyTableName` route through the polymorphic\n * `PostgresUnboundSchema` overrides and produce unqualified\n * (search-path-resolved) output automatically.\n */\n ddlSchemaName(_storage: SqlStorage): string {\n return this.id;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound Postgres slot whose binding\n * the connection's `search_path` resolves at runtime. Overrides\n * qualifier emission to elide the schema prefix; call sites that consume\n * `qualifier()` / `qualifyTable()` get unqualified output without\n * branching on the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Postgres decides what late-bound means here (the table\n * name, naked — the schema is supplied by the live connection's\n * `search_path`).\n *\n * `ddlSchemaName` is inherited from `PostgresSchema` and returns\n * `UNBOUND_NAMESPACE_ID`. Downstream helpers such as `qualifyTableName`\n * route through the polymorphic factory and produce unqualified output\n * automatically.\n */\nexport class PostgresUnboundSchema extends PostgresSchema {\n static readonly instance: PostgresUnboundSchema = new PostgresUnboundSchema();\n\n constructor(input?: PostgresSchemaInput) {\n super(input ?? { id: UNBOUND_NAMESPACE_ID, entries: { table: {} } });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n\n override schemaSqlExpression(): string {\n return 'current_schema()';\n }\n\n override schemaFilterExpression(): CfExpr {\n return cfExpr.raw('current_schema()', { codecId: PG_TEXT_CODEC_ID, nullable: false });\n }\n\n override tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n ...ifDefined('alias', alias),\n });\n }\n}\n\nPostgresSchema.unbound = PostgresUnboundSchema.instance;\n\n/**\n * Narrow an arbitrary namespace (or `undefined`) to `PostgresSchema`\n * so callers can dispatch to the polymorphic emission methods without\n * branching at the call site. Uses the structural `kind` discriminator\n * (`'schema'`) rather than `instanceof` so the check survives realm /\n * bundle / hot-reload boundaries — matching the rest of the IR's\n * narrowing convention. `PostgresUnboundSchema` passes through because\n * it inherits the same `kind: 'schema'` from `PostgresSchema`.\n */\nexport function isPostgresSchema(ns: unknown): ns is PostgresSchema {\n return (ns as { kind?: unknown } | null | undefined)?.kind === 'schema';\n}\n\n/**\n * Target-supplied `Namespace` factory the Postgres target plumbs\n * through `defineContract({ createNamespace })` and the SQL PSL\n * interpreter. Returns the unbound singleton for the framework\n * sentinel and a fresh `PostgresSchema` for any other coordinate.\n *\n * The factory has no per-call state — every named id deterministically\n * maps to a distinct schema instance — so callers can pass it through\n * by reference and trust the resulting `SqlStorage.namespaces` map to\n * be value-stable for a given input set. Native-enum column type names are\n * schema-qualified earlier, at column construction, via the target's\n * `authoring.qualifyColumnType` hook (`postgresQualifyColumnType`), so this\n * factory just materialises the namespace from already-qualified entries.\n */\nexport function postgresCreateNamespace(input: SqlNamespaceInput): PostgresSchema {\n const schemaInput: PostgresSchemaInput = {\n id: input.id,\n entries: {\n ...input.entries,\n table: input.entries['table'] ?? {},\n },\n };\n if (input.id === UNBOUND_NAMESPACE_ID) {\n return new PostgresUnboundSchema(schemaInput);\n }\n return new PostgresSchema(schemaInput);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAa,oBAAb,cAAuC,QAAQ;CAC7C,OAAyB;CACzB;CACA;CACA;CACA;CACA;CACA;CAGA;CAEA,YAAY,OAA+B;EACzC,MAAM;EACN,KAAK,OAAO,MAAM;EAClB,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,MAAM;EACvB,KAAK,cAAc,MAAM;EACzB,KAAK,YAAY,MAAM;EACvB,KAAK,QAAQ,OAAO,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;EAC3C,IAAI,MAAM,UAAU,KAAA,GAAW,KAAK,QAAQ,MAAM;EAClD,IAAI,MAAM,cAAc,KAAA,GAAW,KAAK,YAAY,MAAM;EAC1D,KAAK,aAAa,MAAM;EACxB,WAAW,IAAI;CACjB;AACF;;;;;;;;;;;;;;;;ACtCA,IAAa,eAAb,cAAkC,QAAQ;CACxC,OAAyB;CACzB;CACA;CAEA,YAAY,OAA0B;EACpC,MAAM;EACN,KAAK,OAAO,MAAM;EAClB,KAAK,cAAc,MAAM;EACzB,WAAW,IAAI;CACjB;AACF;;;AClCA,MAAa,qBAAqB,KAAK;CACrC,MAAM;CACN,MAAM;CACN,aAAa;AACf,CAAC;AAED,MAAa,0BAA0B,KAAK;CAC1C,MAAM;CACN,MAAM;CACN,QAAQ;CACR,WAAW;CACX,aAAa;CACb,WAAW;CACX,OAAO,KAAK,OAAO,MAAM,CAAC,CAAC,SAAS;CACpC,UAAU;CACV,cAAc;CAC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,YAAqB,WAAmB,OAAqC;EAC3E,OAAO,IAAI,oBAAoB;GAC7B,MAAM;GACN,GAAG,UAAU,SAAS,KAAK;EAC7B,CAAC;CACH;AACF;AAEA,eAAe,UAAU,sBAAsB;;;;;;;;;;AAW/C,SAAgB,iBAAiB,IAAmC;CAClE,OAAQ,IAA8C,SAAS;AACjE;;;;;;;;;;;;;;;AAgBA,SAAgB,wBAAwB,OAA0C;CAChF,MAAM,cAAmC;EACvC,IAAI,MAAM;EACV,SAAS;GACP,GAAG,MAAM;GACT,OAAO,MAAM,QAAQ,YAAY,CAAC;EACpC;CACF;CACA,IAAI,MAAM,OAAO,sBACf,OAAO,IAAI,sBAAsB,WAAW;CAE9C,OAAO,IAAI,eAAe,WAAW;AACvC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-table-schema-node-BZWWEo7B.mjs","names":[],"sources":["../src/core/schema-ir/postgres-database-schema-node.ts","../src/core/schema-ir/postgres-namespace-schema-node.ts","../src/core/schema-ir/postgres-policy-schema-node.ts","../src/core/schema-ir/postgres-role-schema-node.ts","../src/core/schema-ir/postgres-table-schema-node.ts"],"sourcesContent":["import type { DiffableNode } from '@prisma-next/framework-components/control';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { assertNode, SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport type { PostgresNamespaceSchemaNode } from './postgres-namespace-schema-node';\nimport type { PostgresRoleSchemaNode } from './postgres-role-schema-node';\nimport { PostgresSchemaNodeKind } from './schema-node-kinds';\n\nexport interface PostgresDatabaseSchemaNodeInput {\n readonly namespaces: Readonly<Record<string, PostgresNamespaceSchemaNode>>;\n readonly roles: readonly PostgresRoleSchemaNode[];\n readonly existingSchemas: readonly string[];\n readonly pgVersion: string;\n}\n\n/**\n * The root of the Postgres schema-diff tree: one node per database.\n *\n * `id` is the fixed sentinel `'database'` — the root has no siblings and\n * the value is never emitted into migration paths. `isEqualTo` is identity\n * (roots always share the `'database'` id). `children()` returns namespace\n * nodes only; roles are held on the root but not yielded (role diffing is a\n * later slice).\n */\nexport class PostgresDatabaseSchemaNode extends SqlSchemaIRNode implements DiffableNode {\n override readonly nodeKind = PostgresSchemaNodeKind.database;\n\n readonly namespaces: Readonly<Record<string, PostgresNamespaceSchemaNode>>;\n readonly roles: readonly PostgresRoleSchemaNode[];\n readonly existingSchemas: readonly string[];\n readonly pgVersion: string;\n\n constructor(input: PostgresDatabaseSchemaNodeInput) {\n super();\n this.namespaces = Object.freeze({ ...input.namespaces });\n this.roles = Object.freeze([...input.roles]);\n this.existingSchemas = Object.freeze([...input.existingSchemas]);\n this.pgVersion = input.pgVersion;\n freezeNode(this);\n }\n\n get id(): string {\n return 'database';\n }\n\n isEqualTo(other: DiffableNode): boolean {\n return this.id === other.id;\n }\n\n children(): readonly DiffableNode[] {\n return Object.values(this.namespaces);\n }\n\n static is(node: SqlSchemaIRNode): node is PostgresDatabaseSchemaNode {\n return node.nodeKind === PostgresSchemaNodeKind.database;\n }\n\n static assert(node: SqlSchemaIRNode): asserts node is PostgresDatabaseSchemaNode {\n assertNode(node, 'PostgresDatabaseSchemaNode', PostgresDatabaseSchemaNode.is);\n }\n}\n","import type { DiffableNode } from '@prisma-next/framework-components/control';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { assertNode, SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport type { PostgresTableSchemaNode } from './postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from './schema-node-kinds';\n\n/** One introspected native Postgres enum type, in `pg_enum.enumsortorder` (declaration) order. */\nexport interface PostgresNativeEnumIntrospection {\n readonly typeName: string;\n readonly values: readonly string[];\n}\n\nexport interface PostgresNamespaceSchemaNodeInput {\n readonly schemaName: string;\n readonly tables: Readonly<Record<string, PostgresTableSchemaNode>>;\n readonly nativeEnumTypeNames: readonly string[];\n readonly nativeEnums?: readonly PostgresNativeEnumIntrospection[];\n}\n\n/**\n * One-per-Postgres-schema diff-tree node. Groups the tables belonging to a\n * single namespace. Per-schema consumers (the relational planner,\n * toSchemaView) read this node's `tables` field structurally via\n * `blindCast`/`SqlSchemaIRNode` — not through a static `SqlSchemaIR`\n * assignment — because `nodeKind` now carries this node's own literal\n * (`postgres-namespace`), distinct from `SqlSchemaIR`'s own (`sql-schema`).\n *\n * `id` is the schema name. `isEqualTo` is identity — two namespace nodes are\n * equal iff their ids (schema names) match. `children()` returns the table\n * nodes. Per-schema metadata is carried on the typed `nativeEnumTypeNames`\n * field, not an annotations bag.\n *\n * `nativeEnums` carries the same enum types with their ordered member\n * values (`{ typeName, values }`), for consumers that need the values\n * (PSL inference, the printer). `nativeEnumTypeNames` stays a plain name\n * list read independently by existing consumers (codec `planTypeOperations`\n * hooks, the infer throw) so none of them need the values to keep working.\n */\nexport class PostgresNamespaceSchemaNode extends SqlSchemaIRNode implements DiffableNode {\n override readonly nodeKind = PostgresSchemaNodeKind.namespace;\n\n readonly schemaName: string;\n readonly tables: Readonly<Record<string, PostgresTableSchemaNode>>;\n readonly nativeEnumTypeNames: readonly string[];\n readonly nativeEnums: readonly PostgresNativeEnumIntrospection[];\n\n constructor(input: PostgresNamespaceSchemaNodeInput) {\n super();\n this.schemaName = input.schemaName;\n this.tables = Object.freeze({ ...input.tables });\n this.nativeEnumTypeNames = Object.freeze([...input.nativeEnumTypeNames]);\n this.nativeEnums = Object.freeze(\n (input.nativeEnums ?? []).map((entry) =>\n Object.freeze({ typeName: entry.typeName, values: Object.freeze([...entry.values]) }),\n ),\n );\n freezeNode(this);\n }\n\n get id(): string {\n return this.schemaName;\n }\n\n isEqualTo(other: DiffableNode): boolean {\n return this.id === other.id;\n }\n\n children(): readonly DiffableNode[] {\n return Object.values(this.tables);\n }\n\n static is(node: SqlSchemaIRNode): node is PostgresNamespaceSchemaNode {\n return node.nodeKind === PostgresSchemaNodeKind.namespace;\n }\n\n static assert(node: SqlSchemaIRNode): asserts node is PostgresNamespaceSchemaNode {\n assertNode(node, 'PostgresNamespaceSchemaNode', PostgresNamespaceSchemaNode.is);\n }\n}\n","import type { DiffableNode } from '@prisma-next/framework-components/control';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { assertNode, SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { RlsPolicyOperation } from '../postgres-rls-policy';\nimport { PostgresSchemaNodeKind } from './schema-node-kinds';\n\nexport interface PostgresPolicySchemaNodeInput {\n /** Full wire name: `<prefix>_<8hex>`. */\n readonly name: string;\n /** User-supplied prefix (the part before the `_<8hex>` suffix). */\n readonly prefix: string;\n /** Name of the table this policy attaches to, by name within the same schema. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). */\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n /** Sorted role names rendered in `TO <roles>`. */\n readonly roles: readonly string[];\n /** USING predicate SQL string, if present. */\n readonly using?: string;\n /** WITH CHECK predicate SQL string, if present. */\n readonly withCheck?: string;\n /** `true` = `AS PERMISSIVE`, `false` = `AS RESTRICTIVE`. */\n readonly permissive: boolean;\n}\n\n/**\n * Schema-diff leaf node for a Postgres row-level security policy.\n *\n * This is a derived, transient node walked by the differ — it is NEVER serialized.\n * Built by project-from-contract and project-from-database from their respective\n * `PostgresRlsPolicy` contract entities / introspected rows.\n *\n * `id` is the wire name (`<prefix>_<sha256(body)[0..8]>`), so name-equality is\n * body-equality. `isEqualTo` compares names only — never byte-compare predicate\n * bodies, because Postgres reprints them.\n */\nexport class PostgresPolicySchemaNode extends SqlSchemaIRNode implements DiffableNode {\n override readonly nodeKind = PostgresSchemaNodeKind.policy;\n\n readonly name: string;\n readonly prefix: string;\n readonly tableName: string;\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n declare readonly using?: string;\n declare readonly withCheck?: string;\n readonly permissive: boolean;\n\n constructor(input: PostgresPolicySchemaNodeInput) {\n super();\n this.name = input.name;\n this.prefix = input.prefix;\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n this.operation = input.operation;\n this.roles = Object.freeze([...input.roles]);\n if (input.using !== undefined) this.using = input.using;\n if (input.withCheck !== undefined) this.withCheck = input.withCheck;\n this.permissive = input.permissive;\n freezeNode(this);\n }\n\n get id(): string {\n return this.name;\n }\n\n children(): readonly DiffableNode[] {\n return [];\n }\n\n isEqualTo(other: DiffableNode): boolean {\n const node = blindCast<\n SqlSchemaIRNode,\n 'every diff-tree node the differ pairs is a SqlSchemaIRNode; the guard rejects non-policy kinds'\n >(other);\n PostgresPolicySchemaNode.assert(node);\n return this.id === node.id;\n }\n\n static is(node: SqlSchemaIRNode): node is PostgresPolicySchemaNode {\n return node.nodeKind === PostgresSchemaNodeKind.policy;\n }\n\n static assert(node: SqlSchemaIRNode | undefined): asserts node is PostgresPolicySchemaNode {\n assertNode(node, 'PostgresPolicySchemaNode', PostgresPolicySchemaNode.is);\n }\n}\n","import type { DiffableNode } from '@prisma-next/framework-components/control';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport { assertNode, SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { PostgresSchemaNodeKind } from './schema-node-kinds';\n\nexport interface PostgresRoleSchemaNodeInput {\n readonly name: string;\n /**\n * Namespace coordinate. Roles are cluster-scoped; callers pass\n * `UNBOUND_NAMESPACE_ID` from `@prisma-next/framework-components/ir`.\n */\n readonly namespaceId: string;\n}\n\n/**\n * Schema-diff leaf node for a Postgres database role.\n *\n * This is a derived, transient node walked by the differ — it is NEVER serialized.\n * Built by project-from-contract and project-from-database from their respective\n * `PostgresRole` contract entities / introspected rows.\n *\n * Roles are cluster-scoped, so `id` is the role name alone. `isEqualTo` compares\n * names — name-equality is role-equality for cluster-scoped objects.\n */\nexport class PostgresRoleSchemaNode extends SqlSchemaIRNode implements DiffableNode {\n override readonly nodeKind = PostgresSchemaNodeKind.role;\n\n readonly name: string;\n readonly namespaceId: string;\n\n constructor(input: PostgresRoleSchemaNodeInput) {\n super();\n this.name = input.name;\n this.namespaceId = input.namespaceId;\n freezeNode(this);\n }\n\n get id(): string {\n return this.name;\n }\n\n children(): readonly DiffableNode[] {\n return [];\n }\n\n isEqualTo(other: DiffableNode): boolean {\n const node = blindCast<\n SqlSchemaIRNode,\n 'every diff-tree node the differ pairs is a SqlSchemaIRNode; the guard rejects non-role kinds'\n >(other);\n PostgresRoleSchemaNode.assert(node);\n return this.id === node.id;\n }\n\n static is(node: SqlSchemaIRNode): node is PostgresRoleSchemaNode {\n return node.nodeKind === PostgresSchemaNodeKind.role;\n }\n\n static assert(node: SqlSchemaIRNode): asserts node is PostgresRoleSchemaNode {\n assertNode(node, 'PostgresRoleSchemaNode', PostgresRoleSchemaNode.is);\n }\n}\n","import type { DiffableNode } from '@prisma-next/framework-components/control';\nimport { freezeNode } from '@prisma-next/framework-components/ir';\nimport {\n assertNode,\n PrimaryKey,\n type SqlAnnotations,\n SqlCheckConstraintIR,\n SqlColumnIR,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlSchemaIRNode,\n type SqlTableIRInput,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport type { PostgresPolicySchemaNode } from './postgres-policy-schema-node';\nimport { PostgresSchemaNodeKind } from './schema-node-kinds';\n\nexport interface PostgresTableSchemaNodeInput extends SqlTableIRInput {\n readonly policies?: readonly PostgresPolicySchemaNode[];\n}\n\n/**\n * Postgres-specific table schema-diff node. Carries all `SqlTableIR` fields\n * plus `policies`, and implements `DiffableNode` so the table instance is\n * directly the diff-tree node — no separate wrapper needed.\n *\n * Extends `SqlSchemaIRNode` directly rather than `SqlTableIR` because\n * `SqlTableIR` calls `freezeNode` in its own constructor, which prevents\n * subclass field initialisation.\n *\n * `id` is the table name. `isEqualTo` is identity — two table nodes are equal\n * iff their ids (names) match; the table's own structural drift is entirely\n * expressed by its children. `children()` returns every column, the primary\n * key (when present), every foreign key, unique, index, and check constraint,\n * plus the policy nodes — one flat list, so a drifted column and a drifted\n * policy are both reported by the same walk. Order is deterministic (object\n * key order for columns, array order for the rest) so two structurally equal\n * tables always produce the same child list.\n */\nexport class PostgresTableSchemaNode extends SqlSchemaIRNode implements DiffableNode {\n override readonly nodeKind = PostgresSchemaNodeKind.table;\n\n readonly name: string;\n readonly columns: Readonly<Record<string, SqlColumnIR>>;\n readonly foreignKeys: ReadonlyArray<SqlForeignKeyIR>;\n readonly uniques: ReadonlyArray<SqlUniqueIR>;\n readonly indexes: ReadonlyArray<SqlIndexIR>;\n declare readonly primaryKey?: PrimaryKey;\n declare readonly annotations?: SqlAnnotations;\n declare readonly checks?: ReadonlyArray<SqlCheckConstraintIR>;\n readonly policies: readonly PostgresPolicySchemaNode[];\n\n constructor(input: PostgresTableSchemaNodeInput) {\n super();\n this.name = input.name;\n this.columns = Object.freeze(\n Object.fromEntries(\n Object.entries(input.columns).map(([key, col]) => [\n key,\n col instanceof SqlColumnIR ? col : new SqlColumnIR(col),\n ]),\n ),\n );\n this.foreignKeys = Object.freeze(\n input.foreignKeys.map((fk) => (fk instanceof SqlForeignKeyIR ? fk : new SqlForeignKeyIR(fk))),\n );\n this.uniques = Object.freeze(\n input.uniques.map((u) => (u instanceof SqlUniqueIR ? u : new SqlUniqueIR(u))),\n );\n this.indexes = Object.freeze(\n input.indexes.map((i) => (i instanceof SqlIndexIR ? i : new SqlIndexIR(i))),\n );\n if (input.primaryKey !== undefined) {\n this.primaryKey =\n input.primaryKey instanceof PrimaryKey\n ? input.primaryKey\n : new PrimaryKey(input.primaryKey);\n }\n if (input.annotations !== undefined) this.annotations = input.annotations;\n if (input.checks !== undefined && input.checks.length > 0) {\n this.checks = Object.freeze(\n input.checks.map((c) =>\n c instanceof SqlCheckConstraintIR ? c : new SqlCheckConstraintIR(c),\n ),\n );\n }\n this.policies = Object.freeze([...(input.policies ?? [])]);\n freezeNode(this);\n }\n\n get id(): string {\n return this.name;\n }\n\n isEqualTo(other: DiffableNode): boolean {\n return this.id === other.id;\n }\n\n children(): readonly DiffableNode[] {\n return [\n ...Object.values(this.columns),\n ...(this.primaryKey ? [this.primaryKey] : []),\n ...this.foreignKeys,\n ...this.uniques,\n ...this.indexes,\n ...(this.checks ?? []),\n ...this.policies,\n ];\n }\n\n static is(node: SqlSchemaIRNode): node is PostgresTableSchemaNode {\n return node.nodeKind === PostgresSchemaNodeKind.table;\n }\n\n static assert(node: SqlSchemaIRNode): asserts node is PostgresTableSchemaNode {\n assertNode(node, 'PostgresTableSchemaNode', PostgresTableSchemaNode.is);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,IAAa,6BAAb,MAAa,mCAAmC,gBAAwC;CACtF,WAA6B,uBAAuB;CAEpD;CACA;CACA;CACA;CAEA,YAAY,OAAwC;EAClD,MAAM;EACN,KAAK,aAAa,OAAO,OAAO,EAAE,GAAG,MAAM,WAAW,CAAC;EACvD,KAAK,QAAQ,OAAO,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;EAC3C,KAAK,kBAAkB,OAAO,OAAO,CAAC,GAAG,MAAM,eAAe,CAAC;EAC/D,KAAK,YAAY,MAAM;EACvB,WAAW,IAAI;CACjB;CAEA,IAAI,KAAa;EACf,OAAO;CACT;CAEA,UAAU,OAA8B;EACtC,OAAO,KAAK,OAAO,MAAM;CAC3B;CAEA,WAAoC;EAClC,OAAO,OAAO,OAAO,KAAK,UAAU;CACtC;CAEA,OAAO,GAAG,MAA2D;EACnE,OAAO,KAAK,aAAa,uBAAuB;CAClD;CAEA,OAAO,OAAO,MAAmE;EAC/E,WAAW,MAAM,8BAA8B,2BAA2B,EAAE;CAC9E;AACF;;;;;;;;;;;;;;;;;;;;;;ACrBA,IAAa,8BAAb,MAAa,oCAAoC,gBAAwC;CACvF,WAA6B,uBAAuB;CAEpD;CACA;CACA;CACA;CAEA,YAAY,OAAyC;EACnD,MAAM;EACN,KAAK,aAAa,MAAM;EACxB,KAAK,SAAS,OAAO,OAAO,EAAE,GAAG,MAAM,OAAO,CAAC;EAC/C,KAAK,sBAAsB,OAAO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