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