@prisma-next/target-postgres 0.12.0-dev.6 → 0.12.0-dev.61

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 (174) hide show
  1. package/dist/{codec-ids-DliyCWPY.d.mts → codec-ids-B1vOchLE.d.mts} +3 -2
  2. package/dist/codec-ids-B1vOchLE.d.mts.map +1 -0
  3. package/dist/{codec-ids-C5qzBqus.mjs → codec-ids-CTikp1if.mjs} +3 -2
  4. package/dist/codec-ids-CTikp1if.mjs.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-BF1DXTPs.d.mts → codec-types-CnFiNML4.d.mts} +8 -9
  8. package/dist/codec-types-CnFiNML4.d.mts.map +1 -0
  9. package/dist/codec-types.d.mts +2 -2
  10. package/dist/{codecs-DuP3d9Au.d.mts → codecs-CBpEv4s5.d.mts} +33 -35
  11. package/dist/codecs-CBpEv4s5.d.mts.map +1 -0
  12. package/dist/codecs.d.mts +1 -1
  13. package/dist/codecs.mjs +37 -2
  14. package/dist/codecs.mjs.map +1 -1
  15. package/dist/contract-free.d.mts +75 -0
  16. package/dist/contract-free.d.mts.map +1 -0
  17. package/dist/contract-free.mjs +139 -0
  18. package/dist/contract-free.mjs.map +1 -0
  19. package/dist/control.d.mts +1 -1
  20. package/dist/control.mjs +62 -36
  21. package/dist/control.mjs.map +1 -1
  22. package/dist/{data-transform-CRkv2T_U.mjs → data-transform-D25tLeYU.mjs} +1 -1
  23. package/dist/{data-transform-CRkv2T_U.mjs.map → data-transform-D25tLeYU.mjs.map} +1 -1
  24. package/dist/{data-transform-CAPmAdxS.d.mts → data-transform-lq3NGdIt.d.mts} +2 -2
  25. package/dist/{data-transform-CAPmAdxS.d.mts.map → data-transform-lq3NGdIt.d.mts.map} +1 -1
  26. package/dist/data-transform.d.mts +1 -1
  27. package/dist/data-transform.mjs +1 -1
  28. package/dist/ddl.d.mts +2 -0
  29. package/dist/ddl.mjs +2 -0
  30. package/dist/{default-normalizer-DaAhmzBV.mjs → default-normalizer-DyyCHQWs.mjs} +1 -1
  31. package/dist/{default-normalizer-DaAhmzBV.mjs.map → default-normalizer-DyyCHQWs.mjs.map} +1 -1
  32. package/dist/default-normalizer.mjs +1 -1
  33. package/dist/{descriptor-meta-Uu8QaClr.mjs → descriptor-meta-DKmj-IMN.mjs} +3 -2
  34. package/dist/descriptor-meta-DKmj-IMN.mjs.map +1 -0
  35. package/dist/{descriptor-meta-runtime-DMRX39kp.mjs → descriptor-meta-runtime-My8_s4cs.mjs} +2 -2
  36. package/dist/{descriptor-meta-runtime-DMRX39kp.mjs.map → descriptor-meta-runtime-My8_s4cs.mjs.map} +1 -1
  37. package/dist/{enum-planning-DRA9LaMU.mjs → enum-planning-BCyvlFHk.mjs} +0 -0
  38. package/dist/{enum-planning-DRA9LaMU.mjs.map → enum-planning-BCyvlFHk.mjs.map} +1 -1
  39. package/dist/enum-planning.d.mts +1 -1
  40. package/dist/enum-planning.mjs +1 -1
  41. package/dist/{errors-BbnITmAD.mjs → errors-CUk87ByX.mjs} +1 -1
  42. package/dist/{errors-BbnITmAD.mjs.map → errors-CUk87ByX.mjs.map} +1 -1
  43. package/dist/errors.d.mts.map +1 -1
  44. package/dist/errors.mjs +1 -1
  45. package/dist/{issue-planner-BtaL6OfW.mjs → issue-planner-hxJaxYHv.mjs} +22 -23
  46. package/dist/issue-planner-hxJaxYHv.mjs.map +1 -0
  47. package/dist/issue-planner.d.mts +1 -1
  48. package/dist/issue-planner.d.mts.map +1 -1
  49. package/dist/issue-planner.mjs +1 -1
  50. package/dist/migration.d.mts +3 -3
  51. package/dist/migration.mjs +3 -3
  52. package/dist/{native-type-normalizer-BNEQ9VDs.mjs → native-type-normalizer-Bc9XJzWC.mjs} +1 -1
  53. package/dist/{native-type-normalizer-BNEQ9VDs.mjs.map → native-type-normalizer-Bc9XJzWC.mjs.map} +1 -1
  54. package/dist/native-type-normalizer.mjs +1 -1
  55. package/dist/nodes-Dm1XR7UL.mjs +42 -0
  56. package/dist/nodes-Dm1XR7UL.mjs.map +1 -0
  57. package/dist/nodes-Dq0ALHOk.d.mts +38 -0
  58. package/dist/nodes-Dq0ALHOk.d.mts.map +1 -0
  59. package/dist/{op-factory-call-CDlImOF_.d.mts → op-factory-call-D47zfLOp.d.mts} +3 -3
  60. package/dist/op-factory-call-D47zfLOp.d.mts.map +1 -0
  61. package/dist/{op-factory-call-ewOd5q6L.mjs → op-factory-call-G9G02kxC.mjs} +2 -2
  62. package/dist/{op-factory-call-ewOd5q6L.mjs.map → op-factory-call-G9G02kxC.mjs.map} +1 -1
  63. package/dist/op-factory-call.d.mts +1 -1
  64. package/dist/op-factory-call.mjs +1 -1
  65. package/dist/pack.d.mts +5 -6
  66. package/dist/pack.d.mts.map +1 -1
  67. package/dist/pack.mjs +1 -1
  68. package/dist/planner-C5tapy2_.mjs +340 -0
  69. package/dist/planner-C5tapy2_.mjs.map +1 -0
  70. package/dist/{planner-ddl-builders-BNMfSE9r.mjs → planner-ddl-builders-DDyptTt5.mjs} +4 -28
  71. package/dist/planner-ddl-builders-DDyptTt5.mjs.map +1 -0
  72. package/dist/planner-ddl-builders.d.mts +3 -4
  73. package/dist/planner-ddl-builders.d.mts.map +1 -1
  74. package/dist/planner-ddl-builders.mjs +2 -2
  75. package/dist/{planner-identity-values-nhVj0hp-.mjs → planner-identity-values-BIpa5p2I.mjs} +1 -1
  76. package/dist/{planner-identity-values-nhVj0hp-.mjs.map → planner-identity-values-BIpa5p2I.mjs.map} +1 -1
  77. package/dist/planner-identity-values.mjs +1 -1
  78. package/dist/{planner-produced-postgres-migration-D_nsXbhl.mjs → planner-produced-postgres-migration-BCy50btZ.mjs} +4 -4
  79. package/dist/{planner-produced-postgres-migration-D_nsXbhl.mjs.map → planner-produced-postgres-migration-BCy50btZ.mjs.map} +1 -1
  80. package/dist/{planner-produced-postgres-migration-D02NOhVQ.d.mts → planner-produced-postgres-migration-CpsGhewL.d.mts} +3 -3
  81. package/dist/planner-produced-postgres-migration-CpsGhewL.d.mts.map +1 -0
  82. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  83. package/dist/planner-produced-postgres-migration.mjs +1 -1
  84. package/dist/{planner-schema-lookup-CGxxYfnD.mjs → planner-schema-lookup-CiVaAQP-.mjs} +1 -1
  85. package/dist/{planner-schema-lookup-CGxxYfnD.mjs.map → planner-schema-lookup-CiVaAQP-.mjs.map} +1 -1
  86. package/dist/planner-schema-lookup.mjs +1 -1
  87. package/dist/{planner-sql-checks-CfEiTXoQ.mjs → planner-sql-checks-DAdhnI2c.mjs} +41 -30
  88. package/dist/planner-sql-checks-DAdhnI2c.mjs.map +1 -0
  89. package/dist/planner-sql-checks.d.mts.map +1 -1
  90. package/dist/planner-sql-checks.mjs +1 -1
  91. package/dist/{planner-target-details-a_wuOiYf.d.mts → planner-target-details-DyUHJ7MY.d.mts} +1 -1
  92. package/dist/{planner-target-details-a_wuOiYf.d.mts.map → planner-target-details-DyUHJ7MY.d.mts.map} +1 -1
  93. package/dist/planner-target-details.d.mts +2 -2
  94. package/dist/planner-type-resolution-836DExFN.mjs +20 -0
  95. package/dist/planner-type-resolution-836DExFN.mjs.map +1 -0
  96. package/dist/planner.d.mts +3 -2
  97. package/dist/planner.d.mts.map +1 -1
  98. package/dist/planner.mjs +1 -1
  99. package/dist/{postgres-contract-serializer-BnOboPWs.mjs → postgres-contract-serializer-DYTyXjPf.mjs} +33 -24
  100. package/dist/postgres-contract-serializer-DYTyXjPf.mjs.map +1 -0
  101. package/dist/{postgres-enum-type-CSzsvXrO.d.mts → postgres-enum-type-BVn63a89.d.mts} +1 -1
  102. package/dist/{postgres-enum-type-CSzsvXrO.d.mts.map → postgres-enum-type-BVn63a89.d.mts.map} +1 -1
  103. package/dist/{postgres-enum-type-BMgyxNyy.mjs → postgres-enum-type-DPKqCBem.mjs} +1 -1
  104. package/dist/{postgres-enum-type-BMgyxNyy.mjs.map → postgres-enum-type-DPKqCBem.mjs.map} +1 -1
  105. package/dist/{postgres-migration-DRY8V-bQ.d.mts → postgres-migration--iqDr7rB.d.mts} +3 -3
  106. package/dist/{postgres-migration-DRY8V-bQ.d.mts.map → postgres-migration--iqDr7rB.d.mts.map} +1 -1
  107. package/dist/{postgres-migration-BatbEvU6.mjs → postgres-migration-DcymFlMG.mjs} +3 -3
  108. package/dist/{postgres-migration-BatbEvU6.mjs.map → postgres-migration-DcymFlMG.mjs.map} +1 -1
  109. package/dist/{postgres-schema-BxAuNFX0.mjs → postgres-schema-BuxCxbvB.mjs} +29 -14
  110. package/dist/postgres-schema-BuxCxbvB.mjs.map +1 -0
  111. package/dist/{render-ops-XhICjX_P.mjs → render-ops-Wb6SCGmj.mjs} +1 -1
  112. package/dist/{render-ops-XhICjX_P.mjs.map → render-ops-Wb6SCGmj.mjs.map} +1 -1
  113. package/dist/render-ops.d.mts +1 -1
  114. package/dist/render-ops.mjs +1 -1
  115. package/dist/{render-typescript-K125n-RZ.mjs → render-typescript-BShM6uyS.mjs} +1 -1
  116. package/dist/{render-typescript-K125n-RZ.mjs.map → render-typescript-BShM6uyS.mjs.map} +1 -1
  117. package/dist/render-typescript.mjs +1 -1
  118. package/dist/runtime.d.mts.map +1 -1
  119. package/dist/runtime.mjs +2 -2
  120. package/dist/{shared-Do_a5ymU.d.mts → shared-C3gXQyxj.d.mts} +2 -2
  121. package/dist/{shared-Do_a5ymU.d.mts.map → shared-C3gXQyxj.d.mts.map} +1 -1
  122. package/dist/{sql-utils-CggjWNij.mjs → sql-utils-DcfMz4MQ.mjs} +1 -1
  123. package/dist/{sql-utils-CggjWNij.mjs.map → sql-utils-DcfMz4MQ.mjs.map} +1 -1
  124. package/dist/sql-utils.mjs +1 -1
  125. package/dist/{tables-DoA39Yqo.mjs → tables-OLIoVjxf.mjs} +3 -3
  126. package/dist/{tables-DoA39Yqo.mjs.map → tables-OLIoVjxf.mjs.map} +1 -1
  127. package/dist/{types-O40IcFV9.d.mts → types-BDKkx8MA.d.mts} +1 -1
  128. package/dist/types-BDKkx8MA.d.mts.map +1 -0
  129. package/dist/types.d.mts +16 -11
  130. package/dist/types.d.mts.map +1 -1
  131. package/dist/types.mjs +2 -2
  132. package/package.json +21 -20
  133. package/src/contract-free/columns.ts +49 -0
  134. package/src/contract-free/control-bootstrap.ts +55 -0
  135. package/src/contract-free/ddl.ts +32 -0
  136. package/src/core/ast/table-source.ts +23 -0
  137. package/src/core/codec-ids.ts +1 -0
  138. package/src/core/codecs.ts +44 -0
  139. package/src/core/ddl/nodes.ts +59 -0
  140. package/src/core/descriptor-meta.ts +1 -0
  141. package/src/core/migrations/control-policy.ts +234 -0
  142. package/src/core/migrations/issue-planner.ts +3 -3
  143. package/src/core/migrations/planner-ddl-builders.ts +0 -42
  144. package/src/core/migrations/planner-sql-checks.ts +9 -9
  145. package/src/core/migrations/planner-strategies.ts +16 -10
  146. package/src/core/migrations/planner.ts +55 -6
  147. package/src/core/migrations/runner.ts +78 -50
  148. package/src/core/postgres-contract-serializer.ts +52 -46
  149. package/src/core/postgres-schema.ts +43 -25
  150. package/src/exports/contract-free.ts +7 -0
  151. package/src/exports/ddl.ts +7 -0
  152. package/src/exports/planner-ddl-builders.ts +0 -1
  153. package/dist/codec-ids-C5qzBqus.mjs.map +0 -1
  154. package/dist/codec-ids-DliyCWPY.d.mts.map +0 -1
  155. package/dist/codec-types-BF1DXTPs.d.mts.map +0 -1
  156. package/dist/codecs-DuP3d9Au.d.mts.map +0 -1
  157. package/dist/descriptor-meta-Uu8QaClr.mjs.map +0 -1
  158. package/dist/issue-planner-BtaL6OfW.mjs.map +0 -1
  159. package/dist/op-factory-call-CDlImOF_.d.mts.map +0 -1
  160. package/dist/planner-Bjz5pnLa.mjs +0 -177
  161. package/dist/planner-Bjz5pnLa.mjs.map +0 -1
  162. package/dist/planner-ddl-builders-BNMfSE9r.mjs.map +0 -1
  163. package/dist/planner-produced-postgres-migration-D02NOhVQ.d.mts.map +0 -1
  164. package/dist/planner-sql-checks-CfEiTXoQ.mjs.map +0 -1
  165. package/dist/postgres-contract-serializer-BnOboPWs.mjs.map +0 -1
  166. package/dist/postgres-schema-BxAuNFX0.mjs.map +0 -1
  167. package/dist/statement-builders-DVI5IVAa.mjs +0 -131
  168. package/dist/statement-builders-DVI5IVAa.mjs.map +0 -1
  169. package/dist/statement-builders.d.mts +0 -51
  170. package/dist/statement-builders.d.mts.map +0 -1
  171. package/dist/statement-builders.mjs +0 -2
  172. package/dist/types-O40IcFV9.d.mts.map +0 -1
  173. package/src/core/migrations/statement-builders.ts +0 -183
  174. package/src/exports/statement-builders.ts +0 -8
