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