@systemfsoftware/drizzle-pg-extras 0.0.0-stage → 0.6.0

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