drizzle-pg-extras 0.0.0-stage → 0.5.0
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/LICENSE +21 -0
- package/README.md +448 -2
- package/dist/cli.js +2995 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +3638 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +764 -0
- package/dist/index.d.ts +764 -0
- package/dist/index.js +3588 -0
- package/dist/index.js.map +1 -0
- package/package.json +84 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2995 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { pathToFileURL } from "url";
|
|
5
|
+
|
|
6
|
+
// src/errors.ts
|
|
7
|
+
var PgExtrasError = class extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "PgExtrasError";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// src/quote.ts
|
|
15
|
+
function quoteIdent(name) {
|
|
16
|
+
if (name.length === 0) {
|
|
17
|
+
throw new PgExtrasError("SQL identifier is empty");
|
|
18
|
+
}
|
|
19
|
+
if (name.includes("\0")) {
|
|
20
|
+
throw new PgExtrasError("SQL identifier contains a null byte");
|
|
21
|
+
}
|
|
22
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
23
|
+
}
|
|
24
|
+
function quoteLiteral(value) {
|
|
25
|
+
if (value.includes("\0")) {
|
|
26
|
+
throw new PgExtrasError("SQL string literal contains a null byte");
|
|
27
|
+
}
|
|
28
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
29
|
+
}
|
|
30
|
+
function qualify(schema, name) {
|
|
31
|
+
return `${quoteIdent(schema)}.${quoteIdent(name)}`;
|
|
32
|
+
}
|
|
33
|
+
function assertIdentifier(kind, name) {
|
|
34
|
+
if (name.length === 0) {
|
|
35
|
+
throw new PgExtrasError(`${kind} name is empty`);
|
|
36
|
+
}
|
|
37
|
+
if (name.includes("\0")) {
|
|
38
|
+
throw new PgExtrasError(`${kind} name contains a null byte`);
|
|
39
|
+
}
|
|
40
|
+
const bytes = Buffer.byteLength(name, "utf8");
|
|
41
|
+
if (bytes > 63) {
|
|
42
|
+
throw new PgExtrasError(
|
|
43
|
+
`${kind} name "${name}" is ${bytes} bytes. Postgres truncates identifiers at 63 bytes`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
var TYPE_ALIASES = {
|
|
48
|
+
int: "integer",
|
|
49
|
+
int2: "smallint",
|
|
50
|
+
int4: "integer",
|
|
51
|
+
int8: "bigint",
|
|
52
|
+
bool: "boolean",
|
|
53
|
+
float4: "real",
|
|
54
|
+
float8: "double precision"
|
|
55
|
+
};
|
|
56
|
+
function normalizeType(type) {
|
|
57
|
+
const trimmed = type.trim();
|
|
58
|
+
if (trimmed.length === 0) {
|
|
59
|
+
throw new PgExtrasError("function argument type is empty");
|
|
60
|
+
}
|
|
61
|
+
if (trimmed.includes('"')) {
|
|
62
|
+
return trimmed.replace(/\s+/g, " ");
|
|
63
|
+
}
|
|
64
|
+
const collapsed = trimmed.replace(/\s+/g, " ").toLowerCase();
|
|
65
|
+
return TYPE_ALIASES[collapsed] ?? collapsed;
|
|
66
|
+
}
|
|
67
|
+
function dollarQuote(body) {
|
|
68
|
+
let tag = "function";
|
|
69
|
+
let n = 0;
|
|
70
|
+
while (body.includes(`$${tag}$`)) {
|
|
71
|
+
n += 1;
|
|
72
|
+
tag = `function${n}`;
|
|
73
|
+
}
|
|
74
|
+
return `$${tag}$
|
|
75
|
+
${body}
|
|
76
|
+
$${tag}$`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/partition-sql.ts
|
|
80
|
+
var STRATEGY_CHAR = { range: "r", list: "l", hash: "h" };
|
|
81
|
+
function convertPartitionedTableSql(parent, direction) {
|
|
82
|
+
const key = `${parent.method.toUpperCase()} (${parent.columns.map((column) => quoteIdent(column)).join(", ")})`;
|
|
83
|
+
const comment = direction === "partition" ? `-- Convert empty ${quoteIdent(parent.schema)}.${quoteIdent(parent.name)} into a ${key} partitioned table. Refuses to run when the table has rows.` : `-- Convert partitioned ${quoteIdent(parent.schema)}.${quoteIdent(parent.name)} back into a regular table. Refuses to run when it has rows or still has partitions.`;
|
|
84
|
+
const body = convertBody(parent, direction);
|
|
85
|
+
return `${comment}
|
|
86
|
+
${wrapDo(body)}`;
|
|
87
|
+
}
|
|
88
|
+
function createPartitionSql(partition) {
|
|
89
|
+
const comment = `-- Create partition ${quoteIdent(partition.schema)}.${quoteIdent(partition.name)} of ${quoteIdent(partition.parentSchema)}.${quoteIdent(partition.parentName)} ${partition.boundSql}.`;
|
|
90
|
+
return `${comment}
|
|
91
|
+
${wrapDo(partitionBody(partition, "create"))}`;
|
|
92
|
+
}
|
|
93
|
+
function attachPartitionSql(partition) {
|
|
94
|
+
const comment = `-- Attach ${quoteIdent(partition.schema)}.${quoteIdent(partition.name)} to ${quoteIdent(partition.parentSchema)}.${quoteIdent(partition.parentName)} ${partition.boundSql}.`;
|
|
95
|
+
return `${comment}
|
|
96
|
+
${wrapDo(partitionBody(partition, "attach"))}`;
|
|
97
|
+
}
|
|
98
|
+
function detachPartitionSql(partition) {
|
|
99
|
+
const comment = `-- Detach ${quoteIdent(partition.schema)}.${quoteIdent(partition.name)} from ${quoteIdent(partition.parentSchema)}.${quoteIdent(partition.parentName)}. The table is kept.`;
|
|
100
|
+
return `${comment}
|
|
101
|
+
${wrapDo(detachBody(partition))}`;
|
|
102
|
+
}
|
|
103
|
+
function dropPartitionSql(partition) {
|
|
104
|
+
const comment = `-- Drop empty partition ${quoteIdent(partition.schema)}.${quoteIdent(partition.name)}. Refuses to run when the partition has rows.`;
|
|
105
|
+
return `${comment}
|
|
106
|
+
${wrapDo(dropBody(partition))}`;
|
|
107
|
+
}
|
|
108
|
+
function convertBody(parent, direction) {
|
|
109
|
+
const partitionBy = `${parent.method.toUpperCase()} (${parent.columns.map((column) => quoteIdent(column)).join(", ")})`;
|
|
110
|
+
return `
|
|
111
|
+
DECLARE
|
|
112
|
+
parent_schema text := ${quoteLiteral(parent.schema)};
|
|
113
|
+
parent_name text := ${quoteLiteral(parent.name)};
|
|
114
|
+
direction text := ${quoteLiteral(direction)};
|
|
115
|
+
strategy "char" := ${quoteLiteral(STRATEGY_CHAR[parent.method])};
|
|
116
|
+
key_columns name[] := ARRAY[${parent.columns.map((column) => `${quoteLiteral(column)}::name`).join(", ")}];
|
|
117
|
+
partition_by text := ${quoteLiteral(partitionBy)};
|
|
118
|
+
swap_name text := ${quoteLiteral(swapName(parent.name))};
|
|
119
|
+
parent_oid oid;
|
|
120
|
+
parent_kind "char";
|
|
121
|
+
current_strategy "char";
|
|
122
|
+
current_cols name[];
|
|
123
|
+
current_natts integer;
|
|
124
|
+
has_expression boolean;
|
|
125
|
+
non_empty boolean;
|
|
126
|
+
dependents text;
|
|
127
|
+
indexes_json jsonb;
|
|
128
|
+
constraints_json jsonb;
|
|
129
|
+
sequences_json jsonb;
|
|
130
|
+
incoming_json jsonb;
|
|
131
|
+
triggers_json jsonb;
|
|
132
|
+
policies_json jsonb;
|
|
133
|
+
grants_json jsonb;
|
|
134
|
+
owner_name text;
|
|
135
|
+
table_comment text;
|
|
136
|
+
replica "char";
|
|
137
|
+
replica_index name;
|
|
138
|
+
rel_options text[];
|
|
139
|
+
rls boolean;
|
|
140
|
+
force_rls boolean;
|
|
141
|
+
item jsonb;
|
|
142
|
+
match_oid oid;
|
|
143
|
+
match_name name;
|
|
144
|
+
seq_schema name;
|
|
145
|
+
seq_name name;
|
|
146
|
+
claimed oid[] := ARRAY[]::oid[];
|
|
147
|
+
new_oid oid;
|
|
148
|
+
BEGIN
|
|
149
|
+
SELECT c.oid, c.relkind
|
|
150
|
+
INTO parent_oid, parent_kind
|
|
151
|
+
FROM pg_class c
|
|
152
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
153
|
+
WHERE n.nspname = parent_schema AND c.relname = parent_name AND c.relkind IN ('r', 'p');
|
|
154
|
+
|
|
155
|
+
IF parent_oid IS NULL THEN
|
|
156
|
+
IF direction = 'unpartition' THEN
|
|
157
|
+
RETURN;
|
|
158
|
+
END IF;
|
|
159
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% does not exist. Run the drizzle-kit migration that creates this empty table before this one.', parent_schema, parent_name;
|
|
160
|
+
END IF;
|
|
161
|
+
|
|
162
|
+
IF direction = 'partition' AND parent_kind = 'p' THEN
|
|
163
|
+
SELECT p.partstrat, p.partnatts,
|
|
164
|
+
EXISTS (SELECT 1 FROM unnest(p.partattrs::smallint[]) AS u(attnum) WHERE u.attnum = 0),
|
|
165
|
+
(
|
|
166
|
+
SELECT array_agg(a.attname ORDER BY k.ord)
|
|
167
|
+
FROM unnest(p.partattrs::smallint[]) WITH ORDINALITY AS k(attnum, ord)
|
|
168
|
+
JOIN pg_attribute a ON a.attrelid = parent_oid AND a.attnum = k.attnum
|
|
169
|
+
WHERE k.attnum > 0
|
|
170
|
+
)
|
|
171
|
+
INTO current_strategy, current_natts, has_expression, current_cols
|
|
172
|
+
FROM pg_partitioned_table p
|
|
173
|
+
WHERE p.partrelid = parent_oid;
|
|
174
|
+
|
|
175
|
+
IF current_strategy = strategy AND NOT has_expression AND current_natts = cardinality(key_columns) AND current_cols = key_columns THEN
|
|
176
|
+
RETURN;
|
|
177
|
+
END IF;
|
|
178
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% is already partitioned and its key does not match %. Partition keys cannot be changed in place.', parent_schema, parent_name, partition_by;
|
|
179
|
+
END IF;
|
|
180
|
+
|
|
181
|
+
IF direction = 'unpartition' AND parent_kind = 'r' THEN
|
|
182
|
+
RETURN;
|
|
183
|
+
END IF;
|
|
184
|
+
|
|
185
|
+
IF parent_kind <> 'r' AND parent_kind <> 'p' THEN
|
|
186
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% is not a regular or partitioned table.', parent_schema, parent_name;
|
|
187
|
+
END IF;
|
|
188
|
+
|
|
189
|
+
IF direction = 'unpartition' THEN
|
|
190
|
+
IF EXISTS (SELECT 1 FROM pg_inherits WHERE inhparent = parent_oid) THEN
|
|
191
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% still has child partitions. Detach or drop them before converting it back to a regular table.', parent_schema, parent_name;
|
|
192
|
+
END IF;
|
|
193
|
+
END IF;
|
|
194
|
+
|
|
195
|
+
EXECUTE format('LOCK TABLE %I.%I IN ACCESS EXCLUSIVE MODE', parent_schema, parent_name);
|
|
196
|
+
|
|
197
|
+
EXECUTE format('SELECT EXISTS (SELECT 1 FROM %I.%I LIMIT 1)', parent_schema, parent_name) INTO non_empty;
|
|
198
|
+
IF non_empty THEN
|
|
199
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% has rows, so it cannot be converted. PARTITION BY is only valid on CREATE TABLE. Empty the table, or load data after this migration.', parent_schema, parent_name;
|
|
200
|
+
END IF;
|
|
201
|
+
|
|
202
|
+
SELECT string_agg(format('%I.%I', vn.nspname, vc.relname), ', ' ORDER BY vn.nspname, vc.relname)
|
|
203
|
+
INTO dependents
|
|
204
|
+
FROM pg_depend d
|
|
205
|
+
JOIN pg_rewrite rw ON rw.oid = d.objid
|
|
206
|
+
JOIN pg_class vc ON vc.oid = rw.ev_class
|
|
207
|
+
JOIN pg_namespace vn ON vn.oid = vc.relnamespace
|
|
208
|
+
WHERE d.refobjid = parent_oid
|
|
209
|
+
AND d.classid = 'pg_rewrite'::regclass
|
|
210
|
+
AND vc.oid <> parent_oid;
|
|
211
|
+
IF dependents IS NOT NULL THEN
|
|
212
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% cannot be converted while these views depend on it: %. Drop the views first and recreate them after the conversion. The conversion recreates the table.', parent_schema, parent_name, dependents;
|
|
213
|
+
END IF;
|
|
214
|
+
|
|
215
|
+
IF to_regclass(format('%I.%I', parent_schema, swap_name)) IS NOT NULL THEN
|
|
216
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% already exists. Rename it before converting %.%.', parent_schema, swap_name, parent_schema, parent_name;
|
|
217
|
+
END IF;
|
|
218
|
+
|
|
219
|
+
SELECT c.relrowsecurity, c.relforcerowsecurity, c.relreplident, c.reloptions, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class')
|
|
220
|
+
INTO rls, force_rls, replica, rel_options, owner_name, table_comment
|
|
221
|
+
FROM pg_class c
|
|
222
|
+
WHERE c.oid = parent_oid;
|
|
223
|
+
|
|
224
|
+
SELECT ic.relname
|
|
225
|
+
INTO replica_index
|
|
226
|
+
FROM pg_index i
|
|
227
|
+
JOIN pg_class ic ON ic.oid = i.indexrelid
|
|
228
|
+
WHERE i.indrelid = parent_oid AND i.indisreplident;
|
|
229
|
+
|
|
230
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
231
|
+
'name', ic.relname,
|
|
232
|
+
'primary', i.indisprimary,
|
|
233
|
+
'unique', i.indisunique,
|
|
234
|
+
'exclusion', i.indisexclusion,
|
|
235
|
+
'cols', (
|
|
236
|
+
SELECT coalesce(jsonb_agg(a.attname ORDER BY u.ord), '[]'::jsonb)
|
|
237
|
+
FROM unnest(i.indkey::smallint[]) WITH ORDINALITY AS u(attnum, ord)
|
|
238
|
+
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = u.attnum
|
|
239
|
+
WHERE u.attnum > 0
|
|
240
|
+
),
|
|
241
|
+
'exprs', pg_get_expr(i.indexprs, i.indrelid),
|
|
242
|
+
'pred', pg_get_expr(i.indpred, i.indrelid)
|
|
243
|
+
)), '[]'::jsonb)
|
|
244
|
+
INTO indexes_json
|
|
245
|
+
FROM pg_index i
|
|
246
|
+
JOIN pg_class ic ON ic.oid = i.indexrelid
|
|
247
|
+
WHERE i.indrelid = parent_oid;
|
|
248
|
+
|
|
249
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
250
|
+
'name', con.conname,
|
|
251
|
+
'type', con.contype,
|
|
252
|
+
'def', pg_get_constraintdef(con.oid),
|
|
253
|
+
'self', con.confrelid = parent_oid
|
|
254
|
+
)), '[]'::jsonb)
|
|
255
|
+
INTO constraints_json
|
|
256
|
+
FROM pg_constraint con
|
|
257
|
+
WHERE con.conrelid = parent_oid AND con.contype IN ('c', 'f', 'p', 'u', 'x');
|
|
258
|
+
|
|
259
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
260
|
+
'schema', sn.nspname,
|
|
261
|
+
'name', sc.relname,
|
|
262
|
+
'column', a.attname,
|
|
263
|
+
'deptype', d.deptype::text
|
|
264
|
+
)), '[]'::jsonb)
|
|
265
|
+
INTO sequences_json
|
|
266
|
+
FROM pg_depend d
|
|
267
|
+
JOIN pg_class sc ON sc.oid = d.objid AND sc.relkind = 'S'
|
|
268
|
+
JOIN pg_namespace sn ON sn.oid = sc.relnamespace
|
|
269
|
+
JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid AND NOT a.attisdropped
|
|
270
|
+
WHERE d.refobjid = parent_oid
|
|
271
|
+
AND d.classid = 'pg_class'::regclass
|
|
272
|
+
AND d.deptype IN ('a', 'i');
|
|
273
|
+
|
|
274
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
275
|
+
'schema', n.nspname,
|
|
276
|
+
'table', rel.relname,
|
|
277
|
+
'name', con.conname,
|
|
278
|
+
'def', pg_get_constraintdef(con.oid)
|
|
279
|
+
)), '[]'::jsonb)
|
|
280
|
+
INTO incoming_json
|
|
281
|
+
FROM pg_constraint con
|
|
282
|
+
JOIN pg_class rel ON rel.oid = con.conrelid
|
|
283
|
+
JOIN pg_namespace n ON n.oid = rel.relnamespace
|
|
284
|
+
WHERE con.confrelid = parent_oid AND con.contype = 'f' AND con.conrelid <> parent_oid;
|
|
285
|
+
|
|
286
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object('def', pg_get_triggerdef(t.oid))), '[]'::jsonb)
|
|
287
|
+
INTO triggers_json
|
|
288
|
+
FROM pg_trigger t
|
|
289
|
+
WHERE t.tgrelid = parent_oid AND NOT t.tgisinternal;
|
|
290
|
+
|
|
291
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
292
|
+
'name', pol.polname,
|
|
293
|
+
'permissive', pol.polpermissive,
|
|
294
|
+
'cmd', pol.polcmd,
|
|
295
|
+
'qual', pg_get_expr(pol.polqual, pol.polrelid),
|
|
296
|
+
'check', pg_get_expr(pol.polwithcheck, pol.polrelid),
|
|
297
|
+
'roles', CASE
|
|
298
|
+
WHEN pol.polroles = ARRAY[0]::oid[] THEN 'PUBLIC'
|
|
299
|
+
ELSE (
|
|
300
|
+
SELECT string_agg(quote_ident(r.rolname), ', ' ORDER BY r.rolname)
|
|
301
|
+
FROM pg_roles r
|
|
302
|
+
WHERE r.oid = ANY (pol.polroles)
|
|
303
|
+
)
|
|
304
|
+
END
|
|
305
|
+
)), '[]'::jsonb)
|
|
306
|
+
INTO policies_json
|
|
307
|
+
FROM pg_policy pol
|
|
308
|
+
WHERE pol.polrelid = parent_oid;
|
|
309
|
+
|
|
310
|
+
SELECT coalesce(jsonb_agg(jsonb_build_object(
|
|
311
|
+
'grantee', acl.grantee,
|
|
312
|
+
'privilege', acl.privilege_type,
|
|
313
|
+
'grantable', acl.is_grantable
|
|
314
|
+
)), '[]'::jsonb)
|
|
315
|
+
INTO grants_json
|
|
316
|
+
FROM pg_class c, LATERAL aclexplode(c.relacl) AS acl
|
|
317
|
+
WHERE c.oid = parent_oid;
|
|
318
|
+
|
|
319
|
+
IF direction = 'partition' THEN
|
|
320
|
+
EXECUTE format('CREATE TABLE %I.%I (LIKE %I.%I INCLUDING ALL) PARTITION BY %s', parent_schema, swap_name, parent_schema, parent_name, partition_by);
|
|
321
|
+
ELSE
|
|
322
|
+
EXECUTE format('CREATE TABLE %I.%I (LIKE %I.%I INCLUDING ALL)', parent_schema, swap_name, parent_schema, parent_name);
|
|
323
|
+
END IF;
|
|
324
|
+
|
|
325
|
+
FOR item IN SELECT value FROM jsonb_array_elements(constraints_json) AS t(value)
|
|
326
|
+
LOOP
|
|
327
|
+
IF item->>'type' = 'f' AND COALESCE((item->>'self')::boolean, false) = false THEN
|
|
328
|
+
EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I %s', parent_schema, swap_name, item->>'name', item->>'def');
|
|
329
|
+
END IF;
|
|
330
|
+
END LOOP;
|
|
331
|
+
|
|
332
|
+
FOR item IN SELECT value FROM jsonb_array_elements(sequences_json) AS t(value)
|
|
333
|
+
LOOP
|
|
334
|
+
IF item->>'deptype' = 'a' THEN
|
|
335
|
+
EXECUTE format(
|
|
336
|
+
'ALTER SEQUENCE %I.%I OWNED BY %I.%I.%I',
|
|
337
|
+
item->>'schema', item->>'name', parent_schema, swap_name, item->>'column'
|
|
338
|
+
);
|
|
339
|
+
END IF;
|
|
340
|
+
END LOOP;
|
|
341
|
+
|
|
342
|
+
FOR item IN SELECT value FROM jsonb_array_elements(incoming_json) AS t(value)
|
|
343
|
+
LOOP
|
|
344
|
+
EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', item->>'schema', item->>'table', item->>'name');
|
|
345
|
+
END LOOP;
|
|
346
|
+
|
|
347
|
+
EXECUTE format('DROP TABLE %I.%I', parent_schema, parent_name);
|
|
348
|
+
EXECUTE format('ALTER TABLE %I.%I RENAME TO %I', parent_schema, swap_name, parent_name);
|
|
349
|
+
|
|
350
|
+
SELECT c.oid INTO new_oid
|
|
351
|
+
FROM pg_class c
|
|
352
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
353
|
+
WHERE n.nspname = parent_schema AND c.relname = parent_name;
|
|
354
|
+
|
|
355
|
+
FOR item IN SELECT value FROM jsonb_array_elements(indexes_json) AS t(value)
|
|
356
|
+
LOOP
|
|
357
|
+
SELECT i.indexrelid, ic.relname
|
|
358
|
+
INTO match_oid, match_name
|
|
359
|
+
FROM pg_index i
|
|
360
|
+
JOIN pg_class ic ON ic.oid = i.indexrelid
|
|
361
|
+
WHERE i.indrelid = new_oid
|
|
362
|
+
AND i.indexrelid <> ALL (claimed)
|
|
363
|
+
AND i.indisprimary = (item->>'primary')::boolean
|
|
364
|
+
AND i.indisunique = (item->>'unique')::boolean
|
|
365
|
+
AND i.indisexclusion = (item->>'exclusion')::boolean
|
|
366
|
+
AND coalesce(pg_get_expr(i.indexprs, i.indrelid), '') = coalesce(item->>'exprs', '')
|
|
367
|
+
AND coalesce(pg_get_expr(i.indpred, i.indrelid), '') = coalesce(item->>'pred', '')
|
|
368
|
+
AND (
|
|
369
|
+
SELECT coalesce(jsonb_agg(a.attname ORDER BY u.ord), '[]'::jsonb)
|
|
370
|
+
FROM unnest(i.indkey::smallint[]) WITH ORDINALITY AS u(attnum, ord)
|
|
371
|
+
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = u.attnum
|
|
372
|
+
WHERE u.attnum > 0
|
|
373
|
+
) = coalesce(item->'cols', '[]'::jsonb)
|
|
374
|
+
LIMIT 1;
|
|
375
|
+
|
|
376
|
+
IF match_oid IS NULL THEN
|
|
377
|
+
RAISE EXCEPTION 'drizzle-pg-extras: could not restore index % on %.% after converting it.', item->>'name', parent_schema, parent_name;
|
|
378
|
+
END IF;
|
|
379
|
+
claimed := claimed || match_oid;
|
|
380
|
+
IF match_name IS DISTINCT FROM item->>'name' THEN
|
|
381
|
+
EXECUTE format('ALTER INDEX %I.%I RENAME TO %I', parent_schema, match_name, item->>'name');
|
|
382
|
+
END IF;
|
|
383
|
+
match_oid := NULL;
|
|
384
|
+
match_name := NULL;
|
|
385
|
+
END LOOP;
|
|
386
|
+
|
|
387
|
+
FOR item IN SELECT value FROM jsonb_array_elements(constraints_json) AS t(value)
|
|
388
|
+
LOOP
|
|
389
|
+
IF item->>'type' = 'f' THEN
|
|
390
|
+
CONTINUE;
|
|
391
|
+
END IF;
|
|
392
|
+
SELECT con.conname
|
|
393
|
+
INTO match_name
|
|
394
|
+
FROM pg_constraint con
|
|
395
|
+
WHERE con.conrelid = new_oid
|
|
396
|
+
AND con.contype = item->>'type'
|
|
397
|
+
AND pg_get_constraintdef(con.oid) = item->>'def'
|
|
398
|
+
LIMIT 1;
|
|
399
|
+
IF match_name IS NULL THEN
|
|
400
|
+
RAISE EXCEPTION 'drizzle-pg-extras: could not restore constraint % on %.% after converting it.', item->>'name', parent_schema, parent_name;
|
|
401
|
+
END IF;
|
|
402
|
+
IF match_name IS DISTINCT FROM item->>'name' THEN
|
|
403
|
+
EXECUTE format('ALTER TABLE %I.%I RENAME CONSTRAINT %I TO %I', parent_schema, parent_name, match_name, item->>'name');
|
|
404
|
+
END IF;
|
|
405
|
+
match_name := NULL;
|
|
406
|
+
END LOOP;
|
|
407
|
+
|
|
408
|
+
FOR item IN SELECT value FROM jsonb_array_elements(constraints_json) AS t(value)
|
|
409
|
+
LOOP
|
|
410
|
+
IF item->>'type' = 'f' AND COALESCE((item->>'self')::boolean, false) THEN
|
|
411
|
+
EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I %s', parent_schema, parent_name, item->>'name', item->>'def');
|
|
412
|
+
END IF;
|
|
413
|
+
END LOOP;
|
|
414
|
+
|
|
415
|
+
FOR item IN SELECT value FROM jsonb_array_elements(incoming_json) AS t(value)
|
|
416
|
+
LOOP
|
|
417
|
+
EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I %s', item->>'schema', item->>'table', item->>'name', item->>'def');
|
|
418
|
+
END LOOP;
|
|
419
|
+
|
|
420
|
+
FOR item IN SELECT value FROM jsonb_array_elements(sequences_json) AS t(value)
|
|
421
|
+
LOOP
|
|
422
|
+
IF item->>'deptype' <> 'i' THEN
|
|
423
|
+
CONTINUE;
|
|
424
|
+
END IF;
|
|
425
|
+
SELECT sn.nspname, sc.relname
|
|
426
|
+
INTO seq_schema, seq_name
|
|
427
|
+
FROM pg_depend d
|
|
428
|
+
JOIN pg_class sc ON sc.oid = d.objid AND sc.relkind = 'S'
|
|
429
|
+
JOIN pg_namespace sn ON sn.oid = sc.relnamespace
|
|
430
|
+
JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid AND NOT a.attisdropped
|
|
431
|
+
WHERE d.refobjid = new_oid
|
|
432
|
+
AND d.classid = 'pg_class'::regclass
|
|
433
|
+
AND d.deptype = 'i'
|
|
434
|
+
AND a.attname = item->>'column'
|
|
435
|
+
LIMIT 1;
|
|
436
|
+
IF seq_name IS NOT NULL AND seq_name IS DISTINCT FROM item->>'name' THEN
|
|
437
|
+
EXECUTE format('ALTER SEQUENCE %I.%I RENAME TO %I', seq_schema, seq_name, item->>'name');
|
|
438
|
+
END IF;
|
|
439
|
+
seq_schema := NULL;
|
|
440
|
+
seq_name := NULL;
|
|
441
|
+
END LOOP;
|
|
442
|
+
|
|
443
|
+
FOR item IN SELECT value FROM jsonb_array_elements(triggers_json) AS t(value)
|
|
444
|
+
LOOP
|
|
445
|
+
IF item->>'def' IS NOT NULL THEN
|
|
446
|
+
EXECUTE item->>'def';
|
|
447
|
+
END IF;
|
|
448
|
+
END LOOP;
|
|
449
|
+
|
|
450
|
+
FOR item IN SELECT value FROM jsonb_array_elements(policies_json) AS t(value)
|
|
451
|
+
LOOP
|
|
452
|
+
EXECUTE format(
|
|
453
|
+
'CREATE POLICY %I ON %I.%I AS %s FOR %s TO %s%s%s',
|
|
454
|
+
item->>'name',
|
|
455
|
+
parent_schema,
|
|
456
|
+
parent_name,
|
|
457
|
+
CASE WHEN (item->>'permissive')::boolean THEN 'PERMISSIVE' ELSE 'RESTRICTIVE' END,
|
|
458
|
+
CASE item->>'cmd'
|
|
459
|
+
WHEN 'r' THEN 'SELECT'
|
|
460
|
+
WHEN 'a' THEN 'INSERT'
|
|
461
|
+
WHEN 'w' THEN 'UPDATE'
|
|
462
|
+
WHEN 'd' THEN 'DELETE'
|
|
463
|
+
ELSE 'ALL'
|
|
464
|
+
END,
|
|
465
|
+
COALESCE(item->>'roles', 'PUBLIC'),
|
|
466
|
+
CASE WHEN item->>'qual' IS NOT NULL THEN format(' USING (%s)', item->>'qual') ELSE '' END,
|
|
467
|
+
CASE WHEN item->>'check' IS NOT NULL THEN format(' WITH CHECK (%s)', item->>'check') ELSE '' END
|
|
468
|
+
);
|
|
469
|
+
END LOOP;
|
|
470
|
+
|
|
471
|
+
IF rls THEN
|
|
472
|
+
EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', parent_schema, parent_name);
|
|
473
|
+
END IF;
|
|
474
|
+
IF force_rls THEN
|
|
475
|
+
EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', parent_schema, parent_name);
|
|
476
|
+
END IF;
|
|
477
|
+
|
|
478
|
+
IF replica = 'f' THEN
|
|
479
|
+
EXECUTE format('ALTER TABLE %I.%I REPLICA IDENTITY FULL', parent_schema, parent_name);
|
|
480
|
+
ELSIF replica = 'n' THEN
|
|
481
|
+
EXECUTE format('ALTER TABLE %I.%I REPLICA IDENTITY NOTHING', parent_schema, parent_name);
|
|
482
|
+
ELSIF replica = 'i' AND replica_index IS NOT NULL THEN
|
|
483
|
+
EXECUTE format('ALTER TABLE %I.%I REPLICA IDENTITY USING INDEX %I', parent_schema, parent_name, replica_index);
|
|
484
|
+
END IF;
|
|
485
|
+
|
|
486
|
+
IF rel_options IS NOT NULL THEN
|
|
487
|
+
EXECUTE format('ALTER TABLE %I.%I SET (%s)', parent_schema, parent_name, array_to_string(rel_options, ', '));
|
|
488
|
+
END IF;
|
|
489
|
+
|
|
490
|
+
FOR item IN SELECT value FROM jsonb_array_elements(grants_json) AS t(value)
|
|
491
|
+
LOOP
|
|
492
|
+
IF (item->>'privilege') NOT IN ('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER', 'MAINTAIN') THEN
|
|
493
|
+
CONTINUE;
|
|
494
|
+
END IF;
|
|
495
|
+
IF (item->>'grantee')::oid = 0 THEN
|
|
496
|
+
match_name := 'PUBLIC';
|
|
497
|
+
ELSE
|
|
498
|
+
SELECT r.rolname INTO match_name FROM pg_roles r WHERE r.oid = (item->>'grantee')::oid;
|
|
499
|
+
IF match_name IS NULL THEN
|
|
500
|
+
CONTINUE;
|
|
501
|
+
END IF;
|
|
502
|
+
match_name := format('%I', match_name);
|
|
503
|
+
END IF;
|
|
504
|
+
EXECUTE format(
|
|
505
|
+
'GRANT %s ON TABLE %I.%I TO %s%s',
|
|
506
|
+
item->>'privilege',
|
|
507
|
+
parent_schema,
|
|
508
|
+
parent_name,
|
|
509
|
+
match_name,
|
|
510
|
+
CASE WHEN (item->>'grantable')::boolean THEN ' WITH GRANT OPTION' ELSE '' END
|
|
511
|
+
);
|
|
512
|
+
match_name := NULL;
|
|
513
|
+
END LOOP;
|
|
514
|
+
|
|
515
|
+
IF owner_name IS NOT NULL THEN
|
|
516
|
+
EXECUTE format('ALTER TABLE %I.%I OWNER TO %I', parent_schema, parent_name, owner_name);
|
|
517
|
+
END IF;
|
|
518
|
+
IF table_comment IS NOT NULL THEN
|
|
519
|
+
EXECUTE format('COMMENT ON TABLE %I.%I IS %L', parent_schema, parent_name, table_comment);
|
|
520
|
+
END IF;
|
|
521
|
+
END
|
|
522
|
+
`;
|
|
523
|
+
}
|
|
524
|
+
function partitionBody(partition, mode) {
|
|
525
|
+
return `
|
|
526
|
+
DECLARE
|
|
527
|
+
child_schema text := ${quoteLiteral(partition.schema)};
|
|
528
|
+
child_name text := ${quoteLiteral(partition.name)};
|
|
529
|
+
parent_schema text := ${quoteLiteral(partition.parentSchema)};
|
|
530
|
+
parent_name text := ${quoteLiteral(partition.parentName)};
|
|
531
|
+
bound_sql text := ${quoteLiteral(partition.boundSql)};
|
|
532
|
+
child_oid oid;
|
|
533
|
+
parent_oid oid;
|
|
534
|
+
attached boolean;
|
|
535
|
+
BEGIN
|
|
536
|
+
parent_oid := to_regclass(format('%I.%I', parent_schema, parent_name));
|
|
537
|
+
child_oid := to_regclass(format('%I.%I', child_schema, child_name));
|
|
538
|
+
IF parent_oid IS NULL THEN
|
|
539
|
+
RAISE EXCEPTION 'drizzle-pg-extras: parent %.% does not exist. Partition the parent before attaching partitions.', parent_schema, parent_name;
|
|
540
|
+
END IF;
|
|
541
|
+
IF child_oid IS NOT NULL THEN
|
|
542
|
+
SELECT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = child_oid AND inhparent = parent_oid) INTO attached;
|
|
543
|
+
IF attached THEN
|
|
544
|
+
RETURN;
|
|
545
|
+
END IF;
|
|
546
|
+
IF EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = child_oid) THEN
|
|
547
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% is already a partition of another table.', child_schema, child_name;
|
|
548
|
+
END IF;
|
|
549
|
+
${mode === "create" ? `RAISE EXCEPTION 'drizzle-pg-extras: %.% already exists and is not a partition of %.%.', child_schema, child_name, parent_schema, parent_name;` : `EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I %s', parent_schema, parent_name, child_schema, child_name, bound_sql); RETURN;`}
|
|
550
|
+
END IF;
|
|
551
|
+
${mode === "create" ? `EXECUTE format('CREATE TABLE %I.%I PARTITION OF %I.%I %s', child_schema, child_name, parent_schema, parent_name, bound_sql);` : `RAISE EXCEPTION 'drizzle-pg-extras: %.% does not exist. Create it with drizzle-kit before attaching it.', child_schema, child_name;`}
|
|
552
|
+
END
|
|
553
|
+
`;
|
|
554
|
+
}
|
|
555
|
+
function detachBody(partition) {
|
|
556
|
+
return `
|
|
557
|
+
DECLARE
|
|
558
|
+
child_schema text := ${quoteLiteral(partition.schema)};
|
|
559
|
+
child_name text := ${quoteLiteral(partition.name)};
|
|
560
|
+
parent_schema text := ${quoteLiteral(partition.parentSchema)};
|
|
561
|
+
parent_name text := ${quoteLiteral(partition.parentName)};
|
|
562
|
+
child_oid oid;
|
|
563
|
+
parent_oid oid;
|
|
564
|
+
BEGIN
|
|
565
|
+
parent_oid := to_regclass(format('%I.%I', parent_schema, parent_name));
|
|
566
|
+
child_oid := to_regclass(format('%I.%I', child_schema, child_name));
|
|
567
|
+
IF parent_oid IS NULL OR child_oid IS NULL THEN
|
|
568
|
+
RETURN;
|
|
569
|
+
END IF;
|
|
570
|
+
IF EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = child_oid AND inhparent = parent_oid) THEN
|
|
571
|
+
EXECUTE format('ALTER TABLE %I.%I DETACH PARTITION %I.%I', parent_schema, parent_name, child_schema, child_name);
|
|
572
|
+
END IF;
|
|
573
|
+
END
|
|
574
|
+
`;
|
|
575
|
+
}
|
|
576
|
+
function dropBody(partition) {
|
|
577
|
+
return `
|
|
578
|
+
DECLARE
|
|
579
|
+
child_schema text := ${quoteLiteral(partition.schema)};
|
|
580
|
+
child_name text := ${quoteLiteral(partition.name)};
|
|
581
|
+
parent_schema text := ${quoteLiteral(partition.parentSchema)};
|
|
582
|
+
parent_name text := ${quoteLiteral(partition.parentName)};
|
|
583
|
+
child_oid oid;
|
|
584
|
+
parent_oid oid;
|
|
585
|
+
non_empty boolean;
|
|
586
|
+
BEGIN
|
|
587
|
+
parent_oid := to_regclass(format('%I.%I', parent_schema, parent_name));
|
|
588
|
+
child_oid := to_regclass(format('%I.%I', child_schema, child_name));
|
|
589
|
+
IF child_oid IS NULL THEN
|
|
590
|
+
RETURN;
|
|
591
|
+
END IF;
|
|
592
|
+
IF EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = child_oid AND (parent_oid IS NULL OR i.inhparent <> parent_oid)) THEN
|
|
593
|
+
RAISE EXCEPTION 'drizzle-pg-extras: %.% is a partition of a different table. Refusing to drop it.', child_schema, child_name;
|
|
594
|
+
END IF;
|
|
595
|
+
EXECUTE format('SELECT EXISTS (SELECT 1 FROM %I.%I LIMIT 1)', child_schema, child_name) INTO non_empty;
|
|
596
|
+
IF non_empty THEN
|
|
597
|
+
RAISE EXCEPTION 'drizzle-pg-extras: partition %.% has rows. Refusing to drop it. Empty it, or set onRemove: "detach" on the partition before removing it.', child_schema, child_name;
|
|
598
|
+
END IF;
|
|
599
|
+
IF parent_oid IS NOT NULL AND EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = child_oid AND inhparent = parent_oid) THEN
|
|
600
|
+
EXECUTE format('ALTER TABLE %I.%I DETACH PARTITION %I.%I', parent_schema, parent_name, child_schema, child_name);
|
|
601
|
+
END IF;
|
|
602
|
+
EXECUTE format('DROP TABLE %I.%I', child_schema, child_name);
|
|
603
|
+
END
|
|
604
|
+
`;
|
|
605
|
+
}
|
|
606
|
+
function wrapDo(body) {
|
|
607
|
+
let tag = "pg_extras";
|
|
608
|
+
let n = 0;
|
|
609
|
+
while (body.includes(`$${tag}$`)) {
|
|
610
|
+
n += 1;
|
|
611
|
+
tag = `pg_extras${n}`;
|
|
612
|
+
}
|
|
613
|
+
return `DO $${tag}$${body.trim()}
|
|
614
|
+
$${tag}$;`;
|
|
615
|
+
}
|
|
616
|
+
function swapName(name) {
|
|
617
|
+
const suffix = "__pgx";
|
|
618
|
+
const max = 63 - Buffer.byteLength(suffix);
|
|
619
|
+
let bytes = Buffer.from(name);
|
|
620
|
+
if (bytes.length > max) bytes = bytes.subarray(0, max);
|
|
621
|
+
while (bytes.length > 0 && (bytes[bytes.length - 1] & 192) === 128) {
|
|
622
|
+
bytes = bytes.subarray(0, bytes.length - 1);
|
|
623
|
+
}
|
|
624
|
+
return bytes.toString() + suffix;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// src/timescale-sql.ts
|
|
628
|
+
function createHypertableStatements(ht) {
|
|
629
|
+
const statements = [createHypertableSql(ht)];
|
|
630
|
+
if (ht.compression) statements.push(enableHypertableCompressionSql(ht, ht.compression, null));
|
|
631
|
+
if (ht.compressionPolicy) statements.push(addCompressionPolicySql(ht));
|
|
632
|
+
if (ht.retention) statements.push(addRetentionPolicySql(ht));
|
|
633
|
+
return statements;
|
|
634
|
+
}
|
|
635
|
+
function createHypertableSql(ht) {
|
|
636
|
+
const args = [relation(ht), nameLiteral(ht.timeColumn)];
|
|
637
|
+
if (ht.partitioningColumn) {
|
|
638
|
+
args.push(`partitioning_column => ${nameLiteral(ht.partitioningColumn)}`);
|
|
639
|
+
args.push(`number_partitions => ${ht.numberPartitions}`);
|
|
640
|
+
}
|
|
641
|
+
if (ht.chunkTimeInterval) args.push(`chunk_time_interval => ${intervalLiteral(ht.chunkTimeInterval)}`);
|
|
642
|
+
if (ht.migrateData) args.push("migrate_data => TRUE");
|
|
643
|
+
args.push("if_not_exists => TRUE");
|
|
644
|
+
const space = ht.partitioningColumn ? ` and ${quoteIdent(ht.partitioningColumn)}` : "";
|
|
645
|
+
return `-- Convert ${qualify(ht.schema, ht.name)} into a TimescaleDB hypertable on ${quoteIdent(ht.timeColumn)}${space}.
|
|
646
|
+
SELECT create_hypertable(${args.join(", ")});`;
|
|
647
|
+
}
|
|
648
|
+
function setChunkTimeIntervalSql(ht) {
|
|
649
|
+
return `-- Set the chunk interval of ${qualify(ht.schema, ht.name)} to ${ht.chunkTimeInterval}.
|
|
650
|
+
SELECT set_chunk_time_interval(${relation(ht)}, ${intervalLiteral(ht.chunkTimeInterval ?? "")});`;
|
|
651
|
+
}
|
|
652
|
+
function addHypertableDimensionSql(ht) {
|
|
653
|
+
return `-- Add a space partition on ${quoteIdent(ht.partitioningColumn ?? "")} to ${qualify(ht.schema, ht.name)}.
|
|
654
|
+
SELECT add_dimension(${relation(ht)}, ${nameLiteral(ht.partitioningColumn ?? "")}, number_partitions => ${ht.numberPartitions}, if_not_exists => TRUE);`;
|
|
655
|
+
}
|
|
656
|
+
function enableHypertableCompressionSql(ht, compression, previous) {
|
|
657
|
+
const options = ["timescaledb.compress"];
|
|
658
|
+
const segment = compression.segmentBy.map((column) => quoteIdent(column)).join(", ");
|
|
659
|
+
if (segment.length > 0 || (previous?.segmentBy.length ?? 0) > 0) {
|
|
660
|
+
options.push(`timescaledb.compress_segmentby = ${quoteLiteral(segment)}`);
|
|
661
|
+
}
|
|
662
|
+
const order = compression.orderBy.map(orderFragment).join(", ");
|
|
663
|
+
if (order.length > 0 || (previous?.orderBy.length ?? 0) > 0) {
|
|
664
|
+
options.push(`timescaledb.compress_orderby = ${quoteLiteral(order)}`);
|
|
665
|
+
}
|
|
666
|
+
return `-- Enable compression on ${qualify(ht.schema, ht.name)}.
|
|
667
|
+
ALTER TABLE ${qualify(ht.schema, ht.name)} SET (
|
|
668
|
+
${options.join(",\n ")}
|
|
669
|
+
);`;
|
|
670
|
+
}
|
|
671
|
+
function disableHypertableCompressionSql(ht) {
|
|
672
|
+
return `-- Turn compression off on ${qualify(ht.schema, ht.name)}.
|
|
673
|
+
ALTER TABLE ${qualify(ht.schema, ht.name)} SET (timescaledb.compress = false);`;
|
|
674
|
+
}
|
|
675
|
+
function addRetentionPolicySql(ht) {
|
|
676
|
+
const policy = ht.retention;
|
|
677
|
+
if (!policy) throw new PgExtrasError("addRetentionPolicySql requires a retention policy");
|
|
678
|
+
return policySql(
|
|
679
|
+
"Add a retention policy to",
|
|
680
|
+
"add_retention_policy",
|
|
681
|
+
ht,
|
|
682
|
+
`drop_after => ${intervalLiteral(policy.dropAfter)}`,
|
|
683
|
+
policy.scheduleInterval
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
function removeRetentionPolicySql(ht) {
|
|
687
|
+
return `-- Remove the retention policy from ${qualify(ht.schema, ht.name)}.
|
|
688
|
+
SELECT remove_retention_policy(${relation(ht)}, if_exists => TRUE);`;
|
|
689
|
+
}
|
|
690
|
+
function addCompressionPolicySql(ht) {
|
|
691
|
+
const policy = ht.compressionPolicy;
|
|
692
|
+
if (!policy) throw new PgExtrasError("addCompressionPolicySql requires a compression policy");
|
|
693
|
+
return policySql(
|
|
694
|
+
"Add a compression policy to",
|
|
695
|
+
"add_compression_policy",
|
|
696
|
+
ht,
|
|
697
|
+
`compress_after => ${intervalLiteral(policy.compressAfter)}`,
|
|
698
|
+
policy.scheduleInterval
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
function removeCompressionPolicySql(ht) {
|
|
702
|
+
return `-- Remove the compression policy from ${qualify(ht.schema, ht.name)}.
|
|
703
|
+
SELECT remove_compression_policy(${relation(ht)}, if_exists => TRUE);`;
|
|
704
|
+
}
|
|
705
|
+
function leaveHypertableDimensionSql(ht) {
|
|
706
|
+
return `-- ${qualify(ht.schema, ht.name)} keeps its space partition on ${quoteIdent(ht.partitioningColumn ?? "")}. This migration does not drop a hash dimension.
|
|
707
|
+
DO $drizzle_pg_extras$
|
|
708
|
+
BEGIN
|
|
709
|
+
RAISE NOTICE 'drizzle-pg-extras: %.% keeps space partition %', ${quoteLiteral(ht.schema)}, ${quoteLiteral(ht.name)}, ${quoteLiteral(ht.partitioningColumn ?? "")};
|
|
710
|
+
END
|
|
711
|
+
$drizzle_pg_extras$;`;
|
|
712
|
+
}
|
|
713
|
+
function leaveChunkIntervalSql(ht) {
|
|
714
|
+
return `-- ${qualify(ht.schema, ht.name)} keeps chunk interval ${ht.chunkTimeInterval}. Clearing chunkTimeInterval is not generated.
|
|
715
|
+
DO $drizzle_pg_extras$
|
|
716
|
+
BEGIN
|
|
717
|
+
RAISE NOTICE 'drizzle-pg-extras: %.% keeps chunk interval %', ${quoteLiteral(ht.schema)}, ${quoteLiteral(ht.name)}, ${quoteLiteral(ht.chunkTimeInterval ?? "")};
|
|
718
|
+
END
|
|
719
|
+
$drizzle_pg_extras$;`;
|
|
720
|
+
}
|
|
721
|
+
function leaveHypertableSql(ht) {
|
|
722
|
+
return `-- ${qualify(ht.schema, ht.name)} stays a hypertable. TimescaleDB cannot turn it back into a regular table from this migration.
|
|
723
|
+
DO $drizzle_pg_extras$
|
|
724
|
+
BEGIN
|
|
725
|
+
RAISE NOTICE 'drizzle-pg-extras: %.% stays a hypertable', ${quoteLiteral(ht.schema)}, ${quoteLiteral(ht.name)};
|
|
726
|
+
END
|
|
727
|
+
$drizzle_pg_extras$;`;
|
|
728
|
+
}
|
|
729
|
+
function policySql(comment, fn, ht, age, scheduleInterval) {
|
|
730
|
+
const schedule = scheduleInterval ? `, schedule_interval => ${intervalLiteral(scheduleInterval)}` : "";
|
|
731
|
+
return `-- ${comment} ${qualify(ht.schema, ht.name)}.
|
|
732
|
+
SELECT ${fn}(${relation(ht)}, ${age}${schedule}, if_not_exists => TRUE);`;
|
|
733
|
+
}
|
|
734
|
+
function relation(ht) {
|
|
735
|
+
return `${quoteLiteral(`${quoteIdent(ht.schema)}.${quoteIdent(ht.name)}`)}::regclass`;
|
|
736
|
+
}
|
|
737
|
+
function nameLiteral(name) {
|
|
738
|
+
return `${quoteLiteral(name)}::name`;
|
|
739
|
+
}
|
|
740
|
+
function intervalLiteral(value) {
|
|
741
|
+
return `INTERVAL ${quoteLiteral(value)}`;
|
|
742
|
+
}
|
|
743
|
+
function orderFragment(order) {
|
|
744
|
+
const parts = [quoteIdent(order.column)];
|
|
745
|
+
if (order.direction) parts.push(order.direction.toUpperCase());
|
|
746
|
+
if (order.nulls) parts.push(`NULLS ${order.nulls.toUpperCase()}`);
|
|
747
|
+
return parts.join(" ");
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// src/snapshot.ts
|
|
751
|
+
import { Column as Column2, SQL as SQL2, getTableColumns as getTableColumns2, is as is3 } from "drizzle-orm";
|
|
752
|
+
import { CasingCache as CasingCache2, toCamelCase, toSnakeCase } from "drizzle-orm/casing";
|
|
753
|
+
import {
|
|
754
|
+
CheckBuilder as CheckBuilder2,
|
|
755
|
+
ForeignKeyBuilder as ForeignKeyBuilder2,
|
|
756
|
+
IndexBuilder as IndexBuilder2,
|
|
757
|
+
PgArray,
|
|
758
|
+
PgEnumColumn,
|
|
759
|
+
PgEnumObjectColumn,
|
|
760
|
+
PgTable as PgTable2,
|
|
761
|
+
PrimaryKeyBuilder as PrimaryKeyBuilder2,
|
|
762
|
+
UniqueConstraintBuilder as UniqueConstraintBuilder2,
|
|
763
|
+
getMaterializedViewConfig as getMaterializedViewConfig2,
|
|
764
|
+
getViewConfig as getViewConfig2,
|
|
765
|
+
isPgEnum as isPgEnum2,
|
|
766
|
+
isPgMaterializedView as isPgMaterializedView2,
|
|
767
|
+
isPgView as isPgView2
|
|
768
|
+
} from "drizzle-orm/pg-core";
|
|
769
|
+
|
|
770
|
+
// src/defs.ts
|
|
771
|
+
import {
|
|
772
|
+
Column,
|
|
773
|
+
ColumnBuilder,
|
|
774
|
+
getTableColumns,
|
|
775
|
+
is as is2,
|
|
776
|
+
sql,
|
|
777
|
+
Table
|
|
778
|
+
} from "drizzle-orm";
|
|
779
|
+
import { CasingCache } from "drizzle-orm/casing";
|
|
780
|
+
import {
|
|
781
|
+
CheckBuilder,
|
|
782
|
+
ForeignKeyBuilder,
|
|
783
|
+
IndexBuilder,
|
|
784
|
+
IndexBuilderOn,
|
|
785
|
+
ManualMaterializedViewBuilder,
|
|
786
|
+
ManualViewBuilder,
|
|
787
|
+
MaterializedViewBuilder,
|
|
788
|
+
PgTable,
|
|
789
|
+
PrimaryKeyBuilder,
|
|
790
|
+
UniqueConstraintBuilder,
|
|
791
|
+
UniqueOnConstraintBuilder,
|
|
792
|
+
ViewBuilder,
|
|
793
|
+
getMaterializedViewConfig,
|
|
794
|
+
getTableConfig,
|
|
795
|
+
getViewConfig,
|
|
796
|
+
isPgEnum,
|
|
797
|
+
isPgMaterializedView,
|
|
798
|
+
isPgView
|
|
799
|
+
} from "drizzle-orm/pg-core";
|
|
800
|
+
|
|
801
|
+
// src/render-sql.ts
|
|
802
|
+
import { is, SQL } from "drizzle-orm";
|
|
803
|
+
import { PgDialect } from "drizzle-orm/pg-core";
|
|
804
|
+
var dialects = /* @__PURE__ */ new Map();
|
|
805
|
+
function dialectFor(casing) {
|
|
806
|
+
const key = casing ?? "";
|
|
807
|
+
let dialect = dialects.get(key);
|
|
808
|
+
if (!dialect) {
|
|
809
|
+
dialect = new PgDialect(casing ? { casing } : void 0);
|
|
810
|
+
dialects.set(key, dialect);
|
|
811
|
+
}
|
|
812
|
+
return dialect;
|
|
813
|
+
}
|
|
814
|
+
function isSqlFragment(value) {
|
|
815
|
+
return is(value, SQL);
|
|
816
|
+
}
|
|
817
|
+
function renderSql(query, casing) {
|
|
818
|
+
return dialectFor(casing).sqlToQuery(query.inlineParams()).sql;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// src/defs.ts
|
|
822
|
+
var KIND = /* @__PURE__ */ Symbol.for("drizzle-pg-extras.kind");
|
|
823
|
+
var COMMENT = /* @__PURE__ */ Symbol.for("drizzle-pg-extras.comment");
|
|
824
|
+
function extrasKind(value) {
|
|
825
|
+
if (typeof value !== "object" || value === null) return null;
|
|
826
|
+
const kind = value[KIND];
|
|
827
|
+
if (kind === "function" || kind === "trigger" || kind === "extension" || kind === "comment" || kind === "partitionedTable" || kind === "partition" || kind === "detach" || kind === "hypertable") {
|
|
828
|
+
return kind;
|
|
829
|
+
}
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
function readComment(target) {
|
|
833
|
+
const direct = target[COMMENT];
|
|
834
|
+
if (typeof direct === "string") return direct;
|
|
835
|
+
const config = target.config;
|
|
836
|
+
const stamped = config?.[COMMENT];
|
|
837
|
+
return typeof stamped === "string" ? stamped : void 0;
|
|
838
|
+
}
|
|
839
|
+
function triggerError(label, message) {
|
|
840
|
+
throw new PgExtrasError(`pgTrigger("${label}"): ${message}`);
|
|
841
|
+
}
|
|
842
|
+
function relationIdentity(relation2) {
|
|
843
|
+
if (is2(relation2, PgTable)) {
|
|
844
|
+
const config = getTableConfig(relation2);
|
|
845
|
+
return { schema: schemaName(config.schema), name: config.name, kind: "table" };
|
|
846
|
+
}
|
|
847
|
+
if (isPgView(relation2) || isPgMaterializedView(relation2)) {
|
|
848
|
+
const materialized = isPgMaterializedView(relation2);
|
|
849
|
+
const config = materialized ? getMaterializedViewConfig(relation2) : getViewConfig(relation2);
|
|
850
|
+
return {
|
|
851
|
+
schema: schemaName(config.schema),
|
|
852
|
+
name: config.name,
|
|
853
|
+
kind: materialized ? "materializedView" : "view"
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
assertIdentifier("table", relation2.name);
|
|
857
|
+
if (relation2.schema) assertIdentifier("table schema", relation2.schema);
|
|
858
|
+
return { schema: schemaName(relation2.schema), name: relation2.name, kind: "name" };
|
|
859
|
+
}
|
|
860
|
+
function relationColumnEntries(relation2) {
|
|
861
|
+
if (is2(relation2, PgTable)) return Object.entries(getTableColumns(relation2));
|
|
862
|
+
const config = isPgMaterializedView(relation2) ? getMaterializedViewConfig(relation2) : getViewConfig(relation2);
|
|
863
|
+
const entries = [];
|
|
864
|
+
for (const [key, field] of Object.entries(config.selectedFields ?? {})) {
|
|
865
|
+
if (is2(field, Column)) entries.push([key, field]);
|
|
866
|
+
}
|
|
867
|
+
return entries;
|
|
868
|
+
}
|
|
869
|
+
function schemaName(schema) {
|
|
870
|
+
return schema && schema.length > 0 ? schema : "public";
|
|
871
|
+
}
|
|
872
|
+
function renderTriggerWhen(trigger, casing) {
|
|
873
|
+
const label = trigger.name ?? "updated-at trigger";
|
|
874
|
+
const text = renderWhenInput(label, trigger.table, trigger.when, casing);
|
|
875
|
+
if (!text) return null;
|
|
876
|
+
assertWhenSql(label, text, { timing: trigger.timing, events: trigger.events, forEach: trigger.forEach });
|
|
877
|
+
return text;
|
|
878
|
+
}
|
|
879
|
+
function renderWhenInput(label, table, when, casing) {
|
|
880
|
+
if (!when) return null;
|
|
881
|
+
let value;
|
|
882
|
+
if (typeof when === "function") {
|
|
883
|
+
if (!is2(table, PgTable) && !isPgView(table) && !isPgMaterializedView(table)) {
|
|
884
|
+
triggerError(label, "WHEN callback needs a Drizzle table or view so NEW and OLD can be typed");
|
|
885
|
+
}
|
|
886
|
+
const entries = relationColumnEntries(table);
|
|
887
|
+
value = when({
|
|
888
|
+
NEW: rowProxy(entries, "NEW", casing),
|
|
889
|
+
OLD: rowProxy(entries, "OLD", casing)
|
|
890
|
+
});
|
|
891
|
+
} else {
|
|
892
|
+
value = when;
|
|
893
|
+
}
|
|
894
|
+
const text = (typeof value === "string" ? value : renderSql(value, casing)).trim().replace(/;+\s*$/, "");
|
|
895
|
+
return text.length === 0 ? null : text;
|
|
896
|
+
}
|
|
897
|
+
function rowProxy(columns, alias, casing) {
|
|
898
|
+
const cache = new CasingCache(casing);
|
|
899
|
+
const refs = {};
|
|
900
|
+
for (const [key, column] of columns) {
|
|
901
|
+
refs[key] = sql.raw(`${alias}.${quoteIdent(cache.getColumnCasing(column))}`);
|
|
902
|
+
}
|
|
903
|
+
return refs;
|
|
904
|
+
}
|
|
905
|
+
function assertWhenSql(label, whenSql, info) {
|
|
906
|
+
if (whenSql.includes(";")) triggerError(label, 'WHEN clause cannot contain ";"');
|
|
907
|
+
if (info.timing === "instead of") triggerError(label, "INSTEAD OF triggers do not support WHEN");
|
|
908
|
+
const refs = whenReferences(whenSql);
|
|
909
|
+
if (refs.subquery) triggerError(label, "WHEN condition cannot contain a subquery");
|
|
910
|
+
if (info.forEach === "statement" && (refs.old || refs.new)) {
|
|
911
|
+
triggerError(label, "statement trigger WHEN cannot reference OLD or NEW");
|
|
912
|
+
}
|
|
913
|
+
if (info.events.includes("insert") && refs.old) triggerError(label, "INSERT trigger WHEN cannot reference OLD");
|
|
914
|
+
if (info.events.includes("delete") && refs.new) triggerError(label, "DELETE trigger WHEN cannot reference NEW");
|
|
915
|
+
}
|
|
916
|
+
function whenReferences(whenSql) {
|
|
917
|
+
const stripped = stripSqlNoise(whenSql);
|
|
918
|
+
return {
|
|
919
|
+
old: /\bOLD\b/i.test(stripped),
|
|
920
|
+
new: /\bNEW\b/i.test(stripped),
|
|
921
|
+
subquery: /\b(?:SELECT|EXISTS)\b/i.test(stripped)
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
function stripSqlNoise(input) {
|
|
925
|
+
let out = "";
|
|
926
|
+
for (let i = 0; i < input.length; i++) {
|
|
927
|
+
const ch = input[i];
|
|
928
|
+
const next = input[i + 1];
|
|
929
|
+
if (ch === "-" && next === "-") {
|
|
930
|
+
out += " ";
|
|
931
|
+
i += 2;
|
|
932
|
+
while (i < input.length && input[i] !== "\n") i++;
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (ch === "/" && next === "*") {
|
|
936
|
+
out += " ";
|
|
937
|
+
const end = input.indexOf("*/", i + 2);
|
|
938
|
+
i = end === -1 ? input.length : end + 1;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
if (ch === "'") {
|
|
942
|
+
out += " ";
|
|
943
|
+
i++;
|
|
944
|
+
while (i < input.length) {
|
|
945
|
+
if (input[i] === "'" && input[i + 1] === "'") {
|
|
946
|
+
i += 2;
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (input[i] === "'") break;
|
|
950
|
+
i++;
|
|
951
|
+
}
|
|
952
|
+
continue;
|
|
953
|
+
}
|
|
954
|
+
if (ch === '"') {
|
|
955
|
+
out += " ";
|
|
956
|
+
i++;
|
|
957
|
+
while (i < input.length) {
|
|
958
|
+
if (input[i] === '"' && input[i + 1] === '"') {
|
|
959
|
+
i += 2;
|
|
960
|
+
continue;
|
|
961
|
+
}
|
|
962
|
+
if (input[i] === '"') break;
|
|
963
|
+
i++;
|
|
964
|
+
}
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
if (ch === "$") {
|
|
968
|
+
const match = /^\$([A-Za-z0-9_]*)\$/.exec(input.slice(i));
|
|
969
|
+
if (match) {
|
|
970
|
+
const tag = match[0];
|
|
971
|
+
const end = input.indexOf(tag, i + tag.length);
|
|
972
|
+
out += " ";
|
|
973
|
+
i = end === -1 ? input.length : end + tag.length - 1;
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
out += ch;
|
|
978
|
+
}
|
|
979
|
+
return out;
|
|
980
|
+
}
|
|
981
|
+
function assertColumnOfTable(table, column) {
|
|
982
|
+
const columns = Object.values(getTableColumns(table));
|
|
983
|
+
if (!columns.includes(column)) {
|
|
984
|
+
throw new PgExtrasError(
|
|
985
|
+
`column "${column.name}" does not belong to table "${getTableConfig(table).name}"`
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
function tableIdentity(table) {
|
|
990
|
+
if (is2(table, PgTable)) {
|
|
991
|
+
const config = getTableConfig(table);
|
|
992
|
+
return { schema: config.schema && config.schema.length > 0 ? config.schema : "public", name: config.name };
|
|
993
|
+
}
|
|
994
|
+
return { schema: table.schema && table.schema.length > 0 ? table.schema : "public", name: table.name };
|
|
995
|
+
}
|
|
996
|
+
var INTERVAL_PART = String.raw`\d+(?:\.\d+)?\s+(?:microseconds?|milliseconds?|seconds?|minutes?|hours?|days?|weeks?|months?|years?)`;
|
|
997
|
+
var INTERVAL_PATTERN = new RegExp(`^${INTERVAL_PART}(?:\\s+${INTERVAL_PART})*$`, "i");
|
|
998
|
+
function isPlainRecord(value) {
|
|
999
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1000
|
+
const proto = Object.getPrototypeOf(value);
|
|
1001
|
+
return proto === Object.prototype || proto === null;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// src/snapshot.ts
|
|
1005
|
+
function emptySnapshot() {
|
|
1006
|
+
return {
|
|
1007
|
+
version: 1,
|
|
1008
|
+
functions: [],
|
|
1009
|
+
triggers: [],
|
|
1010
|
+
extensions: [],
|
|
1011
|
+
comments: [],
|
|
1012
|
+
partitionedTables: [],
|
|
1013
|
+
partitions: [],
|
|
1014
|
+
detaches: [],
|
|
1015
|
+
hypertables: [],
|
|
1016
|
+
inventory: { scanned: false, tables: [], enums: [], views: [], indexes: [], constraints: [] }
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
function functionSignature(schema, name, argTypes) {
|
|
1020
|
+
return JSON.stringify([schema, name, argTypes]);
|
|
1021
|
+
}
|
|
1022
|
+
function snapshotExtras(extras, options) {
|
|
1023
|
+
const casing = options?.casing;
|
|
1024
|
+
const cache = new CasingCache2(casing);
|
|
1025
|
+
const nameOf = (column) => cache.getColumnCasing(column);
|
|
1026
|
+
const functions = [];
|
|
1027
|
+
const fnByObject = /* @__PURE__ */ new Map();
|
|
1028
|
+
for (const fn of extras.functions) {
|
|
1029
|
+
const snap = snapshotFunction(fn, casing);
|
|
1030
|
+
pushFunction(functions, snap);
|
|
1031
|
+
fnByObject.set(fn, snap);
|
|
1032
|
+
}
|
|
1033
|
+
const triggers = [];
|
|
1034
|
+
const triggerByObject = /* @__PURE__ */ new Map();
|
|
1035
|
+
for (const trigger of extras.triggers) {
|
|
1036
|
+
const owned = ownedUpdatedAt(trigger, nameOf);
|
|
1037
|
+
if (owned) {
|
|
1038
|
+
const existing = functions.find((fn) => fn.id === owned.id);
|
|
1039
|
+
if (!existing) functions.push(owned);
|
|
1040
|
+
else if (!sameFunction(existing, owned)) {
|
|
1041
|
+
throw new PgExtrasError(
|
|
1042
|
+
`function ${existing.schema}.${existing.name} is generated twice with different bodies. Pass functionName to updatedAtTrigger() to keep them apart`
|
|
1043
|
+
);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
const snap = snapshotTrigger(trigger, casing, nameOf, fnByObject, owned);
|
|
1047
|
+
triggers.push(snap);
|
|
1048
|
+
triggerByObject.set(trigger, snap);
|
|
1049
|
+
}
|
|
1050
|
+
const extensions = [];
|
|
1051
|
+
for (const ext of extras.extensions) {
|
|
1052
|
+
if (extensions.some((item) => item.id === ext.name)) {
|
|
1053
|
+
throw new PgExtrasError(`extension "${ext.name}" is declared more than once`);
|
|
1054
|
+
}
|
|
1055
|
+
extensions.push({
|
|
1056
|
+
id: ext.name,
|
|
1057
|
+
name: ext.name,
|
|
1058
|
+
schema: ext.schema,
|
|
1059
|
+
version: ext.version,
|
|
1060
|
+
cascade: ext.cascade
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
const comments = [];
|
|
1064
|
+
const inventoryIndexes = [];
|
|
1065
|
+
const inventoryConstraints = [];
|
|
1066
|
+
for (const table of extras.tables) {
|
|
1067
|
+
const harvested = harvest(table, nameOf);
|
|
1068
|
+
if (harvested.table) pushComment(comments, harvested.table);
|
|
1069
|
+
for (const column of harvested.columns) pushComment(comments, column);
|
|
1070
|
+
const relations = harvestRelations(table, nameOf, casing);
|
|
1071
|
+
for (const comment of relations.comments) pushComment(comments, comment);
|
|
1072
|
+
inventoryIndexes.push(...relations.indexes);
|
|
1073
|
+
inventoryConstraints.push(...relations.constraints);
|
|
1074
|
+
}
|
|
1075
|
+
for (const fn of extras.functions) {
|
|
1076
|
+
const text = readComment(fn);
|
|
1077
|
+
const snap = fnByObject.get(fn);
|
|
1078
|
+
if (text && snap) pushComment(comments, functionComment(snap, text));
|
|
1079
|
+
}
|
|
1080
|
+
for (const trigger of extras.triggers) {
|
|
1081
|
+
const text = readComment(trigger);
|
|
1082
|
+
const snap = triggerByObject.get(trigger);
|
|
1083
|
+
if (text && snap) pushComment(comments, triggerComment(snap, text));
|
|
1084
|
+
}
|
|
1085
|
+
for (const ext of extras.extensions) {
|
|
1086
|
+
const text = readComment(ext);
|
|
1087
|
+
if (text) pushComment(comments, extensionComment(ext.name, text));
|
|
1088
|
+
}
|
|
1089
|
+
const enumObjects = enumObjectsIn(extras);
|
|
1090
|
+
for (const enumObject of enumObjects) {
|
|
1091
|
+
const text = readComment(enumObject);
|
|
1092
|
+
if (!text) continue;
|
|
1093
|
+
pushComment(comments, enumComment(enumIdentity(enumObject), text));
|
|
1094
|
+
}
|
|
1095
|
+
for (const view of extras.views) {
|
|
1096
|
+
for (const comment of harvestView(view, nameOf)) pushComment(comments, comment);
|
|
1097
|
+
}
|
|
1098
|
+
for (const comment of extras.comments) {
|
|
1099
|
+
pushComment(comments, snapshotComment(comment, nameOf, casing, fnByObject, triggerByObject, extras));
|
|
1100
|
+
}
|
|
1101
|
+
const inventoryTables = extras.tables.map((table) => {
|
|
1102
|
+
const identity = tableIdentity(table);
|
|
1103
|
+
return {
|
|
1104
|
+
schema: identity.schema,
|
|
1105
|
+
name: identity.name,
|
|
1106
|
+
columns: Object.values(getTableColumns2(table)).map((column) => nameOf(column)).sort()
|
|
1107
|
+
};
|
|
1108
|
+
});
|
|
1109
|
+
inventoryTables.sort((a, b) => `${a.schema}.${a.name}`.localeCompare(`${b.schema}.${b.name}`));
|
|
1110
|
+
const inventoryEnums = uniqueNames(enumObjects.map((enumObject) => enumIdentity(enumObject)));
|
|
1111
|
+
const inventoryViews = extras.views.map((view) => {
|
|
1112
|
+
const identity = viewIdentity(view);
|
|
1113
|
+
return {
|
|
1114
|
+
schema: identity.schema,
|
|
1115
|
+
name: identity.name,
|
|
1116
|
+
materialized: identity.materialized,
|
|
1117
|
+
columns: identity.columns.map((column) => nameOf(column)).sort()
|
|
1118
|
+
};
|
|
1119
|
+
});
|
|
1120
|
+
inventoryViews.sort((a, b) => `${a.schema}.${a.name}`.localeCompare(`${b.schema}.${b.name}`));
|
|
1121
|
+
inventoryIndexes.sort((a, b) => `${a.schema}.${a.table}.${a.name}`.localeCompare(`${b.schema}.${b.table}.${b.name}`));
|
|
1122
|
+
inventoryConstraints.sort((a, b) => `${a.schema}.${a.table}.${a.name}`.localeCompare(`${b.schema}.${b.table}.${b.name}`));
|
|
1123
|
+
const partitionedTables = snapshotPartitionedTables(extras, nameOf);
|
|
1124
|
+
const partitions = snapshotPartitions(extras, partitionedTables);
|
|
1125
|
+
const detaches = snapshotDetaches(extras, partitions);
|
|
1126
|
+
const hypertables = snapshotHypertables(extras, nameOf, partitionedTables, extensions);
|
|
1127
|
+
functions.sort((a, b) => a.id.localeCompare(b.id));
|
|
1128
|
+
triggers.sort((a, b) => a.id.localeCompare(b.id));
|
|
1129
|
+
extensions.sort((a, b) => a.id.localeCompare(b.id));
|
|
1130
|
+
comments.sort((a, b) => a.id.localeCompare(b.id));
|
|
1131
|
+
partitionedTables.sort((a, b) => a.id.localeCompare(b.id));
|
|
1132
|
+
partitions.sort((a, b) => a.id.localeCompare(b.id));
|
|
1133
|
+
detaches.sort((a, b) => a.id.localeCompare(b.id));
|
|
1134
|
+
hypertables.sort((a, b) => a.id.localeCompare(b.id));
|
|
1135
|
+
const triggerIds = /* @__PURE__ */ new Set();
|
|
1136
|
+
for (const trigger of triggers) {
|
|
1137
|
+
if (triggerIds.has(trigger.id)) {
|
|
1138
|
+
throw new PgExtrasError(`trigger "${trigger.name}" is declared more than once on ${trigger.schema}.${trigger.table}`);
|
|
1139
|
+
}
|
|
1140
|
+
triggerIds.add(trigger.id);
|
|
1141
|
+
}
|
|
1142
|
+
return {
|
|
1143
|
+
version: 1,
|
|
1144
|
+
functions,
|
|
1145
|
+
triggers,
|
|
1146
|
+
extensions,
|
|
1147
|
+
comments,
|
|
1148
|
+
partitionedTables,
|
|
1149
|
+
partitions,
|
|
1150
|
+
detaches,
|
|
1151
|
+
hypertables,
|
|
1152
|
+
inventory: {
|
|
1153
|
+
scanned: true,
|
|
1154
|
+
tables: inventoryTables,
|
|
1155
|
+
enums: inventoryEnums,
|
|
1156
|
+
views: inventoryViews,
|
|
1157
|
+
indexes: inventoryIndexes,
|
|
1158
|
+
constraints: inventoryConstraints
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
function pushFunction(functions, snap) {
|
|
1163
|
+
const existing = functions.find((fn) => fn.id === snap.id);
|
|
1164
|
+
if (!existing) {
|
|
1165
|
+
functions.push(snap);
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
if (!sameFunction(existing, snap)) {
|
|
1169
|
+
throw new PgExtrasError(`function ${snap.schema}.${snap.name}(${snap.args.map((arg) => arg.type).join(", ")}) is declared twice with different definitions`);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function pushComment(comments, snap) {
|
|
1173
|
+
const existing = comments.find((comment) => comment.id === snap.id);
|
|
1174
|
+
if (!existing) {
|
|
1175
|
+
comments.push(snap);
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (existing.text !== snap.text) {
|
|
1179
|
+
throw new PgExtrasError(`comment on ${commentLabel(snap)} is declared twice with different text`);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
function snapshotFunction(fn, casing) {
|
|
1183
|
+
const args = fn.args.map((arg) => ({
|
|
1184
|
+
name: arg.name ?? null,
|
|
1185
|
+
type: typeOf(arg.type),
|
|
1186
|
+
defaultExpr: arg.default ?? null
|
|
1187
|
+
}));
|
|
1188
|
+
const body = normalizeBody(fn.body, casing);
|
|
1189
|
+
return {
|
|
1190
|
+
id: functionSignature(fn.schema, fn.name, args.map((arg) => arg.type)),
|
|
1191
|
+
name: fn.name,
|
|
1192
|
+
schema: fn.schema,
|
|
1193
|
+
args,
|
|
1194
|
+
returns: typeOf(fn.returns),
|
|
1195
|
+
language: fn.language,
|
|
1196
|
+
body,
|
|
1197
|
+
volatility: fn.volatility,
|
|
1198
|
+
security: fn.security,
|
|
1199
|
+
searchPath: fn.searchPath ? [...fn.searchPath] : null,
|
|
1200
|
+
strict: fn.strict
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
function ownedUpdatedAt(trigger, nameOf) {
|
|
1204
|
+
if (!trigger.updatedAt) return null;
|
|
1205
|
+
const column = trigger.updatedAt.column;
|
|
1206
|
+
const dbName = nameOf(column);
|
|
1207
|
+
const schema = trigger.updatedAt.schema ?? "public";
|
|
1208
|
+
const name = trigger.updatedAt.functionName ?? `set_${dbName}`;
|
|
1209
|
+
assertIdentifier("function", name);
|
|
1210
|
+
assertIdentifier("function schema", schema);
|
|
1211
|
+
const body = `BEGIN
|
|
1212
|
+
NEW.${quoteIdent(dbName)} = now();
|
|
1213
|
+
RETURN NEW;
|
|
1214
|
+
END;`;
|
|
1215
|
+
return {
|
|
1216
|
+
id: functionSignature(schema, name, []),
|
|
1217
|
+
name,
|
|
1218
|
+
schema,
|
|
1219
|
+
args: [],
|
|
1220
|
+
returns: "trigger",
|
|
1221
|
+
language: "plpgsql",
|
|
1222
|
+
body,
|
|
1223
|
+
volatility: "volatile",
|
|
1224
|
+
security: "invoker",
|
|
1225
|
+
searchPath: null,
|
|
1226
|
+
strict: false
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
function snapshotTrigger(trigger, casing, nameOf, fnByObject, owned) {
|
|
1230
|
+
const identity = relationIdentity(trigger.table);
|
|
1231
|
+
const dbColumns = trigger.columns.map((column) => {
|
|
1232
|
+
if (typeof column === "string") return column;
|
|
1233
|
+
return nameOf(column);
|
|
1234
|
+
});
|
|
1235
|
+
const uniqueColumns = [...new Set(dbColumns)].sort();
|
|
1236
|
+
let functionSchema;
|
|
1237
|
+
let functionName;
|
|
1238
|
+
let functionId;
|
|
1239
|
+
if (owned) {
|
|
1240
|
+
functionSchema = owned.schema;
|
|
1241
|
+
functionName = owned.name;
|
|
1242
|
+
functionId = owned.id;
|
|
1243
|
+
} else if (trigger.function && extrasKind(trigger.function) === "function") {
|
|
1244
|
+
const snap = fnByObject.get(trigger.function) ?? snapshotFunction(trigger.function, casing);
|
|
1245
|
+
functionSchema = snap.schema;
|
|
1246
|
+
functionName = snap.name;
|
|
1247
|
+
functionId = snap.id;
|
|
1248
|
+
} else if (trigger.function && "name" in trigger.function) {
|
|
1249
|
+
functionName = trigger.function.name;
|
|
1250
|
+
functionSchema = trigger.function.schema ?? "public";
|
|
1251
|
+
assertIdentifier("function", functionName);
|
|
1252
|
+
assertIdentifier("function schema", functionSchema);
|
|
1253
|
+
functionId = null;
|
|
1254
|
+
} else {
|
|
1255
|
+
throw new PgExtrasError("trigger is missing a function");
|
|
1256
|
+
}
|
|
1257
|
+
const name = trigger.name ?? `${identity.name}_set_${uniqueColumns[0] ?? nameOf(trigger.updatedAt.column)}`;
|
|
1258
|
+
assertIdentifier("trigger", name);
|
|
1259
|
+
const when = renderTriggerWhen(trigger, casing);
|
|
1260
|
+
const from = trigger.from ? tableIdentity(trigger.from) : null;
|
|
1261
|
+
return {
|
|
1262
|
+
id: JSON.stringify(["trigger", identity.schema, identity.name, name]),
|
|
1263
|
+
name,
|
|
1264
|
+
schema: identity.schema,
|
|
1265
|
+
table: identity.name,
|
|
1266
|
+
timing: trigger.timing,
|
|
1267
|
+
events: [...trigger.events],
|
|
1268
|
+
forEach: trigger.forEach,
|
|
1269
|
+
columns: uniqueColumns,
|
|
1270
|
+
when,
|
|
1271
|
+
functionSchema,
|
|
1272
|
+
functionName,
|
|
1273
|
+
functionArgsSql: trigger.args.map((arg) => renderTriggerArg(arg, casing, nameOf)),
|
|
1274
|
+
functionId,
|
|
1275
|
+
constraint: trigger.constraint,
|
|
1276
|
+
deferrable: trigger.deferrable,
|
|
1277
|
+
initially: trigger.initially,
|
|
1278
|
+
fromSchema: from?.schema ?? null,
|
|
1279
|
+
fromTable: from?.name ?? null,
|
|
1280
|
+
oldTable: trigger.oldTable,
|
|
1281
|
+
newTable: trigger.newTable,
|
|
1282
|
+
enabled: trigger.enabled
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function renderTriggerArg(arg, casing, nameOf) {
|
|
1286
|
+
if (typeof arg === "string") return quoteLiteral(arg);
|
|
1287
|
+
if (typeof arg === "number") {
|
|
1288
|
+
if (!Number.isFinite(arg)) throw new PgExtrasError("trigger argument must be a finite number");
|
|
1289
|
+
return String(arg);
|
|
1290
|
+
}
|
|
1291
|
+
if (typeof arg === "boolean") return arg ? "TRUE" : "FALSE";
|
|
1292
|
+
if (isSqlFragment(arg)) {
|
|
1293
|
+
const text = renderSql(arg, casing).trim();
|
|
1294
|
+
if (text.includes(";")) throw new PgExtrasError('trigger argument SQL cannot contain ";"');
|
|
1295
|
+
return text;
|
|
1296
|
+
}
|
|
1297
|
+
if (typeof arg === "object" && arg && "getSQLType" in arg) {
|
|
1298
|
+
return quoteLiteral(nameOf(arg));
|
|
1299
|
+
}
|
|
1300
|
+
throw new PgExtrasError("trigger argument must be a string, number, boolean, column, or sql fragment");
|
|
1301
|
+
}
|
|
1302
|
+
function typeOf(type) {
|
|
1303
|
+
if (typeof type === "string") return normalizeType(type);
|
|
1304
|
+
return normalizeType(type.getSQLType());
|
|
1305
|
+
}
|
|
1306
|
+
function normalizeBody(body, casing) {
|
|
1307
|
+
const text = typeof body === "string" ? body : renderSql(body, casing);
|
|
1308
|
+
return text.replace(/^\n+/, "").replace(/\s+$/, "");
|
|
1309
|
+
}
|
|
1310
|
+
function harvest(table, nameOf) {
|
|
1311
|
+
const identity = tableIdentity(table);
|
|
1312
|
+
const columns = [];
|
|
1313
|
+
for (const column of Object.values(getTableColumns2(table))) {
|
|
1314
|
+
const text = readComment(column);
|
|
1315
|
+
if (!text) continue;
|
|
1316
|
+
columns.push(columnComment(identity.schema, identity.name, nameOf(column), text));
|
|
1317
|
+
}
|
|
1318
|
+
const tableText = readComment(table);
|
|
1319
|
+
return {
|
|
1320
|
+
table: tableText ? tableComment(identity.schema, identity.name, tableText) : null,
|
|
1321
|
+
columns
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
function snapshotComment(comment, nameOf, casing, fnByObject, triggerByObject, extras) {
|
|
1325
|
+
const target = comment.target;
|
|
1326
|
+
if (is3(target, PgTable2)) {
|
|
1327
|
+
const identity = tableIdentity(target);
|
|
1328
|
+
return tableComment(identity.schema, identity.name, comment.text);
|
|
1329
|
+
}
|
|
1330
|
+
if (is3(target, Column2)) {
|
|
1331
|
+
return columnCommentFrom(target, comment.text, nameOf, extras);
|
|
1332
|
+
}
|
|
1333
|
+
if (isPgEnum2(target)) {
|
|
1334
|
+
return enumComment(enumIdentity(target), comment.text);
|
|
1335
|
+
}
|
|
1336
|
+
if (isPgView2(target) || isPgMaterializedView2(target)) {
|
|
1337
|
+
const identity = viewIdentity(target);
|
|
1338
|
+
return viewComment(identity.schema, identity.name, identity.materialized, comment.text);
|
|
1339
|
+
}
|
|
1340
|
+
if (extrasKind(target) === "function") {
|
|
1341
|
+
const fn = target;
|
|
1342
|
+
const snap = fnByObject.get(fn) ?? snapshotFunction(fn, casing);
|
|
1343
|
+
return functionComment(snap, comment.text);
|
|
1344
|
+
}
|
|
1345
|
+
if (extrasKind(target) === "trigger") {
|
|
1346
|
+
const trigger = target;
|
|
1347
|
+
const snap = triggerByObject.get(trigger) ?? snapshotTrigger(trigger, casing, nameOf, fnByObject, ownedUpdatedAt(trigger, nameOf));
|
|
1348
|
+
return triggerComment(snap, comment.text);
|
|
1349
|
+
}
|
|
1350
|
+
if (extrasKind(target) === "extension") {
|
|
1351
|
+
return extensionComment(target.name, comment.text);
|
|
1352
|
+
}
|
|
1353
|
+
throw new PgExtrasError("commentOn() takes a table, column, enum, view, function, trigger, or extension");
|
|
1354
|
+
}
|
|
1355
|
+
function sameFunction(a, b) {
|
|
1356
|
+
return JSON.stringify(fnShape(a)) === JSON.stringify(fnShape(b));
|
|
1357
|
+
}
|
|
1358
|
+
function fnShape(fn) {
|
|
1359
|
+
return {
|
|
1360
|
+
name: fn.name,
|
|
1361
|
+
schema: fn.schema,
|
|
1362
|
+
args: fn.args,
|
|
1363
|
+
returns: fn.returns,
|
|
1364
|
+
language: fn.language,
|
|
1365
|
+
body: fn.body,
|
|
1366
|
+
volatility: fn.volatility,
|
|
1367
|
+
security: fn.security,
|
|
1368
|
+
searchPath: fn.searchPath,
|
|
1369
|
+
strict: fn.strict
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
function sameTriggerShape(a, b) {
|
|
1373
|
+
return JSON.stringify(triggerShape(a, false)) === JSON.stringify(triggerShape(b, false));
|
|
1374
|
+
}
|
|
1375
|
+
function triggerShape(trigger, includeEnabled) {
|
|
1376
|
+
return {
|
|
1377
|
+
name: trigger.name,
|
|
1378
|
+
schema: trigger.schema,
|
|
1379
|
+
table: trigger.table,
|
|
1380
|
+
timing: trigger.timing,
|
|
1381
|
+
events: trigger.events,
|
|
1382
|
+
forEach: trigger.forEach,
|
|
1383
|
+
columns: trigger.columns,
|
|
1384
|
+
when: trigger.when,
|
|
1385
|
+
functionSchema: trigger.functionSchema,
|
|
1386
|
+
functionName: trigger.functionName,
|
|
1387
|
+
functionArgsSql: trigger.functionArgsSql,
|
|
1388
|
+
functionId: trigger.functionId,
|
|
1389
|
+
constraint: trigger.constraint,
|
|
1390
|
+
deferrable: trigger.deferrable,
|
|
1391
|
+
initially: trigger.initially,
|
|
1392
|
+
fromSchema: trigger.fromSchema,
|
|
1393
|
+
fromTable: trigger.fromTable,
|
|
1394
|
+
oldTable: trigger.oldTable,
|
|
1395
|
+
newTable: trigger.newTable,
|
|
1396
|
+
enabled: includeEnabled ? trigger.enabled : true
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
function normalizeTrigger(value) {
|
|
1400
|
+
if (!value || typeof value !== "object") throw new PgExtrasError("pg extras snapshot trigger is not an object");
|
|
1401
|
+
const raw = value;
|
|
1402
|
+
if (typeof raw.name !== "string" || typeof raw.schema !== "string") {
|
|
1403
|
+
throw new PgExtrasError("pg extras snapshot trigger is missing a name");
|
|
1404
|
+
}
|
|
1405
|
+
const timing = raw.timing === "before" || raw.timing === "after" || raw.timing === "instead of" ? raw.timing : "after";
|
|
1406
|
+
const forEach = raw.forEach === "statement" ? "statement" : "row";
|
|
1407
|
+
const initially = raw.initially === "deferred" ? "deferred" : "immediate";
|
|
1408
|
+
const events = Array.isArray(raw.events) ? raw.events.filter(
|
|
1409
|
+
(event) => event === "insert" || event === "update" || event === "delete" || event === "truncate"
|
|
1410
|
+
) : [];
|
|
1411
|
+
const table = typeof raw.table === "string" ? raw.table : "";
|
|
1412
|
+
return {
|
|
1413
|
+
id: typeof raw.id === "string" ? raw.id : JSON.stringify(["trigger", raw.schema, table, raw.name]),
|
|
1414
|
+
name: raw.name,
|
|
1415
|
+
schema: raw.schema,
|
|
1416
|
+
table,
|
|
1417
|
+
timing,
|
|
1418
|
+
events,
|
|
1419
|
+
forEach,
|
|
1420
|
+
columns: Array.isArray(raw.columns) ? raw.columns.filter((column) => typeof column === "string") : [],
|
|
1421
|
+
when: typeof raw.when === "string" ? raw.when : null,
|
|
1422
|
+
functionSchema: typeof raw.functionSchema === "string" ? raw.functionSchema : "public",
|
|
1423
|
+
functionName: typeof raw.functionName === "string" ? raw.functionName : "",
|
|
1424
|
+
functionArgsSql: Array.isArray(raw.functionArgsSql) ? raw.functionArgsSql.filter((arg) => typeof arg === "string") : [],
|
|
1425
|
+
functionId: typeof raw.functionId === "string" ? raw.functionId : null,
|
|
1426
|
+
constraint: raw.constraint === true,
|
|
1427
|
+
deferrable: raw.deferrable === true,
|
|
1428
|
+
initially,
|
|
1429
|
+
fromSchema: typeof raw.fromSchema === "string" ? raw.fromSchema : null,
|
|
1430
|
+
fromTable: typeof raw.fromTable === "string" ? raw.fromTable : null,
|
|
1431
|
+
oldTable: typeof raw.oldTable === "string" ? raw.oldTable : null,
|
|
1432
|
+
newTable: typeof raw.newTable === "string" ? raw.newTable : null,
|
|
1433
|
+
enabled: raw.enabled === false ? false : true
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
function parseSnapshot(value) {
|
|
1437
|
+
if (!value || typeof value !== "object") throw new PgExtrasError("pg extras snapshot is not an object");
|
|
1438
|
+
const record = value;
|
|
1439
|
+
if (record.version !== 1) throw new PgExtrasError(`pg extras snapshot version ${String(record.version)} is not supported`);
|
|
1440
|
+
const comments = Array.isArray(record.comments) ? record.comments.map((comment) => normalizeComment(comment)) : [];
|
|
1441
|
+
return {
|
|
1442
|
+
version: 1,
|
|
1443
|
+
functions: record.functions ?? [],
|
|
1444
|
+
triggers: Array.isArray(record.triggers) ? record.triggers.map((trigger) => normalizeTrigger(trigger)) : [],
|
|
1445
|
+
extensions: record.extensions ?? [],
|
|
1446
|
+
comments,
|
|
1447
|
+
partitionedTables: record.partitionedTables ?? [],
|
|
1448
|
+
partitions: record.partitions ?? [],
|
|
1449
|
+
detaches: record.detaches ?? [],
|
|
1450
|
+
hypertables: record.hypertables ?? [],
|
|
1451
|
+
inventory: normalizeInventory(record.inventory)
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
var COMMENT_KINDS = /* @__PURE__ */ new Set([
|
|
1455
|
+
"table",
|
|
1456
|
+
"column",
|
|
1457
|
+
"enum",
|
|
1458
|
+
"view",
|
|
1459
|
+
"materializedView",
|
|
1460
|
+
"function",
|
|
1461
|
+
"trigger",
|
|
1462
|
+
"index",
|
|
1463
|
+
"constraint",
|
|
1464
|
+
"extension"
|
|
1465
|
+
]);
|
|
1466
|
+
function normalizeComment(value) {
|
|
1467
|
+
if (!value || typeof value !== "object") throw new PgExtrasError("pg extras snapshot comment is not an object");
|
|
1468
|
+
const raw = value;
|
|
1469
|
+
if (typeof raw.kind !== "string" || !COMMENT_KINDS.has(raw.kind)) {
|
|
1470
|
+
throw new PgExtrasError(`pg extras snapshot has an unknown comment kind ${String(raw.kind)}`);
|
|
1471
|
+
}
|
|
1472
|
+
const kind = raw.kind;
|
|
1473
|
+
const schema = typeof raw.schema === "string" ? raw.schema : "public";
|
|
1474
|
+
const column = typeof raw.column === "string" ? raw.column : null;
|
|
1475
|
+
const legacyRelation = typeof raw.table === "string" ? raw.table : null;
|
|
1476
|
+
const relation2 = typeof raw.relation === "string" ? raw.relation : legacyRelation;
|
|
1477
|
+
const name = typeof raw.name === "string" ? raw.name : kind === "column" ? column ?? "" : legacyRelation ?? "";
|
|
1478
|
+
if (name.length === 0) throw new PgExtrasError("pg extras snapshot comment is missing a name");
|
|
1479
|
+
if (typeof raw.text !== "string") throw new PgExtrasError("pg extras snapshot comment is missing text");
|
|
1480
|
+
const argTypes = Array.isArray(raw.argTypes) ? raw.argTypes.filter((item) => typeof item === "string") : [];
|
|
1481
|
+
const id = typeof raw.id === "string" ? raw.id : JSON.stringify([kind, schema, relation2, name]);
|
|
1482
|
+
return { id, kind, schema, name, relation: relation2, column, argTypes, text: raw.text };
|
|
1483
|
+
}
|
|
1484
|
+
function normalizeInventory(value) {
|
|
1485
|
+
const empty = emptySnapshot().inventory;
|
|
1486
|
+
if (!value || typeof value !== "object") return empty;
|
|
1487
|
+
const raw = value;
|
|
1488
|
+
return {
|
|
1489
|
+
scanned: raw.scanned === true,
|
|
1490
|
+
tables: Array.isArray(raw.tables) ? raw.tables : [],
|
|
1491
|
+
enums: Array.isArray(raw.enums) ? raw.enums : [],
|
|
1492
|
+
views: Array.isArray(raw.views) ? raw.views : [],
|
|
1493
|
+
indexes: Array.isArray(raw.indexes) ? raw.indexes : [],
|
|
1494
|
+
constraints: Array.isArray(raw.constraints) ? raw.constraints : []
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1497
|
+
function tableComment(schema, table, text) {
|
|
1498
|
+
return {
|
|
1499
|
+
id: JSON.stringify(["table", schema, table, null]),
|
|
1500
|
+
kind: "table",
|
|
1501
|
+
schema,
|
|
1502
|
+
name: table,
|
|
1503
|
+
relation: table,
|
|
1504
|
+
column: null,
|
|
1505
|
+
argTypes: [],
|
|
1506
|
+
text
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
function columnComment(schema, relation2, column, text) {
|
|
1510
|
+
return {
|
|
1511
|
+
id: JSON.stringify(["column", schema, relation2, column]),
|
|
1512
|
+
kind: "column",
|
|
1513
|
+
schema,
|
|
1514
|
+
name: column,
|
|
1515
|
+
relation: relation2,
|
|
1516
|
+
column,
|
|
1517
|
+
argTypes: [],
|
|
1518
|
+
text
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
function enumComment(identity, text) {
|
|
1522
|
+
return {
|
|
1523
|
+
id: JSON.stringify(["enum", identity.schema, identity.name]),
|
|
1524
|
+
kind: "enum",
|
|
1525
|
+
schema: identity.schema,
|
|
1526
|
+
name: identity.name,
|
|
1527
|
+
relation: null,
|
|
1528
|
+
column: null,
|
|
1529
|
+
argTypes: [],
|
|
1530
|
+
text
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
function viewComment(schema, name, materialized, text) {
|
|
1534
|
+
const kind = materialized ? "materializedView" : "view";
|
|
1535
|
+
return {
|
|
1536
|
+
id: JSON.stringify([kind, schema, name]),
|
|
1537
|
+
kind,
|
|
1538
|
+
schema,
|
|
1539
|
+
name,
|
|
1540
|
+
relation: null,
|
|
1541
|
+
column: null,
|
|
1542
|
+
argTypes: [],
|
|
1543
|
+
text
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
function functionComment(fn, text) {
|
|
1547
|
+
const argTypes = fn.args.map((arg) => arg.type);
|
|
1548
|
+
return {
|
|
1549
|
+
id: JSON.stringify(["function", fn.schema, fn.name, argTypes]),
|
|
1550
|
+
kind: "function",
|
|
1551
|
+
schema: fn.schema,
|
|
1552
|
+
name: fn.name,
|
|
1553
|
+
relation: null,
|
|
1554
|
+
column: null,
|
|
1555
|
+
argTypes,
|
|
1556
|
+
text
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1559
|
+
function triggerComment(trigger, text) {
|
|
1560
|
+
return {
|
|
1561
|
+
id: trigger.id,
|
|
1562
|
+
kind: "trigger",
|
|
1563
|
+
schema: trigger.schema,
|
|
1564
|
+
name: trigger.name,
|
|
1565
|
+
relation: trigger.table,
|
|
1566
|
+
column: null,
|
|
1567
|
+
argTypes: [],
|
|
1568
|
+
text
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
function extensionComment(name, text) {
|
|
1572
|
+
return {
|
|
1573
|
+
id: JSON.stringify(["extension", name]),
|
|
1574
|
+
kind: "extension",
|
|
1575
|
+
schema: "public",
|
|
1576
|
+
name,
|
|
1577
|
+
relation: null,
|
|
1578
|
+
column: null,
|
|
1579
|
+
argTypes: [],
|
|
1580
|
+
text
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
function indexComment(schema, name, text) {
|
|
1584
|
+
return {
|
|
1585
|
+
id: JSON.stringify(["index", schema, name]),
|
|
1586
|
+
kind: "index",
|
|
1587
|
+
schema,
|
|
1588
|
+
name,
|
|
1589
|
+
relation: null,
|
|
1590
|
+
column: null,
|
|
1591
|
+
argTypes: [],
|
|
1592
|
+
text
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
function constraintComment(schema, table, name, text) {
|
|
1596
|
+
return {
|
|
1597
|
+
id: JSON.stringify(["constraint", schema, table, name]),
|
|
1598
|
+
kind: "constraint",
|
|
1599
|
+
schema,
|
|
1600
|
+
name,
|
|
1601
|
+
relation: table,
|
|
1602
|
+
column: null,
|
|
1603
|
+
argTypes: [],
|
|
1604
|
+
text
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
function commentLabel(comment) {
|
|
1608
|
+
if (comment.kind === "column") return `${comment.schema}.${comment.relation}.${comment.column}`;
|
|
1609
|
+
if (comment.kind === "function") return `function ${comment.schema}.${comment.name}(${comment.argTypes.join(", ")})`;
|
|
1610
|
+
if (comment.kind === "trigger" || comment.kind === "constraint") {
|
|
1611
|
+
return `${comment.kind} ${comment.name} on ${comment.schema}.${comment.relation}`;
|
|
1612
|
+
}
|
|
1613
|
+
if (comment.kind === "extension") return `extension ${comment.name}`;
|
|
1614
|
+
return `${comment.kind} ${comment.schema}.${comment.name}`;
|
|
1615
|
+
}
|
|
1616
|
+
function columnCommentFrom(column, text, nameOf, extras) {
|
|
1617
|
+
if (!column.table || !is3(column.table, PgTable2)) {
|
|
1618
|
+
throw new PgExtrasError(`commentOn() column "${column.name}" is not attached to a Postgres table or view`);
|
|
1619
|
+
}
|
|
1620
|
+
const identity = tableIdentity(column.table);
|
|
1621
|
+
const dbName = nameOf(column);
|
|
1622
|
+
const knownTable = extras.tables.find((table) => {
|
|
1623
|
+
const id = tableIdentity(table);
|
|
1624
|
+
return id.schema === identity.schema && id.name === identity.name;
|
|
1625
|
+
});
|
|
1626
|
+
if (knownTable) {
|
|
1627
|
+
assertColumnOfTable(knownTable, column);
|
|
1628
|
+
return columnComment(identity.schema, identity.name, dbName, text);
|
|
1629
|
+
}
|
|
1630
|
+
const view = extras.views.find((item) => viewIdentity(item).name === identity.name);
|
|
1631
|
+
if (view) {
|
|
1632
|
+
const viewId = viewIdentity(view);
|
|
1633
|
+
return columnComment(viewId.schema, viewId.name, dbName, text);
|
|
1634
|
+
}
|
|
1635
|
+
assertColumnOfTable(column.table, column);
|
|
1636
|
+
return columnComment(identity.schema, identity.name, dbName, text);
|
|
1637
|
+
}
|
|
1638
|
+
var ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder");
|
|
1639
|
+
var ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns");
|
|
1640
|
+
function readExtraConfig(table) {
|
|
1641
|
+
const builder = table[ExtraConfigBuilder];
|
|
1642
|
+
if (typeof builder !== "function") return [];
|
|
1643
|
+
const columns = table[ExtraConfigColumns];
|
|
1644
|
+
const extra = builder(columns);
|
|
1645
|
+
if (!extra || typeof extra !== "object") return [];
|
|
1646
|
+
return Array.isArray(extra) ? extra.flat(1) : Object.values(extra);
|
|
1647
|
+
}
|
|
1648
|
+
function harvestRelations(table, nameOf, casing) {
|
|
1649
|
+
const identity = tableIdentity(table);
|
|
1650
|
+
const comments = [];
|
|
1651
|
+
const indexes = [];
|
|
1652
|
+
const constraints = [];
|
|
1653
|
+
for (const value of readExtraConfig(table)) {
|
|
1654
|
+
if (extrasKind(value) === "comment") {
|
|
1655
|
+
throw new PgExtrasError(
|
|
1656
|
+
"Return the index or constraint from the table extra config wrapped with withComment(). commentOn() is for tables, columns, enums, views, functions, triggers, and extensions."
|
|
1657
|
+
);
|
|
1658
|
+
}
|
|
1659
|
+
if (is3(value, IndexBuilder2)) {
|
|
1660
|
+
const built = value.build(table);
|
|
1661
|
+
const text = readComment(value);
|
|
1662
|
+
let name;
|
|
1663
|
+
try {
|
|
1664
|
+
name = resolveIndexName(built, identity.name, casing);
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
if (text) throw error;
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
indexes.push({ schema: identity.schema, table: identity.name, name });
|
|
1670
|
+
if (text) comments.push(indexComment(identity.schema, name, text));
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
if (is3(value, CheckBuilder2)) {
|
|
1674
|
+
const name = value.name;
|
|
1675
|
+
constraints.push({ schema: identity.schema, table: identity.name, name });
|
|
1676
|
+
const text = readComment(value);
|
|
1677
|
+
if (text) comments.push(constraintComment(identity.schema, identity.name, name, text));
|
|
1678
|
+
continue;
|
|
1679
|
+
}
|
|
1680
|
+
if (is3(value, UniqueConstraintBuilder2)) {
|
|
1681
|
+
const built = buildOf(value, table);
|
|
1682
|
+
const name = constraintName(built);
|
|
1683
|
+
constraints.push({ schema: identity.schema, table: identity.name, name });
|
|
1684
|
+
const text = readComment(value);
|
|
1685
|
+
if (text) comments.push(constraintComment(identity.schema, identity.name, name, text));
|
|
1686
|
+
continue;
|
|
1687
|
+
}
|
|
1688
|
+
if (is3(value, ForeignKeyBuilder2)) {
|
|
1689
|
+
const built = buildOf(value, table);
|
|
1690
|
+
const name = applyCasing(built.getName(), [...built.reference().columns, ...built.reference().foreignColumns], nameOf, casing);
|
|
1691
|
+
constraints.push({ schema: identity.schema, table: identity.name, name });
|
|
1692
|
+
const text = readComment(value);
|
|
1693
|
+
if (text) comments.push(constraintComment(identity.schema, identity.name, name, text));
|
|
1694
|
+
continue;
|
|
1695
|
+
}
|
|
1696
|
+
if (is3(value, PrimaryKeyBuilder2)) {
|
|
1697
|
+
const built = buildOf(value, table);
|
|
1698
|
+
const name = applyCasing(built.getName(), built.columns, nameOf, casing);
|
|
1699
|
+
constraints.push({ schema: identity.schema, table: identity.name, name });
|
|
1700
|
+
const text = readComment(value);
|
|
1701
|
+
if (text) comments.push(constraintComment(identity.schema, identity.name, name, text));
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
return { comments, indexes, constraints };
|
|
1705
|
+
}
|
|
1706
|
+
function buildOf(builder, table) {
|
|
1707
|
+
return builder.build(table);
|
|
1708
|
+
}
|
|
1709
|
+
function constraintName(constraint) {
|
|
1710
|
+
const name = constraint.name ?? constraint.getName();
|
|
1711
|
+
if (!name) throw new PgExtrasError("constraint comment needs a constraint name");
|
|
1712
|
+
return name;
|
|
1713
|
+
}
|
|
1714
|
+
function applyCasing(name, columns, nameOf, casing) {
|
|
1715
|
+
if (!casing) return name;
|
|
1716
|
+
let result = name;
|
|
1717
|
+
for (const column of columns) {
|
|
1718
|
+
const cased = nameOf(column);
|
|
1719
|
+
if (column.name !== cased) result = result.replace(column.name, cased);
|
|
1720
|
+
}
|
|
1721
|
+
return result;
|
|
1722
|
+
}
|
|
1723
|
+
function resolveIndexName(index, tableName, casing) {
|
|
1724
|
+
if (index.config.name && index.config.name.length > 0) return index.config.name;
|
|
1725
|
+
const columns = [];
|
|
1726
|
+
for (const column of index.config.columns) {
|
|
1727
|
+
if (is3(column, SQL2)) {
|
|
1728
|
+
throw new PgExtrasError(
|
|
1729
|
+
`index comment on "${tableName}" needs an index name. Drizzle names indexes made of columns only; name an index whose key is a SQL expression.`
|
|
1730
|
+
);
|
|
1731
|
+
}
|
|
1732
|
+
const indexed = column;
|
|
1733
|
+
if (!indexed.name) {
|
|
1734
|
+
throw new PgExtrasError(`index comment on "${tableName}" needs an index name`);
|
|
1735
|
+
}
|
|
1736
|
+
columns.push(casedIndexColumn(indexed.name, Boolean(indexed.keyAsName), casing));
|
|
1737
|
+
}
|
|
1738
|
+
return `${tableName}_${columns.join("_")}_index`;
|
|
1739
|
+
}
|
|
1740
|
+
function casedIndexColumn(name, keyAsName, casing) {
|
|
1741
|
+
if (!keyAsName || !casing) return name;
|
|
1742
|
+
return casing === "camelCase" ? toCamelCase(name) : toSnakeCase(name);
|
|
1743
|
+
}
|
|
1744
|
+
function harvestView(view, nameOf) {
|
|
1745
|
+
const identity = viewIdentity(view);
|
|
1746
|
+
const comments = [];
|
|
1747
|
+
const text = readComment(view);
|
|
1748
|
+
if (text) comments.push(viewComment(identity.schema, identity.name, identity.materialized, text));
|
|
1749
|
+
for (const column of identity.columns) {
|
|
1750
|
+
const columnText = readComment(column);
|
|
1751
|
+
if (!columnText) continue;
|
|
1752
|
+
comments.push(columnComment(identity.schema, identity.name, nameOf(column), columnText));
|
|
1753
|
+
}
|
|
1754
|
+
return comments;
|
|
1755
|
+
}
|
|
1756
|
+
function viewIdentity(view) {
|
|
1757
|
+
const materialized = isPgMaterializedView2(view);
|
|
1758
|
+
const config = materialized ? getMaterializedViewConfig2(view) : getViewConfig2(view);
|
|
1759
|
+
const columns = [];
|
|
1760
|
+
for (const field of Object.values(config.selectedFields ?? {})) {
|
|
1761
|
+
if (is3(field, Column2)) columns.push(field);
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
schema: config.schema && config.schema.length > 0 ? config.schema : "public",
|
|
1765
|
+
name: config.name,
|
|
1766
|
+
materialized,
|
|
1767
|
+
columns
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
function enumObjectsIn(extras) {
|
|
1771
|
+
const found = [];
|
|
1772
|
+
const add = (value) => {
|
|
1773
|
+
if (!isPgEnum2(value) || found.includes(value)) return;
|
|
1774
|
+
found.push(value);
|
|
1775
|
+
};
|
|
1776
|
+
for (const enumObject of extras.enums) add(enumObject);
|
|
1777
|
+
for (const comment of extras.comments) add(comment.target);
|
|
1778
|
+
for (const table of extras.tables) {
|
|
1779
|
+
for (const column of Object.values(getTableColumns2(table))) add(enumFromColumn(column));
|
|
1780
|
+
}
|
|
1781
|
+
for (const view of extras.views) {
|
|
1782
|
+
for (const column of viewIdentity(view).columns) add(enumFromColumn(column));
|
|
1783
|
+
}
|
|
1784
|
+
return found;
|
|
1785
|
+
}
|
|
1786
|
+
function enumFromColumn(column) {
|
|
1787
|
+
let current = column;
|
|
1788
|
+
while (is3(current, PgArray)) current = current.baseColumn;
|
|
1789
|
+
if (is3(current, PgEnumColumn) || is3(current, PgEnumObjectColumn)) return current.enum;
|
|
1790
|
+
return null;
|
|
1791
|
+
}
|
|
1792
|
+
function enumIdentity(value) {
|
|
1793
|
+
const enumObject = value;
|
|
1794
|
+
if (!enumObject.enumName) throw new PgExtrasError("enum comment is missing an enum name");
|
|
1795
|
+
return {
|
|
1796
|
+
schema: enumObject.schema && enumObject.schema.length > 0 ? enumObject.schema : "public",
|
|
1797
|
+
name: enumObject.enumName
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
function uniqueNames(items) {
|
|
1801
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1802
|
+
const names = [];
|
|
1803
|
+
for (const item of items) {
|
|
1804
|
+
const key = `${item.schema}.${item.name}`;
|
|
1805
|
+
if (seen.has(key)) continue;
|
|
1806
|
+
seen.add(key);
|
|
1807
|
+
names.push({ schema: item.schema, name: item.name });
|
|
1808
|
+
}
|
|
1809
|
+
names.sort((a, b) => `${a.schema}.${a.name}`.localeCompare(`${b.schema}.${b.name}`));
|
|
1810
|
+
return names;
|
|
1811
|
+
}
|
|
1812
|
+
function snapshotHypertables(extras, nameOf, parents, extensions) {
|
|
1813
|
+
const hypertables = [];
|
|
1814
|
+
for (const hypertable of extras.hypertables) {
|
|
1815
|
+
const snap = snapshotHypertable(hypertable, nameOf);
|
|
1816
|
+
if (hypertables.some((item) => item.id === snap.id)) {
|
|
1817
|
+
throw new PgExtrasError(`hypertable ${snap.schema}.${snap.name} is declared more than once`);
|
|
1818
|
+
}
|
|
1819
|
+
if (parents.some((item) => item.schema === snap.schema && item.name === snap.name)) {
|
|
1820
|
+
throw new PgExtrasError(`${snap.schema}.${snap.name} cannot be both a partitioned table and a hypertable`);
|
|
1821
|
+
}
|
|
1822
|
+
hypertables.push(snap);
|
|
1823
|
+
}
|
|
1824
|
+
if (hypertables.length > 0 && !extensions.some((ext) => ext.name === "timescaledb")) {
|
|
1825
|
+
const names = hypertables.map((item) => `${item.schema}.${item.name}`).join(", ");
|
|
1826
|
+
throw new PgExtrasError(
|
|
1827
|
+
`hypertable() requires pgExtension("timescaledb") in the schema (${names}). Declare the extension and export it. generate writes CREATE EXTENSION before create_hypertable.`
|
|
1828
|
+
);
|
|
1829
|
+
}
|
|
1830
|
+
return hypertables;
|
|
1831
|
+
}
|
|
1832
|
+
function snapshotHypertable(hypertable, nameOf) {
|
|
1833
|
+
const identity = tableIdentity(hypertable.table);
|
|
1834
|
+
const columnName = (column) => typeof column === "string" ? column : nameOf(column);
|
|
1835
|
+
return {
|
|
1836
|
+
id: JSON.stringify(["hypertable", identity.schema, identity.name]),
|
|
1837
|
+
schema: identity.schema,
|
|
1838
|
+
name: identity.name,
|
|
1839
|
+
timeColumn: columnName(hypertable.timeColumn),
|
|
1840
|
+
chunkTimeInterval: hypertable.chunkTimeInterval,
|
|
1841
|
+
partitioningColumn: hypertable.partitioningColumn ? columnName(hypertable.partitioningColumn) : null,
|
|
1842
|
+
numberPartitions: hypertable.numberPartitions,
|
|
1843
|
+
migrateData: hypertable.migrateData,
|
|
1844
|
+
compression: hypertable.compression ? {
|
|
1845
|
+
segmentBy: hypertable.compression.segmentBy.map(columnName),
|
|
1846
|
+
orderBy: hypertable.compression.orderBy.map((order) => ({
|
|
1847
|
+
column: columnName(order.column),
|
|
1848
|
+
direction: order.direction,
|
|
1849
|
+
nulls: order.nulls
|
|
1850
|
+
}))
|
|
1851
|
+
} : null,
|
|
1852
|
+
retention: hypertable.retention ? { ...hypertable.retention } : null,
|
|
1853
|
+
compressionPolicy: hypertable.compressionPolicy ? { ...hypertable.compressionPolicy } : null
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
function snapshotPartitionedTables(extras, nameOf) {
|
|
1857
|
+
const tables = [];
|
|
1858
|
+
for (const table of extras.partitionedTables) {
|
|
1859
|
+
const identity = tableIdentity(table.table);
|
|
1860
|
+
const columns = table.columns.map((column) => typeof column === "string" ? column : nameOf(column));
|
|
1861
|
+
const snap = {
|
|
1862
|
+
id: JSON.stringify(["partitioned", identity.schema, identity.name]),
|
|
1863
|
+
schema: identity.schema,
|
|
1864
|
+
name: identity.name,
|
|
1865
|
+
method: table.method,
|
|
1866
|
+
columns
|
|
1867
|
+
};
|
|
1868
|
+
if (tables.some((item) => item.id === snap.id)) {
|
|
1869
|
+
throw new PgExtrasError(`partitioned table ${identity.schema}.${identity.name} is declared more than once`);
|
|
1870
|
+
}
|
|
1871
|
+
tables.push(snap);
|
|
1872
|
+
}
|
|
1873
|
+
return tables;
|
|
1874
|
+
}
|
|
1875
|
+
function snapshotPartitions(extras, parents) {
|
|
1876
|
+
const partitions = [];
|
|
1877
|
+
const childIds = /* @__PURE__ */ new Set();
|
|
1878
|
+
const defaults = /* @__PURE__ */ new Set();
|
|
1879
|
+
const hashSlots = /* @__PURE__ */ new Set();
|
|
1880
|
+
for (const partition of extras.partitions) {
|
|
1881
|
+
const parent = parentIdentity(partition);
|
|
1882
|
+
const declared = parents.find((item) => item.schema === parent.schema && item.name === parent.name);
|
|
1883
|
+
if (!declared) {
|
|
1884
|
+
throw new PgExtrasError(
|
|
1885
|
+
`partition "${partition.name}" refers to ${parent.schema}.${parent.name}, which has no partitionedTable(). Declare the parent as well`
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
assertBoundMatches(partition, declared);
|
|
1889
|
+
const schema = partition.schema ?? declared.schema;
|
|
1890
|
+
const snap = {
|
|
1891
|
+
id: JSON.stringify(["partition", declared.schema, declared.name, schema, partition.name]),
|
|
1892
|
+
schema,
|
|
1893
|
+
name: partition.name,
|
|
1894
|
+
parentSchema: declared.schema,
|
|
1895
|
+
parentName: declared.name,
|
|
1896
|
+
mode: partition.mode,
|
|
1897
|
+
onRemove: partition.onRemove,
|
|
1898
|
+
boundKind: partition.bound.kind,
|
|
1899
|
+
boundSql: boundSqlOf(partition, declared.columns.length)
|
|
1900
|
+
};
|
|
1901
|
+
if (partitions.some((item) => item.id === snap.id)) {
|
|
1902
|
+
throw new PgExtrasError(`partition ${schema}.${partition.name} of ${declared.schema}.${declared.name} is declared more than once`);
|
|
1903
|
+
}
|
|
1904
|
+
const childId = JSON.stringify([schema, partition.name]);
|
|
1905
|
+
if (childIds.has(childId)) {
|
|
1906
|
+
throw new PgExtrasError(`table ${schema}.${partition.name} is declared as a partition more than once`);
|
|
1907
|
+
}
|
|
1908
|
+
childIds.add(childId);
|
|
1909
|
+
if (partition.bound.kind === "default") {
|
|
1910
|
+
const parentId = JSON.stringify([declared.schema, declared.name]);
|
|
1911
|
+
if (defaults.has(parentId)) {
|
|
1912
|
+
throw new PgExtrasError(`partitioned table ${declared.schema}.${declared.name} has more than one DEFAULT partition`);
|
|
1913
|
+
}
|
|
1914
|
+
defaults.add(parentId);
|
|
1915
|
+
}
|
|
1916
|
+
if (partition.bound.kind === "hash") {
|
|
1917
|
+
const slot = JSON.stringify([declared.schema, declared.name, partition.bound.modulus, partition.bound.remainder]);
|
|
1918
|
+
if (hashSlots.has(slot)) {
|
|
1919
|
+
throw new PgExtrasError(
|
|
1920
|
+
`partition ${schema}.${partition.name} repeats modulus ${partition.bound.modulus} remainder ${partition.bound.remainder}`
|
|
1921
|
+
);
|
|
1922
|
+
}
|
|
1923
|
+
hashSlots.add(slot);
|
|
1924
|
+
}
|
|
1925
|
+
partitions.push(snap);
|
|
1926
|
+
}
|
|
1927
|
+
return partitions;
|
|
1928
|
+
}
|
|
1929
|
+
function snapshotDetaches(extras, partitions) {
|
|
1930
|
+
const detaches = [];
|
|
1931
|
+
for (const detach of extras.detaches) {
|
|
1932
|
+
const child = tableIdentity(detach.table);
|
|
1933
|
+
const parent = parentIdentity(detach);
|
|
1934
|
+
const snap = {
|
|
1935
|
+
id: JSON.stringify(["detach", parent.schema, parent.name, child.schema, child.name]),
|
|
1936
|
+
schema: child.schema,
|
|
1937
|
+
name: child.name,
|
|
1938
|
+
parentSchema: parent.schema,
|
|
1939
|
+
parentName: parent.name
|
|
1940
|
+
};
|
|
1941
|
+
if (detaches.some((item) => item.id === snap.id)) {
|
|
1942
|
+
throw new PgExtrasError(`detach of ${child.schema}.${child.name} from ${parent.schema}.${parent.name} is declared more than once`);
|
|
1943
|
+
}
|
|
1944
|
+
if (partitions.some((item) => item.schema === child.schema && item.name === child.name && item.parentSchema === parent.schema && item.parentName === parent.name)) {
|
|
1945
|
+
throw new PgExtrasError(
|
|
1946
|
+
`${child.schema}.${child.name} is both attached to and detached from ${parent.schema}.${parent.name}`
|
|
1947
|
+
);
|
|
1948
|
+
}
|
|
1949
|
+
detaches.push(snap);
|
|
1950
|
+
}
|
|
1951
|
+
return detaches;
|
|
1952
|
+
}
|
|
1953
|
+
function parentIdentity(value) {
|
|
1954
|
+
const parent = value.parent;
|
|
1955
|
+
if (extrasKind(parent) === "partitionedTable") return tableIdentity(parent.table);
|
|
1956
|
+
return tableIdentity(parent);
|
|
1957
|
+
}
|
|
1958
|
+
function assertBoundMatches(partition, parent) {
|
|
1959
|
+
const label = `partition "${partition.schema ?? parent.schema}.${partition.name}"`;
|
|
1960
|
+
const kind = partition.bound.kind;
|
|
1961
|
+
if (parent.method === "hash" && kind === "default") {
|
|
1962
|
+
throw new PgExtrasError(`${label}: a hash-partitioned table cannot have a DEFAULT partition`);
|
|
1963
|
+
}
|
|
1964
|
+
if (parent.method === "range" && kind !== "range" && kind !== "default") {
|
|
1965
|
+
throw new PgExtrasError(`${label}: ${parent.schema}.${parent.name} is partitioned by range, so use from/to or default`);
|
|
1966
|
+
}
|
|
1967
|
+
if (parent.method === "list" && kind !== "list" && kind !== "default") {
|
|
1968
|
+
throw new PgExtrasError(`${label}: ${parent.schema}.${parent.name} is partitioned by list, so use in or default`);
|
|
1969
|
+
}
|
|
1970
|
+
if (parent.method === "hash" && kind !== "hash") {
|
|
1971
|
+
throw new PgExtrasError(`${label}: ${parent.schema}.${parent.name} is partitioned by hash, so use modulus and remainder`);
|
|
1972
|
+
}
|
|
1973
|
+
if (kind === "range" && partition.bound.kind === "range" && partition.bound.from.length !== parent.columns.length) {
|
|
1974
|
+
throw new PgExtrasError(
|
|
1975
|
+
`${label}: from and to need ${parent.columns.length} bound(s) for (${parent.columns.join(", ")})`
|
|
1976
|
+
);
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
function boundSqlOf(partition, keyCount) {
|
|
1980
|
+
const label = `partition "${partition.name}"`;
|
|
1981
|
+
const bound = partition.bound;
|
|
1982
|
+
if (bound.kind === "default") return "DEFAULT";
|
|
1983
|
+
if (bound.kind === "range") {
|
|
1984
|
+
return `FOR VALUES FROM (${bound.from.map((value) => renderPartitionBound(value, "from")).join(", ")}) TO (${bound.to.map((value) => renderPartitionBound(value, "to")).join(", ")})`;
|
|
1985
|
+
}
|
|
1986
|
+
if (bound.kind === "list") {
|
|
1987
|
+
const values = bound.values.map((value) => {
|
|
1988
|
+
if (isBoundTuple(value)) {
|
|
1989
|
+
if (value.length !== keyCount) {
|
|
1990
|
+
throw new PgExtrasError(`${label}: each IN value needs ${keyCount} item(s), one per partition column`);
|
|
1991
|
+
}
|
|
1992
|
+
return `(${value.map((item) => renderPartitionBound(item, "list")).join(", ")})`;
|
|
1993
|
+
}
|
|
1994
|
+
if (keyCount !== 1) {
|
|
1995
|
+
throw new PgExtrasError(`${label}: a ${keyCount}-column list partition needs tuples, such as in: [["a", 1]]`);
|
|
1996
|
+
}
|
|
1997
|
+
return renderPartitionBound(value, "list");
|
|
1998
|
+
});
|
|
1999
|
+
return `FOR VALUES IN (${values.join(", ")})`;
|
|
2000
|
+
}
|
|
2001
|
+
return `FOR VALUES WITH (MODULUS ${bound.modulus}, REMAINDER ${bound.remainder})`;
|
|
2002
|
+
}
|
|
2003
|
+
function isBoundTuple(value) {
|
|
2004
|
+
return Array.isArray(value);
|
|
2005
|
+
}
|
|
2006
|
+
function renderPartitionBound(value, side) {
|
|
2007
|
+
if (value === "MINVALUE") {
|
|
2008
|
+
if (side !== "from") throw new PgExtrasError('MINVALUE is only valid in a range partition "from" bound');
|
|
2009
|
+
return "MINVALUE";
|
|
2010
|
+
}
|
|
2011
|
+
if (value === "MAXVALUE") {
|
|
2012
|
+
if (side !== "to") throw new PgExtrasError('MAXVALUE is only valid in a range partition "to" bound');
|
|
2013
|
+
return "MAXVALUE";
|
|
2014
|
+
}
|
|
2015
|
+
if (typeof value === "string") return quoteLiteral(value);
|
|
2016
|
+
if (typeof value === "number") {
|
|
2017
|
+
if (!Number.isFinite(value)) throw new PgExtrasError("partition bound must be a finite number");
|
|
2018
|
+
return String(value);
|
|
2019
|
+
}
|
|
2020
|
+
if (typeof value === "bigint") return value.toString();
|
|
2021
|
+
if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
|
|
2022
|
+
if (value === null) return "NULL";
|
|
2023
|
+
throw new PgExtrasError("partition bound must be a string, number, boolean, null, bigint, MINVALUE, or MAXVALUE");
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
// src/statements.ts
|
|
2027
|
+
function createFunctionSql(fn) {
|
|
2028
|
+
const args = fn.args.map((arg) => {
|
|
2029
|
+
const name = arg.name ? `${quoteIdent(arg.name)} ` : "";
|
|
2030
|
+
const def = arg.defaultExpr !== null ? ` DEFAULT ${arg.defaultExpr}` : "";
|
|
2031
|
+
return `${name}${arg.type}${def}`;
|
|
2032
|
+
}).join(", ");
|
|
2033
|
+
const lines = [
|
|
2034
|
+
`CREATE OR REPLACE FUNCTION ${qualify(fn.schema, fn.name)}(${args})`,
|
|
2035
|
+
`RETURNS ${fn.returns}`,
|
|
2036
|
+
`LANGUAGE ${fn.language}`,
|
|
2037
|
+
fn.volatility.toUpperCase()
|
|
2038
|
+
];
|
|
2039
|
+
if (fn.strict) lines.push("STRICT");
|
|
2040
|
+
lines.push(fn.security === "definer" ? "SECURITY DEFINER" : "SECURITY INVOKER");
|
|
2041
|
+
if (fn.searchPath) lines.push(searchPathSql(fn.searchPath));
|
|
2042
|
+
lines.push(`AS ${dollarQuote(fn.body)};`);
|
|
2043
|
+
return lines.join("\n");
|
|
2044
|
+
}
|
|
2045
|
+
function dropFunctionSql(fn) {
|
|
2046
|
+
const types = fn.args.map((arg) => arg.type).join(", ");
|
|
2047
|
+
return `DROP FUNCTION IF EXISTS ${qualify(fn.schema, fn.name)}(${types});`;
|
|
2048
|
+
}
|
|
2049
|
+
function createTriggerSql(trigger) {
|
|
2050
|
+
const timing = trigger.timing === "instead of" ? "INSTEAD OF" : trigger.timing.toUpperCase();
|
|
2051
|
+
const events = trigger.events.map((event) => {
|
|
2052
|
+
if (event === "update" && trigger.columns.length > 0) {
|
|
2053
|
+
return `UPDATE OF ${trigger.columns.map((column) => quoteIdent(column)).join(", ")}`;
|
|
2054
|
+
}
|
|
2055
|
+
return event.toUpperCase();
|
|
2056
|
+
}).join(" OR ");
|
|
2057
|
+
const lines = [
|
|
2058
|
+
`${trigger.constraint ? "CREATE CONSTRAINT TRIGGER" : "CREATE OR REPLACE TRIGGER"} ${quoteIdent(trigger.name)}`,
|
|
2059
|
+
`${timing} ${events} ON ${qualify(trigger.schema, trigger.table)}`
|
|
2060
|
+
];
|
|
2061
|
+
if (trigger.constraint && trigger.fromSchema && trigger.fromTable) {
|
|
2062
|
+
lines.push(`FROM ${qualify(trigger.fromSchema, trigger.fromTable)}`);
|
|
2063
|
+
}
|
|
2064
|
+
if (trigger.constraint) {
|
|
2065
|
+
lines.push(
|
|
2066
|
+
trigger.deferrable ? `DEFERRABLE INITIALLY ${trigger.initially === "deferred" ? "DEFERRED" : "IMMEDIATE"}` : "NOT DEFERRABLE"
|
|
2067
|
+
);
|
|
2068
|
+
}
|
|
2069
|
+
const referencing = [];
|
|
2070
|
+
if (trigger.oldTable) referencing.push(`OLD TABLE AS ${quoteIdent(trigger.oldTable)}`);
|
|
2071
|
+
if (trigger.newTable) referencing.push(`NEW TABLE AS ${quoteIdent(trigger.newTable)}`);
|
|
2072
|
+
if (referencing.length > 0) lines.push(`REFERENCING ${referencing.join(" ")}`);
|
|
2073
|
+
lines.push(`FOR EACH ${trigger.forEach.toUpperCase()}`);
|
|
2074
|
+
if (trigger.when) lines.push(`WHEN (${trigger.when})`);
|
|
2075
|
+
const args = trigger.functionArgsSql.join(", ");
|
|
2076
|
+
lines.push(`EXECUTE FUNCTION ${qualify(trigger.functionSchema, trigger.functionName)}(${args});`);
|
|
2077
|
+
return lines.join("\n");
|
|
2078
|
+
}
|
|
2079
|
+
function dropTriggerSql(trigger) {
|
|
2080
|
+
return `DROP TRIGGER IF EXISTS ${quoteIdent(trigger.name)} ON ${qualify(trigger.schema, trigger.table)};`;
|
|
2081
|
+
}
|
|
2082
|
+
function alterTriggerEnabledSql(trigger) {
|
|
2083
|
+
const action = trigger.enabled === false ? "DISABLE" : "ENABLE";
|
|
2084
|
+
return `ALTER TABLE ${qualify(trigger.schema, trigger.table)} ${action} TRIGGER ${quoteIdent(trigger.name)};`;
|
|
2085
|
+
}
|
|
2086
|
+
function createExtensionSql(ext) {
|
|
2087
|
+
let statement = `CREATE EXTENSION IF NOT EXISTS ${quoteIdent(ext.name)}`;
|
|
2088
|
+
const options = [];
|
|
2089
|
+
if (ext.schema) options.push(`SCHEMA ${quoteIdent(ext.schema)}`);
|
|
2090
|
+
if (ext.version) options.push(`VERSION ${quoteLiteral(ext.version)}`);
|
|
2091
|
+
if (options.length > 0) statement += ` WITH ${options.join(" ")}`;
|
|
2092
|
+
if (ext.cascade) statement += " CASCADE";
|
|
2093
|
+
return `${statement};`;
|
|
2094
|
+
}
|
|
2095
|
+
function dropExtensionSql(ext) {
|
|
2096
|
+
return `DROP EXTENSION IF EXISTS ${quoteIdent(ext.name)}${ext.cascade ? " CASCADE" : ""};`;
|
|
2097
|
+
}
|
|
2098
|
+
function commentSql(comment, text) {
|
|
2099
|
+
const relation2 = comment.relation ?? comment.name;
|
|
2100
|
+
let target;
|
|
2101
|
+
switch (comment.kind) {
|
|
2102
|
+
case "table":
|
|
2103
|
+
target = `TABLE ${qualify(comment.schema, comment.name)}`;
|
|
2104
|
+
break;
|
|
2105
|
+
case "column":
|
|
2106
|
+
target = `COLUMN ${qualify(comment.schema, relation2)}.${quoteIdent(comment.column ?? comment.name)}`;
|
|
2107
|
+
break;
|
|
2108
|
+
case "enum":
|
|
2109
|
+
target = `TYPE ${qualify(comment.schema, comment.name)}`;
|
|
2110
|
+
break;
|
|
2111
|
+
case "view":
|
|
2112
|
+
target = `VIEW ${qualify(comment.schema, comment.name)}`;
|
|
2113
|
+
break;
|
|
2114
|
+
case "materializedView":
|
|
2115
|
+
target = `MATERIALIZED VIEW ${qualify(comment.schema, comment.name)}`;
|
|
2116
|
+
break;
|
|
2117
|
+
case "function":
|
|
2118
|
+
target = `FUNCTION ${qualify(comment.schema, comment.name)}(${(comment.argTypes ?? []).join(", ")})`;
|
|
2119
|
+
break;
|
|
2120
|
+
case "trigger":
|
|
2121
|
+
target = `TRIGGER ${quoteIdent(comment.name)} ON ${qualify(comment.schema, relation2)}`;
|
|
2122
|
+
break;
|
|
2123
|
+
case "index":
|
|
2124
|
+
target = `INDEX ${qualify(comment.schema, comment.name)}`;
|
|
2125
|
+
break;
|
|
2126
|
+
case "constraint":
|
|
2127
|
+
target = `CONSTRAINT ${quoteIdent(comment.name)} ON ${qualify(comment.schema, relation2)}`;
|
|
2128
|
+
break;
|
|
2129
|
+
case "extension":
|
|
2130
|
+
target = `EXTENSION ${quoteIdent(comment.name)}`;
|
|
2131
|
+
break;
|
|
2132
|
+
default: {
|
|
2133
|
+
const unknown = comment.kind;
|
|
2134
|
+
throw new PgExtrasError(`unknown comment kind ${String(unknown)}`);
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
return `COMMENT ON ${target} IS ${text === null ? "NULL" : quoteLiteral(text)};`;
|
|
2138
|
+
}
|
|
2139
|
+
function searchPathSql(paths) {
|
|
2140
|
+
if (paths.length === 0) return "SET search_path TO ''";
|
|
2141
|
+
return `SET search_path TO ${paths.map((entry2) => quoteLiteral(entry2)).join(", ")}`;
|
|
2142
|
+
}
|
|
2143
|
+
|
|
2144
|
+
// src/diff.ts
|
|
2145
|
+
function diffSnapshots(from, to) {
|
|
2146
|
+
return {
|
|
2147
|
+
up: statementsBetween(from, to, true),
|
|
2148
|
+
down: statementsBetween(to, from, false)
|
|
2149
|
+
};
|
|
2150
|
+
}
|
|
2151
|
+
function statementsBetween(from, to, skipDroppedTables) {
|
|
2152
|
+
const fromFns = new Map(from.functions.map((fn) => [fn.id, fn]));
|
|
2153
|
+
const toFns = new Map(to.functions.map((fn) => [fn.id, fn]));
|
|
2154
|
+
const fromTriggers = new Map(from.triggers.map((trigger) => [trigger.id, trigger]));
|
|
2155
|
+
const toTriggers = new Map(to.triggers.map((trigger) => [trigger.id, trigger]));
|
|
2156
|
+
const fromExt = new Map(from.extensions.map((ext) => [ext.id, ext]));
|
|
2157
|
+
const toExt = new Map(to.extensions.map((ext) => [ext.id, ext]));
|
|
2158
|
+
const fromComments = new Map(from.comments.map((comment) => [comment.id, comment]));
|
|
2159
|
+
const toComments = new Map(to.comments.map((comment) => [comment.id, comment]));
|
|
2160
|
+
const dropFnIds = /* @__PURE__ */ new Set();
|
|
2161
|
+
for (const [id, fn] of fromFns) {
|
|
2162
|
+
const next = toFns.get(id);
|
|
2163
|
+
if (!next || next.returns !== fn.returns) dropFnIds.add(id);
|
|
2164
|
+
}
|
|
2165
|
+
const triggersToDrop = [];
|
|
2166
|
+
for (const trigger of from.triggers) {
|
|
2167
|
+
const next = toTriggers.get(trigger.id);
|
|
2168
|
+
const fnDropped = trigger.functionId !== null && dropFnIds.has(trigger.functionId);
|
|
2169
|
+
const constraintReplace = !!next && (trigger.constraint || next.constraint) && !sameTriggerShape(trigger, next);
|
|
2170
|
+
const removed = !next;
|
|
2171
|
+
if ((removed || fnDropped || constraintReplace) && !(skipDroppedTables && removed && tableGone(from, to, trigger.schema, trigger.table))) {
|
|
2172
|
+
triggersToDrop.push(trigger);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
triggersToDrop.sort((a, b) => a.id.localeCompare(b.id));
|
|
2176
|
+
const droppedTriggerIds = new Set(triggersToDrop.map((trigger) => trigger.id));
|
|
2177
|
+
const statements = [];
|
|
2178
|
+
for (const trigger of triggersToDrop) statements.push(dropTriggerSql(trigger));
|
|
2179
|
+
statements.push(...partitionChanges(from, to, skipDroppedTables));
|
|
2180
|
+
const fnIds = [...dropFnIds].sort();
|
|
2181
|
+
for (const id of fnIds) statements.push(dropFunctionSql(fromFns.get(id)));
|
|
2182
|
+
for (const ext of [...to.extensions].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
2183
|
+
const prev = fromExt.get(ext.id);
|
|
2184
|
+
if (!prev) {
|
|
2185
|
+
statements.push(createExtensionSql(ext));
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
if (ext.schema && prev.schema !== ext.schema) {
|
|
2189
|
+
statements.push(`ALTER EXTENSION ${quoteIdent(ext.name)} SET SCHEMA ${quoteIdent(ext.schema)};`);
|
|
2190
|
+
}
|
|
2191
|
+
if (ext.version && prev.version !== ext.version) {
|
|
2192
|
+
statements.push(`ALTER EXTENSION ${quoteIdent(ext.name)} UPDATE TO ${quoteLiteral(ext.version)};`);
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
statements.push(...hypertableChanges(from, to, skipDroppedTables));
|
|
2196
|
+
const fnsToWrite = to.functions.filter((fn) => {
|
|
2197
|
+
const prev = fromFns.get(fn.id);
|
|
2198
|
+
return !prev || !sameFunction(prev, fn);
|
|
2199
|
+
});
|
|
2200
|
+
const needsBodyOff = fnsToWrite.some((fn) => fn.language === "sql");
|
|
2201
|
+
if (needsBodyOff) statements.push("SET check_function_bodies = off");
|
|
2202
|
+
for (const fn of fnsToWrite) statements.push(createFunctionSql(fn));
|
|
2203
|
+
if (needsBodyOff) statements.push("SET check_function_bodies = on");
|
|
2204
|
+
emitComments(statements, from, to, fromComments, toComments, dropFnIds, toFns, droppedTriggerIds, toTriggers, toExt, skipDroppedTables, "other");
|
|
2205
|
+
for (const trigger of to.triggers) {
|
|
2206
|
+
const prev = fromTriggers.get(trigger.id);
|
|
2207
|
+
const dropped = droppedTriggerIds.has(trigger.id);
|
|
2208
|
+
const shapeChanged = !prev || !sameTriggerShape(prev, trigger);
|
|
2209
|
+
if (shapeChanged || dropped) {
|
|
2210
|
+
pushTriggerBody(statements, trigger, trigger.constraint === true && !dropped);
|
|
2211
|
+
continue;
|
|
2212
|
+
}
|
|
2213
|
+
if (prev.enabled !== trigger.enabled) statements.push(alterTriggerEnabledSql(trigger));
|
|
2214
|
+
}
|
|
2215
|
+
emitComments(statements, from, to, fromComments, toComments, dropFnIds, toFns, droppedTriggerIds, toTriggers, toExt, skipDroppedTables, "trigger");
|
|
2216
|
+
for (const ext of [...from.extensions].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
2217
|
+
if (!toExt.has(ext.id)) {
|
|
2218
|
+
if (ext.name === "timescaledb" && !skipDroppedTables && from.hypertables.length > 0) continue;
|
|
2219
|
+
statements.push(dropExtensionSql(ext));
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
return statements;
|
|
2223
|
+
}
|
|
2224
|
+
function pushTriggerBody(statements, trigger, dropFirst) {
|
|
2225
|
+
if (dropFirst) statements.push(dropTriggerSql(trigger));
|
|
2226
|
+
statements.push(createTriggerSql(trigger));
|
|
2227
|
+
if (trigger.enabled === false) statements.push(alterTriggerEnabledSql(trigger));
|
|
2228
|
+
}
|
|
2229
|
+
function emitComments(statements, from, to, fromComments, toComments, dropFnIds, toFns, droppedTriggerIds, toTriggers, toExt, skipDroppedTables, mode) {
|
|
2230
|
+
const ids = [.../* @__PURE__ */ new Set([...fromComments.keys(), ...toComments.keys()])].sort();
|
|
2231
|
+
for (const id of ids) {
|
|
2232
|
+
const prev = fromComments.get(id);
|
|
2233
|
+
const next = toComments.get(id);
|
|
2234
|
+
const subject = next ?? prev;
|
|
2235
|
+
if (!subject) continue;
|
|
2236
|
+
if (mode === "trigger" ? subject.kind !== "trigger" : subject.kind === "trigger") continue;
|
|
2237
|
+
if (prev && next && prev.text === next.text && !commentRewritten(next, dropFnIds, toFns, droppedTriggerIds, toTriggers)) {
|
|
2238
|
+
continue;
|
|
2239
|
+
}
|
|
2240
|
+
if (!next && prev) {
|
|
2241
|
+
if (skipCommentNull(prev, to, toFns, toTriggers, toExt, skipDroppedTables, from)) continue;
|
|
2242
|
+
statements.push(commentSql(prev, null));
|
|
2243
|
+
continue;
|
|
2244
|
+
}
|
|
2245
|
+
if (next) statements.push(commentSql(next, next.text));
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
function commentRewritten(comment, dropFnIds, toFns, droppedTriggerIds, toTriggers) {
|
|
2249
|
+
if (comment.kind === "function") {
|
|
2250
|
+
const id = functionSignature(comment.schema, comment.name, comment.argTypes ?? []);
|
|
2251
|
+
return dropFnIds.has(id) && toFns.has(id);
|
|
2252
|
+
}
|
|
2253
|
+
if (comment.kind === "trigger") return droppedTriggerIds.has(comment.id) && toTriggers.has(comment.id);
|
|
2254
|
+
return false;
|
|
2255
|
+
}
|
|
2256
|
+
function skipCommentNull(comment, to, toFns, toTriggers, toExt, skipDroppedTables, from) {
|
|
2257
|
+
if (comment.kind === "function") return !toFns.has(functionSignature(comment.schema, comment.name, comment.argTypes ?? []));
|
|
2258
|
+
if (comment.kind === "trigger") return !toTriggers.has(comment.id);
|
|
2259
|
+
if (comment.kind === "extension") return !toExt.has(comment.name);
|
|
2260
|
+
return skipDroppedTables && targetGone(from, to, comment);
|
|
2261
|
+
}
|
|
2262
|
+
function hypertableChanges(from, to, forward) {
|
|
2263
|
+
const statements = [];
|
|
2264
|
+
const fromTables = new Map(from.hypertables.map((item) => [item.id, item]));
|
|
2265
|
+
const toTables = new Map(to.hypertables.map((item) => [item.id, item]));
|
|
2266
|
+
for (const prev of from.hypertables) {
|
|
2267
|
+
if (toTables.has(prev.id)) continue;
|
|
2268
|
+
if (forward && tableGone(from, to, prev.schema, prev.name)) continue;
|
|
2269
|
+
if (forward) {
|
|
2270
|
+
throw new PgExtrasError(
|
|
2271
|
+
`hypertable ${prev.schema}.${prev.name} was removed from the schema. This package will not convert a hypertable back into a regular table. Keep hypertable(), or remove the Drizzle table in the same change so drizzle-kit drops it.`
|
|
2272
|
+
);
|
|
2273
|
+
}
|
|
2274
|
+
statements.push(...undoHypertable(prev));
|
|
2275
|
+
}
|
|
2276
|
+
for (const next of to.hypertables) {
|
|
2277
|
+
const prev = fromTables.get(next.id);
|
|
2278
|
+
if (!prev) {
|
|
2279
|
+
statements.push(...createHypertableStatements(next));
|
|
2280
|
+
continue;
|
|
2281
|
+
}
|
|
2282
|
+
statements.push(...alterHypertable(prev, next, forward));
|
|
2283
|
+
}
|
|
2284
|
+
return statements;
|
|
2285
|
+
}
|
|
2286
|
+
function undoHypertable(ht) {
|
|
2287
|
+
const statements = [];
|
|
2288
|
+
if (ht.compressionPolicy) statements.push(removeCompressionPolicySql(ht));
|
|
2289
|
+
if (ht.retention) statements.push(removeRetentionPolicySql(ht));
|
|
2290
|
+
if (ht.compression) statements.push(disableHypertableCompressionSql(ht));
|
|
2291
|
+
statements.push(leaveHypertableSql(ht));
|
|
2292
|
+
return statements;
|
|
2293
|
+
}
|
|
2294
|
+
function alterHypertable(prev, next, forward) {
|
|
2295
|
+
if (prev.timeColumn !== next.timeColumn) {
|
|
2296
|
+
throw new PgExtrasError(
|
|
2297
|
+
`hypertable ${next.schema}.${next.name} time column changed from "${prev.timeColumn}" to "${next.timeColumn}". The time column cannot be changed in place.`
|
|
2298
|
+
);
|
|
2299
|
+
}
|
|
2300
|
+
const statements = [];
|
|
2301
|
+
if (prev.partitioningColumn !== next.partitioningColumn || prev.numberPartitions !== next.numberPartitions) {
|
|
2302
|
+
if (prev.partitioningColumn === null && next.partitioningColumn !== null) {
|
|
2303
|
+
statements.push(addHypertableDimensionSql(next));
|
|
2304
|
+
} else if (!forward && next.partitioningColumn === null) {
|
|
2305
|
+
statements.push(leaveHypertableDimensionSql(prev));
|
|
2306
|
+
} else {
|
|
2307
|
+
throw new PgExtrasError(
|
|
2308
|
+
`hypertable ${next.schema}.${next.name} space partition changed from ${describeSpace(prev)} to ${describeSpace(next)}. create_hypertable does not alter an existing hash dimension. Keep partitioningColumn and numberPartitions.`
|
|
2309
|
+
);
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
if (prev.chunkTimeInterval !== next.chunkTimeInterval) {
|
|
2313
|
+
if (next.chunkTimeInterval === null) {
|
|
2314
|
+
if (forward) {
|
|
2315
|
+
throw new PgExtrasError(
|
|
2316
|
+
`hypertable ${next.schema}.${next.name}: clearing chunkTimeInterval is not supported. Set a new interval instead of removing it.`
|
|
2317
|
+
);
|
|
2318
|
+
}
|
|
2319
|
+
statements.push(leaveChunkIntervalSql(prev));
|
|
2320
|
+
} else {
|
|
2321
|
+
statements.push(setChunkTimeIntervalSql(next));
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
const compressionChanged = JSON.stringify(prev.compression) !== JSON.stringify(next.compression);
|
|
2325
|
+
const compressionPolicyChanged = JSON.stringify(prev.compressionPolicy) !== JSON.stringify(next.compressionPolicy);
|
|
2326
|
+
const retentionChanged = JSON.stringify(prev.retention) !== JSON.stringify(next.retention);
|
|
2327
|
+
if (compressionPolicyChanged && prev.compressionPolicy) statements.push(removeCompressionPolicySql(prev));
|
|
2328
|
+
if (compressionChanged) {
|
|
2329
|
+
if (next.compression) statements.push(enableHypertableCompressionSql(next, next.compression, prev.compression));
|
|
2330
|
+
else statements.push(disableHypertableCompressionSql(next));
|
|
2331
|
+
}
|
|
2332
|
+
if (compressionPolicyChanged && next.compressionPolicy) statements.push(addCompressionPolicySql(next));
|
|
2333
|
+
if (retentionChanged && prev.retention) statements.push(removeRetentionPolicySql(prev));
|
|
2334
|
+
if (retentionChanged && next.retention) statements.push(addRetentionPolicySql(next));
|
|
2335
|
+
return statements;
|
|
2336
|
+
}
|
|
2337
|
+
function describeSpace(ht) {
|
|
2338
|
+
if (!ht.partitioningColumn) return "none";
|
|
2339
|
+
return `${ht.partitioningColumn} (${ht.numberPartitions})`;
|
|
2340
|
+
}
|
|
2341
|
+
function partitionChanges(from, to, skipDroppedTables) {
|
|
2342
|
+
const statements = [];
|
|
2343
|
+
const handled = /* @__PURE__ */ new Set();
|
|
2344
|
+
const fromParents = new Map(from.partitionedTables.map((item) => [item.id, item]));
|
|
2345
|
+
const toParents = new Map(to.partitionedTables.map((item) => [item.id, item]));
|
|
2346
|
+
const fromPartitions = new Map(from.partitions.map((item) => [item.id, item]));
|
|
2347
|
+
const toPartitions = new Map(to.partitions.map((item) => [item.id, item]));
|
|
2348
|
+
const fromDetaches = new Set(from.detaches.map((item) => item.id));
|
|
2349
|
+
for (const partition of from.partitions) {
|
|
2350
|
+
if (toPartitions.has(partition.id)) continue;
|
|
2351
|
+
if (skipDroppedTables && (tableGone(from, to, partition.parentSchema, partition.parentName) || tableGone(from, to, partition.schema, partition.name))) {
|
|
2352
|
+
continue;
|
|
2353
|
+
}
|
|
2354
|
+
if (partition.mode === "attach" || partition.onRemove === "detach") statements.push(detachPartitionSql(partition));
|
|
2355
|
+
else statements.push(dropPartitionSql(partition));
|
|
2356
|
+
handled.add(childKey(partition.schema, partition.name, partition.parentSchema, partition.parentName));
|
|
2357
|
+
}
|
|
2358
|
+
for (const parent of from.partitionedTables) {
|
|
2359
|
+
if (toParents.has(parent.id)) continue;
|
|
2360
|
+
if (skipDroppedTables && tableGone(from, to, parent.schema, parent.name)) continue;
|
|
2361
|
+
statements.push(convertPartitionedTableSql(parent, "unpartition"));
|
|
2362
|
+
}
|
|
2363
|
+
for (const parent of to.partitionedTables) {
|
|
2364
|
+
const previous = fromParents.get(parent.id);
|
|
2365
|
+
if (!previous) {
|
|
2366
|
+
statements.push(convertPartitionedTableSql(parent, "partition"));
|
|
2367
|
+
continue;
|
|
2368
|
+
}
|
|
2369
|
+
if (previous.method !== parent.method || previous.columns.join("\0") !== parent.columns.join("\0")) {
|
|
2370
|
+
throw new PgExtrasError(
|
|
2371
|
+
`partitioned table ${parent.schema}.${parent.name} changed from ${describeKey(previous)} to ${describeKey(parent)}. Postgres cannot change a partition key in place. Keep the original partitionedTable() and move the data in a custom migration if you need a different key.`
|
|
2372
|
+
);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
for (const partition of to.partitions) {
|
|
2376
|
+
const previous = fromPartitions.get(partition.id);
|
|
2377
|
+
if (!previous) {
|
|
2378
|
+
statements.push(partition.mode === "attach" ? attachPartitionSql(partition) : createPartitionSql(partition));
|
|
2379
|
+
continue;
|
|
2380
|
+
}
|
|
2381
|
+
if (previous.mode !== partition.mode || previous.boundSql !== partition.boundSql || previous.boundKind !== partition.boundKind) {
|
|
2382
|
+
throw new PgExtrasError(
|
|
2383
|
+
`partition ${partition.schema}.${partition.name} of ${partition.parentSchema}.${partition.parentName} changed (${previous.mode} ${previous.boundSql} -> ${partition.mode} ${partition.boundSql}). Postgres cannot alter partition bounds in place, and this package will not detach and recreate a partition because that drops rows. Move the rows in a custom migration.`
|
|
2384
|
+
);
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
for (const detach of to.detaches) {
|
|
2388
|
+
if (fromDetaches.has(detach.id)) continue;
|
|
2389
|
+
if (handled.has(childKey(detach.schema, detach.name, detach.parentSchema, detach.parentName))) continue;
|
|
2390
|
+
if (skipDroppedTables && (tableGone(from, to, detach.parentSchema, detach.parentName) || tableGone(from, to, detach.schema, detach.name))) {
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
statements.push(detachPartitionSql(detach));
|
|
2394
|
+
}
|
|
2395
|
+
return statements;
|
|
2396
|
+
}
|
|
2397
|
+
function childKey(schema, name, parentSchema, parentName) {
|
|
2398
|
+
return JSON.stringify([schema, name, parentSchema, parentName]);
|
|
2399
|
+
}
|
|
2400
|
+
function describeKey(parent) {
|
|
2401
|
+
return `${parent.method.toUpperCase()} (${parent.columns.join(", ")})`;
|
|
2402
|
+
}
|
|
2403
|
+
function tableGone(from, to, schema, table) {
|
|
2404
|
+
if (!from.inventory.scanned || !to.inventory.scanned) return false;
|
|
2405
|
+
const had = from.inventory.tables.some((item) => item.schema === schema && item.name === table);
|
|
2406
|
+
const has = to.inventory.tables.some((item) => item.schema === schema && item.name === table);
|
|
2407
|
+
return had && !has;
|
|
2408
|
+
}
|
|
2409
|
+
function targetGone(from, to, comment) {
|
|
2410
|
+
if (!from.inventory.scanned || !to.inventory.scanned) return false;
|
|
2411
|
+
const relation2 = comment.relation ?? comment.name;
|
|
2412
|
+
if (comment.kind === "table" || comment.kind === "column") {
|
|
2413
|
+
if (tableGone(from, to, comment.schema, relation2)) return true;
|
|
2414
|
+
if (comment.kind !== "column" || !comment.column) return false;
|
|
2415
|
+
const prev = from.inventory.tables.find((item) => item.schema === comment.schema && item.name === relation2);
|
|
2416
|
+
const next = to.inventory.tables.find((item) => item.schema === comment.schema && item.name === relation2);
|
|
2417
|
+
if (prev && next) return prev.columns.includes(comment.column) && !next.columns.includes(comment.column);
|
|
2418
|
+
return viewColumnGone(from, to, comment.schema, relation2, comment.column);
|
|
2419
|
+
}
|
|
2420
|
+
if (comment.kind === "enum") return namedGone(from.inventory.enums, to.inventory.enums, comment.schema, comment.name);
|
|
2421
|
+
if (comment.kind === "view" || comment.kind === "materializedView") {
|
|
2422
|
+
return viewGone(from.inventory.views, to.inventory.views, comment.schema, comment.name, comment.kind === "materializedView");
|
|
2423
|
+
}
|
|
2424
|
+
if (comment.kind === "index") {
|
|
2425
|
+
return listedGone(from.inventory.indexes, to.inventory.indexes, comment.schema, comment.name);
|
|
2426
|
+
}
|
|
2427
|
+
if (comment.kind === "constraint") {
|
|
2428
|
+
const had = from.inventory.constraints.some((item) => item.schema === comment.schema && item.table === relation2 && item.name === comment.name);
|
|
2429
|
+
const has = to.inventory.constraints.some((item) => item.schema === comment.schema && item.table === relation2 && item.name === comment.name);
|
|
2430
|
+
return had && !has;
|
|
2431
|
+
}
|
|
2432
|
+
return false;
|
|
2433
|
+
}
|
|
2434
|
+
function namedGone(from, to, schema, name) {
|
|
2435
|
+
const had = from.some((item) => item.schema === schema && item.name === name);
|
|
2436
|
+
const has = to.some((item) => item.schema === schema && item.name === name);
|
|
2437
|
+
return had && !has;
|
|
2438
|
+
}
|
|
2439
|
+
function listedGone(from, to, schema, name) {
|
|
2440
|
+
return namedGone(from, to, schema, name);
|
|
2441
|
+
}
|
|
2442
|
+
function viewGone(from, to, schema, name, materialized) {
|
|
2443
|
+
const had = from.some((item) => item.schema === schema && item.name === name && item.materialized === materialized);
|
|
2444
|
+
const has = to.some((item) => item.schema === schema && item.name === name && item.materialized === materialized);
|
|
2445
|
+
return had && !has;
|
|
2446
|
+
}
|
|
2447
|
+
function viewColumnGone(from, to, schema, relation2, column) {
|
|
2448
|
+
const prev = from.inventory.views.find((item) => item.schema === schema && item.name === relation2);
|
|
2449
|
+
const next = to.inventory.views.find((item) => item.schema === schema && item.name === relation2);
|
|
2450
|
+
if (prev && !next) return true;
|
|
2451
|
+
if (!prev || !next) return false;
|
|
2452
|
+
return prev.columns.includes(column) && !next.columns.includes(column);
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
// src/journal.ts
|
|
2456
|
+
import { randomUUID } from "crypto";
|
|
2457
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "fs";
|
|
2458
|
+
import path from "path";
|
|
2459
|
+
var BREAKPOINT = "--> statement-breakpoint";
|
|
2460
|
+
var ORIGIN_ID = "00000000-0000-0000-0000-000000000000";
|
|
2461
|
+
var EXTRAS_SNAPSHOT = "_pg-extras.json";
|
|
2462
|
+
function joinStatements(statements, breakpoints, header) {
|
|
2463
|
+
const body = statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);
|
|
2464
|
+
if (body.length === 0) return "";
|
|
2465
|
+
const separator = breakpoints ? `
|
|
2466
|
+
${BREAKPOINT}
|
|
2467
|
+
` : "\n";
|
|
2468
|
+
return `${header}
|
|
2469
|
+
${body.join(separator)}
|
|
2470
|
+
`;
|
|
2471
|
+
}
|
|
2472
|
+
function extrasSnapshotPath(out) {
|
|
2473
|
+
return path.join(out, EXTRAS_SNAPSHOT);
|
|
2474
|
+
}
|
|
2475
|
+
function readExtrasSnapshotFile(out) {
|
|
2476
|
+
const file = extrasSnapshotPath(out);
|
|
2477
|
+
if (!existsSync(file)) return null;
|
|
2478
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
2479
|
+
}
|
|
2480
|
+
function sanitizeMigrationName(name) {
|
|
2481
|
+
const clean = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 80).replace(/_+$/g, "");
|
|
2482
|
+
if (!clean) throw new PgExtrasError(`migration name "${name}" is empty after sanitizing`);
|
|
2483
|
+
return clean;
|
|
2484
|
+
}
|
|
2485
|
+
function writeMigration(input) {
|
|
2486
|
+
const out = path.resolve(input.out);
|
|
2487
|
+
mkdirSync(out, { recursive: true });
|
|
2488
|
+
const layout = detectLayout(out);
|
|
2489
|
+
const written = layout === "v1" ? writeV1(out, input) : writeJournal(out, input);
|
|
2490
|
+
writeFileSync(extrasSnapshotPath(out), `${JSON.stringify(input.snapshot, null, 2)}
|
|
2491
|
+
`);
|
|
2492
|
+
return written;
|
|
2493
|
+
}
|
|
2494
|
+
function detectLayout(out) {
|
|
2495
|
+
if (!existsSync(out)) return "journal";
|
|
2496
|
+
const entries = readdirSync(out, { withFileTypes: true });
|
|
2497
|
+
const v1 = entries.filter(
|
|
2498
|
+
(entry2) => entry2.isDirectory() && /^\d{14}_/.test(entry2.name) && existsSync(path.join(out, entry2.name, "migration.sql"))
|
|
2499
|
+
);
|
|
2500
|
+
const journal = existsSync(path.join(out, "meta", "_journal.json"));
|
|
2501
|
+
if (v1.length > 0 && journal) {
|
|
2502
|
+
throw new PgExtrasError(
|
|
2503
|
+
`migrations folder ${out} has both meta/_journal.json and v1 migration folders. Keep one layout.`
|
|
2504
|
+
);
|
|
2505
|
+
}
|
|
2506
|
+
return v1.length > 0 ? "v1" : "journal";
|
|
2507
|
+
}
|
|
2508
|
+
function writeJournal(out, input) {
|
|
2509
|
+
const prefixMode = input.prefix ?? "index";
|
|
2510
|
+
if (prefixMode === "none") {
|
|
2511
|
+
throw new PgExtrasError('migrations.prefix "none" is not supported. Use "index", "timestamp", "supabase", or "unix".');
|
|
2512
|
+
}
|
|
2513
|
+
const meta = path.join(out, "meta");
|
|
2514
|
+
mkdirSync(meta, { recursive: true });
|
|
2515
|
+
const journalPath = path.join(meta, "_journal.json");
|
|
2516
|
+
const journal = existsSync(journalPath) ? readJournal(journalPath) : emptyJournal();
|
|
2517
|
+
if (journal.dialect !== "postgresql") {
|
|
2518
|
+
throw new PgExtrasError(`drizzle-pg-extras only writes postgresql migrations. This journal is ${journal.dialect}.`);
|
|
2519
|
+
}
|
|
2520
|
+
const last = journal.entries[journal.entries.length - 1];
|
|
2521
|
+
const idx = last ? last.idx + 1 : 0;
|
|
2522
|
+
const when = Math.max(Date.now(), last ? last.when + 1 : 0);
|
|
2523
|
+
const prefix = migrationPrefix(idx, prefixMode);
|
|
2524
|
+
const suffix = sanitizeMigrationName(input.name);
|
|
2525
|
+
const tag = `${prefix}_${suffix}`;
|
|
2526
|
+
if (journal.entries.some((entry2) => entry2.tag === tag) || existsSync(path.join(out, `${tag}.sql`))) {
|
|
2527
|
+
throw new PgExtrasError(`migration ${tag} already exists in ${out}`);
|
|
2528
|
+
}
|
|
2529
|
+
const breakpoints = input.breakpoints ?? true;
|
|
2530
|
+
const kitSnapshot = nextKitSnapshot(readLatestKitSnapshot(meta));
|
|
2531
|
+
writeFileSync(path.join(meta, `${prefix}_snapshot.json`), `${JSON.stringify(kitSnapshot, null, 2)}
|
|
2532
|
+
`);
|
|
2533
|
+
journal.entries.push({ idx, version: "7", when, tag, breakpoints });
|
|
2534
|
+
writeFileSync(journalPath, `${JSON.stringify(journal, null, 2)}
|
|
2535
|
+
`);
|
|
2536
|
+
const sqlPath = path.join(out, `${tag}.sql`);
|
|
2537
|
+
const downPath = path.join(out, `${tag}.down.sql`);
|
|
2538
|
+
writeFileSync(sqlPath, input.up);
|
|
2539
|
+
writeFileSync(downPath, input.down);
|
|
2540
|
+
return { tag, sqlPath, downPath, layout: "journal" };
|
|
2541
|
+
}
|
|
2542
|
+
function writeV1(out, input) {
|
|
2543
|
+
const folders = readdirSync(out, { withFileTypes: true }).filter((entry2) => entry2.isDirectory() && /^\d{14}_/.test(entry2.name)).map((entry2) => entry2.name).sort();
|
|
2544
|
+
const suffix = sanitizeMigrationName(input.name);
|
|
2545
|
+
let stamp = utcStamp(/* @__PURE__ */ new Date());
|
|
2546
|
+
let folder = `${stamp}_${suffix}`;
|
|
2547
|
+
while (existsSync(path.join(out, folder))) {
|
|
2548
|
+
stamp = String(Number(stamp) + 1);
|
|
2549
|
+
folder = `${stamp}_${suffix}`;
|
|
2550
|
+
}
|
|
2551
|
+
const dir = path.join(out, folder);
|
|
2552
|
+
mkdirSync(dir, { recursive: true });
|
|
2553
|
+
const sqlPath = path.join(dir, "migration.sql");
|
|
2554
|
+
const downPath = path.join(dir, "down.sql");
|
|
2555
|
+
writeFileSync(sqlPath, input.up);
|
|
2556
|
+
writeFileSync(downPath, input.down);
|
|
2557
|
+
const previous = folders.length > 0 ? path.join(out, folders[folders.length - 1], "snapshot.json") : null;
|
|
2558
|
+
if (previous && existsSync(previous)) {
|
|
2559
|
+
const parsed = JSON.parse(readFileSync(previous, "utf8"));
|
|
2560
|
+
let next = parsed;
|
|
2561
|
+
if (typeof parsed.id === "string") {
|
|
2562
|
+
const { id, prevId: _previous, ...rest } = parsed;
|
|
2563
|
+
next = { id: randomUUID(), prevId: id, ...rest };
|
|
2564
|
+
}
|
|
2565
|
+
writeFileSync(path.join(dir, "snapshot.json"), `${JSON.stringify(next, null, 2)}
|
|
2566
|
+
`);
|
|
2567
|
+
}
|
|
2568
|
+
return { tag: folder, sqlPath, downPath, layout: "v1" };
|
|
2569
|
+
}
|
|
2570
|
+
function emptyJournal() {
|
|
2571
|
+
return { version: "7", dialect: "postgresql", entries: [] };
|
|
2572
|
+
}
|
|
2573
|
+
function readJournal(file) {
|
|
2574
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
2575
|
+
if (!parsed || !Array.isArray(parsed.entries) || typeof parsed.dialect !== "string") {
|
|
2576
|
+
throw new PgExtrasError(`${file} is not a drizzle-kit journal`);
|
|
2577
|
+
}
|
|
2578
|
+
return {
|
|
2579
|
+
version: typeof parsed.version === "string" ? parsed.version : "7",
|
|
2580
|
+
dialect: parsed.dialect,
|
|
2581
|
+
entries: parsed.entries
|
|
2582
|
+
};
|
|
2583
|
+
}
|
|
2584
|
+
function readLatestKitSnapshot(meta) {
|
|
2585
|
+
if (!existsSync(meta)) return null;
|
|
2586
|
+
const files = readdirSync(meta).filter((file) => !file.startsWith("_") && file.endsWith(".json")).sort();
|
|
2587
|
+
const latest = files[files.length - 1];
|
|
2588
|
+
if (!latest) return null;
|
|
2589
|
+
return JSON.parse(readFileSync(path.join(meta, latest), "utf8"));
|
|
2590
|
+
}
|
|
2591
|
+
function nextKitSnapshot(prev) {
|
|
2592
|
+
if (!prev || typeof prev.id !== "string") {
|
|
2593
|
+
return {
|
|
2594
|
+
id: randomUUID(),
|
|
2595
|
+
prevId: ORIGIN_ID,
|
|
2596
|
+
version: "7",
|
|
2597
|
+
dialect: "postgresql",
|
|
2598
|
+
tables: {},
|
|
2599
|
+
enums: {},
|
|
2600
|
+
schemas: {},
|
|
2601
|
+
sequences: {},
|
|
2602
|
+
roles: {},
|
|
2603
|
+
policies: {},
|
|
2604
|
+
views: {},
|
|
2605
|
+
_meta: { columns: {}, schemas: {}, tables: {} }
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
const { id, prevId: _previous, ...rest } = prev;
|
|
2609
|
+
return { id: randomUUID(), prevId: id, ...rest };
|
|
2610
|
+
}
|
|
2611
|
+
function migrationPrefix(idx, mode) {
|
|
2612
|
+
if (mode === "index") return String(idx).padStart(4, "0");
|
|
2613
|
+
if (mode === "unix") return String(Math.floor(Date.now() / 1e3));
|
|
2614
|
+
if (mode === "timestamp" || mode === "supabase") return utcStamp(/* @__PURE__ */ new Date());
|
|
2615
|
+
return "";
|
|
2616
|
+
}
|
|
2617
|
+
function utcStamp(date) {
|
|
2618
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
2619
|
+
return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}`;
|
|
2620
|
+
}
|
|
2621
|
+
|
|
2622
|
+
// src/version.ts
|
|
2623
|
+
var VERSION = "0.5.0";
|
|
2624
|
+
|
|
2625
|
+
// src/generate.ts
|
|
2626
|
+
var UP_HEADER = `-- Generated by drizzle-pg-extras ${VERSION}. Review before applying.`;
|
|
2627
|
+
var DOWN_HEADER = `-- Down SQL for drizzle-pg-extras ${VERSION}. drizzle-kit migrate does not run this file.`;
|
|
2628
|
+
function loadStoredSnapshot(out) {
|
|
2629
|
+
const raw = readExtrasSnapshotFile(out);
|
|
2630
|
+
if (raw === null) return emptySnapshot();
|
|
2631
|
+
try {
|
|
2632
|
+
return parseSnapshot(raw);
|
|
2633
|
+
} catch (error) {
|
|
2634
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2635
|
+
throw new PgExtrasError(`${extrasSnapshotPath(out)}: ${message}`);
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
function planExtras(extras, previous, casing) {
|
|
2639
|
+
const next = snapshotExtras(extras, casing ? { casing } : void 0);
|
|
2640
|
+
const diff = diffSnapshots(previous, next);
|
|
2641
|
+
return { next, ...diff };
|
|
2642
|
+
}
|
|
2643
|
+
function generate(options) {
|
|
2644
|
+
const name = sanitizeMigrationName(options.name ?? "pg_extras");
|
|
2645
|
+
const previous = loadStoredSnapshot(options.out);
|
|
2646
|
+
const planned = planExtras(options.extras, previous, options.casing);
|
|
2647
|
+
if (planned.up.length === 0) {
|
|
2648
|
+
return { written: false, up: [], down: [] };
|
|
2649
|
+
}
|
|
2650
|
+
const breakpoints = options.breakpoints ?? true;
|
|
2651
|
+
const written = writeMigration({
|
|
2652
|
+
out: options.out,
|
|
2653
|
+
name,
|
|
2654
|
+
up: joinStatements(planned.up, breakpoints, UP_HEADER),
|
|
2655
|
+
down: joinStatements(planned.down, breakpoints, DOWN_HEADER),
|
|
2656
|
+
snapshot: planned.next,
|
|
2657
|
+
prefix: options.prefix,
|
|
2658
|
+
breakpoints
|
|
2659
|
+
});
|
|
2660
|
+
return { written: true, up: planned.up, down: planned.down, ...written };
|
|
2661
|
+
}
|
|
2662
|
+
function pendingStatements(extras, out, casing) {
|
|
2663
|
+
return planExtras(extras, loadStoredSnapshot(out), casing).up;
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
// src/load.ts
|
|
2667
|
+
import { existsSync as existsSync2, readdirSync as readdirSync2, statSync } from "fs";
|
|
2668
|
+
import path2 from "path";
|
|
2669
|
+
|
|
2670
|
+
// src/collect.ts
|
|
2671
|
+
import { is as is4 } from "drizzle-orm";
|
|
2672
|
+
import { PgTable as PgTable3, isPgEnum as isPgEnum3, isPgMaterializedView as isPgMaterializedView3, isPgView as isPgView3 } from "drizzle-orm/pg-core";
|
|
2673
|
+
function collectExtras(modules) {
|
|
2674
|
+
const extras = {
|
|
2675
|
+
functions: [],
|
|
2676
|
+
triggers: [],
|
|
2677
|
+
extensions: [],
|
|
2678
|
+
comments: [],
|
|
2679
|
+
tables: [],
|
|
2680
|
+
enums: [],
|
|
2681
|
+
views: [],
|
|
2682
|
+
partitionedTables: [],
|
|
2683
|
+
partitions: [],
|
|
2684
|
+
detaches: [],
|
|
2685
|
+
hypertables: []
|
|
2686
|
+
};
|
|
2687
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2688
|
+
const list = Array.isArray(modules) ? modules : [modules];
|
|
2689
|
+
for (const mod of list) walk(mod, extras, seen);
|
|
2690
|
+
for (const trigger of extras.triggers) {
|
|
2691
|
+
const fn = trigger.function;
|
|
2692
|
+
if (fn && extrasKind(fn) === "function" && !extras.functions.includes(fn)) {
|
|
2693
|
+
extras.functions.push(fn);
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
return extras;
|
|
2697
|
+
}
|
|
2698
|
+
function walk(value, extras, seen) {
|
|
2699
|
+
if (value === null || value === void 0) return;
|
|
2700
|
+
if (typeof value === "function") {
|
|
2701
|
+
if (isPgEnum3(value)) pushEnum(extras, value);
|
|
2702
|
+
return;
|
|
2703
|
+
}
|
|
2704
|
+
if (typeof value !== "object") return;
|
|
2705
|
+
if (seen.has(value)) return;
|
|
2706
|
+
seen.add(value);
|
|
2707
|
+
const kind = extrasKind(value);
|
|
2708
|
+
if (kind === "function") {
|
|
2709
|
+
extras.functions.push(value);
|
|
2710
|
+
return;
|
|
2711
|
+
}
|
|
2712
|
+
if (kind === "trigger") {
|
|
2713
|
+
extras.triggers.push(value);
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
2716
|
+
if (kind === "extension") {
|
|
2717
|
+
extras.extensions.push(value);
|
|
2718
|
+
return;
|
|
2719
|
+
}
|
|
2720
|
+
if (kind === "comment") {
|
|
2721
|
+
extras.comments.push(value);
|
|
2722
|
+
return;
|
|
2723
|
+
}
|
|
2724
|
+
if (kind === "partitionedTable") {
|
|
2725
|
+
const partitioned = value;
|
|
2726
|
+
extras.partitionedTables.push(partitioned);
|
|
2727
|
+
if (is4(partitioned.table, PgTable3)) walk(partitioned.table, extras, seen);
|
|
2728
|
+
return;
|
|
2729
|
+
}
|
|
2730
|
+
if (kind === "partition") {
|
|
2731
|
+
extras.partitions.push(value);
|
|
2732
|
+
return;
|
|
2733
|
+
}
|
|
2734
|
+
if (kind === "detach") {
|
|
2735
|
+
extras.detaches.push(value);
|
|
2736
|
+
return;
|
|
2737
|
+
}
|
|
2738
|
+
if (kind === "hypertable") {
|
|
2739
|
+
const hypertable = value;
|
|
2740
|
+
extras.hypertables.push(hypertable);
|
|
2741
|
+
if (is4(hypertable.table, PgTable3)) walk(hypertable.table, extras, seen);
|
|
2742
|
+
return;
|
|
2743
|
+
}
|
|
2744
|
+
if (isPgView3(value) || isPgMaterializedView3(value)) {
|
|
2745
|
+
pushView(extras, value);
|
|
2746
|
+
return;
|
|
2747
|
+
}
|
|
2748
|
+
if (is4(value, PgTable3)) {
|
|
2749
|
+
if (!extras.tables.includes(value)) extras.tables.push(value);
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
if (Array.isArray(value)) {
|
|
2753
|
+
for (const entry2 of value) walk(entry2, extras, seen);
|
|
2754
|
+
return;
|
|
2755
|
+
}
|
|
2756
|
+
if (isPlainRecord(value)) {
|
|
2757
|
+
for (const entry2 of Object.values(value)) walk(entry2, extras, seen);
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
function pushEnum(extras, value) {
|
|
2761
|
+
const enumObject = value;
|
|
2762
|
+
if (!extras.enums.includes(enumObject)) extras.enums.push(enumObject);
|
|
2763
|
+
}
|
|
2764
|
+
function pushView(extras, value) {
|
|
2765
|
+
if (!extras.views.includes(value)) extras.views.push(value);
|
|
2766
|
+
}
|
|
2767
|
+
|
|
2768
|
+
// src/load.ts
|
|
2769
|
+
var CONFIG_CANDIDATES = ["drizzle.config.ts", "drizzle.config.js", "drizzle.config.mjs", "drizzle.config.cjs"];
|
|
2770
|
+
var SCHEMA_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]);
|
|
2771
|
+
async function loadProject(cwd, configPath) {
|
|
2772
|
+
const resolved = resolveConfigPath(cwd, configPath);
|
|
2773
|
+
const config = await importConfig(resolved);
|
|
2774
|
+
if (config.dialect && config.dialect !== "postgresql") {
|
|
2775
|
+
throw new PgExtrasError(
|
|
2776
|
+
`drizzle-pg-extras supports postgresql only. ${resolved} sets dialect "${config.dialect}".`
|
|
2777
|
+
);
|
|
2778
|
+
}
|
|
2779
|
+
const schema = config.schema;
|
|
2780
|
+
if (!schema || Array.isArray(schema) && schema.length === 0) {
|
|
2781
|
+
throw new PgExtrasError(`${resolved} has no schema path. Set schema in the drizzle config.`);
|
|
2782
|
+
}
|
|
2783
|
+
const patterns = Array.isArray(schema) ? schema : [schema];
|
|
2784
|
+
const configDir = path2.dirname(resolved);
|
|
2785
|
+
const files = expandSchemaPaths(patterns, configDir);
|
|
2786
|
+
const modules = [];
|
|
2787
|
+
for (const file of files) modules.push(await importSchema(file));
|
|
2788
|
+
return {
|
|
2789
|
+
extras: collectExtras(modules),
|
|
2790
|
+
out: path2.resolve(configDir, config.out ?? "drizzle"),
|
|
2791
|
+
casing: config.casing,
|
|
2792
|
+
prefix: config.migrations?.prefix ?? "index",
|
|
2793
|
+
breakpoints: config.breakpoints ?? true,
|
|
2794
|
+
configPath: resolved
|
|
2795
|
+
};
|
|
2796
|
+
}
|
|
2797
|
+
function resolveConfigPath(cwd, configPath) {
|
|
2798
|
+
if (configPath) {
|
|
2799
|
+
const resolved = path2.resolve(cwd, configPath);
|
|
2800
|
+
if (!existsSync2(resolved)) throw new PgExtrasError(`config not found: ${resolved}`);
|
|
2801
|
+
return resolved;
|
|
2802
|
+
}
|
|
2803
|
+
for (const candidate of CONFIG_CANDIDATES) {
|
|
2804
|
+
const resolved = path2.join(cwd, candidate);
|
|
2805
|
+
if (existsSync2(resolved)) return resolved;
|
|
2806
|
+
}
|
|
2807
|
+
throw new PgExtrasError("could not find drizzle.config.ts. Pass --config, or create one with dialect, schema, and out.");
|
|
2808
|
+
}
|
|
2809
|
+
function expandSchemaPaths(patterns, cwd) {
|
|
2810
|
+
const found = [];
|
|
2811
|
+
for (const pattern of patterns) {
|
|
2812
|
+
if (!pattern.includes("*")) {
|
|
2813
|
+
const abs = path2.resolve(cwd, pattern);
|
|
2814
|
+
if (!existsSync2(abs)) throw new PgExtrasError(`schema path not found: ${pattern}`);
|
|
2815
|
+
if (statSync(abs).isDirectory()) found.push(...walkSchemaFiles(abs));
|
|
2816
|
+
else found.push(abs);
|
|
2817
|
+
continue;
|
|
2818
|
+
}
|
|
2819
|
+
const absPattern = path2.isAbsolute(pattern) ? pattern : path2.resolve(cwd, pattern);
|
|
2820
|
+
const star = absPattern.indexOf("*");
|
|
2821
|
+
const slash = absPattern.lastIndexOf("/", star);
|
|
2822
|
+
const base = slash === -1 ? cwd : absPattern.slice(0, slash);
|
|
2823
|
+
if (!existsSync2(base)) throw new PgExtrasError(`schema path not found: ${pattern}`);
|
|
2824
|
+
const regex = globToRegExp(absPattern);
|
|
2825
|
+
const matches = walkSchemaFiles(base).filter((file) => regex.test(file));
|
|
2826
|
+
if (matches.length === 0) throw new PgExtrasError(`schema pattern matched no files: ${pattern}`);
|
|
2827
|
+
found.push(...matches);
|
|
2828
|
+
}
|
|
2829
|
+
return [...new Set(found)].sort();
|
|
2830
|
+
}
|
|
2831
|
+
function walkSchemaFiles(dir) {
|
|
2832
|
+
const out = [];
|
|
2833
|
+
for (const entry2 of readdirSync2(dir, { withFileTypes: true })) {
|
|
2834
|
+
if (entry2.name === "node_modules" || entry2.name === "dist" || entry2.name.startsWith(".")) continue;
|
|
2835
|
+
const full = path2.join(dir, entry2.name);
|
|
2836
|
+
if (entry2.isDirectory()) {
|
|
2837
|
+
out.push(...walkSchemaFiles(full));
|
|
2838
|
+
continue;
|
|
2839
|
+
}
|
|
2840
|
+
if (!entry2.isFile() || entry2.name.endsWith(".d.ts")) continue;
|
|
2841
|
+
if (SCHEMA_EXT.has(path2.extname(entry2.name))) out.push(full);
|
|
2842
|
+
}
|
|
2843
|
+
return out;
|
|
2844
|
+
}
|
|
2845
|
+
function globToRegExp(absPattern) {
|
|
2846
|
+
let source = "";
|
|
2847
|
+
for (let i = 0; i < absPattern.length; i++) {
|
|
2848
|
+
const char = absPattern[i];
|
|
2849
|
+
if (char === "*" && absPattern[i + 1] === "*") {
|
|
2850
|
+
source += ".*";
|
|
2851
|
+
i += 1;
|
|
2852
|
+
if (absPattern[i + 1] === "/") i += 1;
|
|
2853
|
+
continue;
|
|
2854
|
+
}
|
|
2855
|
+
if (char === "*") {
|
|
2856
|
+
source += "[^/]*";
|
|
2857
|
+
continue;
|
|
2858
|
+
}
|
|
2859
|
+
source += "\\^$+?.()|[]{}".includes(char) ? `\\${char}` : char;
|
|
2860
|
+
}
|
|
2861
|
+
return new RegExp(`^${source}$`);
|
|
2862
|
+
}
|
|
2863
|
+
async function importConfig(file) {
|
|
2864
|
+
const { createJiti } = await import("jiti");
|
|
2865
|
+
const jiti = createJiti(import.meta.url, { moduleCache: false, interopDefault: true });
|
|
2866
|
+
const imported = await jiti.import(file);
|
|
2867
|
+
const config = imported && typeof imported === "object" && "default" in imported && imported.default ? imported.default : imported;
|
|
2868
|
+
if (!config || typeof config !== "object") throw new PgExtrasError(`${file} did not export a config object`);
|
|
2869
|
+
return config;
|
|
2870
|
+
}
|
|
2871
|
+
async function importSchema(file) {
|
|
2872
|
+
const { createJiti } = await import("jiti");
|
|
2873
|
+
const jiti = createJiti(import.meta.url, { moduleCache: false, interopDefault: true });
|
|
2874
|
+
const imported = await jiti.import(file);
|
|
2875
|
+
if (!imported || typeof imported !== "object") throw new PgExtrasError(`${file} did not export a module`);
|
|
2876
|
+
const merged = { ...imported };
|
|
2877
|
+
const def = imported.default;
|
|
2878
|
+
if (def && typeof def === "object") Object.assign(merged, def);
|
|
2879
|
+
return merged;
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
// src/cli.ts
|
|
2883
|
+
async function run(argv) {
|
|
2884
|
+
const [command, ...rest] = argv;
|
|
2885
|
+
if (!command || command === "--help" || command === "-h" || command === "help") {
|
|
2886
|
+
printHelp();
|
|
2887
|
+
return 0;
|
|
2888
|
+
}
|
|
2889
|
+
let options;
|
|
2890
|
+
try {
|
|
2891
|
+
options = parseArgs(rest);
|
|
2892
|
+
} catch (error) {
|
|
2893
|
+
return fail(error);
|
|
2894
|
+
}
|
|
2895
|
+
if (options.help) {
|
|
2896
|
+
printHelp();
|
|
2897
|
+
return 0;
|
|
2898
|
+
}
|
|
2899
|
+
try {
|
|
2900
|
+
if (command === "generate") return await generateCommand(options);
|
|
2901
|
+
if (command === "check") return await checkCommand(options);
|
|
2902
|
+
console.error(`Unknown command "${command}".`);
|
|
2903
|
+
printHelp();
|
|
2904
|
+
return 1;
|
|
2905
|
+
} catch (error) {
|
|
2906
|
+
return fail(error);
|
|
2907
|
+
}
|
|
2908
|
+
}
|
|
2909
|
+
async function generateCommand(options) {
|
|
2910
|
+
const project = await loadProject(process.cwd(), options.config);
|
|
2911
|
+
const result = generate({
|
|
2912
|
+
extras: project.extras,
|
|
2913
|
+
out: project.out,
|
|
2914
|
+
name: options.name ?? "pg_extras",
|
|
2915
|
+
casing: project.casing,
|
|
2916
|
+
prefix: project.prefix,
|
|
2917
|
+
breakpoints: project.breakpoints
|
|
2918
|
+
});
|
|
2919
|
+
if (!result.written) {
|
|
2920
|
+
console.log("No changes, nothing to migrate");
|
|
2921
|
+
return 0;
|
|
2922
|
+
}
|
|
2923
|
+
console.log(result.sqlPath);
|
|
2924
|
+
console.log(result.downPath);
|
|
2925
|
+
return 0;
|
|
2926
|
+
}
|
|
2927
|
+
async function checkCommand(options) {
|
|
2928
|
+
const project = await loadProject(process.cwd(), options.config);
|
|
2929
|
+
const pending = pendingStatements(project.extras, project.out, project.casing);
|
|
2930
|
+
if (pending.length === 0) {
|
|
2931
|
+
console.log("pg extras are up to date");
|
|
2932
|
+
return 0;
|
|
2933
|
+
}
|
|
2934
|
+
console.error("Definitions changed and have no migration yet:");
|
|
2935
|
+
console.error(pending.join("\n\n"));
|
|
2936
|
+
return 1;
|
|
2937
|
+
}
|
|
2938
|
+
function parseArgs(args) {
|
|
2939
|
+
const options = {};
|
|
2940
|
+
for (let i = 0; i < args.length; i++) {
|
|
2941
|
+
const arg = args[i];
|
|
2942
|
+
if (arg === "--help" || arg === "-h") {
|
|
2943
|
+
options.help = true;
|
|
2944
|
+
continue;
|
|
2945
|
+
}
|
|
2946
|
+
if (arg === "--config" || arg === "-c") {
|
|
2947
|
+
const value = args[++i];
|
|
2948
|
+
if (!value) throw new PgExtrasError(`${arg} needs a file path`);
|
|
2949
|
+
options.config = value;
|
|
2950
|
+
continue;
|
|
2951
|
+
}
|
|
2952
|
+
if (arg === "--name") {
|
|
2953
|
+
const value = args[++i];
|
|
2954
|
+
if (!value) throw new PgExtrasError("--name needs a migration name");
|
|
2955
|
+
options.name = value;
|
|
2956
|
+
continue;
|
|
2957
|
+
}
|
|
2958
|
+
throw new PgExtrasError(`Unknown option ${arg}`);
|
|
2959
|
+
}
|
|
2960
|
+
return options;
|
|
2961
|
+
}
|
|
2962
|
+
function fail(error) {
|
|
2963
|
+
if (error instanceof PgExtrasError) {
|
|
2964
|
+
console.error(error.message);
|
|
2965
|
+
return 1;
|
|
2966
|
+
}
|
|
2967
|
+
console.error(error);
|
|
2968
|
+
return 1;
|
|
2969
|
+
}
|
|
2970
|
+
function printHelp() {
|
|
2971
|
+
console.log(`drizzle-pg-extras ${commandList()}
|
|
2972
|
+
|
|
2973
|
+
generate Write a drizzle-kit migration for functions, triggers, comments, extensions, partitions, and hypertables that changed
|
|
2974
|
+
check Exit 1 when those definitions changed and no migration was written
|
|
2975
|
+
|
|
2976
|
+
--config, -c <file> drizzle config. Defaults to drizzle.config.ts
|
|
2977
|
+
--name <name> migration name. Defaults to pg_extras
|
|
2978
|
+
`);
|
|
2979
|
+
}
|
|
2980
|
+
function commandList() {
|
|
2981
|
+
return "generate | check";
|
|
2982
|
+
}
|
|
2983
|
+
var entry = process.argv[1];
|
|
2984
|
+
if (entry && import.meta.url === pathToFileURL(entry).href) {
|
|
2985
|
+
run(process.argv.slice(2)).then((code) => {
|
|
2986
|
+
process.exitCode = code;
|
|
2987
|
+
}).catch((error) => {
|
|
2988
|
+
console.error(error);
|
|
2989
|
+
process.exitCode = 1;
|
|
2990
|
+
});
|
|
2991
|
+
}
|
|
2992
|
+
export {
|
|
2993
|
+
run
|
|
2994
|
+
};
|
|
2995
|
+
//# sourceMappingURL=cli.js.map
|