@prisma-next/target-postgres 0.14.0-dev.49 → 0.14.0-dev.50
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.
- package/dist/control-policy-DUFgy9jO.mjs +1103 -0
- package/dist/control-policy-DUFgy9jO.mjs.map +1 -0
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +19 -40
- package/dist/control.mjs.map +1 -1
- package/dist/default-normalizer.mjs +247 -1
- package/dist/default-normalizer.mjs.map +1 -0
- package/dist/diff-database-schema-BmSmWcaY.mjs +313 -0
- package/dist/diff-database-schema-BmSmWcaY.mjs.map +1 -0
- package/dist/diff-database-schema.d.mts +46 -0
- package/dist/diff-database-schema.d.mts.map +1 -0
- package/dist/diff-database-schema.mjs +2 -0
- package/dist/issue-planner.d.mts +34 -10
- package/dist/issue-planner.d.mts.map +1 -1
- package/dist/issue-planner.mjs +2 -2
- package/dist/migration.d.mts +2 -2
- package/dist/migration.mjs +2 -2
- package/dist/native-type-normalizer.mjs +37 -1
- package/dist/native-type-normalizer.mjs.map +1 -0
- package/dist/{op-factory-call-BuoGT5UI.mjs → op-factory-call-BKRnMgrB.mjs} +2 -2
- package/dist/op-factory-call-BKRnMgrB.mjs.map +1 -0
- package/dist/{op-factory-call-Caqus-Qg.d.mts → op-factory-call-Dt-Jx5JS.d.mts} +2 -2
- package/dist/{op-factory-call-Caqus-Qg.d.mts.map → op-factory-call-Dt-Jx5JS.d.mts.map} +1 -1
- package/dist/op-factory-call.d.mts +2 -2
- package/dist/op-factory-call.mjs +2 -2
- package/dist/planner-BMBRPzsv.mjs +367 -0
- package/dist/planner-BMBRPzsv.mjs.map +1 -0
- package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -1
- package/dist/planner-ddl-builders.d.mts +2 -2
- package/dist/planner-ddl-builders.d.mts.map +1 -1
- package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
- package/dist/planner-identity-values.d.mts +7 -1
- package/dist/planner-identity-values.d.mts.map +1 -1
- package/dist/planner-identity-values.mjs +2 -2
- package/dist/{planner-produced-postgres-migration-CtJi4sgS.d.mts → planner-produced-postgres-migration-C0a7I1-e.d.mts} +2 -2
- package/dist/{planner-produced-postgres-migration-CtJi4sgS.d.mts.map → planner-produced-postgres-migration-C0a7I1-e.d.mts.map} +1 -1
- package/dist/{planner-produced-postgres-migration-C2_H6Vvl.mjs → planner-produced-postgres-migration-Dp6IO_gj.mjs} +2 -2
- package/dist/{planner-produced-postgres-migration-C2_H6Vvl.mjs.map → planner-produced-postgres-migration-Dp6IO_gj.mjs.map} +1 -1
- package/dist/planner-produced-postgres-migration.d.mts +1 -1
- package/dist/planner-produced-postgres-migration.mjs +1 -1
- package/dist/planner-sql-checks-Cze3vMfe.mjs.map +1 -1
- package/dist/planner-sql-checks.d.mts +1 -1
- package/dist/planner-sql-checks.d.mts.map +1 -1
- package/dist/planner.d.mts +27 -67
- package/dist/planner.d.mts.map +1 -1
- package/dist/planner.mjs +3 -2
- package/dist/{postgres-database-schema-node-os8ogEap.d.mts → postgres-database-schema-node-C9bTuMrd.d.mts} +14 -7
- package/dist/postgres-database-schema-node-C9bTuMrd.d.mts.map +1 -0
- package/dist/{postgres-migration-D0QIVE-p.mjs → postgres-migration-D0jwzYDT.mjs} +2 -2
- package/dist/{postgres-migration-D0QIVE-p.mjs.map → postgres-migration-D0jwzYDT.mjs.map} +1 -1
- package/dist/{postgres-migration-CfyKDT7b.d.mts → postgres-migration-DFaxuRyI.d.mts} +2 -2
- package/dist/{postgres-migration-CfyKDT7b.d.mts.map → postgres-migration-DFaxuRyI.d.mts.map} +1 -1
- package/dist/{postgres-table-schema-node-Clei_xel.mjs → postgres-table-schema-node-BgaSrxYN.mjs} +30 -29
- package/dist/postgres-table-schema-node-BgaSrxYN.mjs.map +1 -0
- package/dist/schema-node-kinds-ClScchhi.mjs +76 -0
- package/dist/schema-node-kinds-ClScchhi.mjs.map +1 -0
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs +1 -1
- package/package.json +21 -20
- package/src/core/migrations/column-ddl-rendering.ts +117 -0
- package/src/core/migrations/contract-to-postgres-database-schema-node.ts +25 -1
- package/src/core/migrations/control-policy.ts +68 -48
- package/src/core/migrations/diff-database-schema.ts +242 -153
- package/src/core/migrations/issue-planner.ts +621 -667
- package/src/core/migrations/operations/constraints.ts +1 -1
- package/src/core/migrations/planner-ddl-builders.ts +5 -2
- package/src/core/migrations/planner-identity-values.ts +1 -1
- package/src/core/migrations/planner-sql-checks.ts +1 -1
- package/src/core/migrations/planner-strategies.ts +248 -208
- package/src/core/migrations/planner.ts +180 -74
- package/src/core/migrations/runner.ts +1 -4
- package/src/core/migrations/verify-postgres-namespaces.ts +26 -15
- package/src/core/postgres-schema-verifier.ts +10 -7
- package/src/core/psl-infer/infer-psl-contract.ts +5 -10
- package/src/core/schema-ir/postgres-database-schema-node.ts +3 -6
- package/src/core/schema-ir/postgres-namespace-schema-node.ts +8 -9
- package/src/core/schema-ir/postgres-policy-schema-node.ts +3 -6
- package/src/core/schema-ir/postgres-role-schema-node.ts +3 -6
- package/src/core/schema-ir/postgres-table-schema-node.ts +20 -9
- package/src/core/schema-ir/schema-node-kinds.ts +80 -2
- package/src/exports/control.ts +10 -43
- package/src/exports/diff-database-schema.ts +7 -0
- package/src/exports/issue-planner.ts +1 -1
- package/src/exports/op-factory-call.ts +1 -0
- package/src/exports/planner-identity-values.ts +4 -1
- package/src/exports/planner.ts +0 -1
- package/dist/default-normalizer-Dug8Fez9.mjs +0 -248
- package/dist/default-normalizer-Dug8Fez9.mjs.map +0 -1
- package/dist/issue-planner-Cbh-xTEr.mjs +0 -849
- package/dist/issue-planner-Cbh-xTEr.mjs.map +0 -1
- package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
- package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
- package/dist/op-factory-call-BuoGT5UI.mjs.map +0 -1
- package/dist/planner-Bq0Z2sVO.mjs +0 -641
- package/dist/planner-Bq0Z2sVO.mjs.map +0 -1
- package/dist/postgres-database-schema-node-os8ogEap.d.mts.map +0 -1
- package/dist/postgres-table-schema-node-Clei_xel.mjs.map +0 -1
|
@@ -1,2 +1,248 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/core/default-normalizer.ts
|
|
2
|
+
/**
|
|
3
|
+
* Pre-compiled regex patterns for performance.
|
|
4
|
+
* These are compiled once at module load time rather than on each function call.
|
|
5
|
+
*/
|
|
6
|
+
const NEXTVAL_PATTERN = /^nextval\s*\(/i;
|
|
7
|
+
const NOW_FUNCTION_PATTERN = /^(now\s*\(\s*\)|CURRENT_TIMESTAMP)$/i;
|
|
8
|
+
const CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\s*\(\s*\)$/i;
|
|
9
|
+
const TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\s+(?:with|without)\s+time\s+zone)?$/i;
|
|
10
|
+
const TEXT_CAST_SUFFIX = /::text$/i;
|
|
11
|
+
const NOW_LITERAL_PATTERN = /^'now'$/i;
|
|
12
|
+
const UUID_PATTERN = /^gen_random_uuid\s*\(\s*\)$/i;
|
|
13
|
+
const UUID_OSSP_PATTERN = /^uuid_generate_v4\s*\(\s*\)$/i;
|
|
14
|
+
const NULL_PATTERN = /^NULL(?:::.+)?$/i;
|
|
15
|
+
const TRUE_PATTERN = /^true$/i;
|
|
16
|
+
const FALSE_PATTERN = /^false$/i;
|
|
17
|
+
const NUMERIC_PATTERN = /^-?\d+(\.\d+)?$/;
|
|
18
|
+
const STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:"[^"]+"|[\w\s]+)(?:\(\d+\))?)?$/;
|
|
19
|
+
/**
|
|
20
|
+
* Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.
|
|
21
|
+
* The literal body is captured in group 1; the cast (including `[]`) is optional.
|
|
22
|
+
* Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`
|
|
23
|
+
*/
|
|
24
|
+
const ARRAY_LITERAL_PATTERN = /^'(\{.*\})'(?:::.+\[\])?$/;
|
|
25
|
+
/**
|
|
26
|
+
* Returns the canonical expression for a timestamp default function, or undefined
|
|
27
|
+
* if the expression is not a recognized timestamp default.
|
|
28
|
+
*
|
|
29
|
+
* Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:
|
|
30
|
+
* - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'
|
|
31
|
+
* - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'
|
|
32
|
+
*
|
|
33
|
+
* These are semantically different in Postgres: now() returns the transaction
|
|
34
|
+
* start time (constant within a transaction), while clock_timestamp() returns
|
|
35
|
+
* the actual wall-clock time (can differ across rows in a single INSERT).
|
|
36
|
+
*/
|
|
37
|
+
function canonicalizeTimestampDefault(expr) {
|
|
38
|
+
if (NOW_FUNCTION_PATTERN.test(expr)) return "now()";
|
|
39
|
+
if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return "clock_timestamp()";
|
|
40
|
+
if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;
|
|
41
|
+
let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, "").trim();
|
|
42
|
+
if (inner.startsWith("(") && inner.endsWith(")")) inner = inner.slice(1, -1).trim();
|
|
43
|
+
if (NOW_FUNCTION_PATTERN.test(inner)) return "now()";
|
|
44
|
+
if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return "clock_timestamp()";
|
|
45
|
+
inner = inner.replace(TEXT_CAST_SUFFIX, "").trim();
|
|
46
|
+
if (NOW_LITERAL_PATTERN.test(inner)) return "now()";
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Splits a Postgres array literal body (without the enclosing braces) into its
|
|
50
|
+
* element tokens, honouring quoting. A comma only separates elements when it is
|
|
51
|
+
* outside double quotes; inside a quoted element a doubled quote (`""`) or a
|
|
52
|
+
* backslash-escaped quote (`\"`) is a literal quote, and a backslash escapes the
|
|
53
|
+
* next character. Returns undefined if the body is malformed (e.g. an unbalanced
|
|
54
|
+
* quote).
|
|
55
|
+
*/
|
|
56
|
+
function splitArrayElements(inner) {
|
|
57
|
+
const tokens = [];
|
|
58
|
+
let current = "";
|
|
59
|
+
let inQuotes = false;
|
|
60
|
+
let quoted = false;
|
|
61
|
+
for (let i = 0; i < inner.length; i++) {
|
|
62
|
+
const char = inner[i];
|
|
63
|
+
if (inQuotes) {
|
|
64
|
+
if (char === "\\") {
|
|
65
|
+
const next = inner[i + 1];
|
|
66
|
+
if (next === void 0) return void 0;
|
|
67
|
+
current += next;
|
|
68
|
+
i++;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (char === "\"") {
|
|
72
|
+
if (inner[i + 1] === "\"") {
|
|
73
|
+
current += "\"";
|
|
74
|
+
i++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
inQuotes = false;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
current += char;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (char === "\"") {
|
|
84
|
+
inQuotes = true;
|
|
85
|
+
quoted = true;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (char === ",") {
|
|
89
|
+
tokens.push({
|
|
90
|
+
value: current,
|
|
91
|
+
quoted
|
|
92
|
+
});
|
|
93
|
+
current = "";
|
|
94
|
+
quoted = false;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
current += char;
|
|
98
|
+
}
|
|
99
|
+
if (inQuotes) return void 0;
|
|
100
|
+
tokens.push({
|
|
101
|
+
value: current,
|
|
102
|
+
quoted
|
|
103
|
+
});
|
|
104
|
+
return tokens;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Parses a Postgres array literal body (`{...}`) into a JS array of primitives.
|
|
108
|
+
* Returns undefined if the body cannot be reliably parsed.
|
|
109
|
+
*
|
|
110
|
+
* Handles:
|
|
111
|
+
* - `{}` → `[]`
|
|
112
|
+
* - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion
|
|
113
|
+
* - quoted elements that contain commas, doubled/escaped quotes, and the literal
|
|
114
|
+
* strings `NULL`/`true`/`false` (a quoted token is always a string)
|
|
115
|
+
*/
|
|
116
|
+
function parseArrayLiteralBody(body) {
|
|
117
|
+
const inner = body.slice(1, -1).trim();
|
|
118
|
+
if (inner === "") return [];
|
|
119
|
+
const tokens = splitArrayElements(inner);
|
|
120
|
+
if (tokens === void 0) return void 0;
|
|
121
|
+
const result = [];
|
|
122
|
+
for (const token of tokens) {
|
|
123
|
+
if (token.quoted) {
|
|
124
|
+
result.push(token.value);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const el = token.value.trim();
|
|
128
|
+
if (el.toUpperCase() === "NULL") {
|
|
129
|
+
result.push(null);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (el === "true") {
|
|
133
|
+
result.push(true);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (el === "false") {
|
|
137
|
+
result.push(false);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (NUMERIC_PATTERN.test(el)) {
|
|
141
|
+
result.push(Number(el));
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Parses a raw Postgres column default expression into a normalized ColumnDefault.
|
|
150
|
+
* This enables semantic comparison between contract defaults and introspected schema defaults.
|
|
151
|
+
*
|
|
152
|
+
* Used by the migration diff layer to normalize raw database defaults during comparison,
|
|
153
|
+
* keeping the introspection layer focused on faithful data capture.
|
|
154
|
+
*
|
|
155
|
+
* @param rawDefault - Raw default expression from information_schema.columns.column_default
|
|
156
|
+
* @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)
|
|
157
|
+
* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
|
|
158
|
+
*/
|
|
159
|
+
function parsePostgresDefault(rawDefault, nativeType) {
|
|
160
|
+
const trimmed = rawDefault.trim();
|
|
161
|
+
const normalizedType = nativeType?.toLowerCase();
|
|
162
|
+
const isBigInt = normalizedType === "bigint" || normalizedType === "int8";
|
|
163
|
+
const isArrayType = normalizedType?.endsWith("[]") ?? false;
|
|
164
|
+
if (NEXTVAL_PATTERN.test(trimmed)) return {
|
|
165
|
+
kind: "function",
|
|
166
|
+
expression: "autoincrement()"
|
|
167
|
+
};
|
|
168
|
+
if (isArrayType) {
|
|
169
|
+
const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);
|
|
170
|
+
if (arrayMatch?.[1] !== void 0) {
|
|
171
|
+
const parsed = parseArrayLiteralBody(arrayMatch[1]);
|
|
172
|
+
if (parsed !== void 0) return {
|
|
173
|
+
kind: "literal",
|
|
174
|
+
value: parsed
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);
|
|
179
|
+
if (canonicalTimestamp) return {
|
|
180
|
+
kind: "function",
|
|
181
|
+
expression: canonicalTimestamp
|
|
182
|
+
};
|
|
183
|
+
if (UUID_PATTERN.test(trimmed)) return {
|
|
184
|
+
kind: "function",
|
|
185
|
+
expression: "gen_random_uuid()"
|
|
186
|
+
};
|
|
187
|
+
if (UUID_OSSP_PATTERN.test(trimmed)) return {
|
|
188
|
+
kind: "function",
|
|
189
|
+
expression: "gen_random_uuid()"
|
|
190
|
+
};
|
|
191
|
+
if (NULL_PATTERN.test(trimmed)) return {
|
|
192
|
+
kind: "literal",
|
|
193
|
+
value: null
|
|
194
|
+
};
|
|
195
|
+
if (TRUE_PATTERN.test(trimmed)) return {
|
|
196
|
+
kind: "literal",
|
|
197
|
+
value: true
|
|
198
|
+
};
|
|
199
|
+
if (FALSE_PATTERN.test(trimmed)) return {
|
|
200
|
+
kind: "literal",
|
|
201
|
+
value: false
|
|
202
|
+
};
|
|
203
|
+
if (NUMERIC_PATTERN.test(trimmed)) {
|
|
204
|
+
const num = Number(trimmed);
|
|
205
|
+
if (!Number.isFinite(num)) return void 0;
|
|
206
|
+
if (isBigInt && !Number.isSafeInteger(num)) return {
|
|
207
|
+
kind: "literal",
|
|
208
|
+
value: trimmed
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
kind: "literal",
|
|
212
|
+
value: num
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);
|
|
216
|
+
if (stringMatch?.[1] !== void 0) {
|
|
217
|
+
const unescaped = stringMatch[1].replace(/''/g, "'");
|
|
218
|
+
if (normalizedType === "json" || normalizedType === "jsonb") try {
|
|
219
|
+
return {
|
|
220
|
+
kind: "literal",
|
|
221
|
+
value: JSON.parse(unescaped)
|
|
222
|
+
};
|
|
223
|
+
} catch {}
|
|
224
|
+
if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {
|
|
225
|
+
const num = Number(unescaped);
|
|
226
|
+
if (Number.isSafeInteger(num)) return {
|
|
227
|
+
kind: "literal",
|
|
228
|
+
value: num
|
|
229
|
+
};
|
|
230
|
+
return {
|
|
231
|
+
kind: "literal",
|
|
232
|
+
value: unescaped
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
kind: "literal",
|
|
237
|
+
value: unescaped
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
kind: "function",
|
|
242
|
+
expression: trimmed
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
//#endregion
|
|
2
246
|
export { parsePostgresDefault };
|
|
247
|
+
|
|
248
|
+
//# sourceMappingURL=default-normalizer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-normalizer.mjs","names":[],"sources":["../src/core/default-normalizer.ts"],"sourcesContent":["import type { ColumnDefault, JsonValue } from '@prisma-next/contract/types';\n\n/**\n * Pre-compiled regex patterns for performance.\n * These are compiled once at module load time rather than on each function call.\n */\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n\n/**\n * Matches a Postgres array literal default of the form `'{...}'::elemtype[]`.\n * The literal body is captured in group 1; the cast (including `[]`) is optional.\n * Examples: `'{}'::text[]`, `'{1,2}'::integer[]`, `'{}'`\n */\nconst ARRAY_LITERAL_PATTERN = /^'(\\{.*\\})'(?:::.+\\[\\])?$/;\n\n/**\n * Returns the canonical expression for a timestamp default function, or undefined\n * if the expression is not a recognized timestamp default.\n *\n * Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n * - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n * - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n *\n * These are semantically different in Postgres: now() returns the transaction\n * start time (constant within a transaction), while clock_timestamp() returns\n * the actual wall-clock time (can differ across rows in a single INSERT).\n */\nfunction canonicalizeTimestampDefault(expr: string): string | undefined {\n if (NOW_FUNCTION_PATTERN.test(expr)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return 'clock_timestamp()';\n\n if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return undefined;\n\n let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, '').trim();\n\n if (inner.startsWith('(') && inner.endsWith(')')) {\n inner = inner.slice(1, -1).trim();\n }\n\n if (NOW_FUNCTION_PATTERN.test(inner)) return 'now()';\n if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return 'clock_timestamp()';\n\n inner = inner.replace(TEXT_CAST_SUFFIX, '').trim();\n if (NOW_LITERAL_PATTERN.test(inner)) return 'now()';\n\n return undefined;\n}\n\ntype ArrayElementToken = { readonly value: string; readonly quoted: boolean };\n\n/**\n * Splits a Postgres array literal body (without the enclosing braces) into its\n * element tokens, honouring quoting. A comma only separates elements when it is\n * outside double quotes; inside a quoted element a doubled quote (`\"\"`) or a\n * backslash-escaped quote (`\\\"`) is a literal quote, and a backslash escapes the\n * next character. Returns undefined if the body is malformed (e.g. an unbalanced\n * quote).\n */\nfunction splitArrayElements(inner: string): readonly ArrayElementToken[] | undefined {\n const tokens: ArrayElementToken[] = [];\n let current = '';\n let inQuotes = false;\n let quoted = false;\n\n for (let i = 0; i < inner.length; i++) {\n const char = inner[i];\n if (inQuotes) {\n if (char === '\\\\') {\n const next = inner[i + 1];\n if (next === undefined) return undefined;\n current += next;\n i++;\n continue;\n }\n if (char === '\"') {\n if (inner[i + 1] === '\"') {\n current += '\"';\n i++;\n continue;\n }\n inQuotes = false;\n continue;\n }\n current += char;\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n quoted = true;\n continue;\n }\n if (char === ',') {\n tokens.push({ value: current, quoted });\n current = '';\n quoted = false;\n continue;\n }\n current += char;\n }\n\n if (inQuotes) return undefined;\n tokens.push({ value: current, quoted });\n return tokens;\n}\n\n/**\n * Parses a Postgres array literal body (`{...}`) into a JS array of primitives.\n * Returns undefined if the body cannot be reliably parsed.\n *\n * Handles:\n * - `{}` → `[]`\n * - `{elem1,elem2,...}` → `[elem1, elem2, ...]` with numeric and string element coercion\n * - quoted elements that contain commas, doubled/escaped quotes, and the literal\n * strings `NULL`/`true`/`false` (a quoted token is always a string)\n */\nfunction parseArrayLiteralBody(body: string): readonly JsonValue[] | undefined {\n const inner = body.slice(1, -1).trim();\n if (inner === '') return [];\n const tokens = splitArrayElements(inner);\n if (tokens === undefined) return undefined;\n const result: JsonValue[] = [];\n for (const token of tokens) {\n if (token.quoted) {\n // A quoted token is always a string — `\"NULL\"`, `\"true\"`, `\"1\"` are the\n // literal text, never the keyword/number.\n result.push(token.value);\n continue;\n }\n const el = token.value.trim();\n if (el.toUpperCase() === 'NULL') {\n result.push(null);\n continue;\n }\n if (el === 'true') {\n result.push(true);\n continue;\n }\n if (el === 'false') {\n result.push(false);\n continue;\n }\n if (NUMERIC_PATTERN.test(el)) {\n result.push(Number(el));\n continue;\n }\n return undefined;\n }\n return result;\n}\n\n/**\n * Parses a raw Postgres column default expression into a normalized ColumnDefault.\n * This enables semantic comparison between contract defaults and introspected schema defaults.\n *\n * Used by the migration diff layer to normalize raw database defaults during comparison,\n * keeping the introspection layer focused on faithful data capture.\n *\n * @param rawDefault - Raw default expression from information_schema.columns.column_default\n * @param nativeType - Native column type, used for type-aware parsing (array, bigint, JSON)\n * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n */\nexport function parsePostgresDefault(\n rawDefault: string,\n nativeType?: string,\n): ColumnDefault | undefined {\n const trimmed = rawDefault.trim();\n const normalizedType = nativeType?.toLowerCase();\n const isBigInt = normalizedType === 'bigint' || normalizedType === 'int8';\n const isArrayType = normalizedType?.endsWith('[]') ?? false;\n\n if (NEXTVAL_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'autoincrement()' };\n }\n\n if (isArrayType) {\n const arrayMatch = trimmed.match(ARRAY_LITERAL_PATTERN);\n if (arrayMatch?.[1] !== undefined) {\n const parsed = parseArrayLiteralBody(arrayMatch[1]);\n if (parsed !== undefined) {\n return { kind: 'literal', value: parsed };\n }\n }\n }\n\n const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n if (canonicalTimestamp) {\n return { kind: 'function', expression: canonicalTimestamp };\n }\n\n if (UUID_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (UUID_OSSP_PATTERN.test(trimmed)) {\n return { kind: 'function', expression: 'gen_random_uuid()' };\n }\n\n if (NULL_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: null };\n }\n\n if (TRUE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: true };\n }\n if (FALSE_PATTERN.test(trimmed)) {\n return { kind: 'literal', value: false };\n }\n\n if (NUMERIC_PATTERN.test(trimmed)) {\n const num = Number(trimmed);\n if (!Number.isFinite(num)) return undefined;\n if (isBigInt && !Number.isSafeInteger(num)) {\n return { kind: 'literal', value: trimmed };\n }\n return { kind: 'literal', value: num };\n }\n\n const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n if (stringMatch?.[1] !== undefined) {\n const unescaped = stringMatch[1].replace(/''/g, \"'\");\n if (normalizedType === 'json' || normalizedType === 'jsonb') {\n try {\n return { kind: 'literal', value: JSON.parse(unescaped) };\n } catch {\n // Keep legacy behavior for malformed/non-JSON string content.\n }\n }\n if (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n const num = Number(unescaped);\n if (Number.isSafeInteger(num)) {\n return { kind: 'literal', value: num };\n }\n return { kind: 'literal', value: unescaped };\n }\n return { kind: 'literal', value: unescaped };\n }\n\n return { kind: 'function', expression: trimmed };\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eA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OAAO;IAAE,MAAM;IAAW,OAAO;GAAU;EAC7C;EACA,OAAO;GAAE,MAAM;GAAW,OAAO;EAAU;CAC7C;CAEA,OAAO;EAAE,MAAM;EAAY,YAAY;CAAQ;AACjD"}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { r as isPostgresSchema } from "./postgres-schema-CajYAwny.mjs";
|
|
2
|
+
import { r as postgresDiffSubjectGranularity } from "./schema-node-kinds-ClScchhi.mjs";
|
|
3
|
+
import { a as PostgresDatabaseSchemaNode, i as PostgresNamespaceSchemaNode, n as PostgresRoleSchemaNode, r as PostgresPolicySchemaNode, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-BgaSrxYN.mjs";
|
|
4
|
+
import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-Bv1ZvjX8.mjs";
|
|
5
|
+
import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-DUFgy9jO.mjs";
|
|
6
|
+
import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
|
|
7
|
+
import { blindCast } from "@prisma-next/utils/casts";
|
|
8
|
+
import { buildNativeTypeExpander, contractNamespaceToSchemaIR } from "@prisma-next/family-sql/control";
|
|
9
|
+
import { ifDefined } from "@prisma-next/utils/defined";
|
|
10
|
+
import { SqlForeignKeyIR } from "@prisma-next/sql-schema-ir/types";
|
|
11
|
+
import { classifyDiffSubjectGranularity, resolveSemanticSatisfaction } from "@prisma-next/family-sql/diff";
|
|
12
|
+
import { diffSchemas } from "@prisma-next/framework-components/control";
|
|
13
|
+
//#region src/core/migrations/contract-to-postgres-database-schema-node.ts
|
|
14
|
+
function toPolicyNode(policy, namespaceId) {
|
|
15
|
+
return new PostgresPolicySchemaNode({
|
|
16
|
+
name: policy.name,
|
|
17
|
+
prefix: policy.prefix,
|
|
18
|
+
tableName: policy.tableName,
|
|
19
|
+
namespaceId,
|
|
20
|
+
operation: policy.operation,
|
|
21
|
+
roles: [...policy.roles],
|
|
22
|
+
...ifDefined("using", policy.using),
|
|
23
|
+
...ifDefined("withCheck", policy.withCheck),
|
|
24
|
+
permissive: policy.permissive
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Projects a Postgres contract into the expected schema-diff tree: a
|
|
29
|
+
* `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`
|
|
30
|
+
* per Postgres namespace, each holding its `PostgresTableSchemaNode`s with
|
|
31
|
+
* their `PostgresPolicySchemaNode`s, plus the database roles on the root.
|
|
32
|
+
*
|
|
33
|
+
* Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,
|
|
34
|
+
* single `{ tables }` map (and throws on cross-namespace name collisions, with
|
|
35
|
+
* no RLS/role concept) for SQLite's single-schema world. This is the
|
|
36
|
+
* Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.
|
|
37
|
+
* It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)
|
|
38
|
+
* for column/FK/index building and only adds the Postgres tree/policy/role shape.
|
|
39
|
+
*
|
|
40
|
+
* Tables are grouped by their owning namespace (resolved DDL schema name) so
|
|
41
|
+
* the tree mirrors Postgres's object hierarchy. The DDL schema name is
|
|
42
|
+
* resolved once per namespace.
|
|
43
|
+
*
|
|
44
|
+
* A policy that references a table absent from its namespace is a malformed
|
|
45
|
+
* contract — the loop throws rather than fabricating a stub table.
|
|
46
|
+
*/
|
|
47
|
+
function contractToPostgresDatabaseSchemaNode(contract, options) {
|
|
48
|
+
if (contract === null) return new PostgresDatabaseSchemaNode({
|
|
49
|
+
namespaces: {},
|
|
50
|
+
roles: [],
|
|
51
|
+
existingSchemas: [],
|
|
52
|
+
pgVersion: ""
|
|
53
|
+
});
|
|
54
|
+
const namespaces = {};
|
|
55
|
+
const roles = [];
|
|
56
|
+
const ownedSchemas = [];
|
|
57
|
+
for (const ns of Object.values(contract.storage.namespaces)) {
|
|
58
|
+
if (!isPostgresSchema(ns)) continue;
|
|
59
|
+
const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);
|
|
60
|
+
ownedSchemas.push(ddlSchema);
|
|
61
|
+
const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;
|
|
62
|
+
const policiesByTable = /* @__PURE__ */ new Map();
|
|
63
|
+
for (const policy of Object.values(ns.policy)) {
|
|
64
|
+
const list = policiesByTable.get(policy.tableName) ?? [];
|
|
65
|
+
list.push(toPolicyNode(policy, ddlSchema));
|
|
66
|
+
policiesByTable.set(policy.tableName, list);
|
|
67
|
+
}
|
|
68
|
+
const tables = {};
|
|
69
|
+
for (const tableName of Object.keys(ns.table)) {
|
|
70
|
+
const sqlTable = sqlTables[tableName];
|
|
71
|
+
if (sqlTable === void 0) continue;
|
|
72
|
+
const foreignKeys = sqlTable.foreignKeys.map((fk) => new SqlForeignKeyIR({
|
|
73
|
+
columns: fk.columns,
|
|
74
|
+
referencedTable: fk.referencedTable,
|
|
75
|
+
referencedColumns: fk.referencedColumns,
|
|
76
|
+
...ifDefined("referencedSchema", fk.referencedSchema),
|
|
77
|
+
...ifDefined("name", fk.name),
|
|
78
|
+
...ifDefined("onDelete", fk.onDelete),
|
|
79
|
+
...ifDefined("onUpdate", fk.onUpdate),
|
|
80
|
+
...ifDefined("annotations", fk.annotations),
|
|
81
|
+
resolvedReferencedNamespace: resolveDdlSchemaForNamespaceStorage(contract.storage, fk.referencedSchema ?? UNBOUND_NAMESPACE_ID)
|
|
82
|
+
}));
|
|
83
|
+
tables[tableName] = new PostgresTableSchemaNode({
|
|
84
|
+
name: sqlTable.name,
|
|
85
|
+
columns: sqlTable.columns,
|
|
86
|
+
foreignKeys,
|
|
87
|
+
uniques: sqlTable.uniques,
|
|
88
|
+
indexes: sqlTable.indexes,
|
|
89
|
+
...ifDefined("primaryKey", sqlTable.primaryKey),
|
|
90
|
+
...ifDefined("annotations", sqlTable.annotations),
|
|
91
|
+
...ifDefined("checks", sqlTable.checks),
|
|
92
|
+
policies: policiesByTable.get(tableName) ?? []
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
for (const [tableName, tablePolicies] of policiesByTable) if (!(tableName in tables)) {
|
|
96
|
+
const policyName = tablePolicies[0]?.name ?? "(unknown)";
|
|
97
|
+
throw new Error(`contract-to-postgres-database-schema-node: policy "${policyName}" references table "${tableName}" not present in namespace "${ddlSchema}"`);
|
|
98
|
+
}
|
|
99
|
+
namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({
|
|
100
|
+
schemaName: ddlSchema,
|
|
101
|
+
tables,
|
|
102
|
+
nativeEnumTypeNames: []
|
|
103
|
+
});
|
|
104
|
+
for (const role of Object.values(ns.role)) roles.push(new PostgresRoleSchemaNode({
|
|
105
|
+
name: role.name,
|
|
106
|
+
namespaceId: role.namespaceId
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
return new PostgresDatabaseSchemaNode({
|
|
110
|
+
namespaces,
|
|
111
|
+
roles,
|
|
112
|
+
existingSchemas: ownedSchemas,
|
|
113
|
+
pgVersion: ""
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/core/migrations/diff-database-schema.ts
|
|
118
|
+
function ownedSchemaNames(expected) {
|
|
119
|
+
const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) => Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)));
|
|
120
|
+
return new Set([...policyNamespaces, ...expected.existingSchemas]);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Applies the family's semantic-satisfaction normalization across a Postgres
|
|
124
|
+
* tree pair: every actual table with an expected counterpart (paired by
|
|
125
|
+
* namespace id, then table id) gets its unique/index child lists adjusted;
|
|
126
|
+
* everything else passes through untouched.
|
|
127
|
+
*/
|
|
128
|
+
function normalizePostgresActualForDiff(expected, actual) {
|
|
129
|
+
const namespaces = {};
|
|
130
|
+
for (const [nsId, actualNs] of Object.entries(actual.namespaces)) {
|
|
131
|
+
const expectedNs = expected.namespaces[nsId];
|
|
132
|
+
if (expectedNs === void 0) {
|
|
133
|
+
namespaces[nsId] = actualNs;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const tables = {};
|
|
137
|
+
for (const [tableName, actualTable] of Object.entries(actualNs.tables)) {
|
|
138
|
+
const expectedTable = expectedNs.tables[tableName];
|
|
139
|
+
if (expectedTable === void 0) {
|
|
140
|
+
tables[tableName] = actualTable;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const adjusted = resolveSemanticSatisfaction({
|
|
144
|
+
expectedUniques: expectedTable.uniques,
|
|
145
|
+
expectedIndexes: expectedTable.indexes,
|
|
146
|
+
actualUniques: actualTable.uniques,
|
|
147
|
+
actualIndexes: actualTable.indexes
|
|
148
|
+
});
|
|
149
|
+
tables[tableName] = new PostgresTableSchemaNode({
|
|
150
|
+
name: actualTable.name,
|
|
151
|
+
columns: actualTable.columns,
|
|
152
|
+
foreignKeys: actualTable.foreignKeys,
|
|
153
|
+
uniques: adjusted.actualUniques,
|
|
154
|
+
indexes: adjusted.actualIndexes,
|
|
155
|
+
...ifDefined("primaryKey", actualTable.primaryKey),
|
|
156
|
+
...ifDefined("annotations", actualTable.annotations),
|
|
157
|
+
...ifDefined("checks", actualTable.checks),
|
|
158
|
+
policies: [...actualTable.policies]
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
namespaces[nsId] = new PostgresNamespaceSchemaNode({
|
|
162
|
+
schemaName: actualNs.schemaName,
|
|
163
|
+
tables,
|
|
164
|
+
nativeEnumTypeNames: actualNs.nativeEnumTypeNames
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return new PostgresDatabaseSchemaNode({
|
|
168
|
+
namespaces,
|
|
169
|
+
roles: [...actual.roles],
|
|
170
|
+
existingSchemas: [...actual.existingSchemas],
|
|
171
|
+
pgVersion: actual.pgVersion
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Drops contract namespaces that declare no tables from the verdict-diff
|
|
176
|
+
* expected tree and the relational owned-schema set. The legacy relational
|
|
177
|
+
* walk skipped a table-less namespace (e.g. an enums-only schema) before
|
|
178
|
+
* pairing, so neither its DDL schema's absence nor that schema's live
|
|
179
|
+
* relational contents ever reached the verdict — the pruned tree
|
|
180
|
+
* reproduces that. The prune loses no expected policies: policies attach
|
|
181
|
+
* to tables, so a table-less namespace carries none (the projection
|
|
182
|
+
* throws on a policy referencing an absent table). Live policies in a
|
|
183
|
+
* pruned schema remain governed via the full owned set (see
|
|
184
|
+
* {@link diffPostgresSchema}).
|
|
185
|
+
*/
|
|
186
|
+
function pruneTableLessNamespaces(expected) {
|
|
187
|
+
const namespaces = Object.fromEntries(Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0));
|
|
188
|
+
return new PostgresDatabaseSchemaNode({
|
|
189
|
+
namespaces,
|
|
190
|
+
roles: [...expected.roles],
|
|
191
|
+
existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== void 0),
|
|
192
|
+
pgVersion: expected.pgVersion
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Resolves a verdict-diff issue's subject table's declared control policy
|
|
197
|
+
* directly from the contract, by delegating to the same node-typed resolver
|
|
198
|
+
* ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to
|
|
199
|
+
* gate DDL calls. `undefined` when the issue resolves to no contract table.
|
|
200
|
+
*/
|
|
201
|
+
function resolveControlPolicy(issue, contract) {
|
|
202
|
+
return resolvePostgresNodeIssueControlPolicySubject(blindCast(issue), contract)?.explicitNodeControlPolicy;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The Postgres full-tree node diff for the family verify verdict: derive
|
|
206
|
+
* the expected tree (resolved leaf values, expander threaded, FK schemas
|
|
207
|
+
* resolved, table-less namespaces pruned), normalize the actual tree for
|
|
208
|
+
* semantic satisfaction, run the generic
|
|
209
|
+
* differ, and scope out `not-expected` findings under namespaces the
|
|
210
|
+
* contract does not own. Ownership is role-aware, mirroring the legacy
|
|
211
|
+
* decomposition: relational extras check the PRUNED owned set (the legacy
|
|
212
|
+
* per-namespace walk never visited a table-less namespace, so its live
|
|
213
|
+
* relational contents are invisible), while `structural` extras (RLS
|
|
214
|
+
* policies) check the FULL owned set (the legacy policy diff governed
|
|
215
|
+
* every contract schema regardless of tables — RLS governance does not
|
|
216
|
+
* shrink because a namespace declares no tables). The codec `verifyType`
|
|
217
|
+
* hooks run once per contract namespace with tables against that
|
|
218
|
+
* namespace's paired actual node (the hooks read namespace-scoped state
|
|
219
|
+
* such as `nativeEnumTypeNames`).
|
|
220
|
+
*/
|
|
221
|
+
function diffPostgresSchema(input) {
|
|
222
|
+
const postgresContract = blindCast(input.contract);
|
|
223
|
+
PostgresDatabaseSchemaNode.assert(input.schema);
|
|
224
|
+
const actual = input.schema;
|
|
225
|
+
const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
|
|
226
|
+
annotationNamespace: "pg",
|
|
227
|
+
...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
|
|
228
|
+
});
|
|
229
|
+
const expected = pruneTableLessNamespaces(fullExpected);
|
|
230
|
+
const normalizedActual = normalizePostgresActualForDiff(expected, actual);
|
|
231
|
+
const relationalOwned = ownedSchemaNames(expected);
|
|
232
|
+
const structuralOwned = ownedSchemaNames(fullExpected);
|
|
233
|
+
return {
|
|
234
|
+
issues: diffSchemas(expected, normalizedActual).filter((issue) => {
|
|
235
|
+
if (issue.reason !== "not-expected") return true;
|
|
236
|
+
const namespaceSegment = issue.path[1];
|
|
237
|
+
if (namespaceSegment === void 0) return true;
|
|
238
|
+
return (classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity) === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
|
|
239
|
+
}),
|
|
240
|
+
resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),
|
|
241
|
+
namespacePairs: Object.values(expected.namespaces).map((ns) => ({ actual: actual.namespaces[ns.schemaName] }))
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Adds an empty namespace node to the actual tree for every expected namespace
|
|
246
|
+
* absent from it. The relational plan diff pairs on namespace: a contract
|
|
247
|
+
* namespace whose live schema does not exist yet must surface each of its
|
|
248
|
+
* tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace
|
|
249
|
+
* `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`
|
|
250
|
+
* with no tables). Padding makes the namespaces pair, so only table/column/
|
|
251
|
+
* policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized
|
|
252
|
+
* namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the
|
|
253
|
+
* tree diff — matching the retired per-namespace-paired relational walk, which
|
|
254
|
+
* paired a missing schema against an empty namespace node.
|
|
255
|
+
*/
|
|
256
|
+
function padActualNamespaces(expected, actual) {
|
|
257
|
+
const namespaces = { ...actual.namespaces };
|
|
258
|
+
let padded = false;
|
|
259
|
+
for (const schemaName of Object.keys(expected.namespaces)) if (namespaces[schemaName] === void 0) {
|
|
260
|
+
namespaces[schemaName] = new PostgresNamespaceSchemaNode({
|
|
261
|
+
schemaName,
|
|
262
|
+
tables: {},
|
|
263
|
+
nativeEnumTypeNames: []
|
|
264
|
+
});
|
|
265
|
+
padded = true;
|
|
266
|
+
}
|
|
267
|
+
if (!padded) return actual;
|
|
268
|
+
return new PostgresDatabaseSchemaNode({
|
|
269
|
+
namespaces,
|
|
270
|
+
roles: [...actual.roles],
|
|
271
|
+
existingSchemas: [...actual.existingSchemas],
|
|
272
|
+
pgVersion: actual.pgVersion
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* The Postgres planner's diff input: the SAME tree-building
|
|
277
|
+
* `diffPostgresSchema` uses (expander threaded, FK schemas resolved,
|
|
278
|
+
* table-less namespaces pruned, actual normalized for semantic satisfaction,
|
|
279
|
+
* role-aware ownership filter) plus actual namespace padding (so a missing
|
|
280
|
+
* schema's tables surface as `not-found` instead of a swallowed namespace
|
|
281
|
+
* `not-found`). One differ drives both verify and plan; this is the
|
|
282
|
+
* plan-side derivation. The single issue list covers tables / columns /
|
|
283
|
+
* constraints / indexes / defaults AND policies — the caller splits it
|
|
284
|
+
* (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in
|
|
285
|
+
* `CREATE SCHEMA` separately.
|
|
286
|
+
*/
|
|
287
|
+
function buildPostgresPlanDiff(input) {
|
|
288
|
+
const postgresContract = blindCast(input.contract);
|
|
289
|
+
PostgresDatabaseSchemaNode.assert(input.actualSchema);
|
|
290
|
+
const actual = input.actualSchema;
|
|
291
|
+
const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {
|
|
292
|
+
annotationNamespace: "pg",
|
|
293
|
+
...ifDefined("expandNativeType", buildNativeTypeExpander(input.frameworkComponents))
|
|
294
|
+
});
|
|
295
|
+
const expected = pruneTableLessNamespaces(fullExpected);
|
|
296
|
+
const normalizedActual = normalizePostgresActualForDiff(expected, padActualNamespaces(expected, actual));
|
|
297
|
+
const relationalOwned = ownedSchemaNames(expected);
|
|
298
|
+
const structuralOwned = ownedSchemaNames(fullExpected);
|
|
299
|
+
return {
|
|
300
|
+
expected,
|
|
301
|
+
actual: normalizedActual,
|
|
302
|
+
issues: blindCast(diffSchemas(expected, normalizedActual)).filter((issue) => {
|
|
303
|
+
if (issue.reason !== "not-expected") return true;
|
|
304
|
+
const namespaceSegment = issue.path[1];
|
|
305
|
+
if (namespaceSegment === void 0) return true;
|
|
306
|
+
return (classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity) === "structural" ? structuralOwned : relationalOwned).has(namespaceSegment);
|
|
307
|
+
})
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
//#endregion
|
|
311
|
+
export { diffPostgresSchema as n, contractToPostgresDatabaseSchemaNode as r, buildPostgresPlanDiff as t };
|
|
312
|
+
|
|
313
|
+
//# sourceMappingURL=diff-database-schema-BmSmWcaY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diff-database-schema-BmSmWcaY.mjs","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport { SqlForeignKeyIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n // The family conversion stamps `referencedSchema` with the FK target's\n // namespace id verbatim, which can be the unbound sentinel. Resolve it\n // to the real live DDL schema here — introspected FKs already carry the\n // live schema, so this is what lets an expected FK pair (by diff-node\n // id) with its introspected counterpart.\n const foreignKeys = sqlTable.foreignKeys.map(\n (fk) =>\n new SqlForeignKeyIR({\n columns: fk.columns,\n referencedTable: fk.referencedTable,\n referencedColumns: fk.referencedColumns,\n ...ifDefined('referencedSchema', fk.referencedSchema),\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n ...ifDefined('annotations', fk.annotations),\n resolvedReferencedNamespace: resolveDdlSchemaForNamespaceStorage(\n contract.storage,\n fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ),\n }),\n );\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...ifDefined('primaryKey', sqlTable.primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n }\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnumTypeNames: [],\n });\n\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';\nimport { buildNativeTypeExpander } from '@prisma-next/family-sql/control';\nimport {\n classifyDiffSubjectGranularity,\n resolveSemanticSatisfaction,\n} from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport {\n postgresDiffSubjectGranularity,\n type SqlSchemaDiffNode,\n} from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\nimport { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n/**\n * Applies the family's semantic-satisfaction normalization across a Postgres\n * tree pair: every actual table with an expected counterpart (paired by\n * namespace id, then table id) gets its unique/index child lists adjusted;\n * everything else passes through untouched.\n */\nexport function normalizePostgresActualForDiff(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n for (const [nsId, actualNs] of Object.entries(actual.namespaces)) {\n const expectedNs = expected.namespaces[nsId];\n if (expectedNs === undefined) {\n namespaces[nsId] = actualNs;\n continue;\n }\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const [tableName, actualTable] of Object.entries(actualNs.tables)) {\n const expectedTable = expectedNs.tables[tableName];\n if (expectedTable === undefined) {\n tables[tableName] = actualTable;\n continue;\n }\n const adjusted = resolveSemanticSatisfaction({\n expectedUniques: expectedTable.uniques,\n expectedIndexes: expectedTable.indexes,\n actualUniques: actualTable.uniques,\n actualIndexes: actualTable.indexes,\n });\n tables[tableName] = new PostgresTableSchemaNode({\n name: actualTable.name,\n columns: actualTable.columns,\n foreignKeys: actualTable.foreignKeys,\n uniques: adjusted.actualUniques,\n indexes: adjusted.actualIndexes,\n ...ifDefined('primaryKey', actualTable.primaryKey),\n ...ifDefined('annotations', actualTable.annotations),\n ...ifDefined('checks', actualTable.checks),\n policies: [...actualTable.policies],\n });\n }\n namespaces[nsId] = new PostgresNamespaceSchemaNode({\n schemaName: actualNs.schemaName,\n tables,\n nativeEnumTypeNames: actualNs.nativeEnumTypeNames,\n });\n }\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\n/**\n * Drops contract namespaces that declare no tables from the verdict-diff\n * expected tree and the relational owned-schema set. The legacy relational\n * walk skipped a table-less namespace (e.g. an enums-only schema) before\n * pairing, so neither its DDL schema's absence nor that schema's live\n * relational contents ever reached the verdict — the pruned tree\n * reproduces that. The prune loses no expected policies: policies attach\n * to tables, so a table-less namespace carries none (the projection\n * throws on a policy referencing an absent table). Live policies in a\n * pruned schema remain governed via the full owned set (see\n * {@link diffPostgresSchema}).\n */\nfunction pruneTableLessNamespaces(\n expected: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces = Object.fromEntries(\n Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),\n );\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...expected.roles],\n existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),\n pgVersion: expected.pgVersion,\n });\n}\n\n/**\n * Resolves a verdict-diff issue's subject table's declared control policy\n * directly from the contract, by delegating to the same node-typed resolver\n * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to\n * gate DDL calls. `undefined` when the issue resolves to no contract table.\n */\nfunction resolveControlPolicy(\n issue: SchemaDiffIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicy | undefined {\n const nodeIssue = blindCast<\n SchemaDiffIssue<SqlSchemaDiffNode>,\n 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'\n >(issue);\n return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)\n ?.explicitNodeControlPolicy;\n}\n\n/**\n * The Postgres full-tree node diff for the family verify verdict: derive\n * the expected tree (resolved leaf values, expander threaded, FK schemas\n * resolved, table-less namespaces pruned), normalize the actual tree for\n * semantic satisfaction, run the generic\n * differ, and scope out `not-expected` findings under namespaces the\n * contract does not own. Ownership is role-aware, mirroring the legacy\n * decomposition: relational extras check the PRUNED owned set (the legacy\n * per-namespace walk never visited a table-less namespace, so its live\n * relational contents are invisible), while `structural` extras (RLS\n * policies) check the FULL owned set (the legacy policy diff governed\n * every contract schema regardless of tables — RLS governance does not\n * shrink because a namespace declares no tables). The codec `verifyType`\n * hooks run once per contract namespace with tables against that\n * namespace's paired actual node (the hooks read namespace-scoped state\n * such as `nativeEnumTypeNames`).\n */\nexport function diffPostgresSchema(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): SqlSchemaDiffResult {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresSchema is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.schema);\n const actual = input.schema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n });\n const expected = pruneTableLessNamespaces(fullExpected);\n const normalizedActual = normalizePostgresActualForDiff(expected, actual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = diffSchemas(expected, normalizedActual).filter((issue) => {\n if (issue.reason !== 'not-expected') return true;\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n const namespacePairs = Object.values(expected.namespaces).map((ns) => ({\n actual: actual.namespaces[ns.schemaName],\n }));\n return {\n issues,\n resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),\n namespacePairs,\n };\n}\n\n/**\n * Adds an empty namespace node to the actual tree for every expected namespace\n * absent from it. The relational plan diff pairs on namespace: a contract\n * namespace whose live schema does not exist yet must surface each of its\n * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace\n * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`\n * with no tables). Padding makes the namespaces pair, so only table/column/\n * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized\n * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the\n * tree diff — matching the retired per-namespace-paired relational walk, which\n * paired a missing schema against an empty namespace node.\n */\nfunction padActualNamespaces(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };\n let padded = false;\n for (const schemaName of Object.keys(expected.namespaces)) {\n if (namespaces[schemaName] === undefined) {\n namespaces[schemaName] = new PostgresNamespaceSchemaNode({\n schemaName,\n tables: {},\n nativeEnumTypeNames: [],\n });\n padded = true;\n }\n }\n if (!padded) return actual;\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\nexport interface PostgresPlanDiff {\n /** The desired (\"end\") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */\n readonly expected: PostgresDatabaseSchemaNode;\n /** The live (\"start\") tree, padded with empty namespaces and normalized for semantic satisfaction against `expected`. */\n readonly actual: PostgresDatabaseSchemaNode;\n /** The one node diff over the two trees: relational + policy drift, role-aware ownership filtered. */\n readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n}\n\n/**\n * The Postgres planner's diff input: the SAME tree-building\n * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,\n * table-less namespaces pruned, actual normalized for semantic satisfaction,\n * role-aware ownership filter) plus actual namespace padding (so a missing\n * schema's tables surface as `not-found` instead of a swallowed namespace\n * `not-found`). One differ drives both verify and plan; this is the\n * plan-side derivation. The single issue list covers tables / columns /\n * constraints / indexes / defaults AND policies — the caller splits it\n * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in\n * `CREATE SCHEMA` separately.\n */\nexport function buildPostgresPlanDiff(input: {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): PostgresPlanDiff {\n const postgresContract = blindCast<\n PostgresContract,\n 'buildPostgresPlanDiff is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const actual = input.actualSchema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const projectionOptions = {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n };\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);\n const expected = pruneTableLessNamespaces(fullExpected);\n const paddedActual = padActualNamespaces(expected, actual);\n const normalizedActual = normalizePostgresActualForDiff(expected, paddedActual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, normalizedActual)).filter((issue) => {\n if (issue.reason !== 'not-expected') return true;\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n return { expected, actual: normalizedActual, issues };\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG,UAAU,SAAS,OAAO,KAAK;EAClC,GAAG,UAAU,aAAa,OAAO,SAAS;EAC1C,YAAY,OAAO;CACrB,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,qCACd,UACA,SAC4B;CAC5B,IAAI,aAAa,MACf,OAAO,IAAI,2BAA2B;EACpC,YAAY,CAAC;EACb,OAAO,CAAC;EACR,iBAAiB,CAAC;EAClB,WAAW;CACb,CAAC;CAGH,MAAM,aAA0D,CAAC;CACjE,MAAM,QAAkC,CAAC;CACzC,MAAM,eAAyB,CAAC;CAEhC,KAAK,MAAM,MAAM,OAAO,OAAO,SAAS,QAAQ,UAAU,GAAG;EAC3D,IAAI,CAAC,iBAAiB,EAAE,GAAG;EAC3B,MAAM,YAAY,oCAAoC,SAAS,SAAS,GAAG,EAAE;EAC7E,aAAa,KAAK,SAAS;EAK3B,MAAM,YAAY,4BAA4B,SAAS,SAAS,GAAG,IAAI,OAAO,CAAC,CAAC;EAEhF,MAAM,kCAAkB,IAAI,IAAwC;EACpE,KAAK,MAAM,UAAU,OAAO,OAAO,GAAG,MAAM,GAAG;GAC7C,MAAM,OAAO,gBAAgB,IAAI,OAAO,SAAS,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