@prisma-next/target-postgres 0.13.0-dev.28 → 0.13.0-dev.29

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 (128) hide show
  1. package/dist/{codec-ids-C_-Hj6bL.mjs → codec-ids-BvytN2P8.mjs} +2 -3
  2. package/dist/codec-ids-BvytN2P8.mjs.map +1 -0
  3. package/dist/{codec-ids-BzrFF-I4.d.mts → codec-ids-CnXu9Qy3.d.mts} +2 -3
  4. package/dist/codec-ids-CnXu9Qy3.d.mts.map +1 -0
  5. package/dist/codec-ids.d.mts +2 -2
  6. package/dist/codec-ids.mjs +2 -2
  7. package/dist/{codec-types-B0WT0obB.d.mts → codec-types-DHCkwPKE.d.mts} +2 -3
  8. package/dist/codec-types-DHCkwPKE.d.mts.map +1 -0
  9. package/dist/codec-types.d.mts +1 -1
  10. package/dist/{codecs-CX56Smsj.d.mts → codecs--0A5_4Bq.d.mts} +3 -23
  11. package/dist/codecs--0A5_4Bq.d.mts.map +1 -0
  12. package/dist/codecs.d.mts +2 -2
  13. package/dist/codecs.mjs +2 -38
  14. package/dist/codecs.mjs.map +1 -1
  15. package/dist/contract-free.mjs +1 -1
  16. package/dist/control.d.mts.map +1 -1
  17. package/dist/control.mjs +7 -10
  18. package/dist/control.mjs.map +1 -1
  19. package/dist/{descriptor-meta-C7O6XHfh.mjs → descriptor-meta-BKma_hQ5.mjs} +2 -2
  20. package/dist/{descriptor-meta-C7O6XHfh.mjs.map → descriptor-meta-BKma_hQ5.mjs.map} +1 -1
  21. package/dist/{descriptor-meta-runtime-BToWdas9.mjs → descriptor-meta-runtime-e5f2tscJ.mjs} +2 -39
  22. package/dist/descriptor-meta-runtime-e5f2tscJ.mjs.map +1 -0
  23. package/dist/{issue-planner-CK-XWGB0.mjs → issue-planner-DsjB7xDj.mjs} +17 -227
  24. package/dist/issue-planner-DsjB7xDj.mjs.map +1 -0
  25. package/dist/issue-planner.d.mts +8 -11
  26. package/dist/issue-planner.d.mts.map +1 -1
  27. package/dist/issue-planner.mjs +1 -1
  28. package/dist/migration.d.mts +1 -11
  29. package/dist/migration.d.mts.map +1 -1
  30. package/dist/migration.mjs +3 -3
  31. package/dist/{op-factory-call-DxjpXw-A.d.mts → op-factory-call-CdtMyrlU.d.mts} +3 -48
  32. package/dist/{op-factory-call-DxjpXw-A.d.mts.map → op-factory-call-CdtMyrlU.d.mts.map} +1 -1
  33. package/dist/{op-factory-call-CHvtj70z.mjs → op-factory-call-CjR846f7.mjs} +4 -159
  34. package/dist/op-factory-call-CjR846f7.mjs.map +1 -0
  35. package/dist/op-factory-call.d.mts +2 -2
  36. package/dist/op-factory-call.mjs +2 -2
  37. package/dist/pack.d.mts +2 -18
  38. package/dist/pack.d.mts.map +1 -1
  39. package/dist/pack.mjs +1 -1
  40. package/dist/{planner-4FbY_95H.mjs → planner-_FOL4I21.mjs} +9 -41
  41. package/dist/planner-_FOL4I21.mjs.map +1 -0
  42. package/dist/{planner-ddl-builders-Cw2n2llW.mjs → planner-ddl-builders-B2wOwLqI.mjs} +2 -2
  43. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +1 -0
  44. package/dist/planner-ddl-builders.d.mts +4 -4
  45. package/dist/planner-ddl-builders.d.mts.map +1 -1
  46. package/dist/planner-ddl-builders.mjs +1 -1
  47. package/dist/{planner-identity-values-BIpa5p2I.mjs → planner-identity-values-CJPha2Sz.mjs} +3 -9
  48. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -0
  49. package/dist/planner-identity-values.d.mts +1 -1
  50. package/dist/planner-identity-values.d.mts.map +1 -1
  51. package/dist/planner-identity-values.mjs +1 -1
  52. package/dist/{planner-produced-postgres-migration-qfkCkGVe.mjs → planner-produced-postgres-migration-BmCpyWLJ.mjs} +2 -2
  53. package/dist/{planner-produced-postgres-migration-qfkCkGVe.mjs.map → planner-produced-postgres-migration-BmCpyWLJ.mjs.map} +1 -1
  54. package/dist/planner-produced-postgres-migration.mjs +1 -1
  55. package/dist/{planner-sql-checks-BLgdXLsA.mjs → planner-sql-checks-CJJtPfDH.mjs} +3 -3
  56. package/dist/planner-sql-checks-CJJtPfDH.mjs.map +1 -0
  57. package/dist/planner-sql-checks.d.mts +2 -2
  58. package/dist/planner-sql-checks.d.mts.map +1 -1
  59. package/dist/planner-sql-checks.mjs +1 -1
  60. package/dist/{planner-type-resolution-836DExFN.mjs → planner-type-resolution-Bt2f_q-F.mjs} +1 -6
  61. package/dist/planner-type-resolution-Bt2f_q-F.mjs.map +1 -0
  62. package/dist/planner.d.mts.map +1 -1
  63. package/dist/planner.mjs +1 -1
  64. package/dist/{postgres-contract-serializer-CTxVcCVW.mjs → postgres-contract-serializer-CyAe8ZFv.mjs} +12 -29
  65. package/dist/postgres-contract-serializer-CyAe8ZFv.mjs.map +1 -0
  66. package/dist/{postgres-migration-DF5ApLqQ.mjs → postgres-migration-dG-J0aI8.mjs} +2 -2
  67. package/dist/{postgres-migration-DF5ApLqQ.mjs.map → postgres-migration-dG-J0aI8.mjs.map} +1 -1
  68. package/dist/{postgres-schema-C7c9rhGk.mjs → postgres-schema-CTKYiTHu.mjs} +7 -21
  69. package/dist/postgres-schema-CTKYiTHu.mjs.map +1 -0
  70. package/dist/runtime.d.mts +0 -2
  71. package/dist/runtime.d.mts.map +1 -1
  72. package/dist/runtime.mjs +2 -2
  73. package/dist/types.d.mts +5 -25
  74. package/dist/types.d.mts.map +1 -1
  75. package/dist/types.mjs +2 -4
  76. package/package.json +17 -18
  77. package/src/core/authoring.ts +1 -44
  78. package/src/core/codec-helpers.ts +0 -17
  79. package/src/core/codec-ids.ts +0 -1
  80. package/src/core/codec-type-map.ts +0 -2
  81. package/src/core/codecs.ts +0 -49
  82. package/src/core/migrations/control-policy.ts +3 -45
  83. package/src/core/migrations/issue-planner.ts +9 -52
  84. package/src/core/migrations/op-factory-call.ts +2 -124
  85. package/src/core/migrations/planner-ddl-builders.ts +3 -4
  86. package/src/core/migrations/planner-identity-values.ts +4 -28
  87. package/src/core/migrations/planner-recipes.ts +2 -6
  88. package/src/core/migrations/planner-sql-checks.ts +2 -6
  89. package/src/core/migrations/planner-strategies.ts +13 -353
  90. package/src/core/migrations/planner-type-resolution.ts +2 -20
  91. package/src/core/migrations/planner.ts +0 -2
  92. package/src/core/migrations/runner.ts +0 -4
  93. package/src/core/postgres-contract-serializer.ts +9 -67
  94. package/src/core/postgres-schema.ts +6 -37
  95. package/src/exports/codecs.ts +0 -2
  96. package/src/exports/control.ts +0 -15
  97. package/src/exports/migration.ts +0 -6
  98. package/src/exports/op-factory-call.ts +0 -4
  99. package/src/exports/types.ts +0 -2
  100. package/dist/codec-ids-BzrFF-I4.d.mts.map +0 -1
  101. package/dist/codec-ids-C_-Hj6bL.mjs.map +0 -1
  102. package/dist/codec-types-B0WT0obB.d.mts.map +0 -1
  103. package/dist/codecs-CX56Smsj.d.mts.map +0 -1
  104. package/dist/descriptor-meta-runtime-BToWdas9.mjs.map +0 -1
  105. package/dist/enum-planning-D8z4FH7y.mjs +0 -129
  106. package/dist/enum-planning-D8z4FH7y.mjs.map +0 -1
  107. package/dist/enum-planning.d.mts +0 -92
  108. package/dist/enum-planning.d.mts.map +0 -1
  109. package/dist/enum-planning.mjs +0 -2
  110. package/dist/issue-planner-CK-XWGB0.mjs.map +0 -1
  111. package/dist/op-factory-call-CHvtj70z.mjs.map +0 -1
  112. package/dist/planner-4FbY_95H.mjs.map +0 -1
  113. package/dist/planner-ddl-builders-Cw2n2llW.mjs.map +0 -1
  114. package/dist/planner-identity-values-BIpa5p2I.mjs.map +0 -1
  115. package/dist/planner-sql-checks-BLgdXLsA.mjs.map +0 -1
  116. package/dist/planner-type-resolution-836DExFN.mjs.map +0 -1
  117. package/dist/postgres-contract-serializer-CTxVcCVW.mjs.map +0 -1
  118. package/dist/postgres-enum-type-BVn63a89.d.mts +0 -72
  119. package/dist/postgres-enum-type-BVn63a89.d.mts.map +0 -1
  120. package/dist/postgres-enum-type-DPKqCBem.mjs +0 -62
  121. package/dist/postgres-enum-type-DPKqCBem.mjs.map +0 -1
  122. package/dist/postgres-enum-type-schema-DZBTtvBF.mjs +0 -20
  123. package/dist/postgres-enum-type-schema-DZBTtvBF.mjs.map +0 -1
  124. package/dist/postgres-schema-C7c9rhGk.mjs.map +0 -1
  125. package/src/core/migrations/enum-planning.ts +0 -217
  126. package/src/core/migrations/operations/enums.ts +0 -114
  127. package/src/core/postgres-enum-type.ts +0 -89
  128. package/src/exports/enum-planning.ts +0 -10
