@prisma-next/adapter-postgres 0.12.0-dev.6 → 0.12.0-dev.60
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/{adapter-H8BiuXdq.mjs → adapter-DctzSWYj.mjs} +13 -13
- package/dist/adapter-DctzSWYj.mjs.map +1 -0
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.d.mts.map +1 -1
- package/dist/adapter.mjs +1 -1
- package/dist/column-types.d.mts.map +1 -1
- package/dist/control-adapter-B7tCv02A.mjs +1357 -0
- package/dist/control-adapter-B7tCv02A.mjs.map +1 -0
- package/dist/control.d.mts +60 -10
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +4 -660
- package/dist/control.mjs.map +1 -1
- package/dist/{descriptor-meta-C1wNCHkd.mjs → descriptor-meta-NBwpqHS7.mjs} +1 -1
- package/dist/{descriptor-meta-C1wNCHkd.mjs.map → descriptor-meta-NBwpqHS7.mjs.map} +1 -1
- package/dist/operation-types.d.mts +1 -1
- package/dist/runtime.d.mts +2 -2
- package/dist/runtime.mjs +2 -2
- package/dist/{types-B1eiuBHQ.d.mts → types-Dv7M8jx8.d.mts} +1 -1
- package/dist/{types-B1eiuBHQ.d.mts.map → types-Dv7M8jx8.d.mts.map} +1 -1
- package/dist/types.d.mts +2 -2
- package/package.json +24 -24
- package/src/core/adapter.ts +28 -25
- package/src/core/control-adapter.ts +380 -105
- package/src/core/ddl-renderer.ts +73 -0
- package/src/core/enum-control-hooks.ts +2 -2
- package/src/core/marker-ledger.ts +124 -0
- package/src/core/sql-renderer.ts +66 -23
- package/dist/adapter-H8BiuXdq.mjs.map +0 -1
- package/dist/sql-renderer-DlZhVI9B.mjs +0 -457
- package/dist/sql-renderer-DlZhVI9B.mjs.map +0 -1
package/dist/control.mjs
CHANGED
|
@@ -1,666 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as postgresAdapterDescriptorMeta } from "./descriptor-meta-
|
|
3
|
-
import {
|
|
1
|
+
import { t as PostgresControlAdapter } from "./control-adapter-B7tCv02A.mjs";
|
|
2
|
+
import { t as postgresAdapterDescriptorMeta } from "./descriptor-meta-NBwpqHS7.mjs";
|
|
3
|
+
import { parsePostgresDefault } from "@prisma-next/target-postgres/default-normalizer";
|
|
4
|
+
import { normalizeSchemaNativeType } from "@prisma-next/target-postgres/native-type-normalizer";
|
|
4
5
|
import { SqlEscapeError, escapeLiteral, qualifyName, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
|
|
5
|
-
import { ifDefined } from "@prisma-next/utils/defined";
|
|
6
|
-
import { PG_ENUM_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
|
|
7
|
-
import { parseMarkerRowSafely, withMarkerReadErrorHandling } from "@prisma-next/errors/execution";
|
|
8
|
-
import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
|
|
9
|
-
import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
|
|
10
|
-
import { parsePostgresDefault, parsePostgresDefault as parsePostgresDefault$1 } from "@prisma-next/target-postgres/default-normalizer";
|
|
11
|
-
import { createResolveExistingEnumValues, enumStorageCompoundKey, readExistingEnumValues, readPostgresSchemaIrAnnotations } from "@prisma-next/target-postgres/enum-planning";
|
|
12
|
-
import { normalizeSchemaNativeType, normalizeSchemaNativeType as normalizeSchemaNativeType$1 } from "@prisma-next/target-postgres/native-type-normalizer";
|
|
13
|
-
import { blindCast } from "@prisma-next/utils/casts";
|
|
14
6
|
import { timestampNowControlDescriptor } from "@prisma-next/family-sql/control";
|
|
15
7
|
import { builtinGeneratorRegistryMetadata, resolveBuiltinGeneratedColumnDescriptor } from "@prisma-next/ids";
|
|
16
|
-
//#region src/core/enum-control-hooks.ts
|
|
17
|
-
const ENUM_INTROSPECT_QUERY = `
|
|
18
|
-
SELECT
|
|
19
|
-
n.nspname AS schema_name,
|
|
20
|
-
t.typname AS type_name,
|
|
21
|
-
array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
|
|
22
|
-
FROM pg_type t
|
|
23
|
-
JOIN pg_namespace n ON t.typnamespace = n.oid
|
|
24
|
-
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
25
|
-
WHERE n.nspname = $1
|
|
26
|
-
GROUP BY n.nspname, t.typname
|
|
27
|
-
ORDER BY n.nspname, t.typname
|
|
28
|
-
`;
|
|
29
|
-
function isStringArray(value) {
|
|
30
|
-
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Parses a PostgreSQL array value into a JavaScript string array.
|
|
34
|
-
*
|
|
35
|
-
* The `pg` library returns `array_agg` results either as a JS array
|
|
36
|
-
* (when type parsers are configured) or as a string in PostgreSQL array
|
|
37
|
-
* literal format (`{value1,value2,...}`). Handles PG's quoting rules:
|
|
38
|
-
* - Elements containing commas, quotes, backslashes, or whitespace are
|
|
39
|
-
* double-quoted.
|
|
40
|
-
* - Inside quoted elements, `\"` represents `"` and `\\` represents `\`.
|
|
41
|
-
*
|
|
42
|
-
* Returns `null` when the input cannot be parsed as a PG array.
|
|
43
|
-
*/
|
|
44
|
-
function parsePostgresArray(value) {
|
|
45
|
-
if (isStringArray(value)) return value;
|
|
46
|
-
if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
|
|
47
|
-
const inner = value.slice(1, -1);
|
|
48
|
-
if (inner === "") return [];
|
|
49
|
-
return parseArrayElements(inner);
|
|
50
|
-
}
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
function parseArrayElements(input) {
|
|
54
|
-
const result = [];
|
|
55
|
-
let i = 0;
|
|
56
|
-
while (i < input.length) {
|
|
57
|
-
if (input[i] === ",") {
|
|
58
|
-
i++;
|
|
59
|
-
continue;
|
|
60
|
-
}
|
|
61
|
-
if (input[i] === "\"") {
|
|
62
|
-
i++;
|
|
63
|
-
let element = "";
|
|
64
|
-
while (i < input.length && input[i] !== "\"") {
|
|
65
|
-
if (input[i] === "\\" && i + 1 < input.length) {
|
|
66
|
-
i++;
|
|
67
|
-
element += input[i];
|
|
68
|
-
} else element += input[i];
|
|
69
|
-
i++;
|
|
70
|
-
}
|
|
71
|
-
i++;
|
|
72
|
-
result.push(element);
|
|
73
|
-
} else {
|
|
74
|
-
const nextComma = input.indexOf(",", i);
|
|
75
|
-
if (nextComma === -1) {
|
|
76
|
-
result.push(input.slice(i).trim());
|
|
77
|
-
i = input.length;
|
|
78
|
-
} else {
|
|
79
|
-
result.push(input.slice(i, nextComma).trim());
|
|
80
|
-
i = nextComma;
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
return result;
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Reads enum types from the live Postgres schema and returns them in
|
|
88
|
-
* the codec-typed annotation shape consumed by `control-adapter.ts`
|
|
89
|
-
* (which writes them under `schema.annotations.pg.storageTypes`).
|
|
90
|
-
*/
|
|
91
|
-
async function introspectPostgresEnumTypes(options) {
|
|
92
|
-
const namespace = options.schemaName ?? "public";
|
|
93
|
-
const result = await options.driver.query(ENUM_INTROSPECT_QUERY, [namespace]);
|
|
94
|
-
const types = {};
|
|
95
|
-
for (const row of result.rows) {
|
|
96
|
-
const values = parsePostgresArray(row.values);
|
|
97
|
-
if (!values) throw new Error(`Failed to parse enum values for type "${row.type_name}": unexpected format: ${JSON.stringify(row.values)}`);
|
|
98
|
-
types[row.type_name] = {
|
|
99
|
-
codecId: PG_ENUM_CODEC_ID,
|
|
100
|
-
nativeType: row.type_name,
|
|
101
|
-
typeParams: { values }
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
return types;
|
|
105
|
-
}
|
|
106
|
-
//#endregion
|
|
107
|
-
//#region src/core/control-adapter.ts
|
|
108
|
-
const POSTGRES_MARKER_TABLE = "prisma_contract.marker";
|
|
109
|
-
/**
|
|
110
|
-
* Postgres control plane adapter for control-plane operations like introspection.
|
|
111
|
-
* Provides target-specific implementations for control-plane domain actions.
|
|
112
|
-
*/
|
|
113
|
-
var PostgresControlAdapter = class {
|
|
114
|
-
familyId = "sql";
|
|
115
|
-
targetId = "postgres";
|
|
116
|
-
codecLookup;
|
|
117
|
-
/**
|
|
118
|
-
* @param codecLookup - Codec lookup used by the SQL renderer to resolve
|
|
119
|
-
* per-codec metadata at lower-time. Defaults to a Postgres-builtins-only
|
|
120
|
-
* lookup when omitted. Stack-aware callers
|
|
121
|
-
* (`SqlControlAdapterDescriptor.create(stack)`) supply
|
|
122
|
-
* `stack.codecLookup` so extension codecs are visible to the renderer.
|
|
123
|
-
*/
|
|
124
|
-
constructor(codecLookup) {
|
|
125
|
-
this.codecLookup = codecLookup ?? createPostgresBuiltinCodecLookup();
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Target-specific normalizer for raw Postgres default expressions.
|
|
129
|
-
* Used by schema verification to normalize raw defaults before comparison.
|
|
130
|
-
*/
|
|
131
|
-
normalizeDefault = parsePostgresDefault$1;
|
|
132
|
-
/**
|
|
133
|
-
* Target-specific normalizer for Postgres schema native type names.
|
|
134
|
-
* Used by schema verification to normalize introspected type names
|
|
135
|
-
* before comparison with contract native types.
|
|
136
|
-
*/
|
|
137
|
-
normalizeNativeType = normalizeSchemaNativeType$1;
|
|
138
|
-
/**
|
|
139
|
-
* Bridges native `PostgresEnumStorageEntry` IR walks against the Postgres
|
|
140
|
-
* introspection shape (`schema.annotations.pg.storageTypes`). Lets
|
|
141
|
-
* the family-level schema verifier walk enum types without reaching
|
|
142
|
-
* into target-specific annotation layouts itself.
|
|
143
|
-
*/
|
|
144
|
-
resolveExistingEnumValues = (schema, enumType, namespaceId) => {
|
|
145
|
-
return readExistingEnumValues(schema, namespaceId === UNBOUND_NAMESPACE_ID ? readPostgresSchemaIrAnnotations(schema).schema ?? "public" : namespaceId, enumType.nativeType);
|
|
146
|
-
};
|
|
147
|
-
resolveExistingEnumValuesForContract = (contract) => createResolveExistingEnumValues(contract.storage);
|
|
148
|
-
/**
|
|
149
|
-
* Lower a SQL query AST into a Postgres-flavored `{ sql, params }` payload.
|
|
150
|
-
*
|
|
151
|
-
* Delegates to the shared `renderLoweredSql` renderer so the control adapter
|
|
152
|
-
* emits byte-identical SQL to `PostgresAdapterImpl.lower()` for the same AST
|
|
153
|
-
* and contract. Used at migration plan/emit time (e.g. by `dataTransform`)
|
|
154
|
-
* without instantiating the runtime adapter.
|
|
155
|
-
*/
|
|
156
|
-
lower(ast, context) {
|
|
157
|
-
return renderLoweredSql(ast, context.contract, this.codecLookup);
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Reads the contract marker from `prisma_contract.marker`. Probes
|
|
161
|
-
* `information_schema.tables` first so a fresh database (where the
|
|
162
|
-
* `prisma_contract` schema doesn't yet exist) returns `null` instead of a
|
|
163
|
-
* "relation does not exist" error — some Postgres wire-protocol clients
|
|
164
|
-
* (e.g. PGlite's TCP proxy) don't fully recover from extended-protocol
|
|
165
|
-
* parse errors, so we probe before reading.
|
|
166
|
-
*/
|
|
167
|
-
async readMarker(driver, space) {
|
|
168
|
-
const markerContext = {
|
|
169
|
-
space,
|
|
170
|
-
markerLocation: POSTGRES_MARKER_TABLE
|
|
171
|
-
};
|
|
172
|
-
if ((await withMarkerReadErrorHandling(() => driver.query(`select 1
|
|
173
|
-
from information_schema.tables
|
|
174
|
-
where table_schema = $1 and table_name = $2`, ["prisma_contract", "marker"]), markerContext)).rows.length === 0) return null;
|
|
175
|
-
const row = (await withMarkerReadErrorHandling(() => driver.query(`select
|
|
176
|
-
core_hash,
|
|
177
|
-
profile_hash,
|
|
178
|
-
contract_json,
|
|
179
|
-
canonical_version,
|
|
180
|
-
updated_at,
|
|
181
|
-
app_tag,
|
|
182
|
-
meta,
|
|
183
|
-
invariants
|
|
184
|
-
from prisma_contract.marker
|
|
185
|
-
where space = $1`, [space]), markerContext)).rows[0];
|
|
186
|
-
if (!row) return null;
|
|
187
|
-
return parseMarkerRowSafely(row, parseContractMarkerRow, markerContext);
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Reads every row from `prisma_contract.marker` and returns them keyed
|
|
191
|
-
* by `space`. Mirrors the existence probe in {@link readMarker}: a
|
|
192
|
-
* fresh database without the `prisma_contract` schema returns an empty
|
|
193
|
-
* map rather than raising "relation does not exist".
|
|
194
|
-
*/
|
|
195
|
-
async readAllMarkers(driver) {
|
|
196
|
-
const markerContext = {
|
|
197
|
-
space: APP_SPACE_ID,
|
|
198
|
-
markerLocation: POSTGRES_MARKER_TABLE
|
|
199
|
-
};
|
|
200
|
-
if ((await withMarkerReadErrorHandling(() => driver.query(`select 1
|
|
201
|
-
from information_schema.tables
|
|
202
|
-
where table_schema = $1 and table_name = $2`, ["prisma_contract", "marker"]), markerContext)).rows.length === 0) return /* @__PURE__ */ new Map();
|
|
203
|
-
const result = await withMarkerReadErrorHandling(() => driver.query(`select
|
|
204
|
-
space,
|
|
205
|
-
core_hash,
|
|
206
|
-
profile_hash,
|
|
207
|
-
contract_json,
|
|
208
|
-
canonical_version,
|
|
209
|
-
updated_at,
|
|
210
|
-
app_tag,
|
|
211
|
-
meta,
|
|
212
|
-
invariants
|
|
213
|
-
from prisma_contract.marker`), markerContext);
|
|
214
|
-
const rows = /* @__PURE__ */ new Map();
|
|
215
|
-
for (const row of result.rows) rows.set(row.space, parseMarkerRowSafely(row, parseContractMarkerRow, {
|
|
216
|
-
space: row.space,
|
|
217
|
-
markerLocation: POSTGRES_MARKER_TABLE
|
|
218
|
-
}));
|
|
219
|
-
return rows;
|
|
220
|
-
}
|
|
221
|
-
/**
|
|
222
|
-
* Introspects a Postgres database schema and returns a raw SqlSchemaIR.
|
|
223
|
-
*
|
|
224
|
-
* This is a pure schema discovery operation that queries the Postgres catalog
|
|
225
|
-
* and returns the schema structure without type mapping or contract enrichment.
|
|
226
|
-
* Type mapping and enrichment are handled separately by enrichment helpers.
|
|
227
|
-
*
|
|
228
|
-
* When `contract` is provided and its storage declares more than one
|
|
229
|
-
* namespace (or any explicit bound namespace), the adapter walks every
|
|
230
|
-
* declared namespace and merges the per-schema introspection results
|
|
231
|
-
* into a single `SqlSchemaIR`. `UNBOUND_NAMESPACE_ID` resolves to the
|
|
232
|
-
* connection's `current_schema()` so late-bound tables follow the
|
|
233
|
-
* runtime `search_path`. When no contract is passed, the adapter falls
|
|
234
|
-
* back to introspecting the single `schema` argument (defaulting to
|
|
235
|
-
* `'public'`).
|
|
236
|
-
*
|
|
237
|
-
* Uses batched queries to minimize database round trips (6 queries per
|
|
238
|
-
* schema walked).
|
|
239
|
-
*
|
|
240
|
-
* @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries
|
|
241
|
-
* @param contract - Optional contract for contract-guided introspection (multi-namespace walk, filtering)
|
|
242
|
-
* @param schema - Schema name to introspect when no contract is provided (defaults to 'public')
|
|
243
|
-
* @returns Promise resolving to SqlSchemaIR representing the live database schema
|
|
244
|
-
*/
|
|
245
|
-
async introspect(driver, contract, schema = "public") {
|
|
246
|
-
const declaredNamespaces = extractContractNamespaceIds(contract);
|
|
247
|
-
const ir = declaredNamespaces.length > 0 ? await this.introspectNamespaces(driver, declaredNamespaces) : await this.introspectSchema(driver, schema);
|
|
248
|
-
const existingSchemas = await this.listExistingSchemas(driver);
|
|
249
|
-
const annotations = ir.annotations ?? {};
|
|
250
|
-
const pg = annotations.pg ?? {};
|
|
251
|
-
return {
|
|
252
|
-
...ir,
|
|
253
|
-
annotations: {
|
|
254
|
-
...annotations,
|
|
255
|
-
pg: {
|
|
256
|
-
...pg,
|
|
257
|
-
existingSchemas
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Lists every non-system schema present in the connected database.
|
|
264
|
-
* The introspection consumer (`verifyPostgresNamespacePresence`)
|
|
265
|
-
* treats the result as the authoritative ground truth — declared
|
|
266
|
-
* namespaces whose `ddlSchemaName` is missing from this list become
|
|
267
|
-
* `missing_schema` issues, and the planner emits the matching
|
|
268
|
-
* `CREATE SCHEMA` before table DDL.
|
|
269
|
-
*/
|
|
270
|
-
async listExistingSchemas(driver) {
|
|
271
|
-
return (await driver.query(`SELECT nspname
|
|
272
|
-
FROM pg_catalog.pg_namespace
|
|
273
|
-
WHERE nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
274
|
-
AND nspname NOT LIKE 'pg_temp_%'
|
|
275
|
-
AND nspname NOT LIKE 'pg_toast_temp_%'
|
|
276
|
-
ORDER BY nspname`)).rows.map((row) => row.nspname);
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Walks every declared namespace, resolving `UNBOUND_NAMESPACE_ID` to
|
|
280
|
-
* the connection's `current_schema()`, and merges the per-schema results
|
|
281
|
-
* into a single `SqlSchemaIR`. The merged `tables` map is flat (keyed by
|
|
282
|
-
* table name) so callers that look up by `tableName` see every contract
|
|
283
|
-
* table regardless of which namespace it lives in.
|
|
284
|
-
*/
|
|
285
|
-
async introspectNamespaces(driver, namespaceIds) {
|
|
286
|
-
const resolvedSchemas = await Promise.all(namespaceIds.map(async (id) => {
|
|
287
|
-
if (id === UNBOUND_NAMESPACE_ID) {
|
|
288
|
-
const { rows } = await driver.query("SELECT current_schema() AS current_schema");
|
|
289
|
-
return rows[0]?.current_schema ?? "public";
|
|
290
|
-
}
|
|
291
|
-
return id;
|
|
292
|
-
}));
|
|
293
|
-
const uniqueSchemas = Array.from(new Set(resolvedSchemas));
|
|
294
|
-
const perSchema = await Promise.all(uniqueSchemas.map((s) => this.introspectSchema(driver, s)));
|
|
295
|
-
const mergedTables = {};
|
|
296
|
-
for (const ir of perSchema) for (const [tableName, table] of Object.entries(ir.tables)) mergedTables[tableName] = table;
|
|
297
|
-
const mergedStorageTypes = {};
|
|
298
|
-
for (let i = 0; i < perSchema.length; i++) {
|
|
299
|
-
const ir = perSchema[i];
|
|
300
|
-
const pg = blindCast(ir?.annotations?.["pg"])?.storageTypes;
|
|
301
|
-
if (!pg) continue;
|
|
302
|
-
for (const [key, value] of Object.entries(pg)) mergedStorageTypes[key] = value;
|
|
303
|
-
}
|
|
304
|
-
const firstAnnotations = perSchema[0]?.annotations;
|
|
305
|
-
const firstPg = blindCast(firstAnnotations?.["pg"]) ?? {};
|
|
306
|
-
return {
|
|
307
|
-
tables: mergedTables,
|
|
308
|
-
...ifDefined("annotations", {
|
|
309
|
-
...firstAnnotations,
|
|
310
|
-
pg: {
|
|
311
|
-
...firstPg,
|
|
312
|
-
...ifDefined("storageTypes", Object.keys(mergedStorageTypes).length > 0 ? mergedStorageTypes : void 0)
|
|
313
|
-
}
|
|
314
|
-
})
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Introspects a single Postgres schema and returns a raw SqlSchemaIR
|
|
319
|
-
* containing only the tables in that schema. Used by `introspect` as
|
|
320
|
-
* the per-namespace walk.
|
|
321
|
-
*/
|
|
322
|
-
async introspectSchema(driver, schema) {
|
|
323
|
-
const [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult] = await Promise.all([
|
|
324
|
-
driver.query(`SELECT table_name
|
|
325
|
-
FROM information_schema.tables
|
|
326
|
-
WHERE table_schema = $1
|
|
327
|
-
AND table_type = 'BASE TABLE'
|
|
328
|
-
ORDER BY table_name`, [schema]),
|
|
329
|
-
driver.query(`SELECT
|
|
330
|
-
c.table_name,
|
|
331
|
-
column_name,
|
|
332
|
-
data_type,
|
|
333
|
-
udt_name,
|
|
334
|
-
is_nullable,
|
|
335
|
-
character_maximum_length,
|
|
336
|
-
numeric_precision,
|
|
337
|
-
numeric_scale,
|
|
338
|
-
column_default,
|
|
339
|
-
format_type(a.atttypid, a.atttypmod) AS formatted_type
|
|
340
|
-
FROM information_schema.columns c
|
|
341
|
-
JOIN pg_catalog.pg_class cl
|
|
342
|
-
ON cl.relname = c.table_name
|
|
343
|
-
JOIN pg_catalog.pg_namespace ns
|
|
344
|
-
ON ns.nspname = c.table_schema
|
|
345
|
-
AND ns.oid = cl.relnamespace
|
|
346
|
-
JOIN pg_catalog.pg_attribute a
|
|
347
|
-
ON a.attrelid = cl.oid
|
|
348
|
-
AND a.attname = c.column_name
|
|
349
|
-
AND a.attnum > 0
|
|
350
|
-
AND NOT a.attisdropped
|
|
351
|
-
WHERE c.table_schema = $1
|
|
352
|
-
ORDER BY c.table_name, c.ordinal_position`, [schema]),
|
|
353
|
-
driver.query(`SELECT
|
|
354
|
-
tc.table_name,
|
|
355
|
-
tc.constraint_name,
|
|
356
|
-
kcu.column_name,
|
|
357
|
-
kcu.ordinal_position
|
|
358
|
-
FROM information_schema.table_constraints tc
|
|
359
|
-
JOIN information_schema.key_column_usage kcu
|
|
360
|
-
ON tc.constraint_name = kcu.constraint_name
|
|
361
|
-
AND tc.table_schema = kcu.table_schema
|
|
362
|
-
AND tc.table_name = kcu.table_name
|
|
363
|
-
WHERE tc.table_schema = $1
|
|
364
|
-
AND tc.constraint_type = 'PRIMARY KEY'
|
|
365
|
-
ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),
|
|
366
|
-
driver.query(`SELECT
|
|
367
|
-
tc.table_name,
|
|
368
|
-
tc.constraint_name,
|
|
369
|
-
kcu.column_name,
|
|
370
|
-
kcu.ordinal_position,
|
|
371
|
-
ref_ns.nspname AS referenced_table_schema,
|
|
372
|
-
ref_cl.relname AS referenced_table_name,
|
|
373
|
-
ref_att.attname AS referenced_column_name,
|
|
374
|
-
rc.delete_rule,
|
|
375
|
-
rc.update_rule
|
|
376
|
-
FROM information_schema.table_constraints tc
|
|
377
|
-
JOIN information_schema.key_column_usage kcu
|
|
378
|
-
ON tc.constraint_name = kcu.constraint_name
|
|
379
|
-
AND tc.table_schema = kcu.table_schema
|
|
380
|
-
AND tc.table_name = kcu.table_name
|
|
381
|
-
JOIN pg_catalog.pg_constraint pgc
|
|
382
|
-
ON pgc.conname = tc.constraint_name
|
|
383
|
-
AND pgc.connamespace = (
|
|
384
|
-
SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema
|
|
385
|
-
)
|
|
386
|
-
JOIN pg_catalog.pg_class ref_cl
|
|
387
|
-
ON ref_cl.oid = pgc.confrelid
|
|
388
|
-
JOIN pg_catalog.pg_namespace ref_ns
|
|
389
|
-
ON ref_ns.oid = ref_cl.relnamespace
|
|
390
|
-
JOIN pg_catalog.pg_attribute ref_att
|
|
391
|
-
ON ref_att.attrelid = pgc.confrelid
|
|
392
|
-
AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]
|
|
393
|
-
JOIN information_schema.referential_constraints rc
|
|
394
|
-
ON rc.constraint_name = tc.constraint_name
|
|
395
|
-
AND rc.constraint_schema = tc.table_schema
|
|
396
|
-
WHERE tc.table_schema = $1
|
|
397
|
-
AND tc.constraint_type = 'FOREIGN KEY'
|
|
398
|
-
ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
|
|
399
|
-
driver.query(`SELECT
|
|
400
|
-
tc.table_name,
|
|
401
|
-
tc.constraint_name,
|
|
402
|
-
kcu.column_name,
|
|
403
|
-
kcu.ordinal_position
|
|
404
|
-
FROM information_schema.table_constraints tc
|
|
405
|
-
JOIN information_schema.key_column_usage kcu
|
|
406
|
-
ON tc.constraint_name = kcu.constraint_name
|
|
407
|
-
AND tc.table_schema = kcu.table_schema
|
|
408
|
-
AND tc.table_name = kcu.table_name
|
|
409
|
-
WHERE tc.table_schema = $1
|
|
410
|
-
AND tc.constraint_type = 'UNIQUE'
|
|
411
|
-
ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
|
|
412
|
-
driver.query(`SELECT
|
|
413
|
-
i.tablename,
|
|
414
|
-
i.indexname,
|
|
415
|
-
ix.indisunique,
|
|
416
|
-
a.attname,
|
|
417
|
-
k.ord AS index_position,
|
|
418
|
-
am.amname,
|
|
419
|
-
ic.reloptions
|
|
420
|
-
FROM pg_indexes i
|
|
421
|
-
JOIN pg_class ic ON ic.relname = i.indexname
|
|
422
|
-
JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1
|
|
423
|
-
JOIN pg_index ix ON ix.indexrelid = ic.oid
|
|
424
|
-
JOIN pg_am am ON am.oid = ic.relam
|
|
425
|
-
JOIN pg_class t ON t.oid = ix.indrelid
|
|
426
|
-
JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1
|
|
427
|
-
JOIN LATERAL unnest(ix.indkey::int[]) WITH ORDINALITY AS k(attnum, ord) ON true
|
|
428
|
-
LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND a.attnum > 0
|
|
429
|
-
WHERE i.schemaname = $1
|
|
430
|
-
AND NOT EXISTS (
|
|
431
|
-
SELECT 1
|
|
432
|
-
FROM information_schema.table_constraints tc
|
|
433
|
-
WHERE tc.table_schema = $1
|
|
434
|
-
AND tc.table_name = i.tablename
|
|
435
|
-
AND tc.constraint_name = i.indexname
|
|
436
|
-
)
|
|
437
|
-
ORDER BY i.tablename, i.indexname, k.ord`, [schema])
|
|
438
|
-
]);
|
|
439
|
-
const columnsByTable = groupBy(columnsResult.rows, "table_name");
|
|
440
|
-
const pksByTable = groupBy(pkResult.rows, "table_name");
|
|
441
|
-
const fksByTable = groupBy(fkResult.rows, "table_name");
|
|
442
|
-
const uniquesByTable = groupBy(uniqueResult.rows, "table_name");
|
|
443
|
-
const indexesByTable = groupBy(indexResult.rows, "tablename");
|
|
444
|
-
const pkConstraintsByTable = /* @__PURE__ */ new Map();
|
|
445
|
-
for (const row of pkResult.rows) {
|
|
446
|
-
let constraints = pkConstraintsByTable.get(row.table_name);
|
|
447
|
-
if (!constraints) {
|
|
448
|
-
constraints = /* @__PURE__ */ new Set();
|
|
449
|
-
pkConstraintsByTable.set(row.table_name, constraints);
|
|
450
|
-
}
|
|
451
|
-
constraints.add(row.constraint_name);
|
|
452
|
-
}
|
|
453
|
-
const tables = {};
|
|
454
|
-
for (const tableRow of tablesResult.rows) {
|
|
455
|
-
const tableName = tableRow.table_name;
|
|
456
|
-
const columns = {};
|
|
457
|
-
for (const colRow of columnsByTable.get(tableName) ?? []) {
|
|
458
|
-
let nativeType = colRow.udt_name;
|
|
459
|
-
const formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;
|
|
460
|
-
if (formattedType) nativeType = formattedType;
|
|
461
|
-
else if (colRow.data_type === "character varying" || colRow.data_type === "character") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;
|
|
462
|
-
else nativeType = colRow.data_type;
|
|
463
|
-
else if (colRow.data_type === "numeric" || colRow.data_type === "decimal") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;
|
|
464
|
-
else if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;
|
|
465
|
-
else nativeType = colRow.data_type;
|
|
466
|
-
else nativeType = colRow.udt_name || colRow.data_type;
|
|
467
|
-
columns[colRow.column_name] = {
|
|
468
|
-
name: colRow.column_name,
|
|
469
|
-
nativeType,
|
|
470
|
-
nullable: colRow.is_nullable === "YES",
|
|
471
|
-
...ifDefined("default", colRow.column_default ?? void 0)
|
|
472
|
-
};
|
|
473
|
-
}
|
|
474
|
-
const pkRows = [...pksByTable.get(tableName) ?? []];
|
|
475
|
-
const primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);
|
|
476
|
-
const primaryKey = primaryKeyColumns.length > 0 ? {
|
|
477
|
-
columns: primaryKeyColumns,
|
|
478
|
-
...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}
|
|
479
|
-
} : void 0;
|
|
480
|
-
const foreignKeysMap = /* @__PURE__ */ new Map();
|
|
481
|
-
for (const fkRow of fksByTable.get(tableName) ?? []) {
|
|
482
|
-
const existing = foreignKeysMap.get(fkRow.constraint_name);
|
|
483
|
-
if (existing) {
|
|
484
|
-
existing.columns.push(fkRow.column_name);
|
|
485
|
-
existing.referencedColumns.push(fkRow.referenced_column_name);
|
|
486
|
-
} else foreignKeysMap.set(fkRow.constraint_name, {
|
|
487
|
-
columns: [fkRow.column_name],
|
|
488
|
-
referencedTable: fkRow.referenced_table_name,
|
|
489
|
-
referencedSchema: fkRow.referenced_table_schema,
|
|
490
|
-
referencedColumns: [fkRow.referenced_column_name],
|
|
491
|
-
name: fkRow.constraint_name,
|
|
492
|
-
deleteRule: fkRow.delete_rule,
|
|
493
|
-
updateRule: fkRow.update_rule
|
|
494
|
-
});
|
|
495
|
-
}
|
|
496
|
-
const foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({
|
|
497
|
-
columns: Object.freeze([...fk.columns]),
|
|
498
|
-
referencedTable: fk.referencedTable,
|
|
499
|
-
referencedSchema: fk.referencedSchema,
|
|
500
|
-
referencedColumns: Object.freeze([...fk.referencedColumns]),
|
|
501
|
-
name: fk.name,
|
|
502
|
-
...ifDefined("onDelete", mapReferentialAction(fk.deleteRule)),
|
|
503
|
-
...ifDefined("onUpdate", mapReferentialAction(fk.updateRule))
|
|
504
|
-
}));
|
|
505
|
-
const pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();
|
|
506
|
-
const uniquesMap = /* @__PURE__ */ new Map();
|
|
507
|
-
for (const uniqueRow of uniquesByTable.get(tableName) ?? []) {
|
|
508
|
-
if (pkConstraints.has(uniqueRow.constraint_name)) continue;
|
|
509
|
-
const existing = uniquesMap.get(uniqueRow.constraint_name);
|
|
510
|
-
if (existing) existing.columns.push(uniqueRow.column_name);
|
|
511
|
-
else uniquesMap.set(uniqueRow.constraint_name, {
|
|
512
|
-
columns: [uniqueRow.column_name],
|
|
513
|
-
name: uniqueRow.constraint_name
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
const uniques = Array.from(uniquesMap.values()).map((uq) => ({
|
|
517
|
-
columns: Object.freeze([...uq.columns]),
|
|
518
|
-
name: uq.name
|
|
519
|
-
}));
|
|
520
|
-
const indexesMap = /* @__PURE__ */ new Map();
|
|
521
|
-
for (const idxRow of indexesByTable.get(tableName) ?? []) {
|
|
522
|
-
if (!idxRow.attname) continue;
|
|
523
|
-
const existing = indexesMap.get(idxRow.indexname);
|
|
524
|
-
if (existing) existing.columns.push(idxRow.attname);
|
|
525
|
-
else {
|
|
526
|
-
const indexType = idxRow.amname && idxRow.amname !== "btree" ? idxRow.amname : void 0;
|
|
527
|
-
const indexOptions = parsePgReloptions(idxRow.reloptions, idxRow.indexname);
|
|
528
|
-
indexesMap.set(idxRow.indexname, {
|
|
529
|
-
columns: [idxRow.attname],
|
|
530
|
-
name: idxRow.indexname,
|
|
531
|
-
unique: idxRow.indisunique,
|
|
532
|
-
type: indexType,
|
|
533
|
-
options: indexOptions
|
|
534
|
-
});
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
const indexes = Array.from(indexesMap.values()).map((idx) => ({
|
|
538
|
-
columns: Object.freeze([...idx.columns]),
|
|
539
|
-
name: idx.name,
|
|
540
|
-
unique: idx.unique,
|
|
541
|
-
...idx.type !== void 0 && { type: idx.type },
|
|
542
|
-
...idx.options !== void 0 && { options: idx.options }
|
|
543
|
-
}));
|
|
544
|
-
tables[tableName] = {
|
|
545
|
-
name: tableName,
|
|
546
|
-
columns,
|
|
547
|
-
...ifDefined("primaryKey", primaryKey),
|
|
548
|
-
foreignKeys,
|
|
549
|
-
uniques,
|
|
550
|
-
indexes
|
|
551
|
-
};
|
|
552
|
-
}
|
|
553
|
-
const rawStorageTypes = await introspectPostgresEnumTypes({
|
|
554
|
-
driver,
|
|
555
|
-
schemaName: schema
|
|
556
|
-
});
|
|
557
|
-
const storageTypes = {};
|
|
558
|
-
for (const [typeName, annotation] of Object.entries(rawStorageTypes)) storageTypes[enumStorageCompoundKey(schema, typeName)] = annotation;
|
|
559
|
-
return {
|
|
560
|
-
tables,
|
|
561
|
-
annotations: { pg: {
|
|
562
|
-
schema,
|
|
563
|
-
version: await this.getPostgresVersion(driver),
|
|
564
|
-
...ifDefined("storageTypes", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)
|
|
565
|
-
} }
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
/**
|
|
569
|
-
* Gets the Postgres version from the database.
|
|
570
|
-
*/
|
|
571
|
-
async getPostgresVersion(driver) {
|
|
572
|
-
return ((await driver.query("SELECT version() AS version", [])).rows[0]?.version ?? "").match(/PostgreSQL (\d+\.\d+)/)?.[1] ?? "unknown";
|
|
573
|
-
}
|
|
574
|
-
};
|
|
575
|
-
/**
|
|
576
|
-
* Extracts the namespace coordinate ids declared on a contract's storage,
|
|
577
|
-
* or returns an empty array when no contract (or no storage / namespaces)
|
|
578
|
-
* is present. Used by `PostgresControlAdapter.introspect` to decide
|
|
579
|
-
* between the multi-namespace walk and the single-schema fallback.
|
|
580
|
-
*/
|
|
581
|
-
function extractContractNamespaceIds(contract) {
|
|
582
|
-
if (contract === null || typeof contract !== "object") return [];
|
|
583
|
-
const storage = contract.storage;
|
|
584
|
-
if (storage === null || typeof storage !== "object") return [];
|
|
585
|
-
const namespaces = storage.namespaces;
|
|
586
|
-
if (namespaces === null || typeof namespaces !== "object") return [];
|
|
587
|
-
return Object.keys(namespaces);
|
|
588
|
-
}
|
|
589
|
-
function normalizeFormattedType(formattedType, dataType, udtName) {
|
|
590
|
-
if (formattedType === "integer") return "int4";
|
|
591
|
-
if (formattedType === "smallint") return "int2";
|
|
592
|
-
if (formattedType === "bigint") return "int8";
|
|
593
|
-
if (formattedType === "real") return "float4";
|
|
594
|
-
if (formattedType === "double precision") return "float8";
|
|
595
|
-
if (formattedType === "boolean") return "bool";
|
|
596
|
-
if (formattedType.startsWith("varchar")) return formattedType.replace("varchar", "character varying");
|
|
597
|
-
if (formattedType.startsWith("bpchar")) return formattedType.replace("bpchar", "character");
|
|
598
|
-
if (formattedType.startsWith("varbit")) return formattedType.replace("varbit", "bit varying");
|
|
599
|
-
if (dataType === "timestamp with time zone" || udtName === "timestamptz") return formattedType.replace("timestamp", "timestamptz").replace(" with time zone", "").trim();
|
|
600
|
-
if (dataType === "timestamp without time zone" || udtName === "timestamp") return formattedType.replace(" without time zone", "").trim();
|
|
601
|
-
if (dataType === "time with time zone" || udtName === "timetz") return formattedType.replace("time", "timetz").replace(" with time zone", "").trim();
|
|
602
|
-
if (dataType === "time without time zone" || udtName === "time") return formattedType.replace(" without time zone", "").trim();
|
|
603
|
-
if (formattedType.startsWith("\"") && formattedType.endsWith("\"")) return formattedType.slice(1, -1);
|
|
604
|
-
return formattedType;
|
|
605
|
-
}
|
|
606
|
-
const PG_REFERENTIAL_ACTION_MAP = {
|
|
607
|
-
"NO ACTION": "noAction",
|
|
608
|
-
RESTRICT: "restrict",
|
|
609
|
-
CASCADE: "cascade",
|
|
610
|
-
"SET NULL": "setNull",
|
|
611
|
-
"SET DEFAULT": "setDefault"
|
|
612
|
-
};
|
|
613
|
-
/**
|
|
614
|
-
* Maps a Postgres referential action rule to the canonical SqlReferentialAction.
|
|
615
|
-
* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.
|
|
616
|
-
* Throws for unrecognized rules to prevent silent data loss.
|
|
617
|
-
*/
|
|
618
|
-
function mapReferentialAction(rule) {
|
|
619
|
-
const mapped = PG_REFERENTIAL_ACTION_MAP[rule];
|
|
620
|
-
if (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
|
|
621
|
-
if (mapped === "noAction") return void 0;
|
|
622
|
-
return mapped;
|
|
623
|
-
}
|
|
624
|
-
/**
|
|
625
|
-
* Groups an array of objects by a specified key.
|
|
626
|
-
* Returns a Map for O(1) lookup by group key.
|
|
627
|
-
*/
|
|
628
|
-
/**
|
|
629
|
-
* Parses a `pg_class.reloptions` array into a `Record<string, string>`.
|
|
630
|
-
*
|
|
631
|
-
* Postgres returns reloptions as a `text[]` whose entries are `key=value`
|
|
632
|
-
* strings; the value side is always a string regardless of the underlying
|
|
633
|
-
* scalar type. The verifier compares contract options to introspected
|
|
634
|
-
* options after coercing both sides to strings, so keeping the raw text
|
|
635
|
-
* here is correct.
|
|
636
|
-
*
|
|
637
|
-
* Returns `undefined` when the input is null/empty (no WITH clause).
|
|
638
|
-
*/
|
|
639
|
-
function parsePgReloptions(reloptions, indexName) {
|
|
640
|
-
if (!reloptions || reloptions.length === 0) return;
|
|
641
|
-
const result = {};
|
|
642
|
-
for (const entry of reloptions) {
|
|
643
|
-
const eq = entry.indexOf("=");
|
|
644
|
-
if (eq === -1) throw new Error(`Postgres introspection: malformed reloption entry "${entry}" on index "${indexName}" (expected "key=value")`);
|
|
645
|
-
const key = entry.slice(0, eq);
|
|
646
|
-
result[key] = entry.slice(eq + 1);
|
|
647
|
-
}
|
|
648
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
649
|
-
}
|
|
650
|
-
function groupBy(items, key) {
|
|
651
|
-
const map = /* @__PURE__ */ new Map();
|
|
652
|
-
for (const item of items) {
|
|
653
|
-
const groupKey = item[key];
|
|
654
|
-
let group = map.get(groupKey);
|
|
655
|
-
if (!group) {
|
|
656
|
-
group = [];
|
|
657
|
-
map.set(groupKey, group);
|
|
658
|
-
}
|
|
659
|
-
group.push(item);
|
|
660
|
-
}
|
|
661
|
-
return map;
|
|
662
|
-
}
|
|
663
|
-
//#endregion
|
|
664
8
|
//#region src/core/control-mutation-defaults.ts
|
|
665
9
|
function invalidArgumentDiagnostic(input) {
|
|
666
10
|
return {
|