@systemfsoftware/timescale-drizzle 0.8.0 → 0.10.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/README.md +286 -228
- package/dist/cli.js +35 -3
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +90 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -1
- package/dist/index.d.ts +31 -1
- package/dist/index.js +85 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,26 +1,48 @@
|
|
|
1
|
-
# timescale-drizzle
|
|
1
|
+
# @systemfsoftware/timescale-drizzle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@systemfsoftware/timescale-drizzle` lets you declare PostgreSQL and TimescaleDB objects that `drizzle-orm` and `drizzle-kit` do not model natively—functions, triggers, views, grants, comments, extensions, partitioned tables, TimescaleDB hypertables, and continuous aggregates—in TypeScript alongside your Drizzle schema and compile them into idempotent SQL migration files for `drizzle-kit`.
|
|
4
4
|
|
|
5
|
-
`drizzle-kit migrate` applies those files. This package does not patch
|
|
5
|
+
`drizzle-kit migrate` applies those generated SQL files directly. This package does not patch `drizzle-orm` or rewrite migrations that `drizzle-kit` already generated, so any SQL you commit remains valid even if `drizzle-kit` later adds native support for the same objects.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
**Package rename:** In 0.9.0, this package was renamed from `@systemfsoftware/drizzle-pg-extras` to `@systemfsoftware/timescale-drizzle`. The old package receives no further releases. The API (`defineExtras`, `PgExtras`, `PgExtrasError`) and the `_pg-extras.json` snapshot file format are unchanged.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
## Why Use @systemfsoftware/timescale-drizzle
|
|
10
10
|
|
|
11
|
-
|
|
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) |
|
|
11
|
+
`drizzle-orm` (1.0.0-rc.6, with PR #4844 still unmerged) leaves several core PostgreSQL and TimescaleDB features open as feature requests:
|
|
18
12
|
|
|
19
|
-
|
|
13
|
+
| Missing PostgreSQL / TimescaleDB Feature | Upstream Request |
|
|
14
|
+
| -------------------------------------------------------------------------------------- | ------------------ |
|
|
15
|
+
| `CREATE FUNCTION` / `CREATE TRIGGER` | `drizzle-orm#843` |
|
|
16
|
+
| `COMMENT ON` tables, columns, enums, views, routines, indexes, constraints, extensions | `drizzle-orm#886` |
|
|
17
|
+
| `CREATE EXTENSION` | `drizzle-orm#2124` |
|
|
18
|
+
| Partitioned tables | `drizzle-orm#2854` |
|
|
19
|
+
| TimescaleDB hypertables | `drizzle-orm#2962` |
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Single-purpose packages such as `drizzle-triggers`, `@onozaty/drizzle-db-comments-generator`, and `drizzle-partition` each cover one piece. `@systemfsoftware/timescale-drizzle` combines functions, triggers, views, grants, comments, extensions, partitioning, TimescaleDB hypertables, and continuous aggregates in one schema—and unlike `drizzle-partition`, it appends a new migration instead of rewriting existing `CREATE TABLE` files written by `drizzle-kit`.
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
Install `@systemfsoftware/timescale-drizzle` from npm:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm install @systemfsoftware/timescale-drizzle
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
nix.systemfsoftware.com is the package registry for this project's Nix outputs: nix build pulls them from its binary cache, and npm publishes the library.
|
|
32
|
+
|
|
33
|
+
### Requirements
|
|
34
|
+
|
|
35
|
+
- **Node.js:** 20.19 or newer (ships both ESM and CJS builds).
|
|
36
|
+
- **`drizzle-orm`:** `>=1.0.0-rc.6` (peer dependency; Drizzle 0.x is not supported).
|
|
37
|
+
- **`drizzle-kit`:** `>=1.0.0-rc.6` (optional; needed only to generate table migrations and apply migrations with `drizzle-kit migrate`).
|
|
38
|
+
- **PostgreSQL:** 14 or newer (`CREATE OR REPLACE TRIGGER`).
|
|
39
|
+
- **TimescaleDB:** required only if you declare hypertables or continuous aggregates.
|
|
40
|
+
|
|
41
|
+
## Quick Start
|
|
42
|
+
|
|
43
|
+
Export your extensions, functions, triggers, comments, views, grants, partitions, hypertables, and continuous aggregates from the same schema files configured in `drizzle.config.ts`.
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
24
46
|
import { pgExtension, updatedAtTrigger, withComment } from '@systemfsoftware/timescale-drizzle'
|
|
25
47
|
import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core'
|
|
26
48
|
|
|
@@ -38,42 +60,7 @@ export const users = withComment(
|
|
|
38
60
|
export const touchUsers = updatedAtTrigger(users, users.updatedAt)
|
|
39
61
|
```
|
|
40
62
|
|
|
41
|
-
|
|
42
|
-
drizzle-kit generate && timescale-drizzle generate && drizzle-kit migrate
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
`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:
|
|
46
|
-
|
|
47
|
-
```ts
|
|
48
|
-
export const setUpdatedAt = pgFunction('set_updated_at', {
|
|
49
|
-
returns: 'trigger',
|
|
50
|
-
language: 'plpgsql',
|
|
51
|
-
body: 'BEGIN NEW.updated_at = now(); RETURN NEW; END;',
|
|
52
|
-
})
|
|
53
|
-
|
|
54
|
-
export const touchUsers = pgTrigger('users_set_updated_at', {
|
|
55
|
-
table: users,
|
|
56
|
-
timing: 'before',
|
|
57
|
-
events: ['update'],
|
|
58
|
-
columns: [users.email], // UPDATE OF, and the column must belong to `users`
|
|
59
|
-
when: ({ OLD, NEW }) => sql`${OLD.email} IS DISTINCT FROM ${NEW.email}`,
|
|
60
|
-
function: setUpdatedAt,
|
|
61
|
-
})
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
`columns` is `UPDATE OF`. `when` is rendered to text and scanned when `pgTrigger` runs. [Triggers](#triggers) lists what that scan rejects and what is left for Postgres. Constraint triggers, transition tables, `INSTEAD OF` on a view, and `enabled: false` are in that section too.
|
|
65
|
-
|
|
66
|
-
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`).
|
|
67
|
-
|
|
68
|
-
## Install
|
|
69
|
-
|
|
70
|
-
```sh
|
|
71
|
-
npm install @systemfsoftware/timescale-drizzle
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
Peer dependency: `drizzle-orm` `>=1.0.0-rc.6`. `drizzle-kit` `>=1.0.0-rc.6` is optional and only needed to apply migrations. Node.js 20.19 or newer. Drizzle 0.x is not supported; see [Compatibility](#compatibility).
|
|
75
|
-
|
|
76
|
-
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`).
|
|
63
|
+
Add scripts to `package.json` and run `drizzle-kit generate`, `timescale-drizzle generate`, and `drizzle-kit migrate`:
|
|
77
64
|
|
|
78
65
|
```json
|
|
79
66
|
{
|
|
@@ -85,35 +72,64 @@ Put the definitions in the same files your `drizzle.config.ts` `schema` already
|
|
|
85
72
|
}
|
|
86
73
|
```
|
|
87
74
|
|
|
88
|
-
|
|
75
|
+
```bash
|
|
76
|
+
drizzle-kit generate && timescale-drizzle generate && drizzle-kit migrate
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The first `timescale-drizzle generate` writes a migration folder. Subsequent runs write nothing until a declaration changes. Only the diff is emitted, and generated statements are idempotent (`CREATE OR REPLACE`, `IF NOT EXISTS`, `DROP … IF EXISTS`).
|
|
89
80
|
|
|
90
|
-
|
|
81
|
+
### Migration Ordering Rules
|
|
91
82
|
|
|
92
|
-
|
|
83
|
+
- **Tables before dependents:** Run `drizzle-kit generate` before `timescale-drizzle generate` whenever a trigger, comment, partition, or hypertable targets a table so the table migration sorts earlier in the migrations folder.
|
|
84
|
+
- **Extensions before dependent column types:** If a table column type depends on an extension (such as PostGIS), declare and generate the extension migration before running the first `drizzle-kit generate`. `timescale-drizzle` only appends migrations and never inserts a migration before one you have already committed.
|
|
93
85
|
|
|
94
|
-
|
|
86
|
+
## CLI
|
|
87
|
+
|
|
88
|
+
The CLI loads the file given by `--config` (default `drizzle.config.ts`), so its `schema` glob decides which files are read.
|
|
95
89
|
|
|
90
|
+
The `timescale-drizzle` binary reads `dialect`, `schema`, `out`, `casing`, and `breakpoints` from your Drizzle config file.
|
|
91
|
+
|
|
92
|
+
```plaintext
|
|
93
|
+
timescale-drizzle generate [--config drizzle.config.ts] [--name pg_extras]
|
|
94
|
+
timescale-drizzle check [--config drizzle.config.ts]
|
|
96
95
|
```
|
|
96
|
+
|
|
97
|
+
| Command / Option | Description |
|
|
98
|
+
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
99
|
+
| `generate` | Scans exported extras in your schema files, diffs against `_pg-extras.json`, and writes a new migration folder if definitions changed. |
|
|
100
|
+
| `check` | Exits with code 1 when definitions changed without a generated migration. Use this command in CI. |
|
|
101
|
+
| `--config, -c <file>` | Path to the Drizzle configuration file (default: `drizzle.config.ts`). |
|
|
102
|
+
| `--name <name>` | Suffix for the generated migration folder name (default: `pg_extras`). |
|
|
103
|
+
|
|
104
|
+
## Migration File Layout
|
|
105
|
+
|
|
106
|
+
Each folder name is a UTC timestamp, so folders sort in the order they were written.
|
|
107
|
+
|
|
108
|
+
`drizzle-kit` (`>=1.0.0-rc.6`) stores one UTC-timestamped folder per migration, and `timescale-drizzle generate` writes the same folder layout:
|
|
109
|
+
|
|
110
|
+
```plaintext
|
|
97
111
|
drizzle/
|
|
98
112
|
20261118090000_users/ written by drizzle-kit generate
|
|
99
113
|
20261118090100_pg_extras/
|
|
100
114
|
migration.sql applied by drizzle-kit migrate
|
|
101
|
-
down.sql not applied by drizzle-kit
|
|
102
|
-
snapshot.json empty diff
|
|
103
|
-
_pg-extras.json full extras snapshot
|
|
115
|
+
down.sql reverse diff (not applied by drizzle-kit)
|
|
116
|
+
snapshot.json empty diff chaining prevIds to the users snapshot
|
|
117
|
+
_pg-extras.json full extras snapshot (commit this file)
|
|
104
118
|
```
|
|
105
119
|
|
|
106
|
-
|
|
120
|
+
- **`snapshot.json`:** Matches the output of `drizzle-kit generate --custom` for a migration with no table schema change (`type: "diff"`, a new `id`, `prevIds` pointing to the previous snapshot, and empty deltas). Subsequent `drizzle-kit generate` runs continue diffing your Drizzle tables normally. Generated folders always sort after the latest folder—even within the same second—so `drizzle-kit` never sees two base snapshots. When run in an empty migrations directory, no `snapshot.json` is written; `drizzle-kit` writes its base snapshot in the next folder.
|
|
121
|
+
- **`_pg-extras.json`:** Tracks the full state of your declared extras across migrations. Commit this file to version control; `drizzle-kit` ignores it.
|
|
122
|
+
- **`migration.sql`:** Up SQL split on `--> statement-breakpoint`, matching what `drizzle-kit migrate` and `migrate()` from `drizzle-orm` expect.
|
|
123
|
+
- **`down.sql`:** Reverse diff (restoring a prior function body, dropping a newly added trigger, emitting `COMMENT … IS NULL` for a removed comment). `drizzle-kit migrate` does not run `down.sql`, and running it manually does not remove the tracking row in `__drizzle_migrations`. To roll back manually, execute `down.sql`, delete the migration folder, and delete its row from `__drizzle_migrations`.
|
|
124
|
+
- **Legacy 0.x folders:** Directories created by `drizzle-kit` 0.x (containing `meta/_journal.json` or snapshots without `type`) are refused before writing files. Convert them first with `drizzle-kit up`.
|
|
107
125
|
|
|
108
|
-
|
|
126
|
+
## Programmatic API
|
|
109
127
|
|
|
110
|
-
|
|
128
|
+
**Mechanism:** `defineExtras` gathers the declarations, so `generate` writes the migration folder from them, and `renderIdempotent` returns the same SQL as one script.
|
|
111
129
|
|
|
112
|
-
|
|
130
|
+
You can build and render extras directly in TypeScript without using the CLI:
|
|
113
131
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
```ts
|
|
132
|
+
```typescript
|
|
117
133
|
import {
|
|
118
134
|
defineExtras,
|
|
119
135
|
generate,
|
|
@@ -132,37 +148,40 @@ const extras = defineExtras({
|
|
|
132
148
|
|
|
133
149
|
generate({ extras, out: './drizzle', name: 'touch_updated_at' })
|
|
134
150
|
|
|
135
|
-
// Full idempotent script
|
|
151
|
+
// Full idempotent script without drops (useful after drizzle-kit push)
|
|
136
152
|
console.log(renderIdempotent(extras))
|
|
137
153
|
```
|
|
138
154
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
|
142
|
-
|
|
|
143
|
-
| `
|
|
144
|
-
| `
|
|
145
|
-
| `
|
|
146
|
-
| `
|
|
147
|
-
| `
|
|
148
|
-
| `
|
|
149
|
-
| `
|
|
150
|
-
| `
|
|
151
|
-
| `
|
|
152
|
-
| `
|
|
153
|
-
| `
|
|
154
|
-
| `
|
|
155
|
-
| `
|
|
156
|
-
| `
|
|
157
|
-
| `
|
|
158
|
-
|
|
159
|
-
`
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
155
|
+
### Exports Reference
|
|
156
|
+
|
|
157
|
+
| Export | Purpose |
|
|
158
|
+
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
159
|
+
| `pgFunction(name, config)` | Declares a `plpgsql` or `sql` function in a schema (`schema: 'app'` or a Drizzle `pgSchema`). Supports `in`, `inout`, `variadic`, and `out` arguments with SQL defaults, and `returns` as a type, `{ kind: 'table', columns }`, or `{ kind: 'setof', type }`. |
|
|
160
|
+
| `pgTrigger(name, config)` | Declares a trigger on a Drizzle table, `pgView()`, or `{ name, schema }`. Supports `columns` (`UPDATE OF`), `when`, `constraint`, `referencing`, and `enabled: false`. |
|
|
161
|
+
| `updatedAtTrigger(table, column)` | Creates a `BEFORE UPDATE` trigger setting a `date`, `time`, or `timestamp` column to `now()`. Tables sharing the same database column name share one `set_<column>` function. |
|
|
162
|
+
| `pgExtension(name, options)` | Emits `CREATE EXTENSION IF NOT EXISTS` with optional `schema`, `version`, and `cascade`. |
|
|
163
|
+
| `withComment(target, text)` | Attaches a `COMMENT ON` declaration to a table, column builder, enum, finished view or materialized view, `pgFunction`, trigger, extension, or an `index` / `unique` / `check` / `primaryKey` / `foreignKey` builder. Returns the target unchanged. |
|
|
164
|
+
| `commentOn(target, text)` | Attaches `COMMENT ON` to an existing table, column, enum, view, function, trigger, or extension reference. Use `withComment` for indexes and constraints inside a table callback. |
|
|
165
|
+
| `partitionedTable(table, config)` | Marks a Drizzle table as `range`, `list`, or `hash` partitioned and converts the empty table during migration. |
|
|
166
|
+
| `pgPartition(name, config)` | Emits `CREATE TABLE ... PARTITION OF` with `from`/`to` range bounds, `in` list values, `modulus`/`remainder` hash bounds, or `default: true`. |
|
|
167
|
+
| `pgAttachPartition(table, config)` | Emits `ALTER TABLE ... ATTACH PARTITION` for an existing Drizzle-managed table. |
|
|
168
|
+
| `pgDetachPartition(table, config)` | Emits `ALTER TABLE ... DETACH PARTITION` while keeping the detached table. |
|
|
169
|
+
| `hypertable(table, config)` | Emits `create_hypertable` with `by_range` and `if_not_exists => TRUE`, plus optional columnstore settings and retention, columnstore, and reorder policies. Requires `pgExtension('timescaledb')`. |
|
|
170
|
+
| `viewDefinition(view, config)` | Emits `CREATE OR REPLACE VIEW` for a Drizzle `pgView(...).existing()` definition. |
|
|
171
|
+
| `pgGrant(config)` | Emits `GRANT` on a table, view, function, or schema, optionally guarded by `onlyIfRoleExists: true`. |
|
|
172
|
+
| `continuousAggregate(view, config)` | Emits `CREATE MATERIALIZED VIEW ... WITH (timescaledb.continuous)` from a query, plus refresh, columnstore, and retention policies. |
|
|
173
|
+
| `defineExtras` / `collectExtras` | Bundles extra definitions manually (`defineExtras`) or scans exported definitions from a module (`collectExtras`). |
|
|
174
|
+
| `generate` / `diffSnapshots` / `snapshotExtras` | Computes snapshot diffs against `_pg-extras.json` and writes migration files. |
|
|
175
|
+
| `renderIdempotent` | Renders a create-or-replace SQL script for all currently declared objects without `DROP` statements. |
|
|
176
|
+
| `PgExtras` / `PgExtrasError` | TypeScript types and error class exported for programmatic consumers. |
|
|
177
|
+
|
|
178
|
+
## Casing, Function Overloads, and Comments
|
|
179
|
+
|
|
180
|
+
- **Identifier casing:** `casing` from `drizzle.config.ts` is applied to key-named columns (`updatedAt` with `snake_case` becomes `updated_at`), matching `drizzle-kit`. Explicit database column names are preserved as written.
|
|
181
|
+
- **Function signatures:** A function's identity is `schema.name(arg types)`, allowing overloaded functions to coexist. Changes to a function's body, volatility, security, or `search_path` emit `CREATE OR REPLACE`, preserving its OID and keeping dependent triggers intact. Changing argument types or return types emits `DROP FUNCTION` followed by `CREATE` and recreates dependent triggers around it, because PostgreSQL does not allow `CREATE OR REPLACE` to alter a return type.
|
|
182
|
+
- **Comments lifecycle:** Removed comments emit `COMMENT … IS NULL`, except when the target table, column, enum, view, index, constraint, function, trigger, or extension is dropped in the same change. Removing a column referenced in a trigger's `UPDATE OF` or `WHEN` clause requires two `generate` cycles: update the trigger first, then drop the column.
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
166
185
|
import { pgFunction, withComment } from '@systemfsoftware/timescale-drizzle'
|
|
167
186
|
import { sql } from 'drizzle-orm'
|
|
168
187
|
import { check, index, pgEnum, pgTable, pgView, serial, text, unique } from 'drizzle-orm/pg-core'
|
|
@@ -194,22 +213,26 @@ export const setUpdatedAt = withComment(
|
|
|
194
213
|
)
|
|
195
214
|
```
|
|
196
215
|
|
|
197
|
-
|
|
216
|
+
When commenting an enum, view, index, or constraint, run `drizzle-kit generate` before `timescale-drizzle generate` so the object exists before `COMMENT ON` runs. Subsequent `drizzle-kit generate` runs report no schema drift.
|
|
198
217
|
|
|
199
218
|
## Triggers
|
|
200
219
|
|
|
201
|
-
|
|
220
|
+
`pgTrigger` defines custom `BEFORE`, `AFTER`, and `INSTEAD OF` triggers, deferrable constraint triggers, statement transition tables, and disabled triggers alongside your Drizzle tables and views.
|
|
202
221
|
|
|
203
|
-
```
|
|
204
|
-
export const
|
|
222
|
+
```typescript
|
|
223
|
+
export const setUpdatedAt = pgFunction('set_updated_at', {
|
|
205
224
|
returns: 'trigger',
|
|
206
225
|
language: 'plpgsql',
|
|
207
|
-
body:
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
226
|
+
body: 'BEGIN NEW.updated_at = now(); RETURN NEW; END;',
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
export const touchUsers = pgTrigger('users_set_updated_at', {
|
|
230
|
+
table: users,
|
|
231
|
+
timing: 'before',
|
|
232
|
+
events: ['update'],
|
|
233
|
+
columns: [users.email], // UPDATE OF; column must belong to `users`
|
|
234
|
+
when: ({ OLD, NEW }) => sql`${OLD.email} IS DISTINCT FROM ${NEW.email}`,
|
|
235
|
+
function: setUpdatedAt,
|
|
213
236
|
})
|
|
214
237
|
|
|
215
238
|
export const balancesAmount = pgTrigger('balances_amount', {
|
|
@@ -246,34 +269,28 @@ export const profilesGuard = pgTrigger('profiles_guard', {
|
|
|
246
269
|
})
|
|
247
270
|
```
|
|
248
271
|
|
|
249
|
-
`constraint: true`
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
`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.
|
|
272
|
+
- **Constraint triggers (`constraint`):** Addresses deferrable trigger cases (`drizzle-orm#1429`). `constraint: true` emits `CREATE CONSTRAINT TRIGGER ... NOT DEFERRABLE`. `deferrable: true` defaults to `INITIALLY IMMEDIATE`, `initially: 'deferred'` requires `deferrable: true`, and `from` emits `FROM <referenced_table>`. Because PostgreSQL has no `CREATE OR REPLACE` for constraint triggers, they are emitted as `DROP TRIGGER IF EXISTS` followed by `CREATE` (and any trigger comment is re-emitted).
|
|
273
|
+
- **Transition tables (`referencing`):** Emits `REFERENCING OLD TABLE AS ... NEW TABLE AS ...` with quoted identifiers so the trigger function can query `oldTable` (`UPDATE`/`DELETE`) or `newTable` (`INSERT`/`UPDATE`) as a relation. Supports a single event with either `FOR EACH ROW` or `FOR EACH STATEMENT`.
|
|
274
|
+
- **Enable/disable (`enabled`):** `enabled: false` appends `ALTER TABLE ... DISABLE TRIGGER`. Switching back to `enabled: true` emits `ENABLE TRIGGER`. Because `CREATE OR REPLACE` re-enables a trigger, modifying a disabled trigger re-emits `DISABLE TRIGGER`.
|
|
275
|
+
- **`when` validation:** Accepts a string, a `sql` fragment, or `` ({ OLD, NEW }) => sql`…` `` (where `OLD` and `NEW` are typed to the table's columns and render as `OLD."col"` / `NEW."col"`). `pgTrigger` strips a trailing `;` and rejects expressions containing another `;`, `INSTEAD OF` timing, `SELECT` or `EXISTS`, `OLD` or `NEW` on statement triggers, `OLD` when events include `INSERT`, or `NEW` when events include `DELETE`. The lexical scan skips comments, quoted strings, quoted identifiers, and dollar-quoted blocks, and runs again when rendering snapshots.
|
|
254
276
|
|
|
255
|
-
|
|
277
|
+
### Trigger Limits
|
|
256
278
|
|
|
257
|
-
|
|
279
|
+
- Constraint triggers must be `AFTER` and `FOR EACH ROW` on a table; `WHEN` is evaluated at row modification time even when deferred.
|
|
280
|
+
- `UNIQUE` and `FOREIGN KEY` table constraints remain owned by `drizzle-kit`; `from` does not create a foreign key.
|
|
281
|
+
- Transition tables require an `AFTER` trigger on a table with a single event (`INSERT`, `UPDATE`, or `DELETE`) and cannot be combined with `UPDATE OF`, `TRUNCATE`, `constraint`, or views.
|
|
282
|
+
- `INSTEAD OF` triggers require a view, `FOR EACH ROW`, and cannot use `WHEN`, `UPDATE OF`, or `TRUNCATE`.
|
|
283
|
+
- `BEFORE` and `AFTER` triggers on views require `forEach: 'statement'`. Materialized views cannot have triggers.
|
|
284
|
+
- `ALTER TABLE ... DISABLE TRIGGER` is unsupported on views, so `enabled: false` is rejected for views and `INSTEAD OF` triggers. `ENABLE REPLICA` and `ENABLE ALWAYS` are not emitted.
|
|
285
|
+
- Passing `{ name, schema }` skips Drizzle table/view metadata checks; PostgreSQL validates the target at migration time.
|
|
286
|
+
- Row-level transition triggers on partitioned tables are rejected by PostgreSQL during migration; foreign tables are not detected through `{ name, schema }`.
|
|
287
|
+
- View columns are matched by view name and column name; Drizzle view column aliases do not carry schema names, so two views sharing a name in different schemas are not distinguished.
|
|
258
288
|
|
|
259
|
-
|
|
289
|
+
## Views and Grants
|
|
260
290
|
|
|
261
|
-
|
|
262
|
-
- `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.
|
|
263
|
-
- 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.
|
|
264
|
-
- `INSTEAD OF` is a view trigger, `FOR EACH ROW`, without `WHEN`, without `UPDATE OF`, and without `TRUNCATE`.
|
|
265
|
-
- `BEFORE` and `AFTER` on a view are `forEach: "statement"`. Materialized views cannot have triggers.
|
|
266
|
-
- `WHEN` is the text scan above: the words `SELECT` or `EXISTS`, `OLD` or `NEW` on a statement trigger, `OLD` when the events include `INSERT`, and `NEW` when the events include `DELETE`.
|
|
267
|
-
- `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.
|
|
268
|
-
- 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.
|
|
269
|
-
- Row-level transition triggers on a partition are rejected by Postgres when the migration runs. Foreign tables are not detected through `{ name, schema }`.
|
|
270
|
-
- 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.
|
|
291
|
+
`viewDefinition` manages SQL views that `drizzle-kit` cannot express—such as lateral joins, set-returning functions, or window clauses—by pairing a Drizzle `pgView(...).existing()` stub with a raw SQL query, while `pgGrant` manages role privileges.
|
|
271
292
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
A view whose query uses Postgres that Drizzle's query builder cannot express (lateral joins, set-returning functions, window clauses) is declared as a Drizzle view with `.existing()`, so drizzle-kit leaves it alone, and given its query here. Interpolated tables, views, and functions render schema-qualified, so the schema name lives in one place.
|
|
275
|
-
|
|
276
|
-
```ts
|
|
293
|
+
```typescript
|
|
277
294
|
import { pgFunction, pgGrant, viewDefinition } from '@systemfsoftware/timescale-drizzle'
|
|
278
295
|
import { sql } from 'drizzle-orm'
|
|
279
296
|
import { integer, pgSchema, text, timestamp } from 'drizzle-orm/pg-core'
|
|
@@ -305,21 +322,18 @@ export const reporting = [
|
|
|
305
322
|
]
|
|
306
323
|
```
|
|
307
324
|
|
|
308
|
-
Views are created in
|
|
309
|
-
|
|
310
|
-
`onlyIfRoleExists` wraps
|
|
311
|
-
|
|
312
|
-
`RETURNS TABLE` cannot be combined with `out` or `inout` arguments, and only `out` arguments can follow a `variadic` one. A function's identity uses its `in`, `inout`, and `variadic` argument types, so adding an `out` argument is a new signature.
|
|
325
|
+
- **Dependency ordering:** Views are created in topological order after the functions and upstream views they reference. Changing a view's query drops and recreates that view along with any declared views that read from it, re-applying their comments and grants. Removing a view while another declared view still reads from it is refused unless you update or remove the dependent view in the same change.
|
|
326
|
+
- **View options:** `securityInvoker`, `securityBarrier`, and `checkOption` map to the corresponding PostgreSQL `WITH (...)` view options.
|
|
327
|
+
- **Grants and revokes:** `onlyIfRoleExists: true` wraps `GRANT` in a `DO` block checking `pg_roles` so migrations succeed in environments where optional roles do not exist. Grants to `PUBLIC` are rejected. Removing privileges from `pgGrant` emits `REVOKE`.
|
|
328
|
+
- **Function argument rules:** `RETURNS TABLE` cannot be combined with `out` or `inout` arguments, and only `out` arguments may follow a `variadic` argument. Function identity is determined by `in`, `inout`, and `variadic` argument types.
|
|
313
329
|
|
|
314
330
|
## Partitioning
|
|
315
331
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
`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 `timescale-drizzle 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.
|
|
332
|
+
`partitionedTable()` keeps your parent table in your Drizzle schema—so `drizzle-kit` continues owning columns, indexes, and foreign keys—and appends a migration that converts the empty table into a partitioned parent (`RANGE`, `LIST`, or `HASH`).
|
|
319
333
|
|
|
320
|
-
|
|
334
|
+
PostgreSQL only accepts `PARTITION BY` inside `CREATE TABLE`, not `ALTER TABLE`. Rather than rewriting `drizzle-kit`'s generated `CREATE TABLE` file, `timescale-drizzle` rebuilds the table when empty and raises an error if the table already contains rows. Run `drizzle-kit generate`, then `timescale-drizzle generate`, then `drizzle-kit migrate` before loading data.
|
|
321
335
|
|
|
322
|
-
```
|
|
336
|
+
```typescript
|
|
323
337
|
import { partitionedTable, pgAttachPartition, pgPartition } from '@systemfsoftware/timescale-drizzle'
|
|
324
338
|
import { integer, pgTable, primaryKey, serial, text, timestamp } from 'drizzle-orm/pg-core'
|
|
325
339
|
|
|
@@ -333,7 +347,7 @@ export const events = pgTable('events', {
|
|
|
333
347
|
])
|
|
334
348
|
|
|
335
349
|
export const eventsByTime = partitionedTable(events, {
|
|
336
|
-
method: 'range', //
|
|
350
|
+
method: 'range', // 'list' or 'hash'
|
|
337
351
|
columns: [events.createdAt],
|
|
338
352
|
})
|
|
339
353
|
|
|
@@ -364,41 +378,36 @@ export const attachArchive = pgAttachPartition(eventsArchive, {
|
|
|
364
378
|
})
|
|
365
379
|
|
|
366
380
|
// Later, instead of attachArchive:
|
|
367
|
-
// export const detachArchive = pgDetachPartition(eventsArchive, { parent: events })
|
|
381
|
+
// export const detachArchive = pgDetachPartition(eventsArchive, { parent: events })
|
|
368
382
|
```
|
|
369
383
|
|
|
370
|
-
`pgPartition`
|
|
384
|
+
- **Partition bounds:** `pgPartition` emits `CREATE TABLE ... PARTITION OF`. Range bounds use `from` and `to` (including unquoted `MINVALUE` and `MAXVALUE` keywords); list bounds use `in` (tuples when partitioning on multiple columns); hash bounds use `modulus` and `remainder`. Export both the parent `partitionedTable()` and all child partitions.
|
|
385
|
+
- **Constraint validation:** Every primary key and unique constraint on a Drizzle table must include all partition key columns. `partitionedTable()` validates this unless the parent is passed as `{ name, schema }`.
|
|
386
|
+
- **Removal behavior:** Removing a `pgPartition` drops the child partition if empty, or detaches it with data preserved when `onRemove: 'detach'` is set. Removing `pgAttachPartition` always detaches the table because `drizzle-kit` still owns it; `pgDetachPartition` makes detachment explicit. Updating only `onRemove` updates `_pg-extras.json` on the next migration without creating a new SQL file.
|
|
387
|
+
- **Rebuild mechanics and idempotency:** The conversion runs `CREATE TABLE ... (LIKE ... INCLUDING ALL)`, restores outgoing and incoming foreign keys, triggers, row-level security policies, grants, table comments, and ownership, reassigns serial sequences via `ALTER SEQUENCE ... OWNED BY`, and renames indexes and constraints back to the names `drizzle-kit` expects. Re-running the migration or `renderIdempotent` is a no-op once partitioned.
|
|
371
388
|
|
|
372
|
-
|
|
389
|
+
### Partition Limits
|
|
373
390
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
-
|
|
383
|
-
-
|
|
384
|
-
- Hash parents cannot have a `DEFAULT` partition. Postgres rejects it.
|
|
385
|
-
- 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.
|
|
386
|
-
- 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.
|
|
387
|
-
- No expression keys such as `PARTITION BY RANGE (date_trunc('month', created_at))`, no sub-partitions, and no tablespaces.
|
|
388
|
-
- No `DETACH PARTITION CONCURRENTLY`. `drizzle-kit migrate` runs each migration in a transaction, and `CONCURRENTLY` cannot run there.
|
|
389
|
-
- `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`.
|
|
390
|
-
- 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.
|
|
391
|
-
- 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.
|
|
391
|
+
- Only empty parent tables can be converted; move existing rows manually before converting.
|
|
392
|
+
- Changing the partition key or a child partition's bounds throws during `generate` so existing partition data is never dropped silently. Detach, copy rows, and re-attach in a custom migration.
|
|
393
|
+
- Hash-partitioned tables cannot have a `DEFAULT` partition.
|
|
394
|
+
- Attached tables must already match the parent's column order, `NOT NULL` constraints, unique indexes, and check constraints.
|
|
395
|
+
- Dependent views and materialized views are not rewritten automatically; drop them before converting the parent table.
|
|
396
|
+
- Expression partition keys (such as `date_trunc('month', created_at)`), sub-partitioning, and tablespaces are not supported.
|
|
397
|
+
- `DETACH PARTITION CONCURRENTLY` is not emitted because `drizzle-kit migrate` runs migrations inside a transaction.
|
|
398
|
+
- `drizzle-kit push` does not read partition definitions and may offer to drop unmanaged partition child tables; exclude them with `tablesFilter` if you use `push`.
|
|
399
|
+
- If a later `drizzle-kit` migration drops and recreates the parent table (for example on certain column type changes), child partitions are dropped with it and must be repaired manually because `_pg-extras.json` already records the table as partitioned.
|
|
400
|
+
- `down.sql` drops empty created partitions, detaches attached tables, and converts an empty parent back to a standard table, raising an error if created partitions still hold rows.
|
|
392
401
|
|
|
393
402
|
## TimescaleDB
|
|
394
403
|
|
|
395
|
-
|
|
404
|
+
The hypertable is created by `create_hypertable` in the generated migration file, so each policy is added by its own `add_*_policy` call in that same file.
|
|
396
405
|
|
|
397
|
-
|
|
406
|
+
`hypertable()` converts a standard Drizzle-managed table into a TimescaleDB hypertable using `SELECT create_hypertable(..., by_range(...), if_not_exists => TRUE)` and configures columnstore settings and background policies.
|
|
398
407
|
|
|
399
|
-
`pgExtension(
|
|
408
|
+
`pgExtension('timescaledb')` must be exported from your schema; `generate` throws if it is missing and emits `CREATE EXTENSION` before `create_hypertable` when both are created together. Run `drizzle-kit generate`, then `timescale-drizzle generate`, then `drizzle-kit migrate` before loading data.
|
|
400
409
|
|
|
401
|
-
```
|
|
410
|
+
```typescript
|
|
402
411
|
import { hypertable, pgExtension } from '@systemfsoftware/timescale-drizzle'
|
|
403
412
|
import { integer, pgTable, primaryKey, text, timestamp } from 'drizzle-orm/pg-core'
|
|
404
413
|
|
|
@@ -414,11 +423,11 @@ export const metrics = pgTable('metrics', {
|
|
|
414
423
|
|
|
415
424
|
export const metricsHypertable = hypertable(metrics, {
|
|
416
425
|
timeColumn: metrics.time,
|
|
417
|
-
chunkTimeInterval: '1 day', // omitted:
|
|
418
|
-
partitioningColumn: metrics.deviceId, // hash dimension; requires numberPartitions
|
|
426
|
+
chunkTimeInterval: '1 day', // omitted: TimescaleDB defaults to 7 days
|
|
427
|
+
partitioningColumn: metrics.deviceId, // hash space dimension; requires numberPartitions
|
|
419
428
|
numberPartitions: 4,
|
|
420
|
-
migrateData: false, // true
|
|
421
|
-
createDefaultIndexes: true, // false
|
|
429
|
+
migrateData: false, // true copies existing rows during create_hypertable
|
|
430
|
+
createDefaultIndexes: true, // false skips the default time index
|
|
422
431
|
columnstore: {
|
|
423
432
|
segmentBy: [metrics.deviceId],
|
|
424
433
|
orderBy: [{ column: metrics.time, direction: 'desc', nulls: 'last' }],
|
|
@@ -426,38 +435,60 @@ export const metricsHypertable = hypertable(metrics, {
|
|
|
426
435
|
},
|
|
427
436
|
retention: { dropAfter: '6 months', scheduleInterval: '1 day' },
|
|
428
437
|
columnstorePolicy: { after: '7 days' },
|
|
429
|
-
reorder: 'metrics_time_idx',
|
|
438
|
+
reorder: 'metrics_time_idx',
|
|
430
439
|
})
|
|
431
440
|
```
|
|
432
441
|
|
|
433
|
-
`chunkTimeInterval`, `dropAfter`, `dropCreatedBefore`, `after`, `createdBefore`, and `scheduleInterval`
|
|
442
|
+
- **Intervals and timestamps:** `chunkTimeInterval`, `dropAfter`, `dropCreatedBefore`, `after`, `createdBefore`, and `scheduleInterval` accept PostgreSQL interval strings (such as `'7 days'` or `'1 day 12 hours'`) rendered as `INTERVAL '...'`. `initialStart` renders as `TIMESTAMPTZ '...'`. Set either `dropAfter` or `dropCreatedBefore` (not both), and either `after` or `createdBefore` (not both).
|
|
443
|
+
- **Columnstore configuration:** `columnstore: {}` enables the columnstore with TimescaleDB defaults. `columnstorePolicy` requires `columnstore` to be enabled.
|
|
444
|
+
- **Schema validation:** Every primary key and unique index on a Drizzle table must include `timeColumn` (and `partitioningColumn` when configured). `timeColumn` must be `NOT NULL` with type `date`, `timestamp`, or `timestamptz`. Passing `{ name, schema }` skips Drizzle column/index checks.
|
|
445
|
+
- **Idempotency and updates:** `create_hypertable`, `add_retention_policy`, `add_columnstore_policy`, and `add_reorder_policy` use `if_not_exists => TRUE`. Updating policy intervals or `reorder` removes and re-adds the policy; updating `chunkTimeInterval` emits `set_chunk_time_interval`; adding `partitioningColumn` later emits `add_dimension`. `migrateData` and `createDefaultIndexes` apply only on initial hypertable creation.
|
|
446
|
+
|
|
447
|
+
### TimescaleDB Limits
|
|
448
|
+
|
|
449
|
+
- Integer `timeColumn` types are not supported; use `date`, `timestamp`, or `timestamptz`.
|
|
450
|
+
- Changing `timeColumn` or removing/altering an existing `partitioningColumn` or `numberPartitions` throws during `generate`.
|
|
451
|
+
- Clearing `chunkTimeInterval` is not supported; provide a replacement interval instead.
|
|
452
|
+
- Removing `hypertable()` while keeping the underlying Drizzle table throws an error. Drop the table in the Drizzle schema in the same change or drop it in a custom migration.
|
|
453
|
+
- `down.sql` removes policies, converts compressed chunks back with `convert_to_rowstore`, and disables `timescaledb.enable_columnstore`, while leaving the hypertable and `timescaledb` extension in place.
|
|
454
|
+
- `create_hypertable` fails if the target table already contains rows unless `migrateData: true` is set (which locks the table while migrating rows into chunks).
|
|
455
|
+
- Columnstore settings emit `timescaledb.enable_columnstore`, `timescaledb.segmentby`, `timescaledb.orderby`, `timescaledb.sparse_index`, and `add_columnstore_policy`. Removing all `sparseIndex` entries emits `ALTER TABLE ... RESET (timescaledb.sparse_index)` rather than setting an empty string, preventing TimescaleDB crashes on `INSERT`, `UPDATE`, and `DELETE`.
|
|
456
|
+
- Unless `createDefaultIndexes: false`, `create_hypertable` creates a default `<table>_<time_column>_idx` index that is not declared in the Drizzle schema.
|
|
457
|
+
- Chunks and metadata reside in `_timescaledb_internal`, `_timescaledb_catalog`, and `_timescaledb_config`; `drizzle-kit push` and `drizzle-kit pull` may treat those internal tables as unmanaged unless excluded.
|
|
458
|
+
- If a later `drizzle-kit` migration drops and recreates the parent table, the hypertable is dropped with it and must be repaired manually because `_pg-extras.json` already records the table as partitioned.
|
|
459
|
+
- Passing `{ name, schema }` skips `NOT NULL`, column type, and unique-index checks.
|
|
434
460
|
|
|
435
|
-
|
|
461
|
+
### Server Settings for Background Jobs
|
|
436
462
|
|
|
437
|
-
|
|
463
|
+
Every policy above runs as a TimescaleDB background job, and each running job takes one of Postgres's background worker slots (`max_worker_processes`, 8 by default). The TimescaleDB launcher, one scheduler per database and parallel query workers draw from the same slots. A job that finds none free is recorded in `timescaledb_information.job_history` as `failed to start`, not as an error, so an undersized pool stops every policy without a failing statement.
|
|
438
464
|
|
|
439
|
-
|
|
465
|
+
Declare the server the schema runs on next to its tables:
|
|
440
466
|
|
|
441
|
-
|
|
467
|
+
```ts
|
|
468
|
+
import { timescaleServer } from '@systemfsoftware/timescale-drizzle'
|
|
469
|
+
|
|
470
|
+
export const server = timescaleServer({
|
|
471
|
+
databasesWithExtension: 2, // one TimescaleDB scheduler each
|
|
472
|
+
concurrentJobs: 8,
|
|
473
|
+
parallelWorkers: 0, // the default; also turns off parallel query and parallel maintenance
|
|
474
|
+
reservedPostgresWorkers: 4, // the default; Postgres's own workers, such as the logical replication launcher
|
|
475
|
+
preloadLibraries: ['timescaledb', 'pg_stat_statements'], // defaults to ['timescaledb']
|
|
476
|
+
})
|
|
477
|
+
```
|
|
442
478
|
|
|
443
|
-
|
|
444
|
-
- 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.
|
|
445
|
-
- 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.
|
|
446
|
-
- 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.
|
|
447
|
-
- Down SQL removes policies and turns the columnstore off. It converts columnstore chunks back with `convert_to_rowstore` before it sets `timescaledb.enable_columnstore = false`. It leaves the hypertable in place, and it does not `DROP EXTENSION timescaledb` while that hypertable still exists, because the drop would fail. `drizzle-kit migrate` does not run the down file.
|
|
448
|
-
- `create_hypertable` errors with `table "..." is not empty` unless `migrateData: true`. Migrating data takes a lock and rewrites the rows into chunks.
|
|
449
|
-
- The columnstore is emitted as `timescaledb.enable_columnstore`, `timescaledb.segmentby`, `timescaledb.orderby`, `timescaledb.sparse_index`, and `add_columnstore_policy`. Removing every `sparseIndex` entry emits `ALTER TABLE ... RESET (timescaledb.sparse_index)`. The package never emits `timescaledb.sparse_index = ''`, because after it TimescaleDB 2.32.1 crashes on ordinary `INSERT`, `UPDATE` and `DELETE`.
|
|
450
|
-
- No tablespaces.
|
|
451
|
-
- `create_hypertable` creates its default index on the time column unless `createDefaultIndexes: false`. That index is not in the Drizzle schema.
|
|
452
|
-
- 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.
|
|
453
|
-
- 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.
|
|
454
|
-
- A `{ name, schema }` parent skips the NOT NULL, type, and unique-index checks.
|
|
479
|
+
`server.settings` holds `shared_preload_libraries`, `timescaledb.max_background_workers` (the schedulers plus the concurrent jobs), the three parallel-worker settings and `max_worker_processes`, derived so it covers the launcher, TimescaleDB's budget, the parallel workers and the reserved slots. `server.postgresArgs` lists them as postgres command-line arguments: `-c`, `name=value`, for each setting.
|
|
455
480
|
|
|
456
|
-
|
|
481
|
+
These settings are read only when the server starts, so no migration can apply them, and `generate` never writes them. Append `postgresArgs` to the server's command line; command-line settings also override `postgresql.conf` and `ALTER SYSTEM`. Changing one takes a restart.
|
|
457
482
|
|
|
458
|
-
`
|
|
483
|
+
`generate`, `check` and `renderIdempotent` refuse a schema that declares more than one `timescaleServer`, or that declares policies while its server allows no concurrent job. A schema that declares no server is not checked.
|
|
459
484
|
|
|
460
|
-
|
|
485
|
+
To compare a running server with the declaration, run `TIMESCALE_SERVER_SETTINGS_QUERY` with the declared names (`Object.keys(server.settings)`) as `$1` and pass the rows to `timescaleServerDrift(server, rows)`. It lists each setting the server runs differently, does not report, or has changed but not yet applied for want of a restart. It reads only `pg_settings`: it cannot see how many databases on the server load the extension, so a server with more such databases than `databasesWithExtension` gives each extra scheduler a job's slot without any drift.
|
|
486
|
+
|
|
487
|
+
## Continuous Aggregates
|
|
488
|
+
|
|
489
|
+
`continuousAggregate()` emits `CREATE MATERIALIZED VIEW ... WITH (timescaledb.continuous) AS <query> WITH NO DATA` so migrations do not block while materializing historical data. Declare the view stub with `pgMaterializedView(...).existing()` (or `pgView(...).existing()` if you attach `withComment`) so `drizzle-kit` does not overwrite the `timescaledb.continuous` storage option.
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
461
492
|
import { continuousAggregate } from '@systemfsoftware/timescale-drizzle'
|
|
462
493
|
import { doublePrecision, pgMaterializedView, text, timestamp } from 'drizzle-orm/pg-core'
|
|
463
494
|
|
|
@@ -479,61 +510,88 @@ FROM metrics GROUP BY bucket, device_id`,
|
|
|
479
510
|
})
|
|
480
511
|
```
|
|
481
512
|
|
|
482
|
-
- `source`
|
|
483
|
-
- `realTime: false` sets `timescaledb.materialized_only = true`. `chunkInterval`
|
|
484
|
-
-
|
|
485
|
-
-
|
|
486
|
-
- A change to `query`, `source` or `createGroupIndexes` drops the aggregate and creates it again empty. `generate` throws when that aggregate is the source of another one: drop the child first, generate and migrate the parent change, then declare the child again.
|
|
487
|
-
- Removing an aggregate and its source table in the same change throws. Remove the aggregate, generate and migrate, then remove the table.
|
|
488
|
-
- To comment an aggregate with `withComment`, declare it with `pgView(...).existing()`. TimescaleDB accepts `COMMENT ON VIEW` for a continuous aggregate, and a `pgMaterializedView` would emit `COMMENT ON MATERIALIZED VIEW`.
|
|
513
|
+
- **Hierarchical aggregates:** Set `source` to either a `hypertable()` or a parent `continuousAggregate()` so `generate` creates parents before children and drops children before parents.
|
|
514
|
+
- **Options and policies:** `realTime: false` sets `timescaledb.materialized_only = true`. `chunkInterval` configures the aggregate chunk interval (updatable, cannot be cleared). `createGroupIndexes` maps to `timescaledb.create_group_indexes`. `refreshPolicies` accepts one or more windows with `startOffset`, `endOffset`, and `scheduleInterval`, plus optional `initialStart`, `timezone`, `includeTieredData`, `bucketsPerBatch`, `maxBatchesPerExecution`, and `refreshNewestFirst`. `columnstore`, `columnstorePolicy`, and `retention` work identically to hypertables.
|
|
515
|
+
- **Recreating and removing:** Changing `query`, `source`, or `createGroupIndexes` drops and recreates the aggregate empty, and throws if a child continuous aggregate depends on it (remove the child first, migrate the parent change, then re-add the child). Removing an aggregate and its source table in the same change throws; remove the aggregate first.
|
|
516
|
+
- **Commenting aggregates:** Declare the aggregate with `pgView(...).existing()` when wrapping with `withComment()`, because TimescaleDB expects `COMMENT ON VIEW` for continuous aggregates rather than `COMMENT ON MATERIALIZED VIEW`.
|
|
489
517
|
|
|
490
|
-
## drizzle-kit push
|
|
518
|
+
## Using with drizzle-kit push
|
|
491
519
|
|
|
492
|
-
|
|
520
|
+
**Mechanism:** declarations reach the database only through the migration files `timescale-drizzle generate` writes, so `drizzle-kit push` needs the output of `renderIdempotent` instead.
|
|
493
521
|
|
|
494
|
-
drizzle-kit
|
|
522
|
+
`drizzle-kit push` does not read `@systemfsoftware/timescale-drizzle` declarations or execute SQL files in your migrations folder.
|
|
495
523
|
|
|
496
|
-
|
|
524
|
+
If `drizzle-kit push` drops and recreates a table, PostgreSQL drops that table's triggers and comments while standalone functions remain.
|
|
497
525
|
|
|
498
|
-
|
|
526
|
+
Extensions that create tables (such as PostGIS), partition child tables, and TimescaleDB chunk/catalog tables (`_timescaledb_internal`, `_timescaledb_catalog`, `_timescaledb_config`) appear to `drizzle-kit push` as unmanaged tables. Configure `extensionsFilters` (for example `extensionsFilters: ['postgis']`) and `tablesFilter` in `drizzle.config.ts` if you use `push`.
|
|
499
527
|
|
|
500
|
-
|
|
528
|
+
The recommended workflow is `drizzle-kit generate` followed by `timescale-drizzle generate` and `drizzle-kit migrate`. If you use `push`, run `renderIdempotent(extras)` (or re-apply the relevant up migration) after recreating tables.
|
|
501
529
|
|
|
502
|
-
|
|
530
|
+
## Known Limitations
|
|
503
531
|
|
|
504
|
-
|
|
532
|
+
`generate` and `check` diff your TypeScript declarations against `_pg-extras.json` rather than inspecting `pg_catalog` in a live database. If `drizzle-kit` drops and recreates a table, PostgreSQL drops attached triggers, comments, partitions, or hypertable state while `_pg-extras.json` still records them, so the next `generate` writes no diff.
|
|
505
533
|
|
|
506
|
-
|
|
507
|
-
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
508
|
-
| drizzle-orm | `>=1.0.0-rc.6`. Tested with 1.0.0-rc.6, which still does not generate functions, triggers, views with raw queries, grants, comments, extensions, partitions, or hypertables. Drizzle 0.x is not supported. |
|
|
509
|
-
| drizzle-kit | `>=1.0.0-rc.6`, folder-per-migration layout. Tested with 1.0.0-rc.6: `migrate` applies the folder, and the next `generate` reports no schema changes. Convert a 0.x journal folder with `drizzle-kit up` first. |
|
|
510
|
-
| PostgreSQL | 14 or newer (`CREATE OR REPLACE TRIGGER`). Tested on 17. |
|
|
511
|
-
| TimescaleDB | Hypertables, columnstore settings and sparse indexes, retention policies, columnstore policies, reorder policies, and continuous aggregates with refresh policies. Tested on PostgreSQL 17 with the TimescaleDB that the pinned `timescale/timescaledb-ha:pg17` image ships. |
|
|
512
|
-
| Node.js | 20.19 or newer, which drizzle-kit 1.0 needs. ESM and CJS builds. |
|
|
534
|
+
`renderIdempotent(extras)` outputs an idempotent SQL script for all currently declared objects—`CREATE OR REPLACE` for functions and standard triggers, `DROP TRIGGER IF EXISTS` + `CREATE` for constraint triggers, `DISABLE TRIGGER` when `enabled: false`, `COMMENT ON`, `CREATE EXTENSION IF NOT EXISTS`, partition conversion/create/attach/detach statements, `create_hypertable(..., if_not_exists => TRUE)`, and continuous aggregates with their policies—without dropping objects removed from your schema. Run its output to restore extras after a table recreation.
|
|
513
535
|
|
|
514
|
-
|
|
536
|
+
### What It Does Not Do Yet
|
|
515
537
|
|
|
516
|
-
-
|
|
517
|
-
-
|
|
518
|
-
- `DEFERRABLE`
|
|
538
|
+
- Authoring row-level security policies (`drizzle-kit` generates RLS policies natively; partition conversion preserves existing parent policies).
|
|
539
|
+
- Managing standard materialized views other than TimescaleDB continuous aggregates (`drizzle-kit` creates standard materialized views, and `withComment` can comment them).
|
|
540
|
+
- Adding `DEFERRABLE` to `UNIQUE` or `FOREIGN KEY` constraints (use deferrable constraint triggers in `pgTrigger` instead).
|
|
519
541
|
- Comments on policies, sequences, rules, or individual enum labels.
|
|
520
|
-
- Comments on
|
|
521
|
-
-
|
|
522
|
-
-
|
|
523
|
-
-
|
|
524
|
-
-
|
|
525
|
-
- MySQL, SQLite,
|
|
526
|
-
- Creating the schema
|
|
527
|
-
- Clearing
|
|
528
|
-
-
|
|
542
|
+
- Comments on inline column `.unique()`, `.primaryKey()`, or `.references()` chains (declare `unique()`, `primaryKey()`, or `foreignKey()` in the table callback and wrap that builder with `withComment`).
|
|
543
|
+
- Comments on expression-keyed indexes without an explicit index name.
|
|
544
|
+
- Separate comments on the helper function generated by `updatedAtTrigger` (comment the trigger or define the function explicitly with `pgFunction`).
|
|
545
|
+
- Wrapping a view before `.as()` / `.existing()` or an index/unique constraint before `.on()` with `withComment`.
|
|
546
|
+
- Introspecting a live database into `_pg-extras.json`.
|
|
547
|
+
- MySQL, SQLite, or SingleStore dialects.
|
|
548
|
+
- Creating the target schema referenced by `WITH SCHEMA` in `pgExtension` (create the schema with `pgSchema` / `drizzle-kit` first).
|
|
549
|
+
- Clearing a pinned extension version or removing an extension's schema clause (`ALTER EXTENSION … UPDATE` also requires the extension to provide a downgrade script).
|
|
550
|
+
- Modifying already-applied migrations in place (always generate a new migration).
|
|
529
551
|
|
|
530
|
-
##
|
|
552
|
+
## Compatibility
|
|
531
553
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
timescale-drizzle
|
|
535
|
-
|
|
554
|
+
| Component | Supported Versions & Notes |
|
|
555
|
+
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
556
|
+
| `@systemfsoftware/timescale-drizzle` | `0.9.0` (renamed from `@systemfsoftware/drizzle-pg-extras`; ESM and CJS builds). |
|
|
557
|
+
| `drizzle-orm` | `>=1.0.0-rc.6` (peer dependency; tested with `1.0.0-rc.6`; Drizzle 0.x is not supported). |
|
|
558
|
+
| `drizzle-kit` | `>=1.0.0-rc.6` (optional, required only to apply migrations; tested with `1.0.0-rc.6`; folder-per-migration layout; convert 0.x journal folders with `drizzle-kit up` first). |
|
|
559
|
+
| PostgreSQL | 14 or newer (`CREATE OR REPLACE TRIGGER`; tested on PostgreSQL 17). |
|
|
560
|
+
| TimescaleDB | Hypertables, columnstore settings and sparse indexes, retention/columnstore/reorder policies, and continuous aggregates with refresh policies (tested with the `timescale/timescaledb-ha:pg17` image). |
|
|
561
|
+
| Node.js | 20.19 or newer (tested on Node 22 and 24). |
|
|
562
|
+
|
|
563
|
+
## Common Errors
|
|
564
|
+
|
|
565
|
+
Each message is thrown by the check that rejects the input, so the text below is what your terminal shows when that check fails.
|
|
566
|
+
|
|
567
|
+
### `config not found: <path>`
|
|
568
|
+
|
|
569
|
+
The Drizzle config file does not exist at the specified path. Pass `--config <file>` (or `-c <file>`) pointing to your `drizzle.config.ts`.
|
|
570
|
+
|
|
571
|
+
### `schema path not found: <pattern>`
|
|
572
|
+
|
|
573
|
+
No files matched the `schema` path or glob configured in `drizzle.config.ts`. Verify the `schema` setting and confirm the files exist.
|
|
574
|
+
|
|
575
|
+
### `<path> has no schema path. Set schema in the drizzle config.`
|
|
576
|
+
|
|
577
|
+
Your `drizzle.config.ts` does not define a `schema` property. Add `schema` pointing to the TypeScript files that export your Drizzle schema and extras.
|
|
578
|
+
|
|
579
|
+
### `pgGrant(): granting to PUBLIC is not supported. Grant to a named role`
|
|
580
|
+
|
|
581
|
+
`pgGrant()` rejects `to: 'PUBLIC'`. Pass a named database role string or a Drizzle `pgRole` reference instead.
|
|
582
|
+
|
|
583
|
+
### `... Use date, timestamp, or timestamptz. Integer time columns are not supported.`
|
|
584
|
+
|
|
585
|
+
`hypertable()` was configured with an integer `timeColumn`. Use a `NOT NULL` `date`, `timestamp`, or `timestamptz` column instead.
|
|
586
|
+
|
|
587
|
+
### `hypertable ...: clearing chunkTimeInterval is not supported. Set a new interval instead of removing it.`
|
|
588
|
+
|
|
589
|
+
`chunkTimeInterval` was removed from an existing `hypertable()` definition. Specify a new interval string instead of deleting the property.
|
|
590
|
+
|
|
591
|
+
### `pg extras snapshot version <n> is not supported`
|
|
592
|
+
|
|
593
|
+
`_pg-extras.json` has a snapshot version that this release cannot read. Upgrade `@systemfsoftware/timescale-drizzle` or regenerate `_pg-extras.json` with a matching version.
|
|
536
594
|
|
|
537
595
|
## License
|
|
538
596
|
|
|
539
|
-
Apache-2.0. See
|
|
597
|
+
Apache-2.0. See `LICENSE` and `NOTICE`.
|