@@ -1,4 +1,4 @@
1
- import { _ as PG_TEXT_ARRAY_CODEC_ID, d as PG_INT8_CODEC_ID, m as PG_JSONB_CODEC_ID, u as PG_INT4_CODEC_ID, v as PG_TEXT_CODEC_ID, y as PG_TIMESTAMPTZ_CODEC_ID } from "./codec-ids-C_-Hj6bL.mjs";
1
+ import { _ as PG_TEXT_CODEC_ID, g as PG_TEXT_ARRAY_CODEC_ID, l as PG_INT4_CODEC_ID, p as PG_JSONB_CODEC_ID, u as PG_INT8_CODEC_ID, v as PG_TIMESTAMPTZ_CODEC_ID } from "./codec-ids-BvytN2P8.mjs";
2
2
  import { i as createTable, n as alterTable, r as createSchema, t as addColumnAction } from "./ddl-DY2R_Yqz.mjs";
3
3
  import { TableSource } from "@prisma-next/sql-relational-core/ast";
4
4
  import { col, fn, lit, table } from "@prisma-next/sql-relational-core/contract-free";
@@ -1 +1 @@
1
- {"version":3,"file":"control.d.mts","names":[],"sources":["../src/exports/control.ts"],"mappings":";;;;;;iBA8CgB,qBAAA,CAAsB,GAAA,EAAK,aAAA,EAAe,MAAA,EAAQ,aAAa;AAAA,cAOzE,wBAAA,EAA0B,0BAA0B,aAAa,yBAAA"}
1
+ {"version":3,"file":"control.d.mts","names":[],"sources":["../src/exports/control.ts"],"mappings":";;;;;;iBAuCgB,qBAAA,CAAsB,GAAA,EAAK,aAAA,EAAe,MAAA,EAAQ,aAAa;AAAA,cAOzE,wBAAA,EAA0B,0BAA0B,aAAa,yBAAA"}
package/dist/control.mjs CHANGED
@@ -1,15 +1,14 @@
1
- import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-C7O6XHfh.mjs";
2
- import { o as resolveDdlSchemaForNamespaceStorage, t as createResolveExistingEnumValues } from "./enum-planning-D8z4FH7y.mjs";
1
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-BKma_hQ5.mjs";
3
2
  import { t as parsePostgresDefault } from "./default-normalizer-DyyCHQWs.mjs";
