@prisma-next/target-postgres 0.16.0-dev.3 → 0.16.0-dev.5

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 (41) hide show
  1. package/dist/{control-policy-CZKdMztu.mjs → control-policy-S7XBe07W.mjs} +2 -2
  2. package/dist/{control-policy-CZKdMztu.mjs.map → control-policy-S7XBe07W.mjs.map} +1 -1
  3. package/dist/control.mjs +2 -2
  4. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  5. package/dist/{diff-database-schema-C-hnJ5mr.mjs → diff-database-schema-BRxq7l98.mjs} +2 -2
  6. package/dist/{diff-database-schema-C-hnJ5mr.mjs.map → diff-database-schema-BRxq7l98.mjs.map} +1 -1
  7. package/dist/diff-database-schema.mjs +1 -1
  8. package/dist/issue-planner.mjs +1 -1
  9. package/dist/migration.mjs +2 -2
  10. package/dist/{op-factory-call-DuRj7WXX.mjs → op-factory-call-Ci3H6InB.mjs} +1 -6
  11. package/dist/{op-factory-call-DuRj7WXX.mjs.map → op-factory-call-Ci3H6InB.mjs.map} +1 -1
  12. package/dist/op-factory-call-DT7kdjVP.d.mts.map +1 -1
  13. package/dist/op-factory-call.mjs +1 -1
  14. package/dist/{planner-DPGxFcXo.mjs → planner-BpL7uktH.mjs} +7 -7
  15. package/dist/planner-BpL7uktH.mjs.map +1 -0
  16. package/dist/{planner-produced-postgres-migration-C-dwGdb2.d.mts → planner-produced-postgres-migration-8QP8eMph.d.mts} +2 -2
  17. package/dist/planner-produced-postgres-migration-8QP8eMph.d.mts.map +1 -0
  18. package/dist/{planner-produced-postgres-migration-CFDpqWWE.mjs → planner-produced-postgres-migration-D8exrrxA.mjs} +8 -5
  19. package/dist/planner-produced-postgres-migration-D8exrrxA.mjs.map +1 -0
  20. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  21. package/dist/planner-produced-postgres-migration.mjs +1 -1
  22. package/dist/planner.d.mts +7 -1
  23. package/dist/planner.d.mts.map +1 -1
  24. package/dist/planner.mjs +2 -2
  25. package/dist/{postgres-migration-C_OPFhIF.mjs → postgres-migration-Bn3fj1I4.mjs} +2 -2
  26. package/dist/{postgres-migration-C_OPFhIF.mjs.map → postgres-migration-Bn3fj1I4.mjs.map} +1 -1
  27. package/dist/{render-typescript-7yqILcwr.mjs → render-typescript-Ta7_6CGf.mjs} +20 -8
  28. package/dist/render-typescript-Ta7_6CGf.mjs.map +1 -0
  29. package/dist/render-typescript.d.mts +2 -0
  30. package/dist/render-typescript.d.mts.map +1 -1
  31. package/dist/render-typescript.mjs +1 -1
  32. package/package.json +20 -20
  33. package/src/core/migrations/op-factory-call.ts +1 -6
  34. package/src/core/migrations/operations/data-transform.ts +1 -1
  35. package/src/core/migrations/planner-produced-postgres-migration.ts +8 -1
  36. package/src/core/migrations/planner.ts +8 -0
  37. package/src/core/migrations/render-typescript.ts +20 -8
  38. package/dist/planner-DPGxFcXo.mjs.map +0 -1
  39. package/dist/planner-produced-postgres-migration-C-dwGdb2.d.mts.map +0 -1
  40. package/dist/planner-produced-postgres-migration-CFDpqWWE.mjs.map +0 -1
  41. package/dist/render-typescript-7yqILcwr.mjs.map +0 -1
package/dist/control.mjs CHANGED
@@ -2,10 +2,10 @@ import { n as postgresResolveDefault } from "./default-normalizer-B9ZUiyUE.mjs";
2
2
  import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-qubYaxQA.mjs";
3
3
  import { a as postgresDiffSubjectGranularity, i as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-D6LvInCe.mjs";
4
4
  import { i as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-bg32e7I-.mjs";
5
- import { n as diffPostgresSchema, r as contractToPostgresDatabaseSchemaNode } from "./diff-database-schema-C-hnJ5mr.mjs";
5
+ import { n as diffPostgresSchema, r as contractToPostgresDatabaseSchemaNode } from "./diff-database-schema-BRxq7l98.mjs";
6
6
  import { r as renderDefaultLiteral } from "./planner-ddl-builders-BKlmGDJl.mjs";
7
7
  import { n as PostgresContractSerializer } from "./postgres-contract-view-DebHMqGR.mjs";
8
- import { t as createPostgresMigrationPlanner } from "./planner-DPGxFcXo.mjs";
8
+ import { t as createPostgresMigrationPlanner } from "./planner-BpL7uktH.mjs";
9
9
  import { UNBOUND_NAMESPACE_ID, coordinateKey, elementCoordinates } from "@prisma-next/framework-components/ir";
10
10
  import { blindCast } from "@prisma-next/utils/casts";
11
11
  import { buildNativeTypeExpander, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
@@ -1 +1 @@
1
- {"version":3,"file":"data-transform-BOWpliq8.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from './end-contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport async function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check\n ? await invokeAndLower(options.check, contract, adapter, name)\n : null;\n const runPlans = await Promise.all(\n runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name)),\n );\n\n // Raw remnant: the factory lowered the user's `check` plan above before\n // we get a chance to wrap it, so the EXISTS lifting only has text by the\n // time it runs. The fix is to rewrite the factory to defer lowering until\n // after wrapping — so `cfExpr.exists(checkPlan.ast)` can produce the\n // EXISTS query, then lower once at the boundary — not to grow new AST\n // substrate. Out of scope for the slice that introduced this comment.\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params ?? [],\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nasync function invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): Promise<SqlExecuteRequest> {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n return adapter.lowerToExecuteRequest(plan.ast, { contract });\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,eAAsB,cACpB,UACA,MACA,SACA,SAC+D;CAC/D,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QACtB,MAAM,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAC3D;CACJ,MAAM,WAAW,MAAM,QAAQ,IAC7B,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC,CAC/E;CAQA,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK,UAAU,CAAC;CAC1B,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,eAAe,eACb,SACA,UACA,SACA,MAC4B;CAC5B,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,OAAO,QAAQ,sBAAsB,KAAK,KAAK,EAAE,SAAS,CAAC;AAC7D;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
1
+ {"version":3,"file":"data-transform-BOWpliq8.mjs","names":[],"sources":["../src/core/migrations/operations/data-transform.ts"],"sourcesContent":["/**\n * User-facing `dataTransform` factory for the Postgres migration authoring\n * surface. Invoked directly inside a `migration.ts` file via the\n * `PostgresMigration` instance method (`this.dataTransform(...)`), which\n * supplies the control adapter from the migration's injected stack:\n *\n * ```ts\n * import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };\n *\n * class M extends Migration {\n * override get operations() {\n * return [\n * this.dataTransform(endContract, 'backfill emails', {\n * check: () => db.users.select('id').where(({ email }) => email.isNull()).limit(1),\n * run: () => db.users.update({ email: '' }).where(({ email }) => email.isNull()),\n * }),\n * ];\n * }\n * }\n * ```\n *\n * The factory accepts lazy closures (`() => SqlQueryPlan | Buildable`),\n * invokes each one, asserts that its `meta.storageHash` matches the\n * `contract` it was handed (→ `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` on mismatch), and lowers the\n * plan via the supplied control adapter to a serialized `{sql, params}`\n * payload.\n *\n * The factory then lowers the data transform to the unified migration-op\n * shape `{ precheck, execute, postcheck }`. The user's `check` plan is\n * wrapped twice with opposite truth values:\n *\n * - precheck `SELECT EXISTS (<check>) AS ok` asserts there is work to do\n * (precheck is short-circuited by the runner's pre-satisfied-skip path\n * when nothing remains to backfill).\n * - postcheck `SELECT NOT EXISTS (<check>) AS ok` asserts the work is\n * complete after the run steps execute.\n *\n * The `check` plan is therefore expected to be a **rowset query whose\n * presence of any row signals \"work remains\"** — typically `select('id')\n * .where(<violation predicate>).limit(1)`. Scalar/aggregate shapes\n * (`count(*)`, `bool_and(...)`) do not work under this contract: they\n * always return exactly one row, so `EXISTS` is always true and\n * `NOT EXISTS` is always false. (This is the same row-presence contract\n * the pre-unification runner relied on; the wrapping is just lifting it\n * into SQL.)\n *\n * Each `run` plan becomes an execute step. Because the `Step.params`\n * field threads through `driver.query(sql, params)`, the user's bound\n * values flow through the driver's parameter binder rather than being\n * inlined into the SQL text.\n *\n * The free factory remains usable standalone (tests, ad-hoc tooling,\n * non-class contexts) by passing the adapter explicitly as the fourth\n * argument.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport { errorDataTransformContractMismatch } from '@prisma-next/errors/migration';\nimport type {\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresPlanTargetDetails } from '../planner-target-details';\n\ninterface Buildable<R = unknown> {\n build(): SqlQueryPlan<R>;\n}\n\n/**\n * A single-closure producer of a SQL query plan. Shared between\n * `check` and each `run` entry.\n */\nexport type DataTransformClosure = () => SqlQueryPlan | Buildable;\n\nexport interface DataTransformOptions {\n /**\n * Optional opt-in routing identity. Presence opts the transform into\n * invariant-aware routing; absence means it is path-dependent and\n * not referenceable from refs.\n */\n readonly invariantId?: string;\n /**\n * Optional pre-flight query. `undefined` means \"no check\". When\n * supplied, the closure must return a **rowset query** whose\n * presence of any row signals \"violations remain\". Conventional\n * shape: `db.<table>.select('id').where(<violation>).limit(1)`.\n * Scalar/aggregate shapes do not satisfy this contract.\n */\n readonly check?: DataTransformClosure;\n /** One or more mutation queries to execute. */\n readonly run: DataTransformClosure | readonly DataTransformClosure[];\n}\n\nexport async function dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n adapter: SqlControlAdapter<'postgres'>,\n): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n const runClosures: readonly DataTransformClosure[] = Array.isArray(options.run)\n ? options.run\n : [options.run as DataTransformClosure];\n\n const checkPlan = options.check\n ? await invokeAndLower(options.check, contract, adapter, name)\n : null;\n const runPlans = await Promise.all(\n runClosures.map((closure) => invokeAndLower(closure, contract, adapter, name)),\n );\n\n // Raw remnant: the factory lowered the user's `check` plan above before\n // we get a chance to wrap it, so the EXISTS lifting only has text by the\n // time it runs. The fix is to rewrite the factory to defer lowering until\n // after wrapping — so `cfExpr.exists(checkPlan.ast)` can produce the\n // EXISTS query, then lower once at the boundary — not to grow new AST\n // substrate. Out of scope for the slice that introduced this comment.\n const precheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Check ${name} has work to do`,\n sql: `SELECT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n const execute: readonly SqlMigrationPlanOperationStep[] = runPlans.map((plan) => ({\n description: `Run ${name}`,\n sql: plan.sql,\n params: plan.params ?? [],\n }));\n\n const postcheck: readonly SqlMigrationPlanOperationStep[] = checkPlan\n ? [\n {\n description: `Verify ${name} resolved all violations`,\n sql: `SELECT NOT EXISTS (${checkPlan.sql}) AS ok`,\n params: checkPlan.params ?? [],\n },\n ]\n : [];\n\n return {\n id: `data_migration.${name}`,\n label: `Data transform: ${name}`,\n operationClass: 'data',\n ...ifDefined('invariantId', options.invariantId),\n target: { id: 'postgres' },\n precheck,\n execute,\n postcheck,\n };\n}\n\nasync function invokeAndLower(\n closure: DataTransformClosure,\n contract: Contract<SqlStorage>,\n adapter: SqlControlAdapter<'postgres'>,\n name: string,\n): Promise<SqlExecuteRequest> {\n const result = closure();\n const plan = isBuildable(result) ? result.build() : result;\n assertContractMatches(plan, contract, name);\n return adapter.lowerToExecuteRequest(plan.ast, { contract });\n}\n\nfunction isBuildable(value: unknown): value is Buildable {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'build' in value &&\n typeof (value as { build: unknown }).build === 'function'\n );\n}\n\nfunction assertContractMatches(\n plan: SqlQueryPlan,\n contract: Contract<SqlStorage>,\n name: string,\n): void {\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw errorDataTransformContractMismatch({\n dataTransformName: name,\n expected: contract.storage.storageHash,\n actual: plan.meta.storageHash,\n });\n }\n}\n"],"mappings":";;;AAkGA,eAAsB,cACpB,UACA,MACA,SACA,SAC+D;CAC/D,MAAM,cAA+C,MAAM,QAAQ,QAAQ,GAAG,IAC1E,QAAQ,MACR,CAAC,QAAQ,GAA2B;CAExC,MAAM,YAAY,QAAQ,QACtB,MAAM,eAAe,QAAQ,OAAO,UAAU,SAAS,IAAI,IAC3D;CACJ,MAAM,WAAW,MAAM,QAAQ,IAC7B,YAAY,KAAK,YAAY,eAAe,SAAS,UAAU,SAAS,IAAI,CAAC,CAC/E;CAQA,MAAM,WAAqD,YACvD,CACE;EACE,aAAa,SAAS,KAAK;EAC3B,KAAK,kBAAkB,UAAU,IAAI;EACrC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,MAAM,UAAoD,SAAS,KAAK,UAAU;EAChF,aAAa,OAAO;EACpB,KAAK,KAAK;EACV,QAAQ,KAAK,UAAU,CAAC;CAC1B,EAAE;CAEF,MAAM,YAAsD,YACxD,CACE;EACE,aAAa,UAAU,KAAK;EAC5B,KAAK,sBAAsB,UAAU,IAAI;EACzC,QAAQ,UAAU,UAAU,CAAC;CAC/B,CACF,IACA,CAAC;CAEL,OAAO;EACL,IAAI,kBAAkB;EACtB,OAAO,mBAAmB;EAC1B,gBAAgB;EAChB,GAAG,UAAU,eAAe,QAAQ,WAAW;EAC/C,QAAQ,EAAE,IAAI,WAAW;EACzB;EACA;EACA;CACF;AACF;AAEA,eAAe,eACb,SACA,UACA,SACA,MAC4B;CAC5B,MAAM,SAAS,QAAQ;CACvB,MAAM,OAAO,YAAY,MAAM,IAAI,OAAO,MAAM,IAAI;CACpD,sBAAsB,MAAM,UAAU,IAAI;CAC1C,OAAO,QAAQ,sBAAsB,KAAK,KAAK,EAAE,SAAS,CAAC;AAC7D;AAEA,SAAS,YAAY,OAAoC;CACvD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAQ,MAA6B,UAAU;AAEnD;AAEA,SAAS,sBACP,MACA,UACA,MACM;CACN,IAAI,KAAK,KAAK,gBAAgB,SAAS,QAAQ,aAC7C,MAAM,mCAAmC;EACvC,mBAAmB;EACnB,UAAU,SAAS,QAAQ;EAC3B,QAAQ,KAAK,KAAK;CACpB,CAAC;AAEL"}
@@ -3,7 +3,7 @@ import { r as isPostgresSchema } from "./postgres-schema-CewLYHB7.mjs";
3
3
  import { a as postgresDiffSubjectGranularity, n as PostgresNativeEnumSchemaNode, r as PostgresSchemaNodeKind, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-D6LvInCe.mjs";
4
4
  import { i as PostgresDatabaseSchemaNode, n as PostgresPolicySchemaNode, r as PostgresNamespaceSchemaNode, t as PostgresRoleSchemaNode } from "./postgres-role-schema-node-bg32e7I-.mjs";
5
5
  import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-D0wi_P9Q.mjs";
6
- import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-CZKdMztu.mjs";
6
+ import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-S7XBe07W.mjs";
7
7
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
8
8
  import { blindCast } from "@prisma-next/utils/casts";
9
9
  import { buildNativeTypeExpander, contractNamespaceToSchemaIR } from "@prisma-next/family-sql/control";
@@ -368,4 +368,4 @@ function buildPostgresPlanDiff(input) {
368
368
  //#endregion
369
369
  export { diffPostgresSchema as n, contractToPostgresDatabaseSchemaNode as r, buildPostgresPlanDiff as t };
370
370
 
371
- //# sourceMappingURL=diff-database-schema-C-hnJ5mr.mjs.map
371
+ //# sourceMappingURL=diff-database-schema-BRxq7l98.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"diff-database-schema-C-hnJ5mr.mjs","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport type { SchemaNodeRef } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n PrimaryKey,\n RelationalSchemaNodeKind,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\n/** The database root's fixed sentinel id (`PostgresDatabaseSchemaNode#id`). */\nfunction databaseStep(): { readonly nodeKind: string; readonly id: string } {\n return { nodeKind: PostgresSchemaNodeKind.database, id: 'database' };\n}\n\nfunction tableDependsOn(namespaceId: string, tableName: string): SchemaNodeRef {\n return [\n databaseStep(),\n { nodeKind: PostgresSchemaNodeKind.namespace, id: namespaceId },\n { nodeKind: PostgresSchemaNodeKind.table, id: tableName },\n ];\n}\n\nfunction roleDependsOn(role: string): SchemaNodeRef {\n return [databaseStep(), { nodeKind: PostgresSchemaNodeKind.role, id: role }];\n}\n\n/**\n * The chains from a table-child object (foreign key, index, unique, primary\n * key) to each of the own columns it is built on, in the Postgres tree.\n * Dropping a covered column auto-drops the object, so the object's drop must\n * precede the column's; the graph derives that direction from these edges.\n */\nfunction columnDependsOn(\n namespaceId: string,\n tableName: string,\n columns: readonly string[],\n): readonly SchemaNodeRef[] {\n return columns.map((column) => [\n ...tableDependsOn(namespaceId, tableName),\n { nodeKind: RelationalSchemaNodeKind.column, id: `column:${column}` },\n ]);\n}\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n dependsOn: [tableDependsOn(namespaceId, policy.tableName), ...policy.roles.map(roleDependsOn)],\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n\n // Role entries are root-level diff subjects: they hoist to the database\n // root from every slot and never count toward whether a namespace\n // materializes a schema node.\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n\n // The unbound slot resolves its DDL schema to 'public', so it\n // materializes a schema node exactly when it has non-role content — a\n // late-binding contract keeps today's behavior (the slot carries the\n // tables), while a roles-only unbound slot alongside named namespaces\n // contributes only root roles and no node (which would otherwise be a\n // spurious empty 'public' node, clobbering a real bound 'public'\n // namespace's node keyed by the same resolved schema name).\n if (ns.id === UNBOUND_NAMESPACE_ID) {\n const hasNonRoleContent = Object.entries(ns.entries).some(\n ([entriesKey, slot]) => entriesKey !== 'role' && Object.keys(slot).length > 0,\n );\n if (!hasNonRoleContent) continue;\n }\n\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n // The family conversion stamps `referencedSchema` only for bound FK\n // targets; an absent value means the FK targets the unbound namespace.\n // Postgres restores its own coordinate for that slot (the unbound\n // singleton's id) so the raw coordinate keeps qualifying REFERENCES\n // clauses, and resolves the real live DDL schema — introspected FKs\n // already carry the live schema, so this is what lets an expected FK\n // pair (by diff-node id) with its introspected counterpart.\n const foreignKeys = sqlTable.foreignKeys.map((fk) => {\n const resolvedReferencedNamespace = resolveDdlSchemaForNamespaceStorage(\n contract.storage,\n fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n );\n return new SqlForeignKeyIR({\n columns: fk.columns,\n referencedTable: fk.referencedTable,\n referencedColumns: fk.referencedColumns,\n referencedSchema: fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n ...ifDefined('annotations', fk.annotations),\n resolvedReferencedNamespace,\n dependsOn: [\n tableDependsOn(resolvedReferencedNamespace, fk.referencedTable),\n ...columnDependsOn(ddlSchema, tableName, fk.columns),\n ],\n });\n });\n // The family stamped these children's own-column `dependsOn` with the\n // flat (single-schema) chain; the Postgres tree nests them under a\n // namespace, so re-stamp with the multi-schema chain that matches this\n // tree's paths. Every other field is carried through unchanged.\n const uniques = sqlTable.uniques.map(\n (u) =>\n new SqlUniqueIR({\n columns: u.columns,\n ...ifDefined('name', u.name),\n ...ifDefined('annotations', u.annotations),\n dependsOn: columnDependsOn(ddlSchema, tableName, u.columns),\n }),\n );\n const indexes = sqlTable.indexes.map(\n (i) =>\n new SqlIndexIR({\n columns: i.columns,\n unique: i.unique,\n ...ifDefined('name', i.name),\n ...ifDefined('type', i.type),\n ...ifDefined('options', i.options),\n ...ifDefined('annotations', i.annotations),\n dependsOn: columnDependsOn(ddlSchema, tableName, i.columns),\n }),\n );\n const primaryKey =\n sqlTable.primaryKey !== undefined\n ? new PrimaryKey({\n columns: sqlTable.primaryKey.columns,\n ...ifDefined('name', sqlTable.primaryKey.name),\n dependsOn: columnDependsOn(ddlSchema, tableName, sqlTable.primaryKey.columns),\n })\n : undefined;\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys,\n uniques,\n indexes,\n ...ifDefined('primaryKey', primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n // Marker-driven, never derived from the policy set: the `rls` entry\n // is the single authored source of enablement.\n rlsEnabled: Object.hasOwn(ns.rls, tableName),\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n if (!Object.hasOwn(ns.rls, tableName)) {\n const policyPrefix = tablePolicies[0]?.prefix ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyPrefix}\" targets table \"${tableName}\" in namespace \"${ddlSchema}\", which is not RLS-controlled. Mark the model with @@rls (entries.rls[\"${tableName}\"]) or remove the policy.`,\n );\n }\n }\n\n const nativeEnums = Object.values(ns.entries.native_enum ?? {}).map(\n (entity) =>\n new PostgresNativeEnumSchemaNode({\n typeName: entity.typeName,\n namespaceId: ddlSchema,\n members: entity.members,\n ...ifDefined('control', entity.control),\n }),\n );\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnums,\n });\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';\nimport { buildNativeTypeExpander } from '@prisma-next/family-sql/control';\nimport { classifyDiffSubjectGranularity } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas, issueOutcome } 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 { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresResolveDefault } from '../default-normalizer';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport {\n postgresDiffSubjectGranularity,\n type SqlSchemaDiffNode,\n} from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\nimport { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';\n\n/**\n * Whether a diff issue's subject node is cluster-scoped — it carries its own\n * `namespaceId` field (only role and policy diff nodes do) and that\n * coordinate is the unbound sentinel, meaning the node is not owned by any\n * schema/namespace. A role node is always cluster-scoped (roles are\n * cluster-level objects); a policy node's `namespaceId` is always its\n * table's resolved DDL schema, never the sentinel. Namespace-ownership\n * scoping (which compares `issue.path[1]` against the set of DDL schemas\n * the contract owns) makes no sense for a cluster-scoped subject — its path\n * segment at that index is the object's own name, not a schema name — so\n * such an issue bypasses that scoping entirely.\n */\nfunction isClusterScopedIssue(issue: SchemaDiffIssue): boolean {\n const node = issue.expected ?? issue.actual;\n return node !== undefined && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;\n}\n\nfunction nodeNamespaceId(node: DiffableNode): string | undefined {\n if (!Object.hasOwn(node, 'namespaceId')) return undefined;\n return blindCast<\n { namespaceId: string },\n 'presence of an own namespaceId field was just checked via Object.hasOwn'\n >(node).namespaceId;\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n/**\n * Drops contract namespaces that declare no tables from the verdict-diff\n * expected tree and the relational owned-schema set. The legacy relational\n * walk skipped a table-less namespace (e.g. an enums-only schema) before\n * pairing, so neither its DDL schema's absence nor that schema's live\n * relational contents ever reached the verdict — the pruned tree\n * reproduces that. The prune loses no expected policies: policies attach\n * to tables, so a table-less namespace carries none (the projection\n * throws on a policy referencing an absent table). Live policies in a\n * pruned schema remain governed via the full owned set (see\n * {@link diffPostgresSchema}).\n */\nfunction pruneTableLessNamespaces(\n expected: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces = Object.fromEntries(\n Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),\n );\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...expected.roles],\n existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),\n pgVersion: expected.pgVersion,\n });\n}\n\n/**\n * Resolves a verdict-diff issue's subject's declared control policy directly\n * from the contract, by delegating to the same node-typed resolver\n * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to\n * gate DDL calls. `undefined` when the issue resolves to no contract subject.\n *\n * A role issue resolves through that same resolver to `external`\n * unconditionally (see its role branch), regardless of the contract's own\n * default policy: a role is referenced by the contract but not owned, and\n * `external`'s existing semantics — a missing declared subject still fails,\n * every extra is suppressed — are exactly the wanted asymmetric grading for\n * a cluster object the framework does not own.\n */\nfunction resolveControlPolicy(\n issue: SchemaDiffIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicy | undefined {\n const nodeIssue = blindCast<\n SchemaDiffIssue<SqlSchemaDiffNode>,\n 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'\n >(issue);\n return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)\n ?.explicitNodeControlPolicy;\n}\n\n/**\n * The Postgres full-tree node diff for the family verify verdict: derive\n * the expected tree (resolved leaf values, expander threaded, FK schemas\n * resolved, table-less namespaces pruned), run the generic\n * differ over the trees as derived, and scope out `not-expected` findings under namespaces the\n * contract does not own. Ownership scoping bypasses cluster-scoped subjects\n * (roles today), mirroring the legacy decomposition: relational extras check\n * the PRUNED owned set (the legacy\n * per-namespace walk never visited a table-less namespace, so its live\n * relational contents are invisible), while `structural` extras (RLS\n * policies) check the FULL owned set (the legacy policy diff governed\n * every contract schema regardless of tables — RLS governance does not\n * shrink because a namespace declares no tables). The codec `verifyType`\n * hooks run once per contract namespace with tables against that\n * namespace's paired actual node (the hooks read namespace-scoped state\n * such as `nativeEnums`).\n */\nexport function diffPostgresSchema(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): SqlSchemaDiffResult {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresSchema is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.schema);\n const actual = input.schema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n });\n const expected = pruneTableLessNamespaces(fullExpected);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = diffSchemas(expected, actual).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n const namespacePairs = Object.values(expected.namespaces).map((ns) => ({\n actual: actual.namespaces[ns.schemaName],\n }));\n return {\n issues,\n resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),\n namespacePairs,\n };\n}\n\n/**\n * Adds an empty namespace node to the actual tree for every expected namespace\n * absent from it. The relational plan diff pairs on namespace: a contract\n * namespace whose live schema does not exist yet must surface each of its\n * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace\n * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`\n * with no tables). Padding makes the namespaces pair, so only table/column/\n * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized\n * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the\n * tree diff — matching the retired per-namespace-paired relational walk, which\n * paired a missing schema against an empty namespace node.\n */\nfunction padActualNamespaces(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };\n let padded = false;\n for (const schemaName of Object.keys(expected.namespaces)) {\n if (namespaces[schemaName] === undefined) {\n namespaces[schemaName] = new PostgresNamespaceSchemaNode({\n schemaName,\n tables: {},\n });\n padded = true;\n }\n }\n if (!padded) return actual;\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\nexport interface PostgresPlanDiff {\n /** The desired (\"end\") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */\n readonly expected: PostgresDatabaseSchemaNode;\n /** The live (\"start\") tree, padded with empty namespaces so a missing schema's tables pair. */\n readonly actual: PostgresDatabaseSchemaNode;\n /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */\n readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n}\n\n/**\n * The Postgres planner's diff input: the SAME tree-building\n * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,\n * table-less namespaces pruned, cluster-scope-aware ownership filter) plus\n * actual namespace padding (so a missing\n * schema's tables surface as `not-found` instead of a swallowed namespace\n * `not-found`). One differ drives both verify and plan; this is the\n * plan-side derivation. The single issue list covers tables / columns /\n * constraints / indexes / defaults AND policies — the caller splits it\n * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in\n * `CREATE SCHEMA` separately.\n */\nexport function buildPostgresPlanDiff(input: {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): PostgresPlanDiff {\n const postgresContract = blindCast<\n PostgresContract,\n 'buildPostgresPlanDiff is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const actual = input.actualSchema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const projectionOptions = {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n };\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);\n const expected = pruneTableLessNamespaces(fullExpected);\n const paddedActual = padActualNamespaces(expected, actual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, paddedActual)).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n return { expected, actual: paddedActual, issues };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAS,eAAmE;CAC1E,OAAO;EAAE,UAAU,uBAAuB;EAAU,IAAI;CAAW;AACrE;AAEA,SAAS,eAAe,aAAqB,WAAkC;CAC7E,OAAO;EACL,aAAa;EACb;GAAE,UAAU,uBAAuB;GAAW,IAAI;EAAY;EAC9D;GAAE,UAAU,uBAAuB;GAAO,IAAI;EAAU;CAC1D;AACF;AAEA,SAAS,cAAc,MAA6B;CAClD,OAAO,CAAC,aAAa,GAAG;EAAE,UAAU,uBAAuB;EAAM,IAAI;CAAK,CAAC;AAC7E;;;;;;;AAQA,SAAS,gBACP,aACA,WACA,SAC0B;CAC1B,OAAO,QAAQ,KAAK,WAAW,CAC7B,GAAG,eAAe,aAAa,SAAS,GACxC;EAAE,UAAU,yBAAyB;EAAQ,IAAI,UAAU;CAAS,CACtE,CAAC;AACH;AAEA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG,UAAU,SAAS,OAAO,KAAK;EAClC,GAAG,UAAU,aAAa,OAAO,SAAS;EAC1C,YAAY,OAAO;EACnB,WAAW,CAAC,eAAe,a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BAAkB,iBAAiB,QAAQ;CACjD,MAAM,kBAAkB,iBAAiB,YAAY;CAarD,OAAO;EAAE;EAAU,QAAQ;EAAc,QAZ1B,UAGb,YAAY,UAAU,YAAY,CAAC,CAAC,CAAC,QAAQ,UAAU;GACvD,IAAI,aAAa,KAAK,MAAM,gBAAgB,OAAO;GACnD,IAAI,qBAAqB,KAAK,GAAG,OAAO;GACxC,MAAM,cAAc,+BAA+B,OAAO,8BAA8B;GACxF,MAAM,mBAAmB,MAAM,KAAK;GACpC,IAAI,qBAAqB,KAAA,GAAW,OAAO;GAE3C,QADc,gBAAgB,eAAe,kBAAkB,gBAAA,CAClD,IAAI,gBAAgB;EACnC,CAC8C;CAAE;AAClD"}
1
+ {"version":3,"file":"diff-database-schema-BRxq7l98.mjs","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport type { SchemaNodeRef } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n PrimaryKey,\n RelationalSchemaNodeKind,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\n/** The database root's fixed sentinel id (`PostgresDatabaseSchemaNode#id`). */\nfunction databaseStep(): { readonly nodeKind: string; readonly id: string } {\n return { nodeKind: PostgresSchemaNodeKind.database, id: 'database' };\n}\n\nfunction tableDependsOn(namespaceId: string, tableName: string): SchemaNodeRef {\n return [\n databaseStep(),\n { nodeKind: PostgresSchemaNodeKind.namespace, id: namespaceId },\n { nodeKind: PostgresSchemaNodeKind.table, id: tableName },\n ];\n}\n\nfunction roleDependsOn(role: string): SchemaNodeRef {\n return [databaseStep(), { nodeKind: PostgresSchemaNodeKind.role, id: role }];\n}\n\n/**\n * The chains from a table-child object (foreign key, index, unique, primary\n * key) to each of the own columns it is built on, in the Postgres tree.\n * Dropping a covered column auto-drops the object, so the object's drop must\n * precede the column's; the graph derives that direction from these edges.\n */\nfunction columnDependsOn(\n namespaceId: string,\n tableName: string,\n columns: readonly string[],\n): readonly SchemaNodeRef[] {\n return columns.map((column) => [\n ...tableDependsOn(namespaceId, tableName),\n { nodeKind: RelationalSchemaNodeKind.column, id: `column:${column}` },\n ]);\n}\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n dependsOn: [tableDependsOn(namespaceId, policy.tableName), ...policy.roles.map(roleDependsOn)],\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n\n // Role entries are root-level diff subjects: they hoist to the database\n // root from every slot and never count toward whether a namespace\n // materializes a schema node.\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n\n // The unbound slot resolves its DDL schema to 'public', so it\n // materializes a schema node exactly when it has non-role content — a\n // late-binding contract keeps today's behavior (the slot carries the\n // tables), while a roles-only unbound slot alongside named namespaces\n // contributes only root roles and no node (which would otherwise be a\n // spurious empty 'public' node, clobbering a real bound 'public'\n // namespace's node keyed by the same resolved schema name).\n if (ns.id === UNBOUND_NAMESPACE_ID) {\n const hasNonRoleContent = Object.entries(ns.entries).some(\n ([entriesKey, slot]) => entriesKey !== 'role' && Object.keys(slot).length > 0,\n );\n if (!hasNonRoleContent) continue;\n }\n\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n // The family conversion stamps `referencedSchema` only for bound FK\n // targets; an absent value means the FK targets the unbound namespace.\n // Postgres restores its own coordinate for that slot (the unbound\n // singleton's id) so the raw coordinate keeps qualifying REFERENCES\n // clauses, and resolves the real live DDL schema — introspected FKs\n // already carry the live schema, so this is what lets an expected FK\n // pair (by diff-node id) with its introspected counterpart.\n const foreignKeys = sqlTable.foreignKeys.map((fk) => {\n const resolvedReferencedNamespace = resolveDdlSchemaForNamespaceStorage(\n contract.storage,\n fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n );\n return new SqlForeignKeyIR({\n columns: fk.columns,\n referencedTable: fk.referencedTable,\n referencedColumns: fk.referencedColumns,\n referencedSchema: fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n ...ifDefined('annotations', fk.annotations),\n resolvedReferencedNamespace,\n dependsOn: [\n tableDependsOn(resolvedReferencedNamespace, fk.referencedTable),\n ...columnDependsOn(ddlSchema, tableName, fk.columns),\n ],\n });\n });\n // The family stamped these children's own-column `dependsOn` with the\n // flat (single-schema) chain; the Postgres tree nests them under a\n // namespace, so re-stamp with the multi-schema chain that matches this\n // tree's paths. Every other field is carried through unchanged.\n const uniques = sqlTable.uniques.map(\n (u) =>\n new SqlUniqueIR({\n columns: u.columns,\n ...ifDefined('name', u.name),\n ...ifDefined('annotations', u.annotations),\n dependsOn: columnDependsOn(ddlSchema, tableName, u.columns),\n }),\n );\n const indexes = sqlTable.indexes.map(\n (i) =>\n new SqlIndexIR({\n columns: i.columns,\n unique: i.unique,\n ...ifDefined('name', i.name),\n ...ifDefined('type', i.type),\n ...ifDefined('options', i.options),\n ...ifDefined('annotations', i.annotations),\n dependsOn: columnDependsOn(ddlSchema, tableName, i.columns),\n }),\n );\n const primaryKey =\n sqlTable.primaryKey !== undefined\n ? new PrimaryKey({\n columns: sqlTable.primaryKey.columns,\n ...ifDefined('name', sqlTable.primaryKey.name),\n dependsOn: columnDependsOn(ddlSchema, tableName, sqlTable.primaryKey.columns),\n })\n : undefined;\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys,\n uniques,\n indexes,\n ...ifDefined('primaryKey', primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n // Marker-driven, never derived from the policy set: the `rls` entry\n // is the single authored source of enablement.\n rlsEnabled: Object.hasOwn(ns.rls, tableName),\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n if (!Object.hasOwn(ns.rls, tableName)) {\n const policyPrefix = tablePolicies[0]?.prefix ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyPrefix}\" targets table \"${tableName}\" in namespace \"${ddlSchema}\", which is not RLS-controlled. Mark the model with @@rls (entries.rls[\"${tableName}\"]) or remove the policy.`,\n );\n }\n }\n\n const nativeEnums = Object.values(ns.entries.native_enum ?? {}).map(\n (entity) =>\n new PostgresNativeEnumSchemaNode({\n typeName: entity.typeName,\n namespaceId: ddlSchema,\n members: entity.members,\n ...ifDefined('control', entity.control),\n }),\n );\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnums,\n });\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';\nimport { buildNativeTypeExpander } from '@prisma-next/family-sql/control';\nimport { classifyDiffSubjectGranularity } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas, issueOutcome } 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 { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresResolveDefault } from '../default-normalizer';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport {\n postgresDiffSubjectGranularity,\n type SqlSchemaDiffNode,\n} from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\nimport { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';\n\n/**\n * Whether a diff issue's subject node is cluster-scoped — it carries its own\n * `namespaceId` field (only role and policy diff nodes do) and that\n * coordinate is the unbound sentinel, meaning the node is not owned by any\n * schema/namespace. A role node is always cluster-scoped (roles are\n * cluster-level objects); a policy node's `namespaceId` is always its\n * table's resolved DDL schema, never the sentinel. Namespace-ownership\n * scoping (which compares `issue.path[1]` against the set of DDL schemas\n * the contract owns) makes no sense for a cluster-scoped subject — its path\n * segment at that index is the object's own name, not a schema name — so\n * such an issue bypasses that scoping entirely.\n */\nfunction isClusterScopedIssue(issue: SchemaDiffIssue): boolean {\n const node = issue.expected ?? issue.actual;\n return node !== undefined && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;\n}\n\nfunction nodeNamespaceId(node: DiffableNode): string | undefined {\n if (!Object.hasOwn(node, 'namespaceId')) return undefined;\n return blindCast<\n { namespaceId: string },\n 'presence of an own namespaceId field was just checked via Object.hasOwn'\n >(node).namespaceId;\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n/**\n * Drops contract namespaces that declare no tables from the verdict-diff\n * expected tree and the relational owned-schema set. The legacy relational\n * walk skipped a table-less namespace (e.g. an enums-only schema) before\n * pairing, so neither its DDL schema's absence nor that schema's live\n * relational contents ever reached the verdict — the pruned tree\n * reproduces that. The prune loses no expected policies: policies attach\n * to tables, so a table-less namespace carries none (the projection\n * throws on a policy referencing an absent table). Live policies in a\n * pruned schema remain governed via the full owned set (see\n * {@link diffPostgresSchema}).\n */\nfunction pruneTableLessNamespaces(\n expected: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces = Object.fromEntries(\n Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),\n );\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...expected.roles],\n existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),\n pgVersion: expected.pgVersion,\n });\n}\n\n/**\n * Resolves a verdict-diff issue's subject's declared control policy directly\n * from the contract, by delegating to the same node-typed resolver\n * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to\n * gate DDL calls. `undefined` when the issue resolves to no contract subject.\n *\n * A role issue resolves through that same resolver to `external`\n * unconditionally (see its role branch), regardless of the contract's own\n * default policy: a role is referenced by the contract but not owned, and\n * `external`'s existing semantics — a missing declared subject still fails,\n * every extra is suppressed — are exactly the wanted asymmetric grading for\n * a cluster object the framework does not own.\n */\nfunction resolveControlPolicy(\n issue: SchemaDiffIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicy | undefined {\n const nodeIssue = blindCast<\n SchemaDiffIssue<SqlSchemaDiffNode>,\n 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'\n >(issue);\n return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)\n ?.explicitNodeControlPolicy;\n}\n\n/**\n * The Postgres full-tree node diff for the family verify verdict: derive\n * the expected tree (resolved leaf values, expander threaded, FK schemas\n * resolved, table-less namespaces pruned), run the generic\n * differ over the trees as derived, and scope out `not-expected` findings under namespaces the\n * contract does not own. Ownership scoping bypasses cluster-scoped subjects\n * (roles today), mirroring the legacy decomposition: relational extras check\n * the PRUNED owned set (the legacy\n * per-namespace walk never visited a table-less namespace, so its live\n * relational contents are invisible), while `structural` extras (RLS\n * policies) check the FULL owned set (the legacy policy diff governed\n * every contract schema regardless of tables — RLS governance does not\n * shrink because a namespace declares no tables). The codec `verifyType`\n * hooks run once per contract namespace with tables against that\n * namespace's paired actual node (the hooks read namespace-scoped state\n * such as `nativeEnums`).\n */\nexport function diffPostgresSchema(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): SqlSchemaDiffResult {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresSchema is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.schema);\n const actual = input.schema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n });\n const expected = pruneTableLessNamespaces(fullExpected);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = diffSchemas(expected, actual).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n const namespacePairs = Object.values(expected.namespaces).map((ns) => ({\n actual: actual.namespaces[ns.schemaName],\n }));\n return {\n issues,\n resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),\n namespacePairs,\n };\n}\n\n/**\n * Adds an empty namespace node to the actual tree for every expected namespace\n * absent from it. The relational plan diff pairs on namespace: a contract\n * namespace whose live schema does not exist yet must surface each of its\n * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace\n * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`\n * with no tables). Padding makes the namespaces pair, so only table/column/\n * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized\n * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the\n * tree diff — matching the retired per-namespace-paired relational walk, which\n * paired a missing schema against an empty namespace node.\n */\nfunction padActualNamespaces(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };\n let padded = false;\n for (const schemaName of Object.keys(expected.namespaces)) {\n if (namespaces[schemaName] === undefined) {\n namespaces[schemaName] = new PostgresNamespaceSchemaNode({\n schemaName,\n tables: {},\n });\n padded = true;\n }\n }\n if (!padded) return actual;\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\nexport interface PostgresPlanDiff {\n /** The desired (\"end\") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */\n readonly expected: PostgresDatabaseSchemaNode;\n /** The live (\"start\") tree, padded with empty namespaces so a missing schema's tables pair. */\n readonly actual: PostgresDatabaseSchemaNode;\n /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */\n readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n}\n\n/**\n * The Postgres planner's diff input: the SAME tree-building\n * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,\n * table-less namespaces pruned, cluster-scope-aware ownership filter) plus\n * actual namespace padding (so a missing\n * schema's tables surface as `not-found` instead of a swallowed namespace\n * `not-found`). One differ drives both verify and plan; this is the\n * plan-side derivation. The single issue list covers tables / columns /\n * constraints / indexes / defaults AND policies — the caller splits it\n * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in\n * `CREATE SCHEMA` separately.\n */\nexport function buildPostgresPlanDiff(input: {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): PostgresPlanDiff {\n const postgresContract = blindCast<\n PostgresContract,\n 'buildPostgresPlanDiff is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const actual = input.actualSchema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const projectionOptions = {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n };\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);\n const expected = pruneTableLessNamespaces(fullExpected);\n const paddedActual = padActualNamespaces(expected, actual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, paddedActual)).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n return { expected, actual: paddedActual, issues };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAS,eAAmE;CAC1E,OAAO;EAAE,UAAU,uBAAuB;EAAU,IAAI;CAAW;AACrE;AAEA,SAAS,eAAe,aAAqB,WAAkC;CAC7E,OAAO;EACL,aAAa;EACb;GAAE,UAAU,uBAAuB;GAAW,IAAI;EAAY;EAC9D;GAAE,UAAU,uBAAuB;GAAO,IAAI;EAAU;CAC1D;AACF;AAEA,SAAS,cAAc,MAA6B;CAClD,OAAO,CAAC,aAAa,GAAG;EAAE,UAAU,uBAAuB;EAAM,IAAI;CAAK,CAAC;AAC7E;;;;;;;AAQA,SAAS,gBACP,aACA,WACA,SAC0B;CAC1B,OAAO,QAAQ,KAAK,WAAW,CAC7B,GAAG,eAAe,aAAa,SAAS,GACxC;EAAE,UAAU,yBAAyB;EAAQ,IAAI,UAAU;CAAS,CACtE,CAAC;AACH;AAEA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG,UAAU,SAAS,OAAO,KAAK;EAClC,GAAG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AW,yBAAyB,YAAY;CACtD,MAAM,eAAe,oBAAoB,UAAU,MAAM;CACzD,MAAM,kBAAkB,iBAAiB,QAAQ;CACjD,MAAM,kBAAkB,iBAAiB,YAAY;CAarD,OAAO;EAAE;EAAU,QAAQ;EAAc,QAZ1B,UAGb,YAAY,UAAU,YAAY,CAAC,CAAC,CAAC,QAAQ,UAAU;GACvD,IAAI,aAAa,KAAK,MAAM,gBAAgB,OAAO;GACnD,IAAI,qBAAqB,KAAK,GAAG,OAAO;GACxC,MAAM,cAAc,+BAA+B,OAAO,8BAA8B;GACxF,MAAM,mBAAmB,MAAM,KAAK;GACpC,IAAI,qBAAqB,KAAA,GAAW,OAAO;GAE3C,QADc,gBAAgB,eAAe,kBAAkB,gBAAA,CAClD,IAAI,gBAAgB;EACnC,CAC8C;CAAE;AAClD"}
@@ -1,2 +1,2 @@
1
- import { t as buildPostgresPlanDiff } from "./diff-database-schema-C-hnJ5mr.mjs";
1
+ import { t as buildPostgresPlanDiff } from "./diff-database-schema-BRxq7l98.mjs";
2
2
  export { buildPostgresPlanDiff };
@@ -1,2 +1,2 @@
1
- import { l as planIssues, o as coalesceSubtreeIssues } from "./control-policy-CZKdMztu.mjs";
1
+ import { l as planIssues, o as coalesceSubtreeIssues } from "./control-policy-S7XBe07W.mjs";
2
2
  export { coalesceSubtreeIssues, planIssues };
@@ -1,6 +1,6 @@
1
- import { P as createExtension } from "./op-factory-call-DuRj7WXX.mjs";
1
+ import { P as createExtension } from "./op-factory-call-Ci3H6InB.mjs";
2
2
  import { t as dataTransform } from "./data-transform-BOWpliq8.mjs";
3
- import { t as PostgresMigration } from "./postgres-migration-C_OPFhIF.mjs";
3
+ import { t as PostgresMigration } from "./postgres-migration-Bn3fj1I4.mjs";
4
4
  import { checkExpression, col, fn, foreignKey, lit, primaryKey, unique } from "@prisma-next/sql-relational-core/contract-free";
5
5
  import { placeholder } from "@prisma-next/errors/migration";
6
6
  import { MigrationCLI } from "@prisma-next/cli/migration-cli";
@@ -1794,11 +1794,6 @@ var DataTransformCall = class extends PostgresOpFactoryCallNode {
1794
1794
  return [{
1795
1795
  moduleSpecifier: POSTGRES_MIGRATION_FACADE,
1796
1796
  symbol: "placeholder"
1797
- }, {
1798
- moduleSpecifier: "./end-contract.json",
1799
- symbol: "endContract",
1800
- kind: "default",
1801
- attributes: { type: "json" }
1802
1797
  }];
1803
1798
  }
1804
1799
  };
@@ -1945,4 +1940,4 @@ var RenamePostgresRlsPolicyCall = class extends PostgresOpFactoryCallNode {
1945
1940
  //#endregion
1946
1941
  export { SetDefaultCall as A, DropNativeEnumTypeCall as C, EnableRowLevelSecurityCall as D, DropTableCall as E, installExtension as F, postgresDefaultToDdlColumnDefault as M, buildTargetDetails as N, RawSqlCall as O, createExtension as P, DropIndexCall as S, DropPostgresRlsPolicyCall as T, DisableRowLevelSecurityCall as _, AddNotNullColumnDirectCall as a, DropConstraintCall as b, AddUniqueCall as c, CreateIndexCall as d, CreateNativeEnumTypeCall as f, DataTransformCall as g, CreateTableCall as h, AddNativeEnumValueCall as i, SetNotNullCall as j, RenamePostgresRlsPolicyCall as k, AlterColumnTypeCall as l, CreateSchemaCall as m, AddColumnCall as n, AddNotNullColumnWithTempDefaultCall as o, CreatePostgresRlsPolicyCall as p, AddForeignKeyCall as r, AddPrimaryKeyCall as s, AddCheckConstraintCall as t, CreateExtensionCall as u, DropCheckConstraintCall as v, DropNotNullCall as w, DropDefaultCall as x, DropColumnCall as y };
1947
1942
 
1948
- //# sourceMappingURL=op-factory-call-DuRj7WXX.mjs.map
1943
+ //# sourceMappingURL=op-factory-call-Ci3H6InB.mjs.map