@@ -1,177 +0,0 @@
1
- import { r as isPostgresSchema } from "./postgres-schema-BxAuNFX0.mjs";
2
- import { t as createResolveExistingEnumValues } from "./enum-planning-DRA9LaMU.mjs";
3
- import { t as parsePostgresDefault } from "./default-normalizer-DaAhmzBV.mjs";
4
- import { t as normalizeSchemaNativeType } from "./native-type-normalizer-BNEQ9VDs.mjs";
5
- import { n as postgresPlannerStrategies, t as planIssues } from "./issue-planner-BtaL6OfW.mjs";
6
- import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-D_nsXbhl.mjs";
7
- import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
8
- import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
9
- import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
10
- //#region src/core/migrations/verify-postgres-namespaces.ts
11
- /**
12
- * Resolves the live-database schema name for a given namespace
13
- * coordinate. Mirrors `resolveDdlSchemaForNamespace` in
14
- * `planner-strategies.ts` so the verifier's projection and the
15
- * planner's projection always agree — Postgres-aware namespaces (the
16
- * production path) dispatch to `ddlSchemaName(storage)`, and bare
17
- * object payloads (used by some tests) fall back to the coordinate
18
- * itself.
19
- */
20
- function resolveDdlSchemaName(storage, namespaceId) {
21
- const namespace = storage.namespaces[namespaceId];
22
- if (isPostgresSchema(namespace)) return namespace.ddlSchemaName(storage);
23
- return namespaceId;
24
- }
25
- /**
26
- * Reads the introspected list of schema names from the Postgres-flavoured
27
- * annotations slot on the schema IR. Defaults to the always-present
28
- * `public` schema when introspection did not populate the slot — a fresh
29
- * Postgres database always carries `public` (unless an operator dropped
30
- * it manually), so any verifier path that runs without an enriched
31
- * introspection still suppresses the redundant `CREATE SCHEMA "public"`.
32
- *
33
- * Production introspection (`PostgresControlAdapter.introspect`) is the
34
- * authoritative source: it queries `pg_namespace` and writes every
35
- * non-system schema into `annotations.pg.existingSchemas`. Tests that
36
- * want to assert against a richer initial state pass the slot
37
- * explicitly via the schema IR.
38
- */
39
- function existingSchemasFromSchema(schema) {
40
- const slot = schema.annotations?.pg?.existingSchemas;
41
- if (Array.isArray(slot)) return slot.filter((s) => typeof s === "string");
42
- return ["public"];
43
- }
44
- /**
45
- * Emits a `missing_schema` issue for every contract-declared Postgres
46
- * namespace whose live container does not yet exist.
47
- *
48
- * A namespace's live container is the schema returned by its
49
- * polymorphic `ddlSchemaName(storage)` method — named schemas resolve
50
- * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`
51
- * and is skipped explicitly (late-bound namespaces have no fixed DDL
52
- * schema). Issues are emitted only when the resolved name is a real,
53
- * creatable schema (not the unbound sentinel) and is missing from the
54
- * introspected list. `public` is suppressed implicitly because the
55
- * introspection (or its sensible default) always carries it.
56
- *
57
- * Each emitted issue stamps `namespaceId` with the contract namespace
58
- * coordinate so the downstream `mapIssueToCall` re-resolves the DDL
59
- * schema name through the same polymorphic path — keeping the
60
- * coordinate, not the resolved name, as the issue's stable identity.
61
- */
62
- function verifyPostgresNamespacePresence(input) {
63
- const { contract, schema } = input;
64
- const existing = new Set(existingSchemasFromSchema(schema));
65
- const issues = [];
66
- const namespaceIds = Object.keys(contract.storage.namespaces).sort();
67
- for (const namespaceId of namespaceIds) {
68
- if (namespaceId === UNBOUND_NAMESPACE_ID) continue;
69
- const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);
70
- if (ddlName === UNBOUND_NAMESPACE_ID) continue;
71
- if (existing.has(ddlName)) continue;
72
- issues.push({
73
- kind: "missing_schema",
74
- namespaceId,
75
- message: `Schema "${ddlName}" is missing from database`
76
- });
77
- }
78
- return issues;
79
- }
80
- //#endregion
81
- //#region src/core/migrations/planner.ts
82
- function createPostgresMigrationPlanner() {
83
- return new PostgresMigrationPlanner();
84
- }
85
- /**
86
- * Postgres migration planner — a thin wrapper over `planIssues`.
87
- *
88
- * `plan()` verifies the live schema against the target contract (producing
89
- * `SchemaIssue[]`) and delegates to `planIssues` with the unified
90
- * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,
91
- * type-change, nullable-tightening, codec-hook storage types,
92
- * component-declared dependency installs, and shared-temp-default /
93
- * empty-table-guarded NOT-NULL add-column. The same strategy list runs for
94
- * `migration plan`, `db update`, and `db init`; behavior diverges purely on
95
- * `policy.allowedOperationClasses` (the data-safe strategies short-circuit
96
- * when `'data'` is excluded). The issue planner applies operation-class
97
- * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both
98
- * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`
99
- * authoring surface.
100
- */
101
- var PostgresMigrationPlanner = class {
102
- plan(options) {
103
- return this.planSql(options);
104
- }
105
- emptyMigration(context, spaceId) {
106
- return new TypeScriptRenderablePostgresMigration([], {
107
- from: context.fromHash,
108
- to: context.toHash
109
- }, spaceId);
110
- }
111
- planSql(options) {
112
- const schemaName = options.schemaName ?? Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ?? UNBOUND_NAMESPACE_ID;
113
- const policyResult = this.ensureAdditivePolicy(options.policy);
114
- if (policyResult) return policyResult;
115
- const schemaIssues = this.collectSchemaIssues(options);
116
- const codecHooks = extractCodecControlHooks(options.frameworkComponents);
117
- const storageTypes = options.contract.storage.types ?? {};
118
- const result = planIssues({
119
- issues: schemaIssues,
120
- toContract: options.contract,
121
- fromContract: options.fromContract,
122
- schemaName,
123
- codecHooks,
124
- storageTypes,
125
- schema: options.schema,
126
- policy: options.policy,
127
- frameworkComponents: options.frameworkComponents,
128
- strategies: postgresPlannerStrategies
129
- });
130
- if (!result.ok) return plannerFailure(result.failure);
131
- const fieldEventOps = planFieldEventOperations({
132
- priorContract: options.fromContract,
133
- newContract: options.contract,
134
- codecHooks
135
- });
136
- const calls = [...result.value.calls, ...fieldEventOps];
137
- return Object.freeze({
138
- kind: "success",
139
- plan: new TypeScriptRenderablePostgresMigration(calls, {
140
- from: options.fromContract?.storage.storageHash ?? null,
141
- to: options.contract.storage.storageHash
142
- }, options.spaceId)
143
- });
144
- }
145
- ensureAdditivePolicy(policy) {
146
- if (!policy.allowedOperationClasses.includes("additive")) return plannerFailure([{
147
- kind: "unsupportedOperation",
148
- summary: "Migration planner requires additive operations be allowed",
149
- why: "The planner requires the \"additive\" operation class to be allowed in the policy."
150
- }]);
151
- return null;
152
- }
153
- collectSchemaIssues(options) {
154
- const allowed = options.policy.allowedOperationClasses;
155
- const strict = allowed.includes("widening") || allowed.includes("destructive");
156
- const verifyResult = verifySqlSchema({
157
- contract: options.contract,
158
- schema: options.schema,
159
- strict,
160
- typeMetadataRegistry: /* @__PURE__ */ new Map(),
161
- frameworkComponents: options.frameworkComponents,
162
- normalizeDefault: parsePostgresDefault,
163
- normalizeNativeType: normalizeSchemaNativeType,
164
- resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage)
165
- });
166
- const namespaceIssues = verifyPostgresNamespacePresence({
167
- contract: options.contract,
168
- schema: options.schema
169
- });
170
- if (namespaceIssues.length === 0) return verifyResult.schema.issues;
171
- return [...namespaceIssues, ...verifyResult.schema.issues];
172
- }
173
- };
174
- //#endregion
175
- export { createPostgresMigrationPlanner as t };
176
-
177
- //# sourceMappingURL=planner-Bjz5pnLa.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-Bjz5pnLa.mjs","names":[],"sources":["../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the Postgres-flavoured\n * annotations slot on the schema IR. Defaults to the always-present\n * `public` schema when introspection did not populate the slot — a fresh\n * Postgres database always carries `public` (unless an operator dropped\n * it manually), so any verifier path that runs without an enriched\n * introspection still suppresses the redundant `CREATE SCHEMA \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and writes every\n * non-system schema into `annotations.pg.existingSchemas`. Tests that\n * want to assert against a richer initial state pass the slot\n * explicitly via the schema IR.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIR): readonly string[] {\n const annotations = (schema as { annotations?: { pg?: { existingSchemas?: unknown } } })\n .annotations;\n const slot = annotations?.pg?.existingSchemas;\n if (Array.isArray(slot)) {\n return slot.filter((s): s is string => typeof s === 'string');\n }\n return ['public'];\n}\n\n/**\n * Emits a `missing_schema` issue for every contract-declared Postgres\n * namespace whose live container does not yet exist.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue stamps `namespaceId` with the contract namespace\n * coordinate so the downstream `mapIssueToCall` re-resolves the DDL\n * schema name through the same polymorphic path — keeping the\n * coordinate, not the resolved name, as the issue's stable identity.\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIR;\n}): readonly SchemaIssue[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaIssue[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n issues.push({\n kind: 'missing_schema',\n namespaceId,\n message: `Schema \"${ddlName}\" is missing from database`,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { createResolveExistingEnumValues } from './enum-planning';\nimport { planIssues } from './issue-planner';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner();\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec-emitted calls already conform to `OpFactoryCall` — render +\n // toOp + importRequirements ride directly through the same emit path\n // as structural ops, no `RawSqlCall` wrap.\n const calls = [...result.value.calls, ...fieldEventOps];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n ),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage),\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n // Schema presence is a Postgres-specific concern (no equivalent in\n // SQLite / Mongo), so the issue emission lives in the target layer\n // rather than in the family verifier. Stitch it in here so a single\n // `SchemaIssue[]` flows through `planIssues` and the planner emits\n // CREATE SCHEMA in the dep bucket before any CreateTableCall.\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n if (namespaceIssues.length === 0) {\n return verifyResult.schema.issues;\n }\n return [...namespaceIssues, ...verifyResult.schema.issues];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,SAAS,qBAAqB,SAAqB,aAA6B;CAC9E,MAAM,YAAY,QAAQ,WAAW;CACrC,IAAI,iBAAiB,SAAS,GAC5B,OAAO,UAAU,cAAc,OAAO;CAExC,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,SAAS,0BAA0B,QAAwC;CAGzE,MAAM,OAFe,OAClB,aACuB,IAAI;CAC9B,IAAI,MAAM,QAAQ,IAAI,GACpB,OAAO,KAAK,QAAQ,MAAmB,OAAO,MAAM,QAAQ;CAE9D,OAAO,CAAC,QAAQ;AAClB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,gCAAgC,OAGrB;CACzB,MAAM,EAAE,UAAU,WAAW;CAC7B,MAAM,WAAW,IAAI,IAAI,0BAA0B,MAAM,CAAC;CAC1D,MAAM,SAAwB,CAAC;CAC/B,MAAM,eAAe,OAAO,KAAK,SAAS,QAAQ,UAAU,EAAE,KAAK;CACnE,KAAK,MAAM,eAAe,cAAc;EACtC,IAAI,gBAAgB,sBAAsB;EAC1C,MAAM,UAAU,qBAAqB,SAAS,SAAS,WAAW;EAClE,IAAI,YAAY,sBAAsB;EACtC,IAAI,SAAS,IAAI,OAAO,GAAG;EAC3B,OAAO,KAAK;GACV,MAAM;GACN;GACA,SAAS,WAAW,QAAQ;EAC9B,CAAC;CACH;CACA,OA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ACrD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;EACP,CACF,CAAC;EAEH,OAAO;CACT;CAEA,oBAA4B,SAA+D;EAIzF,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,aAAa;EAW7E,MAAM,eAAe,gBAAgB;GATnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,IAAI;GAC9B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACrB,2BAA2B,gCAAgC,QAAQ,SAAS,OAAO;EAEpC,CAAC;EAMlD,MAAM,kBAAkB,gCAAgC;GACtD,UAAU,QAAQ;GAClB,QAAQ,QAAQ;EAClB,CAAC;EACD,IAAI,gBAAgB,WAAW,GAC7B,OAAO,aAAa,OAAO;EAE7B,OAAO,CAAC,GAAG,iBAAiB,GAAG,aAAa,OAAO,MAAM;CAC3D;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-ddl-builders-BNMfSE9r.mjs","names":[],"sources":["../src/core/migrations/planner-ddl-builders.ts"],"sourcesContent":["import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n PostgresEnumStorageEntry,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\nimport type { PostgresColumnDefault } from '../types';\nimport { qualifyTableName } from './planner-sql-checks';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks, storageTypes),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * Pattern for safe PostgreSQL type names.\n * Allows letters, digits, underscores, spaces (for \"double precision\", \"character varying\"),\n * and trailing [] for array types.\n */\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\\\[\\\\])?$/',\n );\n }\n}\n\n/**\n * Sanity check against accidental SQL injection from malformed contract files.\n * Rejects semicolons, SQL comment tokens, and dollar-quoting.\n * Not a comprehensive security boundary — the contract is developer-authored.\n */\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\$\\$|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the SQL type for a column in DDL context.\n *\n * @param allowPseudoTypes - When true (default), autoincrement integer columns\n * produce SERIAL/BIGSERIAL/SMALLSERIAL pseudo-types. Set to false for contexts\n * like ALTER COLUMN TYPE where pseudo-types are invalid.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n allowPseudoTypes = true,\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (allowPseudoTypes) {\n const columnDefault = column.default;\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (resolved.nativeType === 'int4' || resolved.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (resolved.nativeType === 'int8' || resolved.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (resolved.nativeType === 'int2' || resolved.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n }\n\n const expanded = expandParameterizedTypeSql(resolved, codecHooks);\n if (expanded !== null) {\n return expanded;\n }\n\n if (column.typeRef) {\n return quoteIdentifier(resolved.nativeType);\n }\n\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType;\n}\n\nfunction expandParameterizedTypeSql(\n column: Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n if (hooks?.planTypeOperations) {\n return null;\n }\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/** Autoincrement columns use SERIAL types, so this returns empty for them. */\nexport function buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`;\n }\n}\n\nexport function renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nexport function buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n temporaryDefault?: string | null,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (temporaryDefault ? `DEFAULT ${temporaryDefault}` : '');\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nexport function buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.source.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.target.tableName)} (${foreignKey.target.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n"],"mappings":";;;AAcA,SAAgB,oBACd,oBACA,OACA,YACA,eAA+E,CAAC,GACxE;CACR,MAAM,oBAAoB,OAAO,QAAQ,MAAM,OAAO,EAAE,KACrD,CAAC,YAAY,YAAqC;EAOjD,OANc;GACZ,gBAAgB,UAAU;GAC1B,mBAAmB,QAAQ,YAAY,YAAY;GACnD,sBAAsB,OAAO,SAAS,MAAM;GAC5C,OAAO,WAAW,KAAK;EACzB,EAAE,OAAO,OACE,EAAE,KAAK,GAAG;CACvB,CACF;CAEA,MAAM,wBAAkC,CAAC;CACzC,IAAI,MAAM,YACR,sBAAsB,KACpB,gBAAgB,MAAM,WAAW,QAAQ,IAAI,eAAe,EAAE,KAAK,IAAI,EAAE,EAC3E;CAIF,OAAO,gBAAgB,mBAAmB,QAAQ,CAD1B,GAAG,mBAAmB,GAAG,qBACc,EAAE,KAAK,OAAO,EAAE;AACjF;;;;;;AAOA,MAAM,2BAA2B;AAEjC,SAAS,qBAAqB,YAA0B;CACtD,IAAI,CAAC,yBAAyB,KAAK,UAAU,GAC3C,MAAM,IAAI,MACR,yCAAyC,WAAW,qEAEtD;AAEJ;;;;;;AAOA,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AI,eAAe,EAAE,KAAK,IAAI,EAAE;aAC5D,iBAAiB,YAAY,WAAW,OAAO,SAAS,EAAE,IAAI,WAAW,OAAO,QACxF,IAAI,eAAe,EACnB,KAAK,IAAI,EAAE;CAEd,IAAI,WAAW,aAAa,KAAA,GAAW;EACrC,MAAM,SAAS,uBAAuB,WAAW;EACjD,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,4CAA4C,OAAO,WAAW,QAAQ,GAAG;EAE3F,OAAO,eAAe;CACxB;CACA,IAAI,WAAW,aAAa,KAAA,GAAW;EACrC,MAAM,SAAS,uBAAuB,WAAW;EACjD,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,4CAA4C,OAAO,WAAW,QAAQ,GAAG;EAE3F,OAAO,eAAe;CACxB;CAEA,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-produced-postgres-migration-D02NOhVQ.d.mts","names":[],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"mappings":";;;;;;;KAoCK,EAAA,GAAK,yBAAyB,CAAC,yBAAA;AAAA,cAEvB,qCAAA,SACH,iBAAA,YACG,iCAAA;EAAA;cAMC,KAAA,WAAgB,aAAA,IAAiB,IAAA,EAAM,aAAA,EAAe,OAAA;EAAA,IAOrD,UAAA,CAAA,YAAuB,EAAA;EAI3B,QAAA,CAAA,GAAY,aAAA;EAAA;;;;AAaL;EAbK,IASjB,OAAA,CAAA;EAIJ,gBAAA,CAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-sql-checks-CfEiTXoQ.mjs","names":[],"sources":["../src/core/migrations/planner-type-resolution.ts","../src/core/migrations/planner-sql-checks.ts"],"sourcesContent":["import {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n type StorageColumn,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\n\nexport type ResolvedColumnTypeMetadata = Pick<\n StorageColumn,\n 'nativeType' | 'codecId' | 'typeParams'\n>;\n\nexport function resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n return column;\n }\n\n if (isPostgresEnumStorageEntry(referencedType)) {\n // Enum types are referenced by name (`quoteIdentifier(nativeType)`),\n // not via parameterised codec expansion. The structural shape\n // carries `codecId` as an enumerable property (mirroring the\n // codec-typed view); `typeParams` is intentionally omitted here so\n // `expandParameterizedTypeSql` does not try to look up a\n // (deliberately absent) `expandNativeType` hook for `pg/enum@*`.\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n };\n }\n\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n PostgresEnumStorageEntry,\n StorageColumn,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { postgresCreateNamespace } from '../postgres-schema';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\n/**\n * String-keyed entry points the migration ops use to render\n * schema-qualified DDL and catalog checks. The `schema` argument is\n * interpreted as a namespace coordinate: the framework `__unbound__`\n * sentinel resolves to the late-bound `PostgresUnboundSchema` singleton\n * (which elides the qualifier so `search_path` decides at runtime); any\n * other id materialises a `PostgresSchema(id)` whose qualifier is the\n * named schema. Helpers route through these `Namespace` concretions so\n * the unbound branch lives in the polymorphic override, not the call\n * site.\n */\nexport function qualifyTableName(schema: string, table: string): string {\n return postgresCreateNamespace({ id: schema }).qualifyTable(table);\n}\n\nexport function toRegclassLiteral(schema: string, name: string): string {\n return postgresCreateNamespace({ id: schema }).regclassLiteral(name);\n}\n\n/**\n * When `table` is omitted the check matches by name + schema across all tables.\n * Pass `table` to scope the check to a single table (prevents false matches on\n * identically-named constraints in different tables).\n */\nexport function constraintExistsCheck({\n constraintName,\n schema,\n table,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n table?: string;\n exists?: boolean;\n}): string {\n const namespace = postgresCreateNamespace({ id: schema });\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n const tableFilter = table\n ? `AND c.conrelid = to_regclass(${namespace.regclassLiteral(table)})`\n : '';\n return `SELECT ${existsClause} (\n SELECT 1 FROM pg_constraint c\n JOIN pg_namespace n ON c.connamespace = n.oid\n WHERE c.conname = '${escapeLiteral(constraintName)}'\n AND n.nspname = ${namespace.schemaSqlExpression()}\n ${tableFilter}\n)`;\n}\n\nexport function columnExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const namespace = postgresCreateNamespace({ id: schema });\n const existsClause = exists ? '' : 'NOT ';\n return `SELECT ${existsClause}EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = ${namespace.schemaSqlExpression()}\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n)`;\n}\n\nexport function columnNullabilityCheck({\n schema,\n table,\n column,\n nullable,\n}: {\n schema: string;\n table: string;\n column: string;\n nullable: boolean;\n}): string {\n const namespace = postgresCreateNamespace({ id: schema });\n const expected = nullable ? 'YES' : 'NO';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = ${namespace.schemaSqlExpression()}\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND is_nullable = '${expected}'\n)`;\n}\n\nexport function tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nexport function columnHasNoDefaultCheck(opts: {\n schema: string;\n table: string;\n column: string;\n}): string {\n const namespace = postgresCreateNamespace({ id: opts.schema });\n return `SELECT NOT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = ${namespace.schemaSqlExpression()}\n AND table_name = '${escapeLiteral(opts.table)}'\n AND column_name = '${escapeLiteral(opts.column)}'\n AND column_default IS NOT NULL\n)`;\n}\n\nconst FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string> = new Map([\n ['int2', 'smallint'],\n ['int4', 'integer'],\n ['int8', 'bigint'],\n ['float4', 'real'],\n ['float8', 'double precision'],\n ['bool', 'boolean'],\n ['timestamp', 'timestamp without time zone'],\n ['timestamptz', 'timestamp with time zone'],\n ['time', 'time without time zone'],\n ['timetz', 'time with time zone'],\n]);\n\nconst UNQUOTED_POSTGRES_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/;\n\nconst POSTGRES_RESERVED_IDENTIFIER_WORDS = new Set([\n 'all',\n 'analyse',\n 'analyze',\n 'and',\n 'any',\n 'array',\n 'as',\n 'asc',\n 'asymmetric',\n 'authorization',\n 'between',\n 'binary',\n 'both',\n 'case',\n 'cast',\n 'check',\n 'collate',\n 'column',\n 'constraint',\n 'create',\n 'current_catalog',\n 'current_date',\n 'current_role',\n 'current_time',\n 'current_timestamp',\n 'current_user',\n 'default',\n 'deferrable',\n 'desc',\n 'distinct',\n 'do',\n 'else',\n 'end',\n 'except',\n 'false',\n 'fetch',\n 'for',\n 'foreign',\n 'freeze',\n 'from',\n 'full',\n 'grant',\n 'group',\n 'having',\n 'ilike',\n 'in',\n 'initially',\n 'inner',\n 'intersect',\n 'into',\n 'is',\n 'isnull',\n 'join',\n 'lateral',\n 'leading',\n 'left',\n 'like',\n 'limit',\n 'localtime',\n 'localtimestamp',\n 'natural',\n 'not',\n 'notnull',\n 'null',\n 'offset',\n 'on',\n 'only',\n 'or',\n 'order',\n 'outer',\n 'overlaps',\n 'placing',\n 'primary',\n 'references',\n 'right',\n 'select',\n 'session_user',\n 'similar',\n 'some',\n 'symmetric',\n 'table',\n 'then',\n 'to',\n 'trailing',\n 'true',\n 'union',\n 'unique',\n 'user',\n 'using',\n 'variadic',\n 'verbose',\n 'when',\n 'where',\n 'window',\n 'with',\n]);\n\nfunction formatUserDefinedTypeName(identifier: string): string {\n if (\n UNQUOTED_POSTGRES_IDENTIFIER_PATTERN.test(identifier) &&\n !POSTGRES_RESERVED_IDENTIFIER_WORDS.has(identifier)\n ) {\n return identifier;\n }\n\n return quoteIdentifier(identifier);\n}\n\nexport function buildExpectedFormatType(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (resolved.typeParams && resolved.codecId) {\n const hooks = codecHooks.get(resolved.codecId);\n if (hooks?.expandNativeType) {\n return hooks.expandNativeType({\n nativeType: resolved.nativeType,\n codecId: resolved.codecId,\n typeParams: resolved.typeParams,\n });\n }\n }\n\n if (column.typeRef) {\n return formatUserDefinedTypeName(resolved.nativeType);\n }\n\n return FORMAT_TYPE_DISPLAY.get(resolved.nativeType) ?? resolved.nativeType;\n}\n\nexport function columnTypeCheck({\n schema,\n table,\n column,\n expectedType,\n}: {\n schema: string;\n table: string;\n column: string;\n expectedType: string;\n}): string {\n const namespace = postgresCreateNamespace({ id: schema });\n return `SELECT EXISTS (\n SELECT 1\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${namespace.schemaSqlExpression()}\n AND c.relname = '${escapeLiteral(table)}'\n AND a.attname = '${escapeLiteral(column)}'\n AND format_type(a.atttypid, a.atttypmod) = '${escapeLiteral(expectedType)}'\n AND NOT a.attisdropped\n)`;\n}\n\nexport function columnDefaultExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const namespace = postgresCreateNamespace({ id: schema });\n const nullCheck = exists ? 'IS NOT NULL' : 'IS NULL';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = ${namespace.schemaSqlExpression()}\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND column_default ${nullCheck}\n)`;\n}\n\nexport function tableHasPrimaryKeyCheck(\n schema: string,\n table: string,\n exists: boolean,\n constraintName?: string,\n): string {\n const namespace = postgresCreateNamespace({ id: schema });\n const comparison = exists ? '' : 'NOT ';\n const constraintFilter = constraintName\n ? `AND c2.relname = '${escapeLiteral(constraintName)}'`\n : '';\n return `SELECT ${comparison}EXISTS (\n SELECT 1\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n WHERE n.nspname = ${namespace.schemaSqlExpression()}\n AND c.relname = '${escapeLiteral(table)}'\n AND i.indisprimary\n ${constraintFilter}\n)`;\n}\n"],"mappings":";;;;AAYA,SAAgB,0BACd,QACA,cAC4B;CAC5B,IAAI,CAAC,OAAO,SACV,OAAO;CAGT,MAAM,iBAAiB,aAAa,OAAO;CAC3C,IAAI,CAAC,gBACH,OAAO;CAGT,IAAI,2BAA2B,cAAc,GAO3C,OAAO;EACL,SAAS,eAAe;EACxB,YAAY,eAAe;CAC7B;CAGF,OAAO;EACL,SAAS,eAAe;EACxB,YAAY,eAAe;EAC3B,YAAY,eAAe;CAC7B;AACF;;;;;;;;;;;;;;ACtBA,SAAgB,iBAAiB,QAAgB,OAAuB;CACtE,OAAO,wBAAwB,EAAE,IAAI,OAAO,CAAC,EAAE,aAAa,KAAK;AACnE;AAEA,SAAgB,kBAAkB,QAAgB,MAAsB;CACtE,OAAO,wBAAwB,EAAE,IAAI,OAAO,CAAC,EAAE,gBAAgB,IAAI;AACrE;;;;;;AAOA,SAAgB,sBAAsB,EACpC,gBACA,QACA,OACA,SAAS,QAMA;CACT,MAAM,YAAY,wBAAwB,EAAE,IAAI,OAAO,CAAC;CACxD,MAAM,eAAe,SAAS,WAAW;CACzC,MAAM,cAAc,Q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;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,0BAA0B,YAA4B;CAC7D,IACE,qCAAqC,KAAK,UAAU,KACpD,CAAC,mCAAmC,IAAI,UAAU,GAElD,OAAO;CAGT,OAAO,gBAAgB,UAAU;AACnC;AAEA,SAAgB,wBACd,QACA,YACA,eAA+E,CAAC,GACxE;CACR,MAAM,WAAW,0BAA0B,QAAQ,YAAY;CAE/D,IAAI,SAAS,cAAc,SAAS,SAAS;EAC3C,MAAM,QAAQ,WAAW,IAAI,SAAS,OAAO;EAC7C,IAAI,OAAO,kBACT,OAAO,MAAM,iBAAiB;GAC5B,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,YAAY,SAAS;EACvB,CAAC;CAEL;CAEA,IAAI,OAAO,SACT,OAAO,0BAA0B,SAAS,UAAU;CAGtD,OAAO,oBAAoB,IAAI,SAAS,UAAU,KAAK,SAAS;AAClE;AAEA,SAAgB,gBAAgB,EAC9B,QACA,OACA,QACA,gBAMS;CAET,OAAO;;;;;sBADW,wBAAwB,EAAE,IAAI,OAAO,CAM3B,EAAE,oBAAoB,EAAE;uBAC/B,cAAc,KAAK,EAAE;uBACrB,cAAc,MAAM,EAAE;kDACK,cAAc,YAAY,EAAE;;;AAG9E;AAEA,SAAgB,yBAAyB,EACvC,QACA,OACA,QACA,SAAS,QAMA;CACT,MAAM,YAAY,wBAAwB,EAAE,IAAI,OAAO,CAAC;CACxD,MAAM,YAAY,SAAS,gBAAgB;CAC3C,OAAO;;;yBAGgB,UAAU,oBAAoB,EAAE;wBACjC,cAAc,KAAK,EAAE;yBACpB,cAAc,MAAM,EAAE;yBACtB,UAAU;;AAEnC;AAEA,SAAgB,wBACd,QACA,OACA,QACA,gBACQ;CACR,MAAM,YAAY,wBAAwB,EAAE,IAAI,OAAO,CAAC;CACxD,MAAM,aAAa,SAAS,KAAK;CACjC,MAAM,mBAAmB,iBACrB,qBAAqB,cAAc,cAAc,EAAE,KACnD;CACJ,OAAO,UAAU,WAAW;;;;;;sBAMR,UAAU,oBAAoB,EAAE;uBAC/B,cAAc,KAAK,EAAE;;MAEtC,iBAAiB;;AAEvB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-contract-serializer-BnOboPWs.mjs","names":[],"sources":["../src/core/postgres-contract-serializer.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n SqlContractSerializerBase,\n type SqlEntityHydrationFactory,\n} from '@prisma-next/family-sql/ir';\nimport {\n type AuthoringEntityContext,\n type AuthoringEntityTypeFactoryOutput,\n type AuthoringEntityTypeNamespace,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport {\n type Namespace,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type {\n SqlNamespaceTablesInput,\n SqlStorage,\n SqlStorageTypeEntry,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport type { Type } from 'arktype';\nimport { postgresAuthoringEntityTypes } from './authoring';\nimport type { PostgresEnumType } from './postgres-enum-type';\nimport { isPostgresSchema, PostgresSchema } from './postgres-schema';\n\nconst POSTGRES_AUTHORING_CTX: AuthoringEntityContext = {\n family: 'sql',\n target: 'postgres',\n};\n\nfunction isAuthoringEntityTypeFactoryOutput(\n output: unknown,\n): output is AuthoringEntityTypeFactoryOutput<unknown, unknown> {\n return (\n typeof output === 'object' &&\n output !== null &&\n typeof (output as AuthoringEntityTypeFactoryOutput).factory === 'function'\n );\n}\n\n/**\n * Walks a pack's entity-type namespace tree and emits the maps the\n * family base consumes — hydrators and validator-schema fragments, both\n * keyed by the descriptor's `discriminator`.\n */\nfunction collectEntityRegistryContributions(namespace: AuthoringEntityTypeNamespace): {\n readonly entityTypeRegistry: ReadonlyMap<string, SqlEntityHydrationFactory>;\n readonly validatorFragments: ReadonlyMap<string, Type<unknown>>;\n} {\n const entityTypeRegistry = new Map<string, SqlEntityHydrationFactory>();\n const validatorFragments = new Map<string, Type<unknown>>();\n const walk = (node: AuthoringEntityTypeNamespace): void => {\n for (const value of Object.values(node)) {\n if (isAuthoringEntityTypeDescriptor(value)) {\n if (isAuthoringEntityTypeFactoryOutput(value.output)) {\n const { factory } = value.output;\n entityTypeRegistry.set(\n value.discriminator,\n (raw) => factory(raw, POSTGRES_AUTHORING_CTX) as SqlStorageTypeEntry,\n );\n }\n if (value.validatorSchema !== undefined) {\n validatorFragments.set(value.discriminator, value.validatorSchema);\n }\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n walk(value);\n }\n }\n };\n walk(namespace);\n return { entityTypeRegistry, validatorFragments };\n}\n\nexport class PostgresContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor() {\n const { entityTypeRegistry, validatorFragments } = collectEntityRegistryContributions(\n postgresAuthoringEntityTypes,\n );\n super(entityTypeRegistry, validatorFragments);\n }\n\n protected override hydrateSqlNamespaceEntry(\n nsId: string,\n raw: Namespace | Record<string, unknown>,\n ): Namespace | SqlNamespaceTablesInput {\n if (raw instanceof NamespaceBase) {\n return raw;\n }\n const hydrated = super.hydrateSqlNamespaceEntry(nsId, raw) as {\n id: string;\n tables: Readonly<Record<string, StorageTable>>;\n enum?: Readonly<Record<string, PostgresEnumType>>;\n };\n const { id, tables, enum: hydratedNsEnums } = hydrated;\n\n const emptyTables = Object.keys(tables).length === 0;\n const emptyEnums = !hydratedNsEnums || Object.keys(hydratedNsEnums).length === 0;\n if (id === UNBOUND_NAMESPACE_ID && emptyTables && emptyEnums) {\n return PostgresSchema.unbound;\n }\n return new PostgresSchema({\n id,\n tables,\n ...(hydratedNsEnums !== undefined ? { enum: hydratedNsEnums } : {}),\n });\n }\n\n override serializeContract(contract: Contract<SqlStorage>): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n if (isPostgresSchema(ns)) {\n namespacesJson[nsId] = this.serializePostgresNamespace(ns, ns.id === UNBOUND_NAMESPACE_ID);\n } else {\n // Family-level SqlUnboundNamespace or other family-built SQL\n // namespaces haven't been promoted to a PostgresSchema instance\n // yet (e.g. they came straight from the TS builder before a target\n // `createNamespace` factory ran). Serialise them as postgres-schema /\n // postgres-unbound-schema so the round-trip through\n // deserializeContract hydrates them back into PostgresSchema\n // instances.\n const isUnboundSlot = nsId === UNBOUND_NAMESPACE_ID;\n const nsEnums = (ns as { readonly enum?: Readonly<Record<string, unknown>> }).enum ?? {};\n namespacesJson[nsId] = {\n id: nsId,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n tables: Object.fromEntries(\n Object.entries(ns.tables).map(([tableName, table]) => [\n tableName,\n this.serializeJsonValue(table) as JsonObject,\n ]),\n ),\n enum: Object.fromEntries(\n Object.entries(nsEnums).map(([typeName, entry]) => [\n typeName,\n this.serializeJsonValue(entry) as JsonObject,\n ]),\n ),\n };\n }\n }\n const storageOut: Record<string, unknown> = {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n };\n if (storage.types !== undefined) {\n const typesOut: Record<string, JsonObject> = {};\n for (const [name, entry] of Object.entries(storage.types)) {\n typesOut[name] = this.serializeJsonValue(entry) as JsonObject;\n }\n storageOut['types'] = typesOut;\n }\n return {\n ...rest,\n storage: storageOut,\n } as unknown as JsonObject;\n }\n\n private serializePostgresNamespace(ns: PostgresSchema, isUnboundSlot: boolean): JsonObject {\n const tablesOut: Record<string, JsonObject> = {};\n for (const [tableName, table] of Object.entries(ns.tables)) {\n tablesOut[tableName] = this.serializeJsonValue(table) as JsonObject;\n }\n const enumOut: Record<string, JsonObject> = {};\n for (const [typeName, ty] of Object.entries(ns.enum)) {\n enumOut[typeName] = this.serializeJsonValue(ty) as JsonObject;\n }\n return {\n id: ns.id,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n tables: tablesOut,\n enum: enumOut,\n };\n }\n\n private serializeJsonValue(value: unknown): unknown {\n return JSON.parse(JSON.stringify(value)) as unknown;\n }\n}\n"],"mappings":";;;;;;AA4BA,MAAM,yBAAiD;CACrD,QAAQ;CACR,QAAQ;AACV;AAEA,SAAS,mCACP,QAC8D;CAC9D,OACE,OAAO,WAAW,YAClB,WAAW,QACX,OAAQ,OAA4C,YAAY;AAEpE;;;;;;AAOA,SAAS,mCAAmC,WAG1C;CACA,MAAM,qCAAqB,IAAI,IAAuC;CACtE,MAAM,qCAAqB,IAAI,IAA2B;CAC1D,MAAM,QAAQ,SAA6C;EACzD,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,GAAG;GACvC,IAAI,gCAAgC,KAAK,GAAG;IAC1C,IAAI,mCAAmC,MAAM,MAAM,GAAG;KACpD,MAAM,EAAE,YAAY,MAAM;KAC1B,mBAAmB,IACjB,MAAM,gBACL,QAAQ,QAAQ,KAAK,sBAAsB,CAC9C;IACF;IACA,IAAI,MAAM,oBAAoB,KAAA,GAC5B,mBAAmB,IAAI,MAAM,eAAe,MAAM,eAAe;IAEnE;GACF;GACA,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,KAAK,KAAK;EAEd;CACF;CACA,KAAK,SAAS;CACd,OAAO;EAAE;EAAoB;CAAmB;AAClD;AAEA,IAAa,6BAAb,cAAgD,0BAAgD;CAC9F,cAAc;EACZ,MA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GAC9C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,KAAK,GACtD,SAAS,QAAQ,KAAK,mBAAmB,KAAK;GAEhD,WAAW,WAAW;EACxB;EACA,OAAO;GACL,GAAG;GACH,SAAS;EACX;CACF;CAEA,2BAAmC,IAAoB,eAAoC;EACzF,MAAM,YAAwC,CAAC;EAC/C,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,GAAG,MAAM,GACvD,UAAU,aAAa,KAAK,mBAAmB,KAAK;EAEtD,MAAM,UAAsC,CAAC;EAC7C,KAAK,MAAM,CAAC,UAAU,OAAO,OAAO,QAAQ,GAAG,IAAI,GACjD,QAAQ,YAAY,KAAK,mBAAmB,EAAE;EAEhD,OAAO;GACL,IAAI,GAAG;GACP,MAAM,gBAAgB,4BAA4B;GAClD,QAAQ;GACR,MAAM;EACR;CACF;CAEA,mBAA2B,OAAyB;EAClD,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;CACzC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-schema-BxAuNFX0.mjs","names":[],"sources":["../src/core/postgres-schema.ts"],"sourcesContent":["import {\n freezeNode,\n NamespaceBase,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport {\n type SqlNamespaceTablesInput,\n type SqlStorage,\n StorageTable,\n type StorageTableInput,\n} from '@prisma-next/sql-contract/types';\nimport { PostgresEnumType, type PostgresEnumTypeInput } from './postgres-enum-type';\nimport { escapeLiteral } from './sql-utils';\n\nexport interface PostgresSchemaInput {\n readonly id: string;\n readonly tables?: Record<string, StorageTable | StorageTableInput>;\n readonly enum?: Record<string, PostgresEnumType | PostgresEnumTypeInput>;\n}\n\n/**\n * Postgres target `Namespace` concretion — a Postgres schema (`CREATE\n * SCHEMA …`). Each Postgres `SqlStorage` carries a\n * `namespaces: Record<NamespaceId, PostgresSchema>` map populated by\n * the Postgres PSL interpreter from `namespace { … }` AST buckets.\n *\n * Qualifier emission is the rendering seam: DDL / SQL emission asks the\n * namespace for its qualifier (`\"<schema>\"`) or for a qualified table\n * name (`\"<schema>\".\"<table>\"`) and consumes the result polymorphically.\n * The unbound singleton below overrides these methods to elide the\n * prefix entirely — call sites stay polymorphic and never branch on\n * `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class PostgresSchema extends NamespaceBase {\n /**\n * Stable singleton reference for the late-bound slot. Materialised\n * lazily below the singleton subclass declaration so the static\n * initialiser sees the subclass before assigning. Consumers always\n * reach for `PostgresSchema.unbound` (or `PostgresUnboundSchema.instance`\n * — same identity).\n */\n static unbound: PostgresUnboundSchema;\n\n declare readonly kind: 'schema';\n readonly id: string;\n readonly tables: Readonly<Record<string, StorageTable>>;\n readonly enum: Readonly<Record<string, PostgresEnumType>>;\n\n constructor(input: PostgresSchemaInput) {\n super();\n this.id = input.id;\n this.tables = Object.freeze(\n Object.fromEntries(\n Object.entries(input.tables ?? {}).map(([name, t]) => [\n name,\n t instanceof StorageTable ? t : new StorageTable(t),\n ]),\n ),\n );\n this.enum = Object.freeze(\n Object.fromEntries(\n Object.entries(input.enum ?? {}).map(([name, ty]) => [\n name,\n ty instanceof PostgresEnumType ? ty : new PostgresEnumType(ty),\n ]),\n ),\n );\n Object.defineProperty(this, 'kind', {\n value: 'schema',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n /**\n * The bare schema qualifier as it would appear in a rendered SQL\n * fragment (already quoted). The unbound-schema singleton overrides\n * this to return `''`.\n */\n qualifier(): string {\n return `\"${this.id}\"`;\n }\n\n /**\n * Qualify a table name with the schema prefix\n * (`\"<schema>\".\"<table>\"`). The unbound-schema singleton overrides\n * this to emit just `\"<table>\"` so the resolved DDL is unqualified\n * and `search_path` decides where the object lands at runtime.\n */\n qualifyTable(tableName: string): string {\n return `\"${this.id}\".\"${tableName}\"`;\n }\n\n /**\n * Render a SQL string-literal containing the qualified-name form\n * suitable for `to_regclass(...)` arguments (e.g. `'\"public\".\"user\"'`).\n * The unbound singleton overrides this to elide the schema prefix\n * (`'\"user\"'`) so `search_path` resolves the object at runtime.\n */\n regclassLiteral(name: string): string {\n return `'${escapeLiteral(this.qualifyTable(name))}'`;\n }\n\n /**\n * Render a SQL expression that evaluates to this namespace's schema\n * name at runtime, ready to drop into a `WHERE table_schema = …` /\n * `WHERE n.nspname = …` clause. Named schemas emit a quoted SQL\n * literal (`'public'`); the unbound singleton overrides this to emit\n * `current_schema()` so catalog queries match whichever schema the\n * connection's `search_path` resolved at runtime.\n */\n schemaSqlExpression(): string {\n return `'${escapeLiteral(this.id)}'`;\n }\n\n /**\n * The bare schema name a DDL planner should target when emitting\n * statements that need to identify this namespace in the live\n * database (e.g. `CREATE TABLE \"<ddlSchemaName>\".\"<table>\" …`,\n * catalog filters, planner conflict lookups). Named schemas resolve\n * to their own id. The `PostgresUnboundSchema` singleton inherits\n * this and returns `UNBOUND_NAMESPACE_ID` — callers that dispatch\n * through `qualifyTableName` / `toRegclassLiteral` route through the\n * polymorphic `PostgresUnboundSchema` overrides and produce\n * unqualified (search-path-resolved) output automatically.\n */\n ddlSchemaName(_storage: SqlStorage): string {\n return this.id;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound Postgres slot whose binding\n * the connection's `search_path` resolves at runtime. Overrides\n * qualifier emission to elide the schema prefix; call sites that consume\n * `qualifier()` / `qualifyTable()` get unqualified output without\n * branching on the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Postgres decides what late-bound means here (the table\n * name, naked — the schema is supplied by the live connection's\n * `search_path`).\n *\n * `ddlSchemaName` is inherited from `PostgresSchema` and returns\n * `UNBOUND_NAMESPACE_ID`. Downstream helpers (`qualifyTableName`,\n * `toRegclassLiteral`) route through the polymorphic factory and\n * produce unqualified output automatically.\n */\nexport class PostgresUnboundSchema extends PostgresSchema {\n static readonly instance: PostgresUnboundSchema = new PostgresUnboundSchema();\n\n constructor(input?: PostgresSchemaInput) {\n super(input ?? { id: UNBOUND_NAMESPACE_ID });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n\n override schemaSqlExpression(): string {\n return 'current_schema()';\n }\n}\n\nPostgresSchema.unbound = PostgresUnboundSchema.instance;\n\n/**\n * Narrow an arbitrary namespace (or `undefined`) to `PostgresSchema`\n * so callers can dispatch to the polymorphic emission methods without\n * branching at the call site. Uses the structural `kind` discriminator\n * (`'schema'`) rather than `instanceof` so the check survives realm /\n * bundle / hot-reload boundaries — matching the rest of the IR's\n * narrowing convention. `PostgresUnboundSchema` passes through because\n * it inherits the same `kind: 'schema'` from `PostgresSchema`.\n */\nexport function isPostgresSchema(ns: unknown): ns is PostgresSchema {\n return (ns as { kind?: unknown } | null | undefined)?.kind === 'schema';\n}\n\n/**\n * Target-supplied `Namespace` factory the Postgres target plumbs\n * through `defineContract({ createNamespace })` and the SQL PSL\n * interpreter. Returns the unbound singleton for the framework\n * sentinel and a fresh `PostgresSchema` for any other coordinate.\n *\n * The factory has no per-call state — every named id deterministically\n * maps to a distinct schema instance — so callers can pass it through\n * by reference and trust the resulting `SqlStorage.namespaces` map to\n * be value-stable for a given input set.\n */\nexport function postgresCreateNamespace(input: SqlNamespaceTablesInput): PostgresSchema {\n if (input.id === UNBOUND_NAMESPACE_ID) {\n return new PostgresUnboundSchema(input);\n }\n return new PostgresSchema(input);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiCA,IAAa,iBAAb,cAAoC,cAAc;;;;;;;;CAQhD,OAAO;CAGP;CACA;CACA;CAEA,YAAY,OAA4B;EACtC,MAAM;EACN,KAAK,KAAK,MAAM;EAChB,KAAK,SAAS,OAAO,OACnB,OAAO,YACL,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,OAAO,CACpD,MACA,aAAa,eAAe,IAAI,IAAI,aAAa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_SPACE_ID as APP_SPACE_ID$1 } from "@prisma-next/framework-components/control";
2
- //#region src/core/migrations/statement-builders.ts
3
- const ensurePrismaContractSchemaStatement = {
4
- sql: "create schema if not exists prisma_contract",
5
- params: []
6
- };
7
- /**
8
- * Schema for `prisma_contract.marker`. The `space text` primary key
9
- * supports one row per loaded contract space (`'app'`,
10
- * `'<extension-id>'`, …); on a brand-new database `CREATE TABLE IF NOT
11
- * EXISTS` produces this shape directly. The migration runner detects
12
- * pre-1.0 single-row markers (no `space` column) at boot and fails with
13
- * a structured `LEGACY_MARKER_SHAPE` error rather than auto-migrating —
14
- * see `specs/framework-mechanism.spec.md § 2`.
15
- */
16
- const ensureMarkerTableStatement = {
17
- sql: `create table if not exists prisma_contract.marker (
18
- space text not null primary key default '${APP_SPACE_ID$1}',
19
- core_hash text not null,
20
- profile_hash text not null,
21
- contract_json jsonb,
22
- canonical_version int,
23
- updated_at timestamptz not null default now(),
24
- app_tag text,
25
- meta jsonb not null default '{}',
26
- invariants text[] not null default '{}'
27
- )`,
28
- params: []
29
- };
30
- const ensureLedgerTableStatement = {
31
- sql: `create table if not exists prisma_contract.ledger (
32
- id bigserial primary key,
33
- created_at timestamptz not null default now(),
34
- origin_core_hash text,
35
- origin_profile_hash text,
36
- destination_core_hash text not null,
37
- destination_profile_hash text,
38
- contract_json_before jsonb,
39
- contract_json_after jsonb,
40
- operations jsonb not null
41
- )`,
42
- params: []
43
- };
44
- function buildMergeMarkerStatements(input) {
45
- const params = [
46
- input.space,
47
- input.storageHash,
48
- input.profileHash,
49
- jsonParam(input.contractJson),
50
- input.canonicalVersion ?? null,
51
- input.appTag ?? null,
52
- jsonParam(input.meta ?? {}),
53
- input.invariants
54
- ];
55
- return {
56
- insert: {
57
- sql: `insert into prisma_contract.marker (
58
- space,
59
- core_hash,
60
- profile_hash,
61
- contract_json,
62
- canonical_version,
63
- updated_at,
64
- app_tag,
65
- meta,
66
- invariants
67
- ) values (
68
- $1,
69
- $2,
70
- $3,
71
- $4::jsonb,
72
- $5,
73
- now(),
74
- $6,
75
- $7::jsonb,
76
- $8::text[]
77
- )`,
78
- params
79
- },
80
- update: {
81
- sql: `update prisma_contract.marker set
82
- core_hash = $2,
83
- profile_hash = $3,
84
- contract_json = $4::jsonb,
85
- canonical_version = $5,
86
- updated_at = now(),
87
- app_tag = $6,
88
- meta = $7::jsonb,
89
- invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)
90
- where space = $1`,
91
- params
92
- }
93
- };
94
- }
95
- function buildLedgerInsertStatement(input) {
96
- return {
97
- sql: `insert into prisma_contract.ledger (
98
- origin_core_hash,
99
- origin_profile_hash,
100
- destination_core_hash,
101
- destination_profile_hash,
102
- contract_json_before,
103
- contract_json_after,
104
- operations
105
- ) values (
106
- $1,
107
- $2,
108
- $3,
109
- $4,
110
- $5::jsonb,
111
- $6::jsonb,
112
- $7::jsonb
113
- )`,
114
- params: [
115
- input.originStorageHash ?? null,
116
- input.originProfileHash ?? null,
117
- input.destinationStorageHash,
118
- input.destinationProfileHash ?? null,
119
- jsonParam(input.contractJsonBefore),
120
- jsonParam(input.contractJsonAfter),
121
- jsonParam(input.operations)
122
- ]
123
- };
124
- }
125
- function jsonParam(value) {
126
- return JSON.stringify(value ?? null);
127
- }
128
- //#endregion
129
- export { ensureMarkerTableStatement as a, ensureLedgerTableStatement as i, buildLedgerInsertStatement as n, ensurePrismaContractSchemaStatement as o, buildMergeMarkerStatements as r, APP_SPACE_ID$1 as t };
130
-
131
- //# sourceMappingURL=statement-builders-DVI5IVAa.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"statement-builders-DVI5IVAa.mjs","names":["APP_SPACE_ID"],"sources":["../src/core/migrations/statement-builders.ts"],"sourcesContent":["import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\n\nexport { APP_SPACE_ID };\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); on a brand-new database `CREATE TABLE IF NOT\n * EXISTS` produces this shape directly. The migration runner detects\n * pre-1.0 single-row markers (no `space` column) at boot and fails with\n * a structured `LEGACY_MARKER_SHAPE` error rather than auto-migrating —\n * see `specs/framework-mechanism.spec.md § 2`.\n */\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}',\n invariants text[] not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface MergeMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse per-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers (planner / runner / verifier\n * extensions over contract spaces) pass the extension's space id.\n */\n readonly space: string;\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n /**\n * Invariants to merge into `marker.invariants`. INSERT writes them as\n * the initial value (callers are expected to pass a sorted, deduped\n * array). UPDATE merges them with the existing column server-side via\n * a single atomic SQL expression.\n */\n readonly invariants: readonly string[];\n}\n\nexport function buildMergeMarkerStatements(input: MergeMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n input.space,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n input.invariants,\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n space,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb,\n $8::text[]\n )`,\n params,\n },\n update: {\n // `invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)`\n // reads the current column value under the UPDATE's row lock, unions\n // with the incoming array, dedupes, and sorts ascending — single\n // statement, atomic, no read-then-write window.\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb,\n invariants = array(select distinct unnest(invariants || $8::text[]) order by 1)\n where space = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null);\n}\n"],"mappings":";;AASA,MAAa,sCAAoD;CAC/D,KAAK;CACL,QAAQ,CAAC;AACX;;;;;;;;;;AAWA,MAAa,6BAA2C;CACtD,KAAK;+CACwCA,eAAa;;;;;;;;;;CAU1D,QAAQ,CAAC;AACX;AAEA,MAAa,6BAA2C;CACtD,KAAK;;;;;;;;;;;CAWL,QAAQ,CAAC;AACX;AA4BA,SAAgB,2BAA2B,OAGzC;CACA,MAAM,SAA6B;EACjC,MAAM;EACN,MAAM;EACN,MAAM;EACN,UAAU,MAAM,YAAY;EAC5B,MAAM,oBAAoB;EAC1B,MAAM,UAAU;EAChB,UAAU,MAAM,QAAQ,CAAC,CAAC;EAC1B,MAAM;CACR;CAEA,OAAO;EACL,QAAQ;GACN,KAAK;;;;;;;;;;;;;;;;;;;;;GAqBL;EACF;EACA,QAAQ;GAKN,KAAK;;;;;;;;;;GAUL;EACF;CACF;AACF;AAYA,SAAgB,2BAA2B,OAAwC;CACjF,OAAO;EACL,KAAK;;;;;;;;;;;;;;;;;EAiBL,QAAQ;GACN,MAAM,qBAAqB;GAC3B,MAAM,qBAAqB;GAC3B,MAAM;GACN,MAAM,0BAA0B;GAChC,UAAU,MAAM,kBAAkB;GAClC,UAAU,MAAM,iBAAiB;GACjC,UAAU,MAAM,UAAU;EAC5B;CACF;AACF;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,KAAK,UAAU,SAAS,IAAI;AACrC"}
@@ -1,51 +0,0 @@
1
- import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
2
-
3
- //#region src/core/migrations/statement-builders.d.ts
4
- interface SqlStatement {
5
- readonly sql: string;
6
- readonly params: readonly unknown[];
7
- }
8
- declare const ensurePrismaContractSchemaStatement: SqlStatement;
9
- /**
10
- * Schema for `prisma_contract.marker`. The `space text` primary key
11
- * supports one row per loaded contract space (`'app'`,
12
- * `'<extension-id>'`, …); on a brand-new database `CREATE TABLE IF NOT
13
- * EXISTS` produces this shape directly. The migration runner detects
14
- * pre-1.0 single-row markers (no `space` column) at boot and fails with
15
- * a structured `LEGACY_MARKER_SHAPE` error rather than auto-migrating —
16
- * see `specs/framework-mechanism.spec.md § 2`.
17
- */
18
- declare const ensureMarkerTableStatement: SqlStatement;
19
- declare const ensureLedgerTableStatement: SqlStatement;
20
- interface MergeMarkerInput {
21
- /**
22
- * Logical space identifier for this marker row. Required at every
23
- * call site so the type system surfaces every place that needs to
24
- * thread the value (rather than letting an `?? APP_SPACE_ID`
25
- * fall-through silently collapse per-space markers onto the
26
- * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}
27
- * (`'app'`); per-extension callers (planner / runner / verifier
28
- * extensions over contract spaces) pass the extension's space id.
29
- */
30
- readonly space: string;
31
- readonly storageHash: string;
32
- readonly profileHash: string;
33
- readonly contractJson?: unknown;
34
- readonly canonicalVersion?: number | null;
35
- readonly appTag?: string | null;
36
- readonly meta?: Record<string, unknown>;
37
- /**
38
- * Invariants to merge into `marker.invariants`. INSERT writes them as
39
- * the initial value (callers are expected to pass a sorted, deduped
40
- * array). UPDATE merges them with the existing column server-side via
41
- * a single atomic SQL expression.
42
- */
43
- readonly invariants: readonly string[];
44
- }
45
- declare function buildMergeMarkerStatements(input: MergeMarkerInput): {
46
- readonly insert: SqlStatement;
47
- readonly update: SqlStatement;
48
- };
49
- //#endregion
50
- export { APP_SPACE_ID, type SqlStatement, buildMergeMarkerStatements, ensureLedgerTableStatement, ensureMarkerTableStatement, ensurePrismaContractSchemaStatement };
51
- //# sourceMappingURL=statement-builders.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"statement-builders.d.mts","names":[],"sources":["../src/core/migrations/statement-builders.ts"],"mappings":";;;UAIiB,YAAA;EAAA,SACN,GAAA;EAAA,SACA,MAAM;AAAA;AAAA,cAGJ,mCAAA,EAAqC,YAGjD;AANgB;AAGjB;;;;AAGC;AAWD;;;AAjBiB,cAiBJ,0BAAA,EAA4B,YAaxC;AAAA,cAEY,0BAAA,EAA4B,YAaxC;AAAA,UAEgB,gBAAA;EAFhB;;;AAAA;AAED;;;;;EAFC,SAYU,KAAA;EAAA,SACA,WAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;EAAA,SACA,gBAAA;EAAA,SACA,MAAA;EAAA,SACA,IAAA,GAAO,MAAM;EAOb;;AAAU;AAGrB;;;EAHW,SAAA,UAAA;AAAA;AAAA,iBAGK,0BAAA,CAA2B,KAAA,EAAO,gBAAA;EAAA,SACvC,MAAA,EAAQ,YAAA;EAAA,SACR,MAAA,EAAQ,YAAA;AAAA"}
@@ -1,2 +0,0 @@
1
- import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements, t as APP_SPACE_ID } from "./statement-builders-DVI5IVAa.mjs";
2
- export { APP_SPACE_ID, buildMergeMarkerStatements, ensureLedgerTableStatement, ensureMarkerTableStatement, ensurePrismaContractSchemaStatement };
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-O40IcFV9.d.mts","names":[],"sources":["../src/core/types.ts"],"mappings":";;;KAEY,qBAAA,GACR,aAAa;EAAA,SACF,IAAA;EAAA,SAA2B,IAAA;AAAA"}