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