@prisma/orm-target-postgres 8.0.0-rc.16-dev.6 → 8.0.0-rc.16-dev.7

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 (98) hide show
  1. package/dist/{adapter-RtS8vD8U-BnPjAiLV.mjs → adapter-RtS8vD8U-CkJSaICZ.mjs} +2 -2
  2. package/dist/{adapter-RtS8vD8U-BnPjAiLV.mjs.map → adapter-RtS8vD8U-CkJSaICZ.mjs.map} +1 -1
  3. package/dist/adapter.mjs +2 -2
  4. package/dist/adapter__adapter.mjs +2 -2
  5. package/dist/adapter__control.mjs +4 -4
  6. package/dist/adapter__runtime.mjs +3 -3
  7. package/dist/{authoring-B2hHIzvd-D5NgHs0e.mjs → authoring-_2G2lsLt-VmVbrMPn.mjs} +3 -3
  8. package/dist/{authoring-B2hHIzvd-D5NgHs0e.mjs.map → authoring-_2G2lsLt-VmVbrMPn.mjs.map} +1 -1
  9. package/dist/{contract-free-DaK6wmmo.mjs → contract-free-BMKFjlIG.mjs} +3 -3
  10. package/dist/{contract-free-DaK6wmmo.mjs.map → contract-free-BMKFjlIG.mjs.map} +1 -1
  11. package/dist/{control-Bpd77Aeq.mjs → control-Ltn8Dzpi.mjs} +9 -9
  12. package/dist/{control-Bpd77Aeq.mjs.map → control-Ltn8Dzpi.mjs.map} +1 -1
  13. package/dist/{control-adapter-Co30P4lH-e6oCFCC2.mjs → control-adapter-Co30P4lH-CpxXk5cz.mjs} +2 -2
  14. package/dist/{control-adapter-Co30P4lH-e6oCFCC2.mjs.map → control-adapter-Co30P4lH-CpxXk5cz.mjs.map} +1 -1
  15. package/dist/{control-policy-B7t5CB1S-CotIwNO4.mjs → control-policy-DMOu5nnt-DslefUx9.mjs} +8 -7
  16. package/dist/control-policy-DMOu5nnt-DslefUx9.mjs.map +1 -0
  17. package/dist/{ddl-C_vTj7b5-vyGLBKLo.mjs → ddl-D5hYRCTf-DRSajCVT.mjs} +3 -3
  18. package/dist/{ddl-C_vTj7b5-vyGLBKLo.mjs.map → ddl-D5hYRCTf-DRSajCVT.mjs.map} +1 -1
  19. package/dist/{descriptor-meta-ARufwwWW-C5hsT7UQ.mjs → descriptor-meta-ARufwwWW-ChZm5Hg5.mjs} +2 -2
  20. package/dist/{descriptor-meta-ARufwwWW-C5hsT7UQ.mjs.map → descriptor-meta-ARufwwWW-ChZm5Hg5.mjs.map} +1 -1
  21. package/dist/{descriptor-meta-C8lkQFHe-Cluy19Tk.mjs → descriptor-meta-WHc6Kv-m-BLzsaP0M.mjs} +4 -4
  22. package/dist/{descriptor-meta-C8lkQFHe-Cluy19Tk.mjs.map → descriptor-meta-WHc6Kv-m-BLzsaP0M.mjs.map} +1 -1
  23. package/dist/{diff-database-schema-KGNaKzKp-Bt2yYSIt.mjs → diff-database-schema-DgAMDjHF-YATlptWC.mjs} +5 -5
  24. package/dist/{diff-database-schema-KGNaKzKp-Bt2yYSIt.mjs.map → diff-database-schema-DgAMDjHF-YATlptWC.mjs.map} +1 -1
  25. package/dist/{infer-psl-contract-DoIdoifj-Co9thnGu.mjs → infer-psl-contract-D-3st5lU-DKQhhsut.mjs} +3 -3
  26. package/dist/{infer-psl-contract-DoIdoifj-Co9thnGu.mjs.map → infer-psl-contract-D-3st5lU-DKQhhsut.mjs.map} +1 -1
  27. package/dist/{issue-planner-pmBrIrEN.d.mts → issue-planner-DWRClmiP.d.mts} +2 -2
  28. package/dist/{issue-planner-pmBrIrEN.d.mts.map → issue-planner-DWRClmiP.d.mts.map} +1 -1
  29. package/dist/{migration-D189kh3f.d.mts → migration--J8vKZ8z.d.mts} +3 -3
  30. package/dist/{migration-D189kh3f.d.mts.map → migration--J8vKZ8z.d.mts.map} +1 -1
  31. package/dist/migration-PTHAY9Cv.mjs.map +1 -1
  32. package/dist/{op-factory-call-CqKUB1XP-CsEGx4Jd.d.mts → op-factory-call-BFnGNPJD-5vgAjFpd.d.mts} +44 -14
  33. package/dist/op-factory-call-BFnGNPJD-5vgAjFpd.d.mts.map +1 -0
  34. package/dist/{op-factory-call-BAgAln5R-BTkhp29z.mjs → op-factory-call-BbTtrII--CbCFZfSd.mjs} +123 -27
  35. package/dist/op-factory-call-BbTtrII--CbCFZfSd.mjs.map +1 -0
  36. package/dist/op-factory-call-CsuauFRs.d.mts +1 -0
  37. package/dist/{planner-CvUO8Zpn.d.mts → planner-B9c5vxQo.d.mts} +15 -8
  38. package/dist/planner-B9c5vxQo.d.mts.map +1 -0
  39. package/dist/{planner-DSTSuAc8-BAfUo5KV.mjs → planner-_mo_t-l3-DPAQVG1x.mjs} +117 -23
  40. package/dist/planner-_mo_t-l3-DPAQVG1x.mjs.map +1 -0
  41. package/dist/{planner-produced-postgres-migration-D7-3OBb_-BGHFKj3i.mjs → planner-produced-postgres-migration-BdWg8TP2-QE9uzt2K.mjs} +4 -4
  42. package/dist/{planner-produced-postgres-migration-D7-3OBb_-BGHFKj3i.mjs.map → planner-produced-postgres-migration-BdWg8TP2-QE9uzt2K.mjs.map} +1 -1
  43. package/dist/planner-produced-postgres-migration-BqcWgPjb.d.mts +1 -0
  44. package/dist/{planner-produced-postgres-migration-DT3i_p3G-CyQUv3ac.d.mts → planner-produced-postgres-migration-Bw145mJT-qpLKF3Vf.d.mts} +3 -3
  45. package/dist/planner-produced-postgres-migration-Bw145mJT-qpLKF3Vf.d.mts.map +1 -0
  46. package/dist/{planner-sql-checks-rqOH8naU-B6xOE5lC.mjs → planner-sql-checks-DCGV2qdu-eaeFLtn8.mjs} +3 -3
  47. package/dist/{planner-sql-checks-rqOH8naU-B6xOE5lC.mjs.map → planner-sql-checks-DCGV2qdu-eaeFLtn8.mjs.map} +1 -1
  48. package/dist/{postgres-contract-view-C1bi3x4v-BAfk6euQ.mjs → postgres-contract-view-CL-YTH_3-Diah6i2a.mjs} +4 -4
  49. package/dist/{postgres-contract-view-C1bi3x4v-BAfk6euQ.mjs.map → postgres-contract-view-CL-YTH_3-Diah6i2a.mjs.map} +1 -1
  50. package/dist/{postgres-migration-e8UybR1y-C_m4i1jp.d.mts → postgres-migration-DVY2ALDJ-DTWECas_.d.mts} +36 -4
  51. package/dist/postgres-migration-DVY2ALDJ-DTWECas_.d.mts.map +1 -0
  52. package/dist/postgres-migration-DmczQSHT-DsWlow8L.mjs +1075 -0
  53. package/dist/postgres-migration-DmczQSHT-DsWlow8L.mjs.map +1 -0
  54. package/dist/{postgres-schema-AlEVkXXS-ZfXWYddl.mjs → postgres-schema-COkaqci7-C6JpiSha.mjs} +6 -6
  55. package/dist/postgres-schema-COkaqci7-C6JpiSha.mjs.map +1 -0
  56. package/dist/{prisma7-binding-B4BfqE0o.mjs → prisma7-binding-CAzQh1rQ.mjs} +5 -5
  57. package/dist/{prisma7-binding-B4BfqE0o.mjs.map → prisma7-binding-CAzQh1rQ.mjs.map} +1 -1
  58. package/dist/{render-ops-D2vJApKB-B281fzmn.mjs → render-ops-DaCy6StH-BgzbTE_9.mjs} +16 -9
  59. package/dist/render-ops-DaCy6StH-BgzbTE_9.mjs.map +1 -0
  60. package/dist/{resolve-ddl-schema-BthOWVjF-DuZ9iUh-.mjs → resolve-ddl-schema-DD69Bwve-e-BpAfFa.mjs} +3 -3
  61. package/dist/{resolve-ddl-schema-BthOWVjF-DuZ9iUh-.mjs.map → resolve-ddl-schema-DD69Bwve-e-BpAfFa.mjs.map} +1 -1
  62. package/dist/target.d.mts +9 -9
  63. package/dist/target.mjs +17 -17
  64. package/dist/target__contract-free.mjs +3 -3
  65. package/dist/target__control.mjs +3 -3
  66. package/dist/target__diff-database-schema.mjs +1 -1
  67. package/dist/target__issue-planner.d.mts +1 -1
  68. package/dist/target__issue-planner.mjs +1 -1
  69. package/dist/target__migration.d.mts +2 -2
  70. package/dist/target__migration.mjs +2 -2
  71. package/dist/target__op-factory-call.d.mts +3 -3
  72. package/dist/target__op-factory-call.mjs +2 -2
  73. package/dist/target__pack.mjs +1 -1
  74. package/dist/target__planner-produced-postgres-migration.d.mts +2 -2
  75. package/dist/target__planner-produced-postgres-migration.mjs +1 -1
  76. package/dist/target__planner-sql-checks.mjs +1 -1
  77. package/dist/target__planner.d.mts +1 -1
  78. package/dist/target__planner.mjs +2 -2
  79. package/dist/target__prisma7-binding.mjs +1 -1
  80. package/dist/target__render-ops.mjs +1 -1
  81. package/dist/target__runtime.mjs +2 -2
  82. package/dist/target__runtime.mjs.map +1 -1
  83. package/dist/target__schema-ir-annotations.mjs +1 -1
  84. package/dist/target__types.mjs +1 -1
  85. package/package.json +9 -9
  86. package/dist/control-policy-B7t5CB1S-CotIwNO4.mjs.map +0 -1
  87. package/dist/op-factory-call-BAgAln5R-BTkhp29z.mjs.map +0 -1
  88. package/dist/op-factory-call-CqKUB1XP-CsEGx4Jd.d.mts.map +0 -1
  89. package/dist/op-factory-call-D5UJ7cDi.d.mts +0 -1
  90. package/dist/planner-CvUO8Zpn.d.mts.map +0 -1
  91. package/dist/planner-DSTSuAc8-BAfUo5KV.mjs.map +0 -1
  92. package/dist/planner-produced-postgres-migration-BI_aepPp.d.mts +0 -1
  93. package/dist/planner-produced-postgres-migration-DT3i_p3G-CyQUv3ac.d.mts.map +0 -1
  94. package/dist/postgres-migration-CeX6vfEU-DsmCRCnD.mjs +0 -596
  95. package/dist/postgres-migration-CeX6vfEU-DsmCRCnD.mjs.map +0 -1
  96. package/dist/postgres-migration-e8UybR1y-C_m4i1jp.d.mts.map +0 -1
  97. package/dist/postgres-schema-AlEVkXXS-ZfXWYddl.mjs.map +0 -1
  98. package/dist/render-ops-D2vJApKB-B281fzmn.mjs.map +0 -1
@@ -0,0 +1,1075 @@
1
+ import { t as errorPostgresMigrationStackMissing } from "./errors-DYyzTYzE-39CV_aMo.mjs";
2
+ import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86-Cpp8PTxD.mjs";
3
+ import { i as PostgresRlsPolicy } from "./postgres-schema-COkaqci7-C6JpiSha.mjs";
4
+ import { n as PostgresSchemaNodeKind, r as PostgresTableSchemaNode } from "./postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs";
5
+ import { n as PostgresNamespaceSchemaNode, r as PostgresPolicySchemaNode, t as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs";
6
+ import { n as postgresResolveDefault } from "./default-normalizer-Bf_Fhv4v-CugGfLAe.mjs";
7
+ import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-DD69Bwve-e-BpAfFa.mjs";
8
+ import { a as renderDefaultLiteral } from "./planner-ddl-builders-Y0_96xpe-BzugdEDO.mjs";
9
+ import { A as RenameConstraintCall, C as DropNativeEnumTypeCall, D as EnableRowLevelSecurityCall, E as DropTableCall, F as SetNotNullCall, H as renameTableStatement, M as RenamePostgresRlsPolicyCall, N as RenameTableCall, P as SetDefaultCall, S as DropIndexCall, T as DropPostgresRlsPolicyCall, _ as DisableRowLevelSecurityCall, b as DropConstraintCall, c as AddUniqueCall, d as CreateIndexCall, f as CreateNativeEnumTypeCall, h as CreateTableCall, i as AddNativeEnumValueCall, j as RenameIndexCall, k as RenameColumnCall, l as AlterColumnTypeCall, m as CreateSchemaCall, n as AddColumnCall, p as CreatePostgresRlsPolicyCall, r as AddForeignKeyCall, s as AddPrimaryKeyCall, t as AddCheckConstraintCall, v as DropCheckConstraintCall, w as DropNotNullCall, x as DropDefaultCall, y as DropColumnCall, z as installExtension } from "./op-factory-call-BbTtrII--CbCFZfSd.mjs";
10
+ import { n as defaultPrimaryKeyName, r as defaultUniqueName, t as defaultForeignKeyName } from "./default-constraint-names-CtcRXhV8-nz3ff6b8.mjs";
11
+ import { l as resolveNamespaceIdForDdlSchema, r as issueNode } from "./control-policy-DMOu5nnt-DslefUx9.mjs";
12
+ import { n as contractToPostgresDatabaseSchemaNode, t as buildPostgresPlanDiff } from "./diff-database-schema-DgAMDjHF-YATlptWC.mjs";
13
+ import { n as PostgresContractView } from "./postgres-contract-view-CL-YTH_3-Diah6i2a.mjs";
14
+ import { t as dataTransform } from "./data-transform-Bo32KRbq-BLn1_UG-.mjs";
15
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
16
+ import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
17
+ import { issueOutcome } from "@prisma/orm-framework/components/control";
18
+ import { namingOf, namingOfLiveName, parseWireName } from "@prisma/orm-family-sql/schema-ir/naming";
19
+ import { assertDefined } from "@prisma/orm-framework/utils/assertions";
20
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
21
+ import { resolveColumnRenameAgainst, resolveTableRenameAgainst, sqlTypeLookupsOf, unmatchedColumnRename, unmatchedTableRename } from "@prisma/orm-family-sql/family/control";
22
+ import { PrimaryKey, RelationalSchemaNodeKind, SqlCheckConstraintIR, SqlColumnIR, SqlForeignKeyIR, SqlIndexIR, SqlUniqueIR } from "@prisma/orm-family-sql/schema-ir/types";
23
+ import { isArrayEqual } from "@prisma/orm-framework/utils/array-equal";
24
+ import { errorMigrationOperationOptionRemoved } from "@prisma/orm-framework/errors/migration";
25
+ import { Migration } from "@prisma/orm-family-sql/family/migration";
26
+ import { MigrationContractViews } from "@prisma/orm-toolchain/migration-tools/migration";
27
+ //#region ../../../3-targets/3-targets/postgres/dist/postgres-migration-DmczQSHT.mjs
28
+ function postgresRenderDefault(def, column, type) {
29
+ if (def.kind === "function") return def.expression;
30
+ return renderDefaultLiteral(def.value, {
31
+ many: column.many,
32
+ ...type
33
+ });
34
+ }
35
+ /**
36
+ * The Postgres schema tree a contract describes, as the planner's "from" side:
37
+ * the target descriptor's `migrations.contractToSchema` hook and the trees
38
+ * `renameTable` compares to find its companion renames both go through here,
39
+ * so they are built with the same type lookups, default renderer and default resolver.
40
+ */
41
+ function postgresContractToSchema(contract, frameworkComponents) {
42
+ const types = sqlTypeLookupsOf(frameworkComponents);
43
+ return contractToPostgresDatabaseSchemaNode(blindCast(contract), {
44
+ annotationNamespace: "pg",
45
+ dataTypeLookup: types.dataTypeLookup,
46
+ codecLookup: types.codecLookup,
47
+ renderDefault: postgresRenderDefault,
48
+ resolveDefault: postgresResolveDefault
49
+ });
50
+ }
51
+ /**
52
+ * Rename post-pass for indexes, per `(schema, table)`, widening-only,
53
+ * deterministic by sorted names — the same structure as the policy pass
54
+ * below (which stays untouched: policies pair by hash only).
55
+ *
56
+ * Hash pairing (prefix-only renames): extras whose live names parse as
57
+ * wire names, grouped by `(schema, table, hash)`; missing nodes iterated
58
+ * in sorted-name order consume the sorted-name-first candidate.
59
+ *
60
+ * Content pairing (exact→wire convergence), after hash pairing has
61
+ * consumed its matches: the remaining wire-named-missing nodes
62
+ * (`prefix` defined) against the remaining extras of any name shape,
63
+ * paired iff content-equal (columns ordered-strict both-defined-or-
64
+ * both-undefined, `unique`/`type` strict, `options` loose, bodies
65
+ * byte-equal).
66
+ *
67
+ * Leftovers proceed as create/drop exactly as before; without the
68
+ * widening allowance the pass is skipped and pairing degrades to the
69
+ * additive half, like the policy pass.
70
+ */
71
+ function pairIndexRenames(options, issues) {
72
+ const consumed = /* @__PURE__ */ new Set();
73
+ const calls = [];
74
+ if (!options.policy.allowedOperationClasses.includes("widening")) return {
75
+ calls,
76
+ consumed
77
+ };
78
+ const missing = [];
79
+ const extra = [];
80
+ for (const issue of issues) {
81
+ const node = issueNode(issue);
82
+ if (node === void 0 || !SqlIndexIR.is(node)) continue;
83
+ const ddlSchema = issue.path[1];
84
+ const tableName = issue.path[2];
85
+ if (ddlSchema === void 0 || tableName === void 0) continue;
86
+ if (issueOutcome(issue) === "not-found") missing.push({
87
+ issue,
88
+ node,
89
+ ddlSchema,
90
+ tableName
91
+ });
92
+ else if (issueOutcome(issue) === "not-expected") extra.push({
93
+ issue,
94
+ node,
95
+ ddlSchema,
96
+ tableName
97
+ });
98
+ }
99
+ if (missing.length === 0 || extra.length === 0) return {
100
+ calls,
101
+ consumed
102
+ };
103
+ const byName = (a, b) => a.node.name < b.node.name ? -1 : a.node.name > b.node.name ? 1 : 0;
104
+ const emissionSchema = (ddlSchema) => resolveNamespaceIdForDdlSchema(options.contract, ddlSchema) === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchema;
105
+ const pairingKey = (finding, hash) => JSON.stringify([
106
+ finding.ddlSchema,
107
+ finding.tableName,
108
+ hash
109
+ ]);
110
+ const rename = (missingFinding, candidate) => {
111
+ consumed.add(missingFinding.issue);
112
+ consumed.add(candidate.issue);
113
+ calls.push(new RenameIndexCall(emissionSchema(missingFinding.ddlSchema), missingFinding.tableName, candidate.node.name, missingFinding.node.name));
114
+ };
115
+ const sortedMissing = [...missing].sort(byName);
116
+ const extrasByHash = /* @__PURE__ */ new Map();
117
+ for (const finding of extra) {
118
+ const parsed = parseWireName(finding.node.name);
119
+ if (parsed === void 0) continue;
120
+ const key = pairingKey(finding, parsed.hash);
121
+ const group = extrasByHash.get(key) ?? [];
122
+ group.push(finding);
123
+ extrasByHash.set(key, group);
124
+ }
125
+ for (const group of extrasByHash.values()) group.sort(byName);
126
+ for (const missingFinding of sortedMissing) {
127
+ const parsed = parseWireName(missingFinding.node.name);
128
+ if (parsed === void 0) continue;
129
+ const candidate = extrasByHash.get(pairingKey(missingFinding, parsed.hash))?.shift();
130
+ if (candidate === void 0) continue;
131
+ rename(missingFinding, candidate);
132
+ }
133
+ const sortedExtras = [...extra].sort(byName);
134
+ for (const missingFinding of sortedMissing) {
135
+ if (consumed.has(missingFinding.issue)) continue;
136
+ if (missingFinding.node.prefix === void 0) continue;
137
+ const candidate = sortedExtras.find((extraFinding) => !consumed.has(extraFinding.issue) && extraFinding.ddlSchema === missingFinding.ddlSchema && extraFinding.tableName === missingFinding.tableName && missingFinding.node.contentEquals(extraFinding.node, {
138
+ columnPresence: "matching",
139
+ bodies: "verbatim"
140
+ }));
141
+ if (candidate === void 0) continue;
142
+ rename(missingFinding, candidate);
143
+ }
144
+ return {
145
+ calls,
146
+ consumed
147
+ };
148
+ }
149
+ /**
150
+ * Check-constraint rename post-pass: a `not-found` and a `not-expected`
151
+ * check on the same table whose wire-name content hashes match but whose
152
+ * prefixes differ is a prefix-only rename, and collapses into one
153
+ * `ALTER TABLE … RENAME CONSTRAINT`.
154
+ *
155
+ * This is the index pass's hash-pairing phase and nothing else. There is
156
+ * deliberately no content-pairing phase: a live check body is whatever
157
+ * Postgres reprinted, so it never byte-matches the authored text, and
158
+ * pairing an exact-named live check by content would bless whatever
159
+ * predicate is actually live. Adoption of an old exact-named check stays
160
+ * drop + add.
161
+ *
162
+ * Runs only when the policy allows `widening` (rename's class). Without it
163
+ * the pass no-ops and the pair degrades to an add and a drop, and the drop,
164
+ * which is `widening` too, is refused as a conflict.
165
+ */
166
+ function pairCheckRenames(options, issues) {
167
+ const consumed = /* @__PURE__ */ new Set();
168
+ const calls = [];
169
+ if (!options.policy.allowedOperationClasses.includes("widening")) return {
170
+ calls,
171
+ consumed
172
+ };
173
+ const missing = [];
174
+ const extra = [];
175
+ for (const issue of issues) {
176
+ const node = issueNode(issue);
177
+ if (node === void 0 || !SqlCheckConstraintIR.is(node)) continue;
178
+ const ddlSchema = issue.path[1];
179
+ const tableName = issue.path[2];
180
+ if (ddlSchema === void 0 || tableName === void 0) continue;
181
+ if (issueOutcome(issue) === "not-found") missing.push({
182
+ issue,
183
+ node,
184
+ ddlSchema,
185
+ tableName
186
+ });
187
+ else if (issueOutcome(issue) === "not-expected") extra.push({
188
+ issue,
189
+ node,
190
+ ddlSchema,
191
+ tableName
192
+ });
193
+ }
194
+ if (missing.length === 0 || extra.length === 0) return {
195
+ calls,
196
+ consumed
197
+ };
198
+ const byName = (a, b) => a.node.name < b.node.name ? -1 : a.node.name > b.node.name ? 1 : 0;
199
+ const emissionSchema = (ddlSchema) => resolveNamespaceIdForDdlSchema(options.contract, ddlSchema) === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchema;
200
+ const pairingKey = (finding, hash) => JSON.stringify([
201
+ finding.ddlSchema,
202
+ finding.tableName,
203
+ hash
204
+ ]);
205
+ const sortedMissing = [...missing].sort(byName);
206
+ const extrasByHash = /* @__PURE__ */ new Map();
207
+ for (const finding of extra) {
208
+ const parsed = parseWireName(finding.node.name);
209
+ if (parsed === void 0) continue;
210
+ const key = pairingKey(finding, parsed.hash);
211
+ const group = extrasByHash.get(key) ?? [];
212
+ group.push(finding);
213
+ extrasByHash.set(key, group);
214
+ }
215
+ for (const group of extrasByHash.values()) group.sort(byName);
216
+ for (const missingFinding of sortedMissing) {
217
+ const parsed = parseWireName(missingFinding.node.name);
218
+ if (parsed === void 0) continue;
219
+ const candidate = extrasByHash.get(pairingKey(missingFinding, parsed.hash))?.shift();
220
+ if (candidate === void 0) continue;
221
+ consumed.add(missingFinding.issue);
222
+ consumed.add(candidate.issue);
223
+ calls.push(new RenameConstraintCall(emissionSchema(missingFinding.ddlSchema), missingFinding.tableName, "checkConstraint", candidate.node.name, missingFinding.node.name));
224
+ }
225
+ return {
226
+ calls,
227
+ consumed
228
+ };
229
+ }
230
+ /**
231
+ * The tables of a Postgres schema, addressed by `contract`'s namespace ids, each mapped to its DDL
232
+ * schema.
233
+ */
234
+ function postgresSchemaTables(schema, contract) {
235
+ const tableIn = (namespaceId, table) => schema.namespaces[resolveDdlSchemaForNamespaceStorage(contract.storage, namespaceId)]?.tables[table];
236
+ const hasTable = (namespaceId, table) => tableIn(namespaceId, table) !== void 0;
237
+ return {
238
+ hasTable,
239
+ hasColumn: (namespaceId, table, column) => Object.hasOwn(tableIn(namespaceId, table)?.columns ?? {}, column),
240
+ tablesNamed: (namespaceId, table) => hasTable(namespaceId, table) ? [table] : [],
241
+ columnsNamed: (namespaceId, table, column) => Object.hasOwn(tableIn(namespaceId, table)?.columns ?? {}, column) ? [column] : [],
242
+ namespacesWithTable: (table) => Object.keys(contract.storage.namespaces).filter((namespaceId) => hasTable(namespaceId, table))
243
+ };
244
+ }
245
+ /**
246
+ * The constraint renames that follow a table rename. Each primary key, unique constraint and
247
+ * foreign key of the renamed table is paired with the destination constraint of the same kind on
248
+ * the same columns, and for a foreign key the same referenced columns. Foreign keys pair first
249
+ * with destination keys to the same referenced table, and the rest then pair with keys to another
250
+ * table, because a later rename in the same plan may change that table and a foreign key's derived
251
+ * name never depends on it. A paired constraint is renamed to the destination's explicit name, or else
252
+ * to the name the planner derives from the new table name, when that differs from its name in the
253
+ * database. Each destination constraint pairs with at most one constraint, in order. An unpaired
254
+ * constraint is being dropped or changed and keeps its name. Indexes and checks are not handled
255
+ * here: their wire names pair by content hash in the index and check rename passes.
256
+ */
257
+ function constraintRenamesForTableRename(input) {
258
+ return pairedConstraintRenames(input, {
259
+ primaryKey: true,
260
+ onColumns: () => true
261
+ });
262
+ }
263
+ /**
264
+ * The renames of the constraints in `scope` that pair with a destination constraint of the same
265
+ * kind on the same columns, to the destination's explicit name or else the derived one.
266
+ */
267
+ function pairedConstraintRenames(input, scope) {
268
+ const { schemaName, previous, next } = input;
269
+ const table = next.name;
270
+ const rename = (kind, actualName, target) => {
271
+ assertDefined(actualName, `the table "${previous.name}" has a ${kind} that has no name; the working schema names every primary key, unique and foreign key a rename can change`);
272
+ return target === void 0 || target === actualName ? [] : [new RenameConstraintCall(schemaName, table, kind, actualName, target)];
273
+ };
274
+ const nextPrimaryKey = next.primaryKey;
275
+ const primaryKey = previous.primaryKey === void 0 || !scope.primaryKey ? [] : rename("primaryKey", previous.primaryKey.name, nextPrimaryKey !== void 0 && isArrayEqual(previous.primaryKey.columns, nextPrimaryKey.columns) ? nextPrimaryKey.name ?? defaultPrimaryKeyName(table) : void 0);
276
+ const pairedUniques = /* @__PURE__ */ new Set();
277
+ const uniques = previous.uniques.filter((unique) => scope.onColumns(unique.columns)).flatMap((unique) => {
278
+ const paired = next.uniques.find((candidate) => !pairedUniques.has(candidate) && isArrayEqual(candidate.columns, unique.columns));
279
+ if (paired !== void 0) pairedUniques.add(paired);
280
+ return rename("unique", unique.name, paired === void 0 ? void 0 : paired.name ?? defaultUniqueName(table, paired.columns));
281
+ });
282
+ const previousForeignKeys = previous.foreignKeys.filter((fk) => scope.onColumns(fk.columns));
283
+ const pairing = pairForeignKeys(previousForeignKeys, next.foreignKeys);
284
+ const foreignKeys = previousForeignKeys.flatMap((fk) => {
285
+ const paired = pairing.get(fk);
286
+ return rename("foreignKey", fk.name, paired === void 0 ? void 0 : paired.name ?? defaultForeignKeyName(table, fk.columns));
287
+ });
288
+ return [
289
+ ...primaryKey,
290
+ ...uniques,
291
+ ...foreignKeys
292
+ ];
293
+ }
294
+ /**
295
+ * Pairs old foreign keys with destination keys on the same columns and referenced columns. Every
296
+ * key to the same referenced table pairs first, so an old key with no such match cannot take the
297
+ * destination key another old key keeps; the remaining keys then pair in order.
298
+ */
299
+ function pairForeignKeys(previous, next) {
300
+ const pairs = /* @__PURE__ */ new Map();
301
+ const taken = /* @__PURE__ */ new Set();
302
+ const pass = (accepts) => {
303
+ for (const fk of previous) {
304
+ if (pairs.has(fk)) continue;
305
+ const paired = next.find((candidate) => !taken.has(candidate) && isArrayEqual(candidate.columns, fk.columns) && isArrayEqual(candidate.referencedColumns, fk.referencedColumns) && accepts(fk, candidate));
306
+ if (paired === void 0) continue;
307
+ pairs.set(fk, paired);
308
+ taken.add(paired);
309
+ }
310
+ };
311
+ pass((fk, candidate) => candidate.referencedTable === fk.referencedTable && candidate.resolvedReferencedNamespace === fk.resolvedReferencedNamespace);
312
+ pass(() => true);
313
+ return pairs;
314
+ }
315
+ /**
316
+ * The constraint renames that follow a column rename. Each unique constraint and foreign key on
317
+ * the renamed column is paired with the destination constraint of the same kind on the same
318
+ * columns, and renamed to the destination's explicit name, or else to the name the planner derives
319
+ * from the table and the new column names, when that differs from its name in the database. The
320
+ * primary key's derived name does not depend on its columns, so it is left alone. `previous` is
321
+ * the table after the column rename, its constraint names as they are in the database.
322
+ */
323
+ function constraintRenamesForColumnRename(input) {
324
+ return pairedConstraintRenames(input, {
325
+ primaryKey: false,
326
+ onColumns: (columns) => columns.includes(input.column)
327
+ });
328
+ }
329
+ function ddlSchemaOf(callSchemaName) {
330
+ return callSchemaName === UNBOUND_NAMESPACE_ID ? DEFAULT_NAMESPACE_ID : callSchemaName;
331
+ }
332
+ function rewriteRefs(refs, rewrite) {
333
+ return refs?.map(rewrite);
334
+ }
335
+ /**
336
+ * Rewrites the step of `kind` and `id` in a ref that runs through the given table, and the table
337
+ * step itself when `kind` is the table kind.
338
+ */
339
+ function stepRewrite(schemaName, tableName, kind, fromId, toId) {
340
+ return (ref) => {
341
+ const namespaceStep = ref[1];
342
+ const tableStep = ref[2];
343
+ if (namespaceStep?.nodeKind !== PostgresSchemaNodeKind.namespace || namespaceStep.id !== schemaName || tableStep?.nodeKind !== PostgresSchemaNodeKind.table || tableStep.id !== tableName) return ref;
344
+ return ref.map((step, index) => index >= 2 && step.nodeKind === kind && step.id === fromId ? {
345
+ nodeKind: kind,
346
+ id: toId
347
+ } : step);
348
+ };
349
+ }
350
+ function withColumnName(column, name) {
351
+ return new SqlColumnIR({
352
+ name,
353
+ nativeType: column.nativeType,
354
+ nullable: column.nullable,
355
+ ...ifDefined("default", column.default),
356
+ ...ifDefined("annotations", column.annotations),
357
+ ...ifDefined("many", column.many),
358
+ ...ifDefined("resolvedNativeType", column.resolvedNativeType),
359
+ ...ifDefined("resolvedDefault", column.resolvedDefault),
360
+ ...ifDefined("authoredDefault", column.authoredDefault),
361
+ ...ifDefined("codecRef", column.codecRef),
362
+ ...ifDefined("codecBaseNativeType", column.codecBaseNativeType),
363
+ ...ifDefined("dataType", column.dataType),
364
+ ...ifDefined("toCanonicalForm", column.toCanonicalForm)
365
+ });
366
+ }
367
+ function withPrimaryKey(primaryKey, name, rewrite, columnName) {
368
+ return new PrimaryKey({
369
+ columns: primaryKey.columns.map(columnName),
370
+ ...ifDefined("name", name),
371
+ ...ifDefined("dependsOn", rewriteRefs(primaryKey.dependsOn, rewrite))
372
+ });
373
+ }
374
+ function withUnique(unique, name, rewrite, columnName) {
375
+ return new SqlUniqueIR({
376
+ columns: unique.columns.map(columnName),
377
+ ...ifDefined("name", name),
378
+ ...ifDefined("annotations", unique.annotations),
379
+ ...ifDefined("dependsOn", rewriteRefs(unique.dependsOn, rewrite))
380
+ });
381
+ }
382
+ function withForeignKey(fk, overrides, rewrite, columnName) {
383
+ return new SqlForeignKeyIR({
384
+ columns: fk.columns.map(columnName),
385
+ referencedTable: overrides.referencedTable,
386
+ referencedColumns: overrides.referencedColumns ?? fk.referencedColumns,
387
+ ...ifDefined("referencedSchema", fk.referencedSchema),
388
+ ...ifDefined("name", overrides.name),
389
+ ...ifDefined("onDelete", fk.onDelete),
390
+ ...ifDefined("onUpdate", fk.onUpdate),
391
+ ...ifDefined("annotations", fk.annotations),
392
+ ...ifDefined("resolvedReferencedNamespace", fk.resolvedReferencedNamespace),
393
+ ...ifDefined("dependsOn", rewriteRefs(fk.dependsOn, rewrite))
394
+ });
395
+ }
396
+ /**
397
+ * An index whose definition carries SQL text, an expression or a predicate, keeps its columns as
398
+ * they are: a column named inside the text cannot be renamed here, so the diff plans the index.
399
+ */
400
+ function withIndex(index, naming, rewrite, columnName) {
401
+ const columnsFollow = index.expression === void 0 && index.where === void 0;
402
+ const base = {
403
+ naming,
404
+ where: index.where,
405
+ unique: index.unique,
406
+ partial: index.partial,
407
+ type: index.type,
408
+ options: index.options,
409
+ annotations: index.annotations,
410
+ dependsOn: rewriteRefs(index.dependsOn, rewrite)
411
+ };
412
+ return new SqlIndexIR(index.expression !== void 0 ? {
413
+ ...base,
414
+ expression: index.expression
415
+ } : {
416
+ ...base,
417
+ columns: (index.columns ?? []).map(columnsFollow ? columnName : (c) => c)
418
+ });
419
+ }
420
+ function withCheck(check, naming, rewrite) {
421
+ return new SqlCheckConstraintIR({
422
+ naming,
423
+ expression: check.expression,
424
+ dependsOn: rewriteRefs(check.dependsOn, rewrite)
425
+ });
426
+ }
427
+ function withPolicy(policy, overrides, rewrite) {
428
+ return new PostgresPolicySchemaNode({
429
+ naming: overrides.naming,
430
+ tableName: overrides.tableName,
431
+ namespaceId: policy.namespaceId,
432
+ operation: policy.operation,
433
+ roles: policy.roles,
434
+ using: policy.using,
435
+ withCheck: policy.withCheck,
436
+ permissive: policy.permissive,
437
+ dependsOn: rewriteRefs(policy.dependsOn, rewrite)
438
+ });
439
+ }
440
+ function unchangedEdit(table) {
441
+ return {
442
+ name: table.name,
443
+ primaryKeyName: (primaryKey) => primaryKey.name,
444
+ uniqueName: (unique) => unique.name,
445
+ foreignKey: (fk) => ({
446
+ name: fk.name,
447
+ referencedTable: fk.referencedTable
448
+ }),
449
+ columnName: (column) => column,
450
+ indexNaming: (index) => namingOf(index.name, index.prefix),
451
+ checkNaming: (check) => namingOf(check.name, check.prefix),
452
+ policy: (policy) => ({
453
+ naming: namingOf(policy.name, policy.prefix),
454
+ tableName: policy.tableName
455
+ })
456
+ };
457
+ }
458
+ function rebuildTable(table, edit, rewrite) {
459
+ const { columnName } = edit;
460
+ return new PostgresTableSchemaNode({
461
+ name: edit.name,
462
+ columns: Object.fromEntries(Object.values(table.columns).map((column) => {
463
+ const name = columnName(column.name);
464
+ return [name, name === column.name ? column : withColumnName(column, name)];
465
+ })),
466
+ ...ifDefined("primaryKey", table.primaryKey === void 0 ? void 0 : withPrimaryKey(table.primaryKey, edit.primaryKeyName(table.primaryKey), rewrite, columnName)),
467
+ uniques: table.uniques.map((unique) => withUnique(unique, edit.uniqueName(unique), rewrite, columnName)),
468
+ foreignKeys: table.foreignKeys.map((fk) => withForeignKey(fk, edit.foreignKey(fk), rewrite, columnName)),
469
+ indexes: table.indexes.map((index) => withIndex(index, edit.indexNaming(index), rewrite, columnName)),
470
+ ...ifDefined("checks", table.checks?.map((check) => withCheck(check, edit.checkNaming(check), rewrite))),
471
+ ...ifDefined("annotations", table.annotations),
472
+ policies: table.policies.map((policy) => withPolicy(policy, edit.policy(policy), rewrite)),
473
+ rlsEnabled: table.rlsEnabled
474
+ });
475
+ }
476
+ /**
477
+ * Rebuilds every table of the schema: `editFor` returns the edit for a table, or `undefined` to
478
+ * only rewrite its dependencies.
479
+ */
480
+ function mapTables(schema, rewrite, editFor) {
481
+ return new PostgresDatabaseSchemaNode({
482
+ namespaces: Object.fromEntries(Object.entries(schema.namespaces).map(([key, namespace]) => [key, new PostgresNamespaceSchemaNode({
483
+ schemaName: namespace.schemaName,
484
+ nativeEnums: namespace.nativeEnums,
485
+ tables: Object.fromEntries(Object.values(namespace.tables).map((table) => {
486
+ const rebuilt = rebuildTable(table, editFor(namespace.schemaName, table) ?? unchangedEdit(table), rewrite);
487
+ return [rebuilt.name, rebuilt];
488
+ }))
489
+ })])),
490
+ roles: schema.roles,
491
+ existingSchemas: schema.existingSchemas,
492
+ pgVersion: schema.pgVersion
493
+ });
494
+ }
495
+ /**
496
+ * The schema with one table under its new name. Foreign keys anywhere that reference the table
497
+ * follow it, its policies and every dependency that names it move with it, and row-level security
498
+ * is carried. Constraint, index, check and policy names do not change: a primary key, unique
499
+ * constraint or foreign key whose name was derived from the old table name gets that name spelled
500
+ * out, since it no longer derives from the table it is on.
501
+ */
502
+ function renameTableInPostgresSchema(schema, rename) {
503
+ const { schemaName, from, to } = rename;
504
+ const rewrite = stepRewrite(schemaName, from, PostgresSchemaNodeKind.table, from, to);
505
+ const referencesRenamed = (ownSchema, fk) => (fk.resolvedReferencedNamespace ?? ownSchema) === schemaName && fk.referencedTable === from;
506
+ return mapTables(schema, rewrite, (tableSchema, table) => {
507
+ const unchanged = unchangedEdit(table);
508
+ const followReference = (fk) => ({
509
+ name: fk.name,
510
+ referencedTable: referencesRenamed(tableSchema, fk) ? to : fk.referencedTable
511
+ });
512
+ if (tableSchema !== schemaName || table.name !== from) return {
513
+ ...unchanged,
514
+ foreignKey: followReference
515
+ };
516
+ return {
517
+ ...unchanged,
518
+ name: to,
519
+ primaryKeyName: (primaryKey) => primaryKey.name ?? defaultPrimaryKeyName(from),
520
+ uniqueName: (unique) => unique.name ?? defaultUniqueName(from, unique.columns),
521
+ foreignKey: (fk) => ({
522
+ ...followReference(fk),
523
+ name: fk.name ?? defaultForeignKeyName(from, fk.columns)
524
+ }),
525
+ policy: (policy) => ({
526
+ ...unchanged.policy(policy),
527
+ tableName: to
528
+ })
529
+ };
530
+ });
531
+ }
532
+ /**
533
+ * The schema with one column under its new name. The table's primary key, unique constraints,
534
+ * foreign keys and plain column indexes name it under the new name, foreign keys anywhere that
535
+ * reference it follow it, and every dependency that names it moves with it. An index with an
536
+ * expression or a predicate, and a check, keep their SQL text. Constraint and index names do not
537
+ * change: a unique constraint or foreign key on the column whose name was derived from the old
538
+ * column name gets that name spelled out.
539
+ */
540
+ function renameColumnInPostgresSchema(schema, rename) {
541
+ const { schemaName, table: tableName, from, to } = rename;
542
+ const rewrite = stepRewrite(schemaName, tableName, RelationalSchemaNodeKind.column, `column:${from}`, `column:${to}`);
543
+ const renamed = (column) => column === from ? to : column;
544
+ const referencesTable = (ownSchema, fk) => (fk.resolvedReferencedNamespace ?? ownSchema) === schemaName && fk.referencedTable === tableName;
545
+ return mapTables(schema, rewrite, (tableSchema, table) => {
546
+ const unchanged = unchangedEdit(table);
547
+ const followReference = (fk) => ({
548
+ name: fk.name,
549
+ referencedTable: fk.referencedTable,
550
+ referencedColumns: referencesTable(tableSchema, fk) ? fk.referencedColumns.map(renamed) : fk.referencedColumns
551
+ });
552
+ if (tableSchema !== schemaName || table.name !== tableName) return {
553
+ ...unchanged,
554
+ foreignKey: followReference
555
+ };
556
+ return {
557
+ ...unchanged,
558
+ columnName: renamed,
559
+ uniqueName: (unique) => unique.name ?? (unique.columns.includes(from) ? defaultUniqueName(tableName, unique.columns) : void 0),
560
+ foreignKey: (fk) => ({
561
+ ...followReference(fk),
562
+ name: fk.name ?? (fk.columns.includes(from) ? defaultForeignKeyName(tableName, fk.columns) : void 0)
563
+ })
564
+ };
565
+ });
566
+ }
567
+ function renamedNaming(previous, name) {
568
+ return previous.prefix === void 0 ? namingOf(name, void 0) : namingOfLiveName(name);
569
+ }
570
+ function renameConstraint(schema, call) {
571
+ const schemaName = ddlSchemaOf(call.schemaName);
572
+ const { tableName, oldConstraintName, newConstraintName } = call;
573
+ const renamed = (name, derived) => (name ?? derived) === oldConstraintName ? newConstraintName : name;
574
+ return mapTables(schema, stepRewrite(schemaName, tableName, RelationalSchemaNodeKind.check, `check:${oldConstraintName}`, `check:${newConstraintName}`), (tableSchema, table) => {
575
+ if (tableSchema !== schemaName || table.name !== tableName) return void 0;
576
+ const unchanged = unchangedEdit(table);
577
+ switch (call.kind) {
578
+ case "primaryKey": return {
579
+ ...unchanged,
580
+ primaryKeyName: (primaryKey) => renamed(primaryKey.name, defaultPrimaryKeyName(tableName))
581
+ };
582
+ case "unique": return {
583
+ ...unchanged,
584
+ uniqueName: (unique) => renamed(unique.name, defaultUniqueName(tableName, unique.columns))
585
+ };
586
+ case "foreignKey": return {
587
+ ...unchanged,
588
+ foreignKey: (fk) => ({
589
+ referencedTable: fk.referencedTable,
590
+ name: renamed(fk.name, defaultForeignKeyName(tableName, fk.columns))
591
+ })
592
+ };
593
+ case "checkConstraint": return {
594
+ ...unchanged,
595
+ checkNaming: (check) => check.name === oldConstraintName ? renamedNaming(check, newConstraintName) : unchanged.checkNaming(check)
596
+ };
597
+ }
598
+ });
599
+ }
600
+ function renameIndex(schema, call) {
601
+ const schemaName = ddlSchemaOf(call.schemaName);
602
+ const { tableName, oldIndexName, newIndexName } = call;
603
+ return mapTables(schema, stepRewrite(schemaName, tableName, RelationalSchemaNodeKind.index, `index:${oldIndexName}`, `index:${newIndexName}`), (tableSchema, table) => {
604
+ if (tableSchema !== schemaName || table.name !== tableName) return void 0;
605
+ const unchanged = unchangedEdit(table);
606
+ return {
607
+ ...unchanged,
608
+ indexNaming: (index) => index.name === oldIndexName ? renamedNaming(index, newIndexName) : unchanged.indexNaming(index)
609
+ };
610
+ });
611
+ }
612
+ function renamePolicy(schema, call) {
613
+ const schemaName = ddlSchemaOf(call.schemaName);
614
+ const { tableName, oldPolicyName, newPolicyName } = call;
615
+ return mapTables(schema, stepRewrite(schemaName, tableName, PostgresSchemaNodeKind.policy, oldPolicyName, newPolicyName), (tableSchema, table) => {
616
+ if (tableSchema !== schemaName || table.name !== tableName) return void 0;
617
+ const unchanged = unchangedEdit(table);
618
+ return {
619
+ ...unchanged,
620
+ policy: (policy) => policy.name === oldPolicyName ? {
621
+ naming: renamedNaming(policy, newPolicyName),
622
+ tableName: policy.tableName
623
+ } : unchanged.policy(policy)
624
+ };
625
+ });
626
+ }
627
+ function applied(schema, call) {
628
+ if (call instanceof RenameTableCall) {
629
+ const renamed = renameTableInPostgresSchema(schema, {
630
+ schemaName: ddlSchemaOf(call.schemaName),
631
+ from: call.oldTableName,
632
+ to: call.tableName
633
+ });
634
+ return call.companions.reduce(applied, renamed);
635
+ }
636
+ if (call instanceof RenameColumnCall) {
637
+ const renamed = renameColumnInPostgresSchema(schema, {
638
+ schemaName: ddlSchemaOf(call.schemaName),
639
+ table: call.tableName,
640
+ from: call.oldColumnName,
641
+ to: call.columnName
642
+ });
643
+ return call.companions.reduce(applied, renamed);
644
+ }
645
+ if (call instanceof RenameConstraintCall) return renameConstraint(schema, call);
646
+ if (call instanceof RenameIndexCall) return renameIndex(schema, call);
647
+ return renamePolicy(schema, call);
648
+ }
649
+ /** The working schema of a plan or a migration, starting from `initial`. */
650
+ function createWorkingSchema(initial) {
651
+ return new WorkingSchemaImpl(initial);
652
+ }
653
+ var WorkingSchemaImpl = class {
654
+ #current;
655
+ constructor(initial) {
656
+ this.#current = initial;
657
+ }
658
+ get current() {
659
+ return this.#current;
660
+ }
661
+ apply(call) {
662
+ this.#current = applied(this.#current, call);
663
+ }
664
+ };
665
+ const RENAME_POLICY = { allowedOperationClasses: ["widening"] };
666
+ function emissionSchemaForNamespace(contract, namespaceId) {
667
+ return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : resolveDdlSchemaForNamespaceStorage(contract.storage, namespaceId);
668
+ }
669
+ /**
670
+ * The `renameTable` call a user writes in `migration.ts` for `rename`. `schema` names the namespace
671
+ * the facade resolves the table in, and is left out for the unbound namespace or when not given.
672
+ */
673
+ function renderRenameTableCall(rename) {
674
+ return new RenameTableCall(rename.namespaceId ?? UNBOUND_NAMESPACE_ID, rename.from, rename.to, []).renderTypeScript();
675
+ }
676
+ /** The SQL a user runs against the database to rename the table by hand. */
677
+ function renameTableByHandStatements(contract, rename) {
678
+ return [renameTableStatement(emissionSchemaForNamespace(contract, rename.namespaceId), rename.from, rename.to)];
679
+ }
680
+ function tableNode(schema, ddlSchema, tableName) {
681
+ const table = schema.namespaces[ddlSchema]?.tables[tableName];
682
+ assertDefined(table, `a resolved rename names table "${tableName}" in schema "${ddlSchema}"`);
683
+ return table;
684
+ }
685
+ /**
686
+ * The call that renames a table, carrying as companions the renames of the objects on the table
687
+ * whose names derive from the table name: each primary key, unique constraint and foreign key the
688
+ * destination keeps, named as the destination names it, and each wire-named index and check whose
689
+ * prefix changes. `previous` is the schema before the rename; the renamed copy is diffed against
690
+ * the destination built from `contract`.
691
+ */
692
+ function postgresTableRenameCall(input) {
693
+ const { contract, rename } = input;
694
+ const schemaName = emissionSchemaForNamespace(contract, rename.namespaceId);
695
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, rename.namespaceId);
696
+ const renamed = renameTableInPostgresSchema(input.previous, {
697
+ schemaName: ddlSchema,
698
+ from: rename.from,
699
+ to: rename.to
700
+ });
701
+ const { expected, issues } = buildPostgresPlanDiff({
702
+ contract,
703
+ actualSchema: renamed,
704
+ frameworkComponents: input.frameworkComponents
705
+ });
706
+ const onRenamedTable = (call) => call.schemaName === schemaName && call.tableName === rename.to;
707
+ const pairing = {
708
+ contract,
709
+ policy: RENAME_POLICY
710
+ };
711
+ return new RenameTableCall(schemaName, rename.from, rename.to, [
712
+ ...constraintRenamesForTableRename({
713
+ schemaName,
714
+ previous: tableNode(renamed, ddlSchema, rename.to),
715
+ next: tableNode(expected, ddlSchema, rename.to)
716
+ }),
717
+ ...pairIndexRenames(pairing, issues).calls.filter(onRenamedTable),
718
+ ...pairCheckRenames(pairing, issues).calls.filter(onRenamedTable)
719
+ ]);
720
+ }
721
+ /**
722
+ * The call that renames a column, carrying as companions the renames of the objects on its table
723
+ * whose names derive from the column name: each unique constraint and foreign key on the column
724
+ * the destination keeps, named as the destination names it, and each index on the column renamed
725
+ * to the destination's wire name. `previous` is the schema before the rename; the renamed copy is
726
+ * diffed against the destination built from `contract`. A check on the column keeps its name: its
727
+ * expression names the column, so the diff replaces it.
728
+ */
729
+ function postgresColumnRenameCall(input) {
730
+ const { contract, rename } = input;
731
+ const schemaName = emissionSchemaForNamespace(contract, rename.namespaceId);
732
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, rename.namespaceId);
733
+ const renamed = renameColumnInPostgresSchema(input.previous, {
734
+ schemaName: ddlSchema,
735
+ table: rename.table,
736
+ from: rename.from,
737
+ to: rename.to
738
+ });
739
+ const { expected, issues } = buildPostgresPlanDiff({
740
+ contract,
741
+ actualSchema: renamed,
742
+ frameworkComponents: input.frameworkComponents
743
+ });
744
+ const table = tableNode(renamed, ddlSchema, rename.table);
745
+ const destination = expected.namespaces[ddlSchema]?.tables[rename.table];
746
+ const indexesOnColumn = new Set(table.indexes.filter((index) => index.columns?.includes(rename.to)).map((index) => index.name));
747
+ const indexRenames = pairIndexRenames({
748
+ contract,
749
+ policy: RENAME_POLICY
750
+ }, issues).calls.filter((call) => call.schemaName === schemaName && call.tableName === rename.table && indexesOnColumn.has(call.oldIndexName));
751
+ return new RenameColumnCall(schemaName, rename.table, rename.from, rename.to, [...destination === void 0 ? [] : constraintRenamesForColumnRename({
752
+ schemaName,
753
+ column: rename.to,
754
+ previous: table,
755
+ next: destination
756
+ }), ...indexRenames]);
757
+ }
758
+ /**
759
+ * Target-owned base class for Postgres migrations.
760
+ *
761
+ * Fixes the `SqlMigration` generic to `PostgresPlanTargetDetails` and the
762
+ * abstract `targetId` to the Postgres target-id string literal, so both
763
+ * user-authored migrations and renderer-generated scaffolds (the output of
764
+ * `renderCallsToTypeScript`) can extend `PostgresMigration` directly without
765
+ * redeclaring target-local identity.
766
+ *
767
+ * Mirrors `MongoMigration` in `@internal/family-mongo`: the renderer
768
+ * emits `extends Migration` against a facade re-export of this class
769
+ * from `@internal/postgres/migration`, keeping the authoring surface
770
+ * target-scoped rather than family-scoped.
771
+ *
772
+ * The constructor materializes a single Postgres `SqlControlAdapter` from
773
+ * `stack.adapter.create(stack)` and stores it; the protected `dataTransform`
774
+ * instance method forwards to the free `dataTransform` factory with that
775
+ * stored adapter, so user migrations can write `this.dataTransform(...)`
776
+ * without threading the adapter through every call.
777
+ *
778
+ * Every method requires an explicit `schema`. Postgres migrations name their
779
+ * schema deliberately — there is no default and no `search_path`-relative
780
+ * option. A migration that left the schema unspecified would resolve against
781
+ * whatever `search_path` the connection happened to carry, and that ambiguity
782
+ * is an antipattern in a migration. (The unbound/unspecified namespace concept
783
+ * remains for SQLite, which has no schemas, and for Mongo's connection `db`.)
784
+ */
785
+ var PostgresMigration = class extends Migration {
786
+ targetId = "postgres";
787
+ /**
788
+ * Materialized Postgres control adapter, created once per migration
789
+ * instance from the injected stack. `undefined` only when the migration
790
+ * was instantiated without a stack (test fixtures); `controlAdapterFor`
791
+ * throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING in that case to surface the misuse.
792
+ */
793
+ controlAdapter;
794
+ /** The rename calls this read of `operations` has made so far, in order. */
795
+ #renames = [];
796
+ #endView = new MigrationContractViews(this, "PostgresMigration", (json) => PostgresContractView.fromJson(json));
797
+ #startView = new MigrationContractViews(this, "PostgresMigration", (json) => PostgresContractView.fromJson(json));
798
+ constructor(stack) {
799
+ super(stack);
800
+ this.controlAdapter = stack?.adapter ? blindCast(stack.adapter.create(stack)) : void 0;
801
+ }
802
+ frameworkComponents() {
803
+ const stack = this.stack;
804
+ if (stack === void 0) return [];
805
+ return [
806
+ stack.target,
807
+ ...stack.adapter === void 0 ? [] : [stack.adapter],
808
+ ...stack.extensions
809
+ ];
810
+ }
811
+ /**
812
+ * Returns the materialized control adapter, or throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING naming
813
+ * `operation` when the migration was constructed without a `ControlStack`.
814
+ * Single home for the null-check that every DDL/DML method shares.
815
+ */
816
+ controlAdapterFor(operation) {
817
+ if (!this.controlAdapter) throw errorPostgresMigrationStackMissing(operation);
818
+ return this.controlAdapter;
819
+ }
820
+ /**
821
+ * The typed, schema-qualified Postgres view over this migration's end-state
822
+ * contract — `this.endContract.namespace.<schema>.table.<name>`, etc. Throws
823
+ * if no `endContractJson` was provided.
824
+ */
825
+ get endContract() {
826
+ return this.#endView.endContract;
827
+ }
828
+ /**
829
+ * The typed Postgres view over this migration's start-state contract, or
830
+ * `null` for a baseline migration (no `startContractJson`).
831
+ */
832
+ get startContract() {
833
+ return this.#startView.startContract;
834
+ }
835
+ /**
836
+ * Instance-method wrapper around the free `dataTransform` factory that
837
+ * supplies the stored control adapter. Authors call this from inside
838
+ * `get operations()`; the adapter argument is hidden from the call site.
839
+ */
840
+ dataTransform(contract, name, options) {
841
+ return dataTransform(contract, name, options, this.controlAdapterFor("dataTransform"));
842
+ }
843
+ /**
844
+ * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from
845
+ * the supplied options and lowers it through the stored control adapter.
846
+ * Throws if no adapter is present (i.e. migration instantiated without a stack).
847
+ */
848
+ createTable(options) {
849
+ return new CreateTableCall(options.schema, options.table, options.columns, options.constraints).toOp(this.controlAdapterFor("createTable"));
850
+ }
851
+ /**
852
+ * Emit a `CREATE SCHEMA` migration operation. Builds a typed DDL node from
853
+ * the supplied options and lowers it through the stored control adapter.
854
+ * Throws if no adapter is present (i.e. migration instantiated without a stack).
855
+ */
856
+ createSchema(options) {
857
+ return new CreateSchemaCall(options.schema).toOp(this.controlAdapterFor("createSchema"));
858
+ }
859
+ /**
860
+ * Emit a `CREATE TYPE ... AS ENUM (...)` migration operation for a managed
861
+ * native enum. Builds a typed DDL node and lowers it through the stored
862
+ * control adapter (members render in declaration order). Throws if no adapter
863
+ * is present.
864
+ */
865
+ createNativeEnumType(options) {
866
+ return new CreateNativeEnumTypeCall(options.schema, options.typeName, options.members).toOp(this.controlAdapterFor("createNativeEnumType"));
867
+ }
868
+ /**
869
+ * Emit a `DROP TYPE` migration operation for a managed native enum, lowered
870
+ * through the stored control adapter. Throws if no adapter is present.
871
+ */
872
+ dropNativeEnumType(options) {
873
+ return new DropNativeEnumTypeCall(options.schema, options.typeName).toOp(this.controlAdapterFor("dropNativeEnumType"));
874
+ }
875
+ /**
876
+ * Emit an `ALTER TYPE ... ADD VALUE` migration operation appending one
877
+ * member to a managed native enum, lowered through the stored control
878
+ * adapter. Throws if no adapter is present. Every appended value is its
879
+ * own operation — call this once per value to append more than one.
880
+ */
881
+ addNativeEnumValue(options) {
882
+ return new AddNativeEnumValueCall(options.schema, options.typeName, options.value).toOp(this.controlAdapterFor("addNativeEnumValue"));
883
+ }
884
+ addColumn(options) {
885
+ return new AddColumnCall(options.schema, options.table, options.column).toOp(this.controlAdapterFor("addColumn"));
886
+ }
887
+ addPrimaryKey(options) {
888
+ return new AddPrimaryKeyCall(options.schema, options.table, options.constraint, options.columns).toOp(this.controlAdapterFor("addPrimaryKey"));
889
+ }
890
+ addUnique(options) {
891
+ return new AddUniqueCall(options.schema, options.table, options.constraint, options.columns).toOp(this.controlAdapterFor("addUnique"));
892
+ }
893
+ addForeignKey(options) {
894
+ return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(this.controlAdapterFor("addForeignKey"));
895
+ }
896
+ addCheckConstraint(options) {
897
+ return new AddCheckConstraintCall(options.schema, options.table, options.constraint, options.expression).toOp(this.controlAdapterFor("addCheckConstraint"));
898
+ }
899
+ renameCheckConstraint(options) {
900
+ return this.renameConstraint({
901
+ ...options,
902
+ kind: "checkConstraint"
903
+ });
904
+ }
905
+ renameConstraint(options) {
906
+ const call = new RenameConstraintCall(options.schema ?? UNBOUND_NAMESPACE_ID, options.table, options.kind, options.from, options.to);
907
+ const adapter = this.controlAdapterFor("renameConstraint");
908
+ this.#renames.push(call);
909
+ return call.toOp(adapter);
910
+ }
911
+ dropCheckConstraint(options) {
912
+ return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(this.controlAdapterFor("dropCheckConstraint"));
913
+ }
914
+ dropConstraint(options) {
915
+ return new DropConstraintCall(options.schema, options.table, options.constraint, options.kind ?? "unique").toOp(this.controlAdapterFor("dropConstraint"));
916
+ }
917
+ /**
918
+ * Emit the operations that rename a table: the table rename, then a rename of each primary key,
919
+ * unique constraint, foreign key, index and check whose name was derived from the old table name.
920
+ * The old name is resolved against the schema as this migration's earlier rename calls
921
+ * (`renameTable`, `renameIndex`, `renameConstraint`, `renameRlsPolicy`) leave it, and the new
922
+ * name against the end contract, so the companions start from names an earlier rename gave.
923
+ * Spread the result into `operations`:
924
+ * `...this.renameTable({ table: 'userProfile', to: 'UserProfile' })`. `schema` names the table's
925
+ * namespace when more than one declares the table. Throws `MIGRATION.TABLE_RENAME_UNMATCHED` when
926
+ * the table does not exist at that point of the migration or the end contract lacks the new name.
927
+ */
928
+ renameTable(options) {
929
+ const adapter = this.controlAdapterFor("renameTable");
930
+ const rename = {
931
+ namespaceId: options.schema,
932
+ from: options.table,
933
+ to: options.to
934
+ };
935
+ const startContract = this.startContract;
936
+ if (startContract === null) throw unmatchedTableRename(rename, "the migration has no start contract");
937
+ const current = this.schemaAfterRenames(startContract);
938
+ const endContract = this.endContract;
939
+ const resolved = resolveTableRenameAgainst(postgresSchemaTables(current, startContract), endContract, rename);
940
+ if (!resolved.ok) throw resolved.failure;
941
+ const call = postgresTableRenameCall({
942
+ previous: current,
943
+ contract: endContract,
944
+ rename: resolved.value,
945
+ frameworkComponents: this.frameworkComponents()
946
+ });
947
+ this.#renames.push(call);
948
+ return call.toOps(adapter).map(async (op) => op);
949
+ }
950
+ /**
951
+ * Emit the operations that rename a column: the column rename, then a rename of each unique
952
+ * constraint, foreign key and index on the column whose name was derived from the old column
953
+ * name, to the name the end contract gives it. The column is resolved against the schema as this
954
+ * migration's earlier rename calls leave it, so a column of a table an earlier `renameTable`
955
+ * renamed is named on the table's new name. Spread the result into `operations`:
956
+ * `...this.renameColumn({ table: 'User', column: 'name', to: 'fullName' })`. `schema` names the
957
+ * table's namespace when more than one declares the table. Throws
958
+ * `MIGRATION.COLUMN_RENAME_UNMATCHED` when the table or column does not exist at that point of
959
+ * the migration, the table already has the new column, or the end contract lacks it.
960
+ */
961
+ renameColumn(options) {
962
+ const adapter = this.controlAdapterFor("renameColumn");
963
+ const rename = {
964
+ namespaceId: options.schema,
965
+ table: options.table,
966
+ from: options.column,
967
+ to: options.to
968
+ };
969
+ const startContract = this.startContract;
970
+ if (startContract === null) throw unmatchedColumnRename(rename, "the migration has no start contract");
971
+ const current = this.schemaAfterRenames(startContract);
972
+ const endContract = this.endContract;
973
+ const resolved = resolveColumnRenameAgainst(postgresSchemaTables(current, startContract), endContract, rename);
974
+ if (!resolved.ok) throw resolved.failure;
975
+ const call = postgresColumnRenameCall({
976
+ previous: current,
977
+ contract: endContract,
978
+ rename: resolved.value,
979
+ frameworkComponents: this.frameworkComponents()
980
+ });
981
+ this.#renames.push(call);
982
+ return call.toOps(adapter).map(async (op) => op);
983
+ }
984
+ /**
985
+ * The start contract's schema with this read's rename calls applied in order. It is built only
986
+ * when a `renameTable` needs it, so a migration that renames no table never reads its start
987
+ * contract.
988
+ */
989
+ schemaAfterRenames(startContract) {
990
+ const working = createWorkingSchema(postgresContractToSchema(startContract, this.frameworkComponents()));
991
+ for (const call of this.#renames) working.apply(call);
992
+ return working.current;
993
+ }
994
+ beginOperationsRead() {
995
+ this.#renames = [];
996
+ }
997
+ dropTable(options) {
998
+ return new DropTableCall(options.schema, options.table).toOp(this.controlAdapterFor("dropTable"));
999
+ }
1000
+ dropColumn(options) {
1001
+ return new DropColumnCall(options.schema, options.table, options.column).toOp(this.controlAdapterFor("dropColumn"));
1002
+ }
1003
+ alterColumnType(options) {
1004
+ return new AlterColumnTypeCall(options.schema, options.table, options.column, options.options).toOp(this.controlAdapterFor("alterColumnType"));
1005
+ }
1006
+ setNotNull(options) {
1007
+ return new SetNotNullCall(options.schema, options.table, options.column).toOp(this.controlAdapterFor("setNotNull"));
1008
+ }
1009
+ dropNotNull(options) {
1010
+ return new DropNotNullCall(options.schema, options.table, options.column).toOp(this.controlAdapterFor("dropNotNull"));
1011
+ }
1012
+ setDefault(options) {
1013
+ refuseEarlierSetDefaultOptions(options);
1014
+ return new SetDefaultCall(options.schema, options.table, options.column, options.operationClass).toOp(this.controlAdapterFor("setDefault"));
1015
+ }
1016
+ dropDefault(options) {
1017
+ return new DropDefaultCall(options.schema, options.table, options.column).toOp(this.controlAdapterFor("dropDefault"));
1018
+ }
1019
+ createIndex(options) {
1020
+ return new CreateIndexCall(options.schema, options.table, options.index, options.columns !== void 0 ? { columns: options.columns } : { expression: options.expression }, options.extras).toOp(this.controlAdapterFor("createIndex"));
1021
+ }
1022
+ renameIndex(options) {
1023
+ const call = new RenameIndexCall(options.schema, options.table, options.from, options.to);
1024
+ const adapter = this.controlAdapterFor("renameIndex");
1025
+ this.#renames.push(call);
1026
+ return call.toOp(adapter);
1027
+ }
1028
+ dropIndex(options) {
1029
+ return new DropIndexCall(options.schema, options.table, options.index).toOp(this.controlAdapterFor("dropIndex"));
1030
+ }
1031
+ installExtension(options) {
1032
+ return installExtension(options, this.controlAdapterFor("installExtension"));
1033
+ }
1034
+ enableRowLevelSecurity(options) {
1035
+ return new EnableRowLevelSecurityCall(options.schema, options.table).toOp(this.controlAdapterFor("enableRowLevelSecurity"));
1036
+ }
1037
+ disableRowLevelSecurity(options) {
1038
+ return new DisableRowLevelSecurityCall(options.schema, options.table).toOp(this.controlAdapterFor("disableRowLevelSecurity"));
1039
+ }
1040
+ createRlsPolicy(options) {
1041
+ return new CreatePostgresRlsPolicyCall(options.schema, options.table, new PostgresRlsPolicy({
1042
+ ...options.policy,
1043
+ using: options.policy.using,
1044
+ withCheck: options.policy.withCheck
1045
+ })).toOp(this.controlAdapterFor("createRlsPolicy"));
1046
+ }
1047
+ dropRlsPolicy(options) {
1048
+ return new DropPostgresRlsPolicyCall(options.schema, options.table, options.policy).toOp(this.controlAdapterFor("dropRlsPolicy"));
1049
+ }
1050
+ renameRlsPolicy(options) {
1051
+ const call = new RenamePostgresRlsPolicyCall(options.schema, options.table, options.from, options.to);
1052
+ const adapter = this.controlAdapterFor("renameRlsPolicy");
1053
+ this.#renames.push(call);
1054
+ return call.toOp(adapter);
1055
+ }
1056
+ };
1057
+ /**
1058
+ * `setDefault` options an earlier version wrote carry the column's name in `column` and its default as SQL text in `defaultSql`.
1059
+ */
1060
+ function refuseEarlierSetDefaultOptions(options) {
1061
+ const column = options.column;
1062
+ const columnIsName = typeof column === "string";
1063
+ if (!columnIsName && !Object.hasOwn(options, "defaultSql")) return;
1064
+ throw errorMigrationOperationOptionRemoved({
1065
+ operation: "setDefault",
1066
+ option: "defaultSql",
1067
+ subject: `column ${JSON.stringify(columnIsName ? column : options.column.name)} of table ${JSON.stringify(options.table)}`,
1068
+ rewrite: "Pass the column as `col(name, type, { default, codecRef })`, with its default written as `lit(value)` or `fn(expression)`, in place of its name and `defaultSql`.",
1069
+ upgradeEntry: "migration-ts-column-defaults"
1070
+ });
1071
+ }
1072
+ //#endregion
1073
+ export { postgresColumnRenameCall as a, postgresSchemaTables as c, renderRenameTableCall as d, pairIndexRenames as i, postgresTableRenameCall as l, createWorkingSchema as n, postgresContractToSchema as o, pairCheckRenames as r, postgresRenderDefault as s, PostgresMigration as t, renameTableByHandStatements as u };
1074
+
1075
+ //# sourceMappingURL=postgres-migration-DmczQSHT-DsWlow8L.mjs.map