4
3
  import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Bc9XJzWC.mjs";
5
- import { t as createPostgresMigrationPlanner } from "./planner-4FbY_95H.mjs";
6
- import { a as renderDefaultLiteral } from "./planner-ddl-builders-Cw2n2llW.mjs";
7
- import { t as PostgresContractSerializer } from "./postgres-contract-serializer-CTxVcCVW.mjs";
4
+ import { t as createPostgresMigrationPlanner } from "./planner-_FOL4I21.mjs";
5
+ import { a as renderDefaultLiteral } from "./planner-ddl-builders-B2wOwLqI.mjs";
6
+ import { t as PostgresContractSerializer } from "./postgres-contract-serializer-CyAe8ZFv.mjs";
8
7
  import { blindCast } from "@prisma-next/utils/casts";
9
8
  import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
10
9
  import { ifDefined } from "@prisma-next/utils/defined";
11
- import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
12
10
  import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
11
+ import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
13
12
  import { notOk, ok, okVoid } from "@prisma-next/utils/result";
14
13
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
15
14
  import { SqlQueryError } from "@prisma-next/sql-errors";
@@ -87,8 +86,7 @@ var PostgresMigrationRunner = class {
87
86
  typeMetadataRegistry: this.family.typeMetadataRegistry,
88
87
  frameworkComponents: options.frameworkComponents,
89
88
  normalizeDefault: parsePostgresDefault,
90
- normalizeNativeType: normalizeSchemaNativeType,
91
- resolveExistingEnumValues: createResolveExistingEnumValues(options.destinationContract.storage)
89
+ normalizeNativeType: normalizeSchemaNativeType
92
90
  });
