drizzle-pg-extras 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Odinaka Robert Nnamani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,459 @@
1
- # Temporary Holding Version
1
+ # drizzle-pg-extras
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Declare the Postgres objects Drizzle still can't model — functions, triggers, comments, extensions, partitioned tables, and TimescaleDB hypertables — in TypeScript next to your Drizzle tables, and turn them into ordinary SQL migration files.
4
+
5
+ `drizzle-kit migrate` applies those files. This package does not patch Drizzle. If Drizzle later generates the same objects itself, the SQL you already committed stays valid.
6
+
7
+ ## Why
8
+
9
+ These are open Drizzle requests, and the v1.0.0-rc.5 notes don't add them. [PR #4844](https://github.com/drizzle-team/drizzle-orm/pull/4844) is still unmerged.
10
+
11
+ | Gap | Request |
12
+ | --- | --- |
13
+ | `CREATE FUNCTION` / `CREATE TRIGGER` | [drizzle-orm#843](https://github.com/drizzle-team/drizzle-orm/issues/843) |
14
+ | `COMMENT ON` tables, columns, enums, views, routines, indexes, constraints, extensions | [drizzle-orm#886](https://github.com/drizzle-team/drizzle-orm/issues/886) |
15
+ | `CREATE EXTENSION` | [drizzle-orm#2124](https://github.com/drizzle-team/drizzle-orm/issues/2124) |
16
+ | Partitioned tables | [drizzle-orm#2854](https://github.com/drizzle-team/drizzle-orm/issues/2854) |
17
+ | TimescaleDB hypertables | [drizzle-orm#2962](https://github.com/drizzle-team/drizzle-orm/issues/2962) |
18
+
19
+ Smaller packages already cover one of those pieces each: [`drizzle-triggers`](https://github.com/RagedPanda/drizzle-triggers), [`@onozaty/drizzle-db-comments-generator`](https://github.com/onozaty/drizzle-db-comments-generator), and [`drizzle-partition`](https://github.com/Rezarys/drizzle-partition). This package is the Postgres slice people keep asking to put in one schema: functions, triggers, comments, extensions, partitions, and TimescaleDB hypertables. `drizzle-partition` rewrites the `CREATE TABLE` drizzle-kit already wrote. This package leaves that file alone and appends a migration. See [Partitioning](#partitioning) and [TimescaleDB](#timescaledb).
20
+
21
+ ## Example
22
+
23
+ ```ts
24
+ import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";
25
+ import { pgExtension, updatedAtTrigger, withComment } from "drizzle-pg-extras";
26
+
27
+ export const pgcrypto = pgExtension("pgcrypto");
28
+
29
+ export const users = withComment(pgTable("users", {
30
+ id: serial("id").primaryKey(),
31
+ email: withComment(text("email").notNull(), "Login email"),
32
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
33
+ }), "Application users");
34
+
35
+ export const touchUsers = updatedAtTrigger(users, users.updatedAt);
36
+ ```
37
+
38
+ ```sh
39
+ drizzle-kit generate && drizzle-pg-extras generate && drizzle-kit migrate
40
+ ```
41
+
42
+ `updatedAtTrigger` is the case from issue #843: a `BEFORE UPDATE` trigger that sets the column to `now()` for every update, including ones that never go through Drizzle. A hand-written function looks like this:
43
+
44
+ ```ts
45
+ export const setUpdatedAt = pgFunction("set_updated_at", {
46
+ returns: "trigger",
47
+ language: "plpgsql",
48
+ body: "BEGIN NEW.updated_at = now(); RETURN NEW; END;",
49
+ });
50
+
51
+ export const touchUsers = pgTrigger("users_set_updated_at", {
52
+ table: users,
53
+ timing: "before",
54
+ events: ["update"],
55
+ columns: [users.email], // UPDATE OF, and the column must belong to `users`
56
+ when: ({ OLD, NEW }) => sql`${OLD.email} IS DISTINCT FROM ${NEW.email}`,
57
+ function: setUpdatedAt,
58
+ });
59
+ ```
60
+
61
+ `columns` is `UPDATE OF`. `when` is checked when the trigger is declared. Constraint triggers, transition tables, `INSTEAD OF` on a view, and `enabled: false` are in [Triggers](#triggers).
62
+
63
+ The first `generate` writes a migration. The next one writes nothing until a definition changes. Only the difference is emitted, and the statements themselves are idempotent (`CREATE OR REPLACE`, `IF NOT EXISTS`, `DROP … IF EXISTS`).
64
+
65
+ ## Install
66
+
67
+ ```sh
68
+ npm install drizzle-pg-extras
69
+ ```
70
+
71
+ Peer dependency: `drizzle-orm` `>=0.36.4`, including 1.0 (tested with 0.45 and `1.0.0-rc.5`). `drizzle-kit` `>=0.31.0` or 1.0 is optional and only needed to apply migrations. Node.js 18 or newer.
72
+
73
+ Put the definitions in the same files your `drizzle.config.ts` `schema` already points at, and export them. The CLI reads that config (dialect, schema, `out`, `casing`, `breakpoints`, `migrations.prefix`).
74
+
75
+ ```json
76
+ {
77
+ "scripts": {
78
+ "db:generate": "drizzle-kit generate && drizzle-pg-extras generate",
79
+ "db:check": "drizzle-pg-extras check",
80
+ "db:migrate": "drizzle-kit migrate"
81
+ }
82
+ }
83
+ ```
84
+
85
+ `drizzle-pg-extras check` exits 1 when a definition changed and no migration was written. Use it in CI.
86
+
87
+ Run `drizzle-kit generate` first when a trigger or comment targets a table. The table migration has to land above the trigger migration in the journal. Extensions that a column type depends on (PostGIS, for example) are the opposite: that `CREATE EXTENSION` has to run before the table migration. On a new project, generate the extension migration before the first `drizzle-kit generate`, then add triggers and generate again. This package only appends migrations. It will not insert one in front of a migration you have already committed.
88
+
89
+ ## What gets written
90
+
91
+ For the stable drizzle-kit 0.31 layout:
92
+
93
+ ```text
94
+ drizzle/
95
+ 0001_pg_extras.sql applied by drizzle-kit migrate
96
+ 0001_pg_extras.down.sql not applied by drizzle-kit
97
+ _pg-extras.json full extras snapshot, commit this
98
+ meta/_journal.json one new entry, same shape kit writes
99
+ meta/0001_snapshot.json copy of the previous kit snapshot
100
+ ```
101
+
102
+ The kit snapshot is copied the way `drizzle-kit generate --custom` copies it (new id, `prevId` pointing at the previous snapshot, schema body unchanged). A later `drizzle-kit generate` still diffs your tables, not these extras. `_pg-extras.json` sits outside `meta/` so kit does not try to parse it as a schema snapshot.
103
+
104
+ Up SQL is split on `--> statement-breakpoint`, which is what `drizzle-kit migrate` and `migrate()` from `drizzle-orm` expect.
105
+
106
+ Down SQL is the reverse diff: restore the previous function body, drop a trigger that was added, `COMMENT … IS NULL` for a comment that was removed. `drizzle-kit migrate` does not run `.down.sql`, and applying it does not delete the row in `__drizzle_migrations`. To roll back, run the down file yourself, then remove that journal entry and the matching migration row if kit's history should forget it too.
107
+
108
+ With drizzle-kit 1.0, migrations are one folder each (a timestamp directory with `migration.sql`). `generate` writes the same shape: a new directory with `migration.sql`, `down.sql`, and a `snapshot.json` that is an empty diff chained to the previous snapshot (`type: "diff"`, `prevIds` pointing at it), which is what `drizzle-kit generate --custom` writes. The directory always sorts after the last one, so kit never sees two base snapshots. An empty migrations folder gets the layout of the drizzle-kit installed in your project. Both layouts are covered by the test suite, against drizzle-kit 0.31 and 1.0.0-rc.5, including `drizzle-kit migrate` on Postgres.
109
+
110
+ ```
111
+ drizzle/
112
+ 20261118090000_users/ written by drizzle-kit generate
113
+ 20261118090100_pg_extras/
114
+ migration.sql applied by drizzle-kit migrate
115
+ down.sql not applied by drizzle-kit
116
+ snapshot.json empty diff, prevIds -> the users snapshot
117
+ _pg-extras.json full extras snapshot, commit this
118
+ ```
119
+
120
+ ## Programmatic API
121
+
122
+ ```ts
123
+ import { defineExtras, generate, pgExtension, pgFunction, pgTrigger, renderIdempotent } from "drizzle-pg-extras";
124
+
125
+ const extras = defineExtras({
126
+ extensions: [pgExtension("vector", { schema: "extensions" })],
127
+ functions: [setUpdatedAt],
128
+ triggers: [touchUsers],
129
+ tables: [users], // picks up withComment() on the table and its columns
130
+ });
131
+
132
+ generate({ extras, out: "./drizzle", name: "touch_updated_at" });
133
+
134
+ // Full idempotent script. See "drizzle-kit push" below.
135
+ console.log(renderIdempotent(extras));
136
+ ```
137
+
138
+ | Export | Role |
139
+ | --- | --- |
140
+ | `pgFunction(name, config)` | `plpgsql` or `sql`. Args are `IN` only. `returns` is a SQL type string or a Drizzle column (`users.id`). `searchPath: []` emits `SET search_path TO ''`. |
141
+ | `pgTrigger(name, config)` | Table, `pgView()`, or `{ name, schema }`. `columns` is `UPDATE OF`. `when` is SQL or `({ OLD, NEW }) => sql\`…\``. `constraint`, `referencing`, and `enabled: false` are in [Triggers](#triggers). |
142
+ | `updatedAtTrigger(table, column)` | `BEFORE UPDATE` trigger. `column` must be `date`, `time`, or `timestamp`. Tables that share a database column name share one function, `set_<column>`. |
143
+ | `pgExtension(name, { schema, version, cascade })` | `CREATE EXTENSION IF NOT EXISTS`, optionally `WITH SCHEMA` and `VERSION`. |
144
+ | `withComment(target, text)` | Table, column builder, enum, finished view or materialized view, `pgFunction`, trigger, extension, or an index / `unique` / `check` / `primaryKey` / `foreignKey` builder. Returns the same object. Does not change Drizzle's SQL. |
145
+ | `commentOn(target, text)` | Same `COMMENT ON` output for a table, column, enum, view, function, trigger, or extension you already hold. Indexes and constraints use `withComment` inside the table callback. |
146
+ | `partitionedTable(table, { method, columns })` | Marks a drizzle-kit table as `RANGE`, `LIST`, or `HASH`. The migration converts the empty table. See [Partitioning](#partitioning). |
147
+ | `pgPartition(name, { parent, ...bounds })` | `CREATE TABLE ... PARTITION OF`. Bounds are `from`/`to`, `in`, `modulus`/`remainder`, or `default: true`. |
148
+ | `pgAttachPartition(table, { parent, ...bounds })` | `ALTER TABLE ... ATTACH PARTITION` for a table drizzle-kit already created. |
149
+ | `pgDetachPartition(table, { parent })` | `ALTER TABLE ... DETACH PARTITION`. The table is kept. |
150
+ | `hypertable(table, config)` | `create_hypertable` with `if_not_exists`, plus optional compression, a retention policy, and a compression policy. Requires `pgExtension("timescaledb")`. See [TimescaleDB](#timescaledb). |
151
+ | `defineExtras` / `collectExtras` | Bundle objects, or scan a module's exports (the CLI does the scan). |
152
+ | `generate` / `diffSnapshots` / `snapshotExtras` | Diff against the stored snapshot and write files. |
153
+ | `renderIdempotent` | Create-or-replace script for everything currently declared. No drops. |
154
+
155
+ `casing` from `drizzle.config.ts` is applied to key-named columns (`updatedAt` with `snake_case` becomes `updated_at`), same as drizzle-kit. Explicit database names are left alone.
156
+
157
+ A function's identity is `schema.name(arg types)`. Two overloads can coexist. A body, volatility, security, or `search_path` change is `CREATE OR REPLACE` (the oid stays, so triggers are left in place). A return type or argument type change is `DROP FUNCTION` plus create, and triggers that call that function are dropped and created around it. Postgres will not `CREATE OR REPLACE` a new return type.
158
+
159
+ Comments that disappear become `COMMENT … IS NULL`. If the table, column, enum, view, index, or constraint also left the schema, the null comment is omitted: drizzle-kit's migration drops the comment with the object. The same omission applies when this package drops the function, trigger, or extension in the same file. Removing a column that a trigger's `UPDATE OF` or `WHEN` still references takes two generates: change the trigger first, then drop the column. Postgres will not drop the column while the trigger depends on it.
160
+
161
+ ```ts
162
+ import { sql } from "drizzle-orm";
163
+ import { check, index, pgEnum, pgTable, pgView, serial, text, unique } from "drizzle-orm/pg-core";
164
+ import { pgFunction, withComment } from "drizzle-pg-extras";
165
+
166
+ export const role = withComment(pgEnum("user_role", ["admin", "member"]), "Account role");
167
+
168
+ export const users = pgTable("users", {
169
+ id: serial("id").primaryKey(),
170
+ email: text("email").notNull(),
171
+ role: role("role").notNull(),
172
+ }, (table) => [
173
+ withComment(index("users_email_idx").on(table.email), "Lookup by email"),
174
+ withComment(unique("users_email_key").on(table.email), "One email"),
175
+ withComment(check("users_email_check", sql`length(${table.email}) > 0`), "Email is not empty"),
176
+ ]);
177
+
178
+ export const activeUsers = withComment(
179
+ pgView("active_users", { email: withComment(text("email"), "Visible email") }).as(sql`select email from users`),
180
+ "Users visible to the app",
181
+ );
182
+
183
+ export const setUpdatedAt = withComment(pgFunction("set_updated_at", {
184
+ returns: "trigger",
185
+ language: "plpgsql",
186
+ body: "BEGIN NEW.updated_at = now(); RETURN NEW; END;",
187
+ }), "Sets updated_at");
188
+ ```
189
+
190
+ `COMMENT ON` is idempotent. A removed comment is `COMMENT … IS NULL`. Run `drizzle-kit generate` before `drizzle-pg-extras generate` when the comment targets an enum, view, index, or constraint, so that object exists before the comment runs. A later `drizzle-kit generate` still reports no schema changes: the comment is not part of the kit snapshot.
191
+
192
+ ## Triggers
193
+
194
+ These sit next to the Drizzle tables they name. `profileEmails` is a `pgView`. The functions return `trigger`.
195
+
196
+ ```ts
197
+ export const rejectNegative = pgFunction("reject_negative", {
198
+ returns: "trigger",
199
+ language: "plpgsql",
200
+ body: `BEGIN
201
+ IF NEW.amount < 0 THEN
202
+ RAISE EXCEPTION 'negative balance';
203
+ END IF;
204
+ RETURN NEW;
205
+ END;`,
206
+ });
207
+
208
+ export const balancesAmount = pgTrigger("balances_amount", {
209
+ table: balances,
210
+ timing: "after",
211
+ events: ["insert", "update"],
212
+ columns: [balances.amount],
213
+ constraint: { deferrable: true, initially: "deferred", from: customers },
214
+ function: rejectNegative,
215
+ });
216
+
217
+ export const ledgerInserted = pgTrigger("ledger_inserted", {
218
+ table: ledger,
219
+ timing: "after",
220
+ events: ["insert"],
221
+ forEach: "statement",
222
+ referencing: { newTable: "inserted" },
223
+ function: countInserted,
224
+ });
225
+
226
+ export const profileEmailsInsert = pgTrigger("profile_emails_insert", {
227
+ table: profileEmails, // pgView(...)
228
+ timing: "instead of",
229
+ events: ["insert"],
230
+ function: insertProfile,
231
+ });
232
+
233
+ export const profilesGuard = pgTrigger("profiles_guard", {
234
+ table: profiles,
235
+ timing: "before",
236
+ events: ["delete"],
237
+ function: raiseAlways,
238
+ enabled: false, // ALTER TABLE ... DISABLE TRIGGER
239
+ });
240
+ ```
241
+
242
+ `constraint: true` is `CREATE CONSTRAINT TRIGGER ... NOT DEFERRABLE`. `deferrable: true` defaults to `INITIALLY IMMEDIATE`. `initially: "deferred"` requires `deferrable: true`. `from` is the referenced table in `FROM`. These are the deferrable trigger case from [drizzle-orm#1429](https://github.com/drizzle-team/drizzle-orm/issues/1429). `SET CONSTRAINTS` uses the trigger name. Postgres has no `CREATE OR REPLACE` for constraint triggers, so the first migration is `DROP TRIGGER IF EXISTS` plus `CREATE`, and a later change drops and creates again. A comment on that trigger is written again in the same migration.
243
+
244
+ `referencing` is `REFERENCING OLD TABLE AS ... NEW TABLE AS ...`. The names are quoted identifiers. The trigger function reads them as tables (`SELECT count(*) FROM inserted`). `oldTable` is the before-image (`UPDATE` or `DELETE`). `newTable` is the after-image (`INSERT` or `UPDATE`). One event only. `FOR EACH ROW` and `FOR EACH STATEMENT` are both valid. The transition table is the whole statement either way.
245
+
246
+ `enabled: false` appends `ALTER TABLE ... DISABLE TRIGGER`. `enabled: true` after that emits `ENABLE TRIGGER` and leaves the definition in place. `CREATE OR REPLACE` turns a trigger back on, so a body change that stays disabled emits `DISABLE` again.
247
+
248
+ `withComment` on a trigger still emits `COMMENT ON TRIGGER ... ON table`. A normal `CREATE OR REPLACE` keeps that comment. A constraint trigger that is dropped and created gets the comment statement again.
249
+
250
+ ### Trigger limits
251
+
252
+ - Constraint triggers are `AFTER` and `FOR EACH ROW` on a table. `WHEN` on one is evaluated when the row changes, including when the trigger itself is deferred.
253
+ - `UNIQUE` and foreign keys are still drizzle-kit's. This package does not add `DEFERRABLE` to those table constraints. `from` does not create a foreign key.
254
+ - Transition tables are `AFTER` triggers on tables, with one of `INSERT`, `UPDATE`, or `DELETE`. They cannot be combined with `UPDATE OF`, `TRUNCATE`, a constraint trigger, or a view.
255
+ - `INSTEAD OF` is a view trigger, `FOR EACH ROW`, without `WHEN`, without `UPDATE OF`, and without `TRUNCATE`.
256
+ - `BEFORE` and `AFTER` on a view are `forEach: "statement"`. Materialized views cannot have triggers.
257
+ - `WHEN` cannot contain a subquery. An `INSERT` trigger cannot read `OLD`. A `DELETE` trigger cannot read `NEW`. A statement trigger cannot read `OLD` or `NEW`.
258
+ - `ALTER TABLE ... DISABLE TRIGGER` does not work on a view, so `enabled: false` is rejected for views and for `INSTEAD OF`. `ENABLE REPLICA` and `ENABLE ALWAYS` are not emitted.
259
+ - A `{ name, schema }` relation skips the checks that need a Drizzle table or view. Postgres still rejects a view trigger that was declared as a table.
260
+ - Row-level transition triggers on a partition are rejected by Postgres when the migration runs. Foreign tables are not detected through `{ name, schema }`.
261
+ - A view column is matched by view name and column name. Drizzle's view column alias does not carry the schema, so two views with the same name in different schemas are not told apart.
262
+
263
+ ## Partitioning
264
+
265
+ Postgres accepts `PARTITION BY` only on `CREATE TABLE`. There is no `ALTER TABLE ... PARTITION BY`. drizzle-kit has already written a normal `CREATE TABLE` by the time this package runs, and this package does not rewrite that file (that is what `drizzle-partition` does).
266
+
267
+ `partitionedTable()` takes the other road. You keep the table in the Drizzle schema, so drizzle-kit still owns columns, indexes, and foreign keys. `generate` appends a migration that rebuilds the table as partitioned **when it is empty**, and raises when it has any rows. Run `drizzle-kit generate` first, then `drizzle-pg-extras generate`, then `drizzle-kit migrate`, and load data after that. Doing it in one `drizzle-kit migrate` is the normal case: kit creates the empty table, then this migration converts it, before the application writes rows.
268
+
269
+ The tradeoff is that conversion is a rebuild, not a flag. It is safe on an empty table and refused on a table that already has data. A helper that emitted the parent `CREATE TABLE` itself would avoid the rebuild, but then the table would have to stay out of drizzle-kit or kit would create it a second time, and this package would have to own later column changes. Keeping the table in the Drizzle schema is the point of fitting the rest of this package.
270
+
271
+ ```ts
272
+ import { integer, pgTable, serial, text, timestamp, primaryKey } from "drizzle-orm/pg-core";
273
+ import { partitionedTable, pgAttachPartition, pgPartition } from "drizzle-pg-extras";
274
+
275
+ export const events = pgTable("events", {
276
+ id: serial("id").notNull(),
277
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
278
+ region: text("region").notNull(),
279
+ payload: text("payload").notNull(),
280
+ }, (t) => [
281
+ primaryKey({ columns: [t.id, t.createdAt] }),
282
+ ]);
283
+
284
+ export const eventsByTime = partitionedTable(events, {
285
+ method: "range", // "list" or "hash"
286
+ columns: [events.createdAt],
287
+ });
288
+
289
+ export const events2024 = pgPartition("events_2024", {
290
+ parent: events,
291
+ from: ["2024-01-01"],
292
+ to: ["2025-01-01"],
293
+ });
294
+
295
+ export const eventsDefault = pgPartition("events_default", {
296
+ parent: events,
297
+ default: true,
298
+ });
299
+
300
+ export const eventsArchive = pgTable("events_archive", {
301
+ id: integer("id").notNull(),
302
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
303
+ region: text("region").notNull(),
304
+ payload: text("payload").notNull(),
305
+ }, (t) => [
306
+ primaryKey({ columns: [t.id, t.createdAt] }),
307
+ ]);
308
+
309
+ export const attachArchive = pgAttachPartition(eventsArchive, {
310
+ parent: events,
311
+ from: ["2020-01-01"],
312
+ to: ["2024-01-01"],
313
+ });
314
+
315
+ // Later, instead of attachArchive:
316
+ // export const detachArchive = pgDetachPartition(eventsArchive, { parent: events });
317
+ ```
318
+
319
+ `pgPartition` creates a child with `CREATE TABLE ... PARTITION OF`. List bounds use `in: ["en", "en-US"]` (a tuple per row when the key has several columns). Hash bounds use `modulus` and `remainder`. `from: ["MINVALUE"]` and `to: ["MAXVALUE"]` are the range keywords, not strings. Export `partitionedTable()` as well as the children. The CLI only sees what the schema module exports.
320
+
321
+ Every primary key and unique constraint on a Drizzle table has to include the partition columns. Postgres requires that, and `partitionedTable()` rejects the table when one does not. A `{ name, schema }` parent skips that check because the columns are only strings.
322
+
323
+ Removing a `pgPartition` drops the child when the child is empty. `onRemove: "detach"` keeps the table and its rows instead. `pgAttachPartition` always detaches on remove, because drizzle-kit still owns that table. `pgDetachPartition` is the explicit form of that detach. Set `onRemove` when you declare the partition. It is written into `_pg-extras.json` the next time a migration is generated. Changing only `onRemove` does not write a migration file.
324
+
325
+ The statements are idempotent. Running the migration twice is a no-op when the parent is already partitioned the same way and the children are already attached. `renderIdempotent` emits the same create-or-attach script and does not drop partitions you removed from the schema.
326
+
327
+ The conversion copies columns, defaults, identity, indexes, checks, and column comments with `CREATE TABLE ... (LIKE ... INCLUDING ALL)`, then puts back outgoing and incoming foreign keys, triggers, row level security policies, grants, the table comment, and ownership. `serial` sequences are reassigned with `ALTER SEQUENCE ... OWNED BY` before the old table is dropped, so `nextval` keeps working. Index and constraint names are renamed back to the names drizzle-kit recorded. A later `drizzle-kit generate` still diffs your tables and reports no schema changes.
328
+
329
+ ### Partition limits
330
+
331
+ - Empty parents only. A table that already has rows is not converted. Move those rows yourself.
332
+ - The partition key cannot be changed in place. `generate` throws. It also throws when a child bound changes. Recreating a partition would drop its rows, and this package will not do that quietly. Detach, copy, and attach in a migration you write.
333
+ - Hash parents cannot have a `DEFAULT` partition. Postgres rejects it.
334
+ - A table you attach has to match the parent already: column order, `NOT NULL`, unique indexes, and check constraints. Postgres checks that at `ATTACH` and the error is Postgres's.
335
+ - Views and materialized views that depend on the parent are not rewritten. The migration raises and leaves the table in place. Drop the views first.
336
+ - No expression keys such as `PARTITION BY RANGE (date_trunc('month', created_at))`, no sub-partitions, and no tablespaces.
337
+ - No `DETACH PARTITION CONCURRENTLY`. `drizzle-kit migrate` runs each migration in a transaction, and `CONCURRENTLY` cannot run there.
338
+ - `drizzle-kit push` does not read these definitions. Partition children are real tables kit did not declare, so push can offer to drop them. The supported path is generate, then migrate. If you push anyway, exclude the children with `tablesFilter`.
339
+ - A later drizzle-kit migration that drops and recreates the parent (some column type changes) drops the partitions with it. The extras snapshot already says the table is partitioned, so this package will not emit the conversion again. Repair that kit migration by hand.
340
+ - Down SQL drops created partitions when they are empty, detaches attached tables, and converts the parent back when it is empty. It raises when a created partition still has rows. `drizzle-kit migrate` does not run the down file.
341
+
342
+ ## TimescaleDB
343
+
344
+ This is a community package. It is not an official Timescale or Tiger Data tool, and it is not part of Drizzle. Nobody at Timescale reviewed this SQL. It generates the calls people asked for on [drizzle-orm#2962](https://github.com/drizzle-team/drizzle-orm/issues/2962): turn a normal table into a hypertable, then optionally compress it and add retention and compression policies.
345
+
346
+ The table stays in the Drizzle schema, so drizzle-kit still owns columns, indexes, and keys. `generate` appends `SELECT create_hypertable(..., if_not_exists => TRUE)`. That is the same shape as the custom migration in the issue thread. Timescale's newer `CREATE TABLE ... WITH (tsdb.hypertable)` has to be on the `CREATE TABLE` itself, and this package does not rewrite the file drizzle-kit already wrote.
347
+
348
+ `pgExtension("timescaledb")` has to be exported from the schema. `generate` throws if it is missing, and it writes `CREATE EXTENSION` before `create_hypertable` when both are new. A hypertable does not need the extension before the table: drizzle-kit creates an ordinary table, then this migration converts it. Run `drizzle-kit generate`, then `drizzle-pg-extras generate`, then `drizzle-kit migrate`, and load data after that.
349
+
350
+ ```ts
351
+ import { integer, pgTable, text, timestamp, primaryKey } from "drizzle-orm/pg-core";
352
+ import { hypertable, pgExtension } from "drizzle-pg-extras";
353
+
354
+ export const timescale = pgExtension("timescaledb");
355
+
356
+ export const metrics = pgTable("metrics", {
357
+ time: timestamp("time", { withTimezone: true }).notNull(),
358
+ deviceId: text("device_id").notNull(),
359
+ value: integer("value").notNull(),
360
+ }, (t) => [
361
+ primaryKey({ columns: [t.time, t.deviceId] }),
362
+ ]);
363
+
364
+ export const metricsHypertable = hypertable(metrics, {
365
+ timeColumn: metrics.time,
366
+ chunkTimeInterval: "1 day", // omitted: Timescale's default is 7 days
367
+ partitioningColumn: metrics.deviceId, // hash dimension; requires numberPartitions
368
+ numberPartitions: 4,
369
+ migrateData: false, // true makes create_hypertable copy rows that are already in the table
370
+ compression: {
371
+ segmentBy: [metrics.deviceId],
372
+ orderBy: [{ column: metrics.time, direction: "desc", nulls: "last" }],
373
+ },
374
+ retention: { dropAfter: "6 months", scheduleInterval: "1 day" },
375
+ compressionPolicy: { compressAfter: "7 days" },
376
+ });
377
+ ```
378
+
379
+ `chunkTimeInterval`, `dropAfter`, `compressAfter`, and `scheduleInterval` are interval strings such as `"7 days"` or `"1 day 12 hours"`. They are quoted into `INTERVAL '...'`. `compression: {}` enables compression with Timescale's defaults. A compression policy requires `compression`, because Timescale rejects the policy until compression is on.
380
+
381
+ Every primary key and unique index on a Drizzle table has to include the time column and the space column, when you set one. Timescale requires that, and `hypertable()` rejects the table when one does not. The time column has to be `NOT NULL` and a `date`, `timestamp`, or `timestamptz`. A `{ name, schema }` table with string column names skips those checks.
382
+
383
+ The statements are idempotent. `create_hypertable`, `add_retention_policy`, and `add_compression_policy` all pass `if_not_exists => TRUE`, and the compression `ALTER TABLE` can run again. Running the migration twice is a no-op when the hypertable, settings, and policies are already in place. `if_not_exists` does not change an existing policy's interval, so a later edit removes the policy and adds it again. A later `chunkTimeInterval` emits `set_chunk_time_interval`. Adding `partitioningColumn` after the hypertable exists emits `add_dimension`. `migrateData` is read only when the hypertable is first created; changing it later does not write a migration.
384
+
385
+ A later `drizzle-kit generate` still diffs your tables and reports no schema changes. `_pg-extras.json` from 0.4.0 still loads. Hypertable keys are added the next time a migration is written.
386
+
387
+ ### Timescale limits
388
+
389
+ - Continuous aggregates are out of scope. They are materialized views with `timescaledb.continuous`, and `drizzle-kit generate` rewrites views, which drops those options. Owning the `SELECT` would also make this package responsible for later column changes. Keep the custom migration from the issue (`CREATE MATERIALIZED VIEW ... WITH (timescaledb.continuous)` and `add_continuous_aggregate_policy`) and, if you query the view, declare it with Drizzle's `materializedView(...).existing()`.
390
+ - The time column cannot be an integer. Integer time needs `set_integer_now_func` and integer chunk sizes, and the policies below are intervals.
391
+ - The time column cannot be changed. An existing space partition cannot be removed or pointed at a different column or partition count. `generate` throws. Move the data in a migration you write. The down file for a migration that only added a space partition leaves that dimension in place.
392
+ - Clearing `chunkTimeInterval` is not generated. Set the new interval. The down file for a migration that set an interval for the first time leaves that interval in place.
393
+ - Removing `hypertable()` while the Drizzle table stays is an error. This package will not pretend it turned the hypertable back into a regular table. Remove the table from the Drizzle schema in the same change and `drizzle-kit` drops it, or drop it in a custom migration.
394
+ - Down SQL removes policies and turns compression off. It leaves the hypertable in place, and it does not `DROP EXTENSION timescaledb` while that hypertable still exists, because the drop would fail. `ALTER TABLE ... SET (timescaledb.compress = false)` fails if a chunk is already compressed. Decompress those chunks yourself first. `drizzle-kit migrate` does not run the down file.
395
+ - `create_hypertable` errors with `table "..." is not empty` unless `migrateData: true`. Migrating data takes a lock and rewrites the rows into chunks.
396
+ - Compression is emitted as `timescaledb.compress`, `timescaledb.compress_segmentby`, `timescaledb.compress_orderby`, and `add_compression_policy`. Current TimescaleDB still accepts those names and treats them as the columnstore. This package does not emit `timescaledb.enable_columnstore` or `add_columnstore_policy`.
397
+ - No `by_range()` / `by_hash()`, reorder policies, retention `drop_created_before`, compression `compress_created_before`, tablespaces, or sparse indexes.
398
+ - `create_hypertable` still creates its default index on the time column. That index is not in the Drizzle schema.
399
+ - Chunks live in `_timescaledb_internal`, next to the `_timescaledb_catalog` and `_timescaledb_config` schemas. `drizzle-kit push` and `drizzle-kit pull` can treat those as tables you forgot to declare. `generate` does not. The supported path is generate, then migrate.
400
+ - A later drizzle-kit migration that drops and recreates the parent (some column type changes) drops the hypertable with it. The extras snapshot already says the table is a hypertable, so this package will not emit `create_hypertable` again. Repair that kit migration by hand.
401
+ - A `{ name, schema }` parent skips the NOT NULL, type, and unique-index checks.
402
+
403
+ ## drizzle-kit push
404
+
405
+ `drizzle-kit push` does not read this package and does not run files in the migrations folder. It will not create functions, triggers, comments, extensions, partitions, or hypertables.
406
+
407
+ Kit 0.31 has no trigger diff, so push does not drop a trigger it never declared. A push that drops or recreates the table still drops that table's triggers and comments, because Postgres drops them with the table. Functions are not attached to the table and stay. Extensions are not created. An extension that installs its own tables (PostGIS) can show up as relations push wants to delete; set `extensionsFilters: ["postgis"]` in `drizzle.config.ts` for that case. Partition children show up the same way: they are tables in the database that are not in the Drizzle schema, and push can try to drop them. Timescale chunks and catalog tables show up the same way. Exclude those names with `tablesFilter` if you push, or don't push.
408
+
409
+ The supported path is `drizzle-kit generate`, then `drizzle-pg-extras generate`, then `drizzle-kit migrate`. If you use push for tables, apply the extras yourself with `renderIdempotent` (or by running the latest up file) after a push that recreated a table.
410
+
411
+ ## Compatibility
412
+
413
+ | | |
414
+ | --- | --- |
415
+ | drizzle-orm | `>=0.36.4` and 1.0. Tested with 0.45.3 and 1.0.0-rc.5. Drizzle 0.45 and v1.0.0-rc.5 still do not generate functions, triggers, comments, extensions, partitions, or hypertables. |
416
+ | drizzle-kit | `>=0.31.0` journal format. Tested with 0.31.11: `migrate` applies the file, and the next `generate` reports no schema changes. |
417
+ | drizzle-kit 1.0 rc | Writes the folder-per-migration layout with an empty diff snapshot, tested through `drizzle-kit generate`, `check` and `migrate` on 1.0.0-rc.5. A drizzle-kit 0.x journal folder still gets journal entries; upgrade it with `drizzle-kit up` before moving to 1.0. |
418
+ | PostgreSQL | 14 or newer (`CREATE OR REPLACE TRIGGER`). Tested on 16. |
419
+ | TimescaleDB | Hypertables, compression settings, retention policies, and compression policies. Tested with TimescaleDB 2.32 on PostgreSQL 16. CI uses `timescale/timescaledb:latest-pg16`. |
420
+ | Node.js | 18 or newer. ESM and CJS builds. |
421
+
422
+ ## What it does not do yet
423
+
424
+ - Row level security policies. drizzle-kit already generates policies. The partition conversion copies policies that already exist on a parent; it does not author new ones.
425
+ - Creating views and materialized views. drizzle-kit does that. This package comments them and can put triggers on a view. Timescale continuous aggregates are included in that, on purpose. See [Timescale limits](#timescale-limits).
426
+ - `DEFERRABLE` on `UNIQUE` and foreign keys. Deferrable constraint triggers are in [Triggers](#triggers).
427
+ - `OUT`, `INOUT`, and `VARIADIC` function arguments. Function comments use the `IN` argument types.
428
+ - Comments on policies, sequences, rules, or individual enum labels.
429
+ - Comments on a column-level `.unique()`, `.primaryKey()`, or `.references()`. Declare `unique()`, `primaryKey()`, or `foreignKey()` in the extra config and wrap that builder.
430
+ - An index whose key is a SQL expression needs an explicit name before it can be commented. drizzle-kit requires that name too.
431
+ - `updatedAtTrigger`'s generated function has no comment of its own. Comment the trigger, or declare the function with `pgFunction` and comment that.
432
+ - Call `.as()` or `.existing()` before `withComment` on a view, and `.on()` before `withComment` on an index or unique constraint.
433
+ - Pulling the live database back into the snapshot. The diff is against `_pg-extras.json`, not `pg_catalog`.
434
+ - MySQL, SQLite, and SingleStore.
435
+ - Creating the schema named in `WITH SCHEMA`. The schema has to exist (drizzle-kit can create it).
436
+ - Clearing an extension version pin, or moving an extension back to "no schema clause". Set the new version or schema explicitly. `ALTER EXTENSION … UPDATE` still depends on that extension shipping a downgrade path.
437
+ - Editing migrations that have already been applied. Generate a new file.
438
+
439
+ ## CLI
440
+
441
+ ```text
442
+ drizzle-pg-extras generate [--config drizzle.config.ts] [--name touch_updated_at]
443
+ drizzle-pg-extras check [--config drizzle.config.ts]
444
+ ```
445
+
446
+ ## Development
447
+
448
+ ```sh
449
+ npm install
450
+ npm test
451
+ npm run typecheck
452
+ npm run lint
453
+ ```
454
+
455
+ Unit tests cover SQL generation and the snapshot diff, including comments, trigger rules, partition bounds, and hypertable SQL. `POSTGRES_URL` points the Postgres integration tests at a real server. One runs `drizzle-kit migrate`, checks that the trigger fires, and that comments on the table, column, enum, view, function, trigger, index, constraint, and extension exist. Another checks a deferred constraint trigger, transition tables, `INSTEAD OF` on a view, `UPDATE OF` / `WHEN`, and `DISABLE TRIGGER`. The partition test checks range, list, and hash routing, attach, the empty-table guard, and the down file. `TIMESCALE_URL` points the Timescale test at a server with the extension. It checks `create_hypertable`, compression, both policies, a second generate that changes the chunk interval, the down file, and that `drizzle-kit generate` reports no schema changes. CI keeps the Postgres 16 job as it was and runs the Timescale test in a separate job on `timescale/timescaledb:latest-pg16`.
456
+
457
+ ## License
458
+
459
+ MIT