@systemfsoftware/timescale-drizzle 0.0.0-bootstrap.0 → 0.8.0

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