93
91
  if (!schemaVerifyResult.ok) return runnerFailure("SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
94
92
  why: "The resulting database schema does not satisfy the destination contract.",
@@ -441,8 +439,7 @@ const postgresTargetDescriptor = {
441
439
  return contractToSchemaIR(contract, {
442
440
  annotationNamespace: "pg",
443
441
  ...ifDefined("expandNativeType", buildNativeTypeExpander(frameworkComponents)),
444
- renderDefault: postgresRenderDefault,
445
- resolveEnumNamespaceSchema: (storage, namespaceId) => resolveDdlSchemaForNamespaceStorage(storage, namespaceId, void 0)
442
+ renderDefault: postgresRenderDefault
446
443
  });
447
444
  }
448
445
  },
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.ts","../src/exports/control.ts"],"sourcesContent":["import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { MigrationRunnerResult } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlControlDriverInstance, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { createResolveExistingEnumValues } from './enum-planning';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Materialize any async ops before running checks or executing.\n const planOps = blindCast<\n readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n 'ops were produced by the PG planner and are SqlMigrationPlanOperation<PostgresPlanTargetDetails>; MigrationPlan.operations uses the wider framework type to accommodate Promise covariance'\n >(await Promise.all(options.plan.operations));\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver, options.destinationContract);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options, planOps);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n resolveExistingEnumValues: createResolveExistingEnumValues(\n options.destinationContract.storage,\n ),\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n const markerResult = await this.upsertMarker(driver, options, existingMarker, space);\n if (!markerResult.ok) return markerResult;\n await this.recordLedgerEntries(\n driver,\n options,\n applyValue.executedOperations,\n planOps.length,\n );\n }\n\n return runnerSuccess({\n operationsPlanned: planOps.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async execute(options: {\n readonly driver: SqlControlDriverInstance<string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ops: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of ops) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n contract: Contract<SqlStorage>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const lowererContext = { contract };\n const bootstrapQueries = this.family.bootstrapControlTableQueries();\n const [schemaQuery, ...tableQueries] = bootstrapQueries;\n if (schemaQuery === undefined) {\n throw new Error('Postgres control-table bootstrap must include CREATE SCHEMA');\n }\n await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n for (const query of tableQueries) {\n await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));\n }\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const destination = {\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n invariants: options.plan.providedInvariants ?? [],\n };\n if (!existingMarker) {\n await this.family.initMarker({ driver, space, destination });\n return okVoid();\n }\n const updated = await this.family.updateMarker({\n driver,\n space,\n expectedFrom: existingMarker.storageHash,\n destination,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: options.plan.destination.storageHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async recordLedgerEntries(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n planOpsLength: number,\n ): Promise<void> {\n const plan = options.plan;\n const space = plan.spaceId;\n const edges = options.migrationEdges;\n const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n if (totalEdgeOps !== planOpsLength) {\n throw new Error(\n `Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n );\n }\n // The ledger records the operations as executed — idempotency-skipped ops\n // are substituted with skip records (empty `execute`) by `applyPlan`, so the\n // journal reflects what actually ran rather than the raw plan.\n let offset = 0;\n for (const edge of edges) {\n const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);\n offset += edge.operationCount;\n await this.family.writeLedgerEntry({\n driver,\n space,\n entry: {\n edgeId: `${edge.from}->${edge.to}`,\n from: edge.from,\n to: edge.to,\n migrationName: edge.dirName,\n migrationHash: edge.migrationHash,\n operations: edgeOps,\n },\n });\n }\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlExecuteRequest,\n ): Promise<void> {\n await driver.query(statement.sql, statement.params);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type { SqlControlTargetDescriptor } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { resolveDdlSchemaForNamespaceStorage } from '../core/migrations/enum-planning';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\n migrations: {\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n // Blind cast: the framework SPI signature\n // (`control-migration-types.ts § contractToSchema`) types\n // `contract` as the generic `Contract | null`. Inside the\n // postgres target descriptor we know any contract reaching\n // this method is SQL-family — the family contract resolver\n // would have refused to construct a postgres target binding\n // otherwise — so we narrow the generic to\n // `Contract<SqlStorage>` for the lowering call.\n return contractToSchemaIR(contract as unknown as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n // Map each namespace to the live DDL schema its enums are stored\n // under, so the projected \"from\" IR nests enums by the same schema\n // `readExistingEnumValues` reads (the contract-to-contract `migration\n // plan` path). `undefined` schema IR ⇒ the unbound coordinate\n // resolves to the default `public` landing schema, matching the\n // read-side fallback.\n resolveEnumNamespaceSchema: (storage, namespaceId) =>\n resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,GAAG,CAAC;MAC/B,IAAI,OAAO,QAAQ,UACxB,OAAO,OAAO,qBAAqB,GAA8B;MAEjE,OAAO,OAAO;CAGlB,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,SAAgB,8BACd,QAC+C;CAC/C,OAAO,IAAI,wBAAwB,MAAM;AAC3C;AAEA,IAAM,0BAAN,MAAuF;CACxD;CAA7B,YAAY,QAAmD;EAA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KA,cAAc,SAAwC;EACpD,OAAO,+BAA+B,OAAO;CAC/C;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
1
+ {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/postgres-schema-verifier.ts","../src/exports/control.ts"],"sourcesContent":["import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { MigrationRunnerResult } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlControlDriverInstance, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport type { SqlExecuteRequest } from '@prisma-next/sql-relational-core/ast';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family);\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n /**\n * Body of the migration runner without transaction management. The\n * caller ({@link PostgresMigrationRunner.execute}) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema =\n options.schemaName ??\n Object.keys(options.destinationContract.storage.namespaces).find(\n (id) => id !== UNBOUND_NAMESPACE_ID,\n ) ??\n UNBOUND_NAMESPACE_ID;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Materialize any async ops before running checks or executing.\n const planOps = blindCast<\n readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n 'ops were produced by the PG planner and are SqlMigrationPlanOperation<PostgresPlanTargetDetails>; MigrationPlan.operations uses the wider framework type to accommodate Promise covariance'\n >(await Promise.all(options.plan.operations));\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver, options.destinationContract);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options, planOps);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n const markerResult = await this.upsertMarker(driver, options, existingMarker, space);\n if (!markerResult.ok) return markerResult;\n await this.recordLedgerEntries(\n driver,\n options,\n applyValue.executedOperations,\n planOps.length,\n );\n }\n\n return runnerSuccess({\n operationsPlanned: planOps.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async execute(options: {\n readonly driver: SqlControlDriverInstance<string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MigrationRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ops: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of ops) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n contract: Contract<SqlStorage>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const lowererContext = { contract };\n const bootstrapQueries = this.family.bootstrapControlTableQueries();\n const [schemaQuery, ...tableQueries] = bootstrapQueries;\n if (schemaQuery === undefined) {\n throw new Error('Postgres control-table bootstrap must include CREATE SCHEMA');\n }\n await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n for (const query of tableQueries) {\n await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));\n }\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const destination = {\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n invariants: options.plan.providedInvariants ?? [],\n };\n if (!existingMarker) {\n await this.family.initMarker({ driver, space, destination });\n return okVoid();\n }\n const updated = await this.family.updateMarker({\n driver,\n space,\n expectedFrom: existingMarker.storageHash,\n destination,\n });\n if (!updated) {\n return runnerFailure(\n 'MARKER_CAS_FAILURE',\n 'Marker was modified by another process during migration execution.',\n {\n meta: {\n space,\n expectedStorageHash: existingMarker.storageHash,\n destinationStorageHash: options.plan.destination.storageHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async recordLedgerEntries(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n planOpsLength: number,\n ): Promise<void> {\n const plan = options.plan;\n const space = plan.spaceId;\n const edges = options.migrationEdges;\n const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);\n if (totalEdgeOps !== planOpsLength) {\n throw new Error(\n `Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`,\n );\n }\n // The ledger records the operations as executed — idempotency-skipped ops\n // are substituted with skip records (empty `execute`) by `applyPlan`, so the\n // journal reflects what actually ran rather than the raw plan.\n let offset = 0;\n for (const edge of edges) {\n const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);\n offset += edge.operationCount;\n await this.family.writeLedgerEntry({\n driver,\n space,\n entry: {\n edgeId: `${edge.from}->${edge.to}`,\n from: edge.from,\n to: edge.to,\n migrationName: edge.dirName,\n migrationHash: edge.migrationHash,\n operations: edgeOps,\n },\n });\n }\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlExecuteRequest,\n ): Promise<void> {\n await driver.query(statement.sql, statement.params);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres target `SchemaVerifier` concretion. Plugs into the\n * SQL-shared verification surface; production verification today still\n * routes through the legacy `verifySqlSchema` entry point, which\n * carries options (codec hooks, normalizers, framework components)\n * that the framework-level `SchemaVerifyOptions` shape does not yet\n * surface.\n *\n * The hooks return the empty list pending the call-site migration that\n * routes the existing verifier behaviour through the SPI — at that\n * point `verifyCommonSqlSchema` will likely lift onto the family base\n * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`\n * will house Postgres-only kinds (functions, RLS policies in a future\n * project).\n */\nexport class PostgresSchemaVerifier extends SqlSchemaVerifierBase<\n Contract<SqlStorage>,\n SqlSchemaIR\n> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type { SqlControlTargetDescriptor } from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\nimport { PostgresContractSerializer } from '../core/postgres-contract-serializer';\nimport { PostgresSchemaVerifier } from '../core/postgres-schema-verifier';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n contractSerializer: new PostgresContractSerializer(),\n schemaVerifier: new PostgresSchemaVerifier(),\n migrations: {\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n // Blind cast: the framework SPI signature\n // (`control-migration-types.ts § contractToSchema`) types\n // `contract` as the generic `Contract | null`. Inside the\n // postgres target descriptor we know any contract reaching\n // this method is SQL-family — the family contract resolver\n // would have refused to construct a postgres target binding\n // otherwise — so we narrow the generic to\n // `Contract<SqlStorage>` for the lowering call.\n return contractToSchemaIR(contract as unknown as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(adapter: SqlControlAdapter<'postgres'>) {\n return createPostgresMigrationPlanner(adapter);\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,KAAK,GAC3C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,GAAG,GAC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;GAU9C,OAAO,mBAAmB,UAAoD;IAC5E,qBAAqB;IACrB,GAAG,UAAU,oBAXE,wBAAwB,mBAWC,CAAC;IACzC,eAAe;GACjB,CAAC;EACH;CACF;CACA,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;EACZ;CACF;;;;;CAKA,cAAc,SAAwC;EACpD,OAAO,+BAA+B,OAAO;CAC/C;;;;;CAKA,aAAa,QAAQ;EACnB,OAAO,8BAA8B,MAAM;CAC7C;AACF"}
@@ -1,4 +1,4 @@
1
- import { i as postgresAuthoringTypes, n as postgresAuthoringEntityTypes, r as postgresAuthoringFieldPresets, t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-BToWdas9.mjs";
1
+ import { i as postgresAuthoringTypes, n as postgresAuthoringEntityTypes, r as postgresAuthoringFieldPresets, t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-e5f2tscJ.mjs";
2
2
  const postgresTargetDescriptorMeta = {
3
3
  ...postgresTargetDescriptorMetaRuntime,
4
4
  defaultNamespaceId: "public",
@@ -11,4 +11,4 @@ const postgresTargetDescriptorMeta = {
11
11
  //#endregion
12
12
  export { postgresTargetDescriptorMeta as t };
13
13
 
14
- //# sourceMappingURL=descriptor-meta-C7O6XHfh.mjs.map
14
+ //# sourceMappingURL=descriptor-meta-BKma_hQ5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"descriptor-meta-C7O6XHfh.mjs","names":[],"sources":["../src/core/descriptor-meta.ts"],"sourcesContent":["import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringTypes,\n} from './authoring';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: 'public',\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";AAkBA,MAAa,+BAET;CAXF,GAAG;CACH,oBAAoB;CACpB,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;CACf;AAKE"}
1
+ {"version":3,"file":"descriptor-meta-BKma_hQ5.mjs","names":[],"sources":["../src/core/descriptor-meta.ts"],"sourcesContent":["import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringTypes,\n} from './authoring';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: 'public',\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";AAkBA,MAAa,+BAET;CAXF,GAAG;CACH,oBAAoB;CACpB,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;CACf;AAKE"}
@@ -1,44 +1,7 @@
1
- import { t as PostgresEnumType } from "./postgres-enum-type-DPKqCBem.mjs";
2
- import { t as PostgresEnumTypeSchema } from "./postgres-enum-type-schema-DZBTtvBF.mjs";
3
1
  import { temporalAuthoringPresets } from "@prisma-next/family-sql/control";
4
2
  //#region src/core/authoring.ts
5
3
  const postgresAuthoringTypes = {};
6
- /**
7
- * Entity type contributions surface as top-level helpers on the
8
- * composed-helpers shape (e.g. `helpers.enum({...})`), flattened
9
- * alongside the built-in `model` / `rel` helpers. Pack contributions
10
- * still ship via the contribution data structure
11
- * `authoring.entityTypes.<name>`; the composed-helpers template
12
- * performs the rename in the type system.
13
- *
14
- * `enum` is the first real consumer of the entities-namespace mechanism:
15
- * the factory constructs a `PostgresEnumType` IR-class instance from
16
- * the user-supplied input. Both authoring runtimes (TS DSL and PSL)
17
- * dispatch through this single contribution — PSL `enum Status { … }`
18
- * declarations are lowered by the interpreter into a factory call
19
- * with the parsed name + value list; TS DSL `helpers.enum({...})`
20
- * resolves through the same path. Removing this contribution makes
21
- * both surfaces fail with a "no entity helper named `enum`" type
22
- * error at the contract-definition site.
23
- */
24
- /**
25
- * The factory constructs a `PostgresEnumType` instance natively — the
26
- * `SqlStorage.types` slot accepts polymorphic IR (the framework
27
- * `StorageType` alphabet), so no cast is needed at the contribution
28
- * surface. The declared return type is the structural
29
- * `PostgresEnumStorageEntry` so the inferred contract type stays
30
- * portable (it names a type exported from
31
- * `@prisma-next/sql-contract/types`, a public surface every consumer
32
- * already imports). Sharpening the inferred contract type to surface
33
- * enum-specific narrowing through `EntityHelperFunction` is a
34
- * separable refinement and lives outside this PR.
35
- */
36
- const postgresAuthoringEntityTypes = { enum: {
37
- kind: "entity",
38
- discriminator: "postgres-enum",
39
- validatorSchema: PostgresEnumTypeSchema,
40
- output: { factory: (input) => new PostgresEnumType(input) }
41
- } };
4
+ const postgresAuthoringEntityTypes = {};
42
5
  /**
43
6
  * Field presets contributed by the Postgres target pack.
44
7
  *
@@ -165,4 +128,4 @@ const postgresTargetDescriptorMetaRuntime = {
165
128
  //#endregion
166
129
  export { postgresAuthoringTypes as i, postgresAuthoringEntityTypes as n, postgresAuthoringFieldPresets as r, postgresTargetDescriptorMetaRuntime as t };
167
130
 
168
- //# sourceMappingURL=descriptor-meta-runtime-BToWdas9.mjs.map
131
+ //# sourceMappingURL=descriptor-meta-runtime-e5f2tscJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-runtime-e5f2tscJ.mjs","names":[],"sources":["../src/core/authoring.ts","../src/core/descriptor-meta-runtime.ts"],"sourcesContent":["import { temporalAuthoringPresets } from '@prisma-next/family-sql/control';\nimport type {\n AuthoringEntityTypeNamespace,\n AuthoringFieldNamespace,\n AuthoringTypeNamespace,\n} from '@prisma-next/framework-components/authoring';\n\nexport const postgresAuthoringTypes = {} as const satisfies AuthoringTypeNamespace;\n\nexport const postgresAuthoringEntityTypes = {} as const satisfies AuthoringEntityTypeNamespace;\n\n/**\n * Field presets contributed by the Postgres target pack.\n *\n * These mirror the PSL scalar-to-codec mapping used by the Postgres adapter\n * (see `createPostgresPslScalarTypeDescriptors`), so that authoring a field\n * via the TS callback surface (e.g. `field.int()`) and via the PSL scalar\n * surface (e.g. `Int`) lowers to byte-identical contracts.\n *\n * The `uuidNative` / `id.uuidv4Native` / `id.uuidv7Native` presets use the\n * native Postgres `uuid` type (codecId `pg/uuid@1`). For cross-target\n * portability use `uuidString` / `id.uuidv4String` / `id.uuidv7String` from\n * the family pack instead.\n */\nexport const postgresAuthoringFieldPresets = {\n text: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/text@1',\n nativeType: 'text',\n },\n },\n int: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/int4@1',\n nativeType: 'int4',\n },\n },\n bigint: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/int8@1',\n nativeType: 'int8',\n },\n },\n float: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/float8@1',\n nativeType: 'float8',\n },\n },\n decimal: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/numeric@1',\n nativeType: 'numeric',\n },\n },\n boolean: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/bool@1',\n nativeType: 'bool',\n },\n },\n json: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/jsonb@1',\n nativeType: 'jsonb',\n },\n },\n bytes: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/bytea@1',\n nativeType: 'bytea',\n },\n },\n dateTime: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/timestamptz@1',\n nativeType: 'timestamptz',\n },\n },\n temporal: /* @__PURE__ */ temporalAuthoringPresets({\n codecId: 'pg/timestamptz@1',\n nativeType: 'timestamptz',\n }),\n uuidNative: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n },\n },\n id: {\n uuidv4Native: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n executionDefaults: {\n onCreate: {\n kind: 'generator',\n id: 'uuidv4',\n },\n },\n id: true,\n },\n },\n uuidv7Native: {\n kind: 'fieldPreset',\n output: {\n codecId: 'pg/uuid@1',\n nativeType: 'uuid',\n executionDefaults: {\n onCreate: {\n kind: 'generator',\n id: 'uuidv7',\n },\n },\n id: true,\n },\n },\n },\n} as const satisfies AuthoringFieldNamespace;\n","// Runtime-safe slice of the postgres target descriptor metadata.\n//\n// This file exists separately from ./descriptor-meta on purpose: the runtime\n// plane reads only `kind/familyId/targetId/id/version/capabilities` (plus the\n// `__codecTypes` phantom). The `authoring` slot lives on the pack/control\n// descriptor only, because authoring contributions are consumed at\n// contract-construction time by `assembleAuthoringContributions` (control\n// plane) and the PSL interpreter — never at runtime.\n//\n// Keeping the runtime closure free of the `./authoring` import is what lets\n// the bundler tree-shake `@prisma-next/family-sql/control` (and its\n// transitive `verify-sql-schema` chunk) out of the runtime entry. Do not\n// add an `authoring` field here — if you need to, the pack/control meta in\n// `./descriptor-meta` is the right place. See TML-2766 for context.\nimport type { CodecTypes } from '../exports/codec-types';\n\nconst postgresTargetDescriptorMetaRuntimeBase = {\n kind: 'target',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {},\n} as const;\n\nexport const postgresTargetDescriptorMetaRuntime: typeof postgresTargetDescriptorMetaRuntimeBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaRuntimeBase;\n"],"mappings":";;AAOA,MAAa,yBAAyB,CAAC;AAEvC,MAAa,+BAA+B,CAAC;;;;;;;;;;;;;;AAe7C,MAAa,gCAAgC;CAC3C,MAAM;EACJ,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,KAAK;EACH,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,QAAQ;EACN,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,OAAO;EACL,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,SAAS;EACP,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,SAAS;EACP,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,MAAM;EACJ,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,OAAO;EACL,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,UAAU;EACR,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,UAA0B,yCAAyB;EACjD,SAAS;EACT,YAAY;CACd,CAAC;CACD,YAAY;EACV,MAAM;EACN,QAAQ;GACN,SAAS;GACT,YAAY;EACd;CACF;CACA,IAAI;EACF,cAAc;GACZ,MAAM;GACN,QAAQ;IACN,SAAS;IACT,YAAY;IACZ,mBAAmB,EACjB,UAAU;KACR,MAAM;KACN,IAAI;IACN,EACF;IACA,IAAI;GACN;EACF;EACA,cAAc;GACZ,MAAM;GACN,QAAQ;IACN,SAAS;IACT,YAAY;IACZ,mBAAmB,EACjB,UAAU;KACR,MAAM;KACN,IAAI;IACN,EACF;IACA,IAAI;GACN;EACF;CACF;AACF;ACxGA,MAAa,sCAET;CAVF,MAAM;CACN,UAAU;CACV,UAAU;CACV,IAAI;CACJ,SAAS;CACT,cAAc,CAAC;AAKb"}