@tailor-platform/sdk 2.1.0 → 2.3.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/CHANGELOG.md +199 -0
- package/{dist/cli/index.mjs → bin/tailor.mjs} +1 -1
- package/dist/application-BZfk4HKm.mjs +3 -0
- package/dist/{application-D77KJFKD.mjs → application-F-nl107y.mjs} +121 -27
- package/dist/application-F-nl107y.mjs.map +1 -0
- package/dist/cli/commands/deploy/tailordb/index.d.mts +2 -1
- package/dist/cli/commands/deploy/types.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +52 -22
- package/dist/cli/commands/tailordb/migrate/file-state.d.mts +1 -0
- package/dist/cli/commands/tailordb/migrate/generate.d.mts +6 -0
- package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +22 -0
- package/dist/cli/commands/tailordb/migrate/schema-checks.d.mts +2 -2
- package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +9 -2
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +30 -9
- package/dist/cli/lib.d.mts +4 -4
- package/dist/cli/lib.mjs +3 -482
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +1151 -208
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/ts-hook.mjs +52 -7
- package/dist/completion/zsh-worker.zsh +167 -4
- package/dist/configure/index.d.mts +3 -3
- package/dist/configure/index.mjs +90 -23
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/index.d.mts +3 -2
- package/dist/configure/services/tailordb/index.d.mts +2 -1
- package/dist/configure/services/tailordb/schema.d.mts +46 -46
- package/dist/configure/services/tailordb/types.d.mts +30 -4
- package/dist/configure/services/workflow/index.d.mts +2 -2
- package/dist/configure/services/workflow/wait-point.d.mts +72 -13
- package/dist/{crashreport-B5LqCTfF.mjs → crashreport-CIIfLnoO.mjs} +2 -2
- package/dist/{crashreport-B5LqCTfF.mjs.map → crashreport-CIIfLnoO.mjs.map} +1 -1
- package/dist/{crashreport-eI7ty7ok.mjs → crashreport-CINZ5dVN.mjs} +1 -1
- package/dist/errors-BVb6vYGy.mjs +89 -0
- package/dist/errors-BVb6vYGy.mjs.map +1 -0
- package/dist/kysely/index.d.mts +53 -5
- package/dist/kysely/index.mjs +7 -2
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/{logger-CXQq9YIp.mjs → logger-DSdExfor.mjs} +83 -42
- package/dist/logger-DSdExfor.mjs.map +1 -0
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/{register-ts-hook-BU18uU44.mjs → register-ts-hook-ClI226n2.mjs} +3541 -703
- package/dist/register-ts-hook-ClI226n2.mjs.map +1 -0
- package/dist/schema--xYWRGfe.mjs.map +1 -1
- package/dist/seed/index.d.mts +52 -3
- package/dist/seed/index.mjs +200 -44
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{seed-B-yckgQY.mjs → seed-xqM9WIHP.mjs} +8 -8
- package/dist/seed-xqM9WIHP.mjs.map +1 -0
- package/dist/{service-k1xy_A5G.mjs → service-C_WpbKHu.mjs} +39 -5
- package/dist/service-C_WpbKHu.mjs.map +1 -0
- package/dist/service-D1RCdzIL.mjs +3 -0
- package/dist/{service-B5WynBHQ.mjs → service-hZskxZmg.mjs} +3 -3
- package/dist/{service-B5WynBHQ.mjs.map → service-hZskxZmg.mjs.map} +1 -1
- package/dist/{service_pb-D5--My_M.mjs → service_pb-BEWj1pOV.mjs} +2 -2
- package/dist/{service_pb-D5--My_M.mjs.map → service_pb-BEWj1pOV.mjs.map} +1 -1
- package/dist/{service_pb-i8CmnQP4.mjs → service_pb-BjlhvK9E.mjs} +1 -1
- package/dist/utils/test/index.d.mts +6 -3
- package/dist/utils/test/index.mjs +25 -13
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/index.d.mts +2 -1
- package/dist/vitest/index.mjs +167 -3
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/workflow.d.mts +13 -1
- package/dist/vitest/pglite-kysely.d.mts +43 -0
- package/dist/wait-point-invoker-__oE88_P.mjs +148 -0
- package/dist/wait-point-invoker-__oE88_P.mjs.map +1 -0
- package/dist/wait-point-registry-TL99zotw.mjs +47 -0
- package/dist/wait-point-registry-TL99zotw.mjs.map +1 -0
- package/dist/{workspace_resource_pb-DXnO2AT-.mjs → workspace_resource_pb-HNIL_Vfj.mjs} +10 -2
- package/dist/{workspace_resource_pb-DXnO2AT-.mjs.map → workspace_resource_pb-HNIL_Vfj.mjs.map} +1 -1
- package/docs/cli/setup.md +14 -1
- package/docs/cli/tailordb.md +96 -28
- package/docs/cli-reference.md +15 -12
- package/docs/configuration.md +1 -1
- package/docs/github-actions.md +73 -28
- package/docs/migration/v2.md +55 -1
- package/docs/plugin/custom.md +48 -48
- package/docs/plugin/index.md +24 -24
- package/docs/services/auth.md +10 -10
- package/docs/services/executor.md +1 -1
- package/docs/services/resolver.md +2 -2
- package/docs/services/tailordb-migration.md +485 -84
- package/docs/services/tailordb.md +28 -28
- package/docs/services/workflow.md +52 -2
- package/docs/testing.md +14 -0
- package/package.json +12 -7
- package/dist/application-Af1zIqSI.mjs +0 -3
- package/dist/application-D77KJFKD.mjs.map +0 -1
- package/dist/errors-D7583Zz7.mjs +0 -58
- package/dist/errors-D7583Zz7.mjs.map +0 -1
- package/dist/logger-CXQq9YIp.mjs.map +0 -1
- package/dist/register-ts-hook-BU18uU44.mjs.map +0 -1
- package/dist/seed-B-yckgQY.mjs.map +0 -1
- package/dist/service-M7OYziQP.mjs +0 -3
- package/dist/service-k1xy_A5G.mjs.map +0 -1
- package/dist/test-env-key-D7UkZp99.mjs +0 -75
- package/dist/test-env-key-D7UkZp99.mjs.map +0 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **Beta:** The `tailordb migration` command and the migration runtime are beta features. They may introduce breaking changes in future releases. The CLI emits a beta warning on every invocation.
|
|
4
4
|
|
|
5
|
-
The migration system tracks changes to your TailorDB
|
|
5
|
+
The migration system tracks changes to your TailorDB table definitions over time and applies them to deployed workspaces with optional data transformation scripts.
|
|
6
6
|
|
|
7
7
|
For the CLI command reference, see [`tailordb migration`](../cli/tailordb.md#tailordb-migration). This document covers concepts, workflows, and operational guidance.
|
|
8
8
|
|
|
@@ -10,9 +10,9 @@ For the CLI command reference, see [`tailordb migration`](../cli/tailordb.md#tai
|
|
|
10
10
|
|
|
11
11
|
**Key Properties**
|
|
12
12
|
|
|
13
|
-
- **Local snapshot–based diff detection** — each migration is generated by diffing your current
|
|
13
|
+
- **Local snapshot–based diff detection** — each migration is generated by diffing your current table definitions against the previous snapshot stored in `migrations/<NNNN>/`.
|
|
14
14
|
- **Transaction-wrapped data migrations** — each `migrate.ts` script runs inside a database transaction on the platform; if the script throws, all changes in that migration roll back.
|
|
15
|
-
- **Automatic execution during `apply`** — `tailor deploy` detects pending migrations, runs the two-stage
|
|
15
|
+
- **Automatic execution during `apply`** — `tailor deploy` detects pending migrations, runs the two-stage table update (pre-migration → script → post-migration), and updates the migration checkpoint label.
|
|
16
16
|
- **Type-safe scripts** — the generated `db.ts` provides Kysely types that reflect the schema state **before** the migration runs, so transformations are written against the actual data shape.
|
|
17
17
|
|
|
18
18
|
**Files in `migrations/`**
|
|
@@ -39,33 +39,33 @@ migrations/
|
|
|
39
39
|
When you start with no `migrations/` directory:
|
|
40
40
|
|
|
41
41
|
1. Add the `migration` block to `tailor.config.ts` (see [Configuration](#configuration)).
|
|
42
|
-
2. Define your initial
|
|
42
|
+
2. Define your initial tables in `tailordb/`.
|
|
43
43
|
3. Generate the initial migration:
|
|
44
44
|
```bash
|
|
45
45
|
tailor tailordb migration generate
|
|
46
46
|
```
|
|
47
|
-
This creates `migrations/0000/schema.json` from your current
|
|
47
|
+
This creates `migrations/0000/schema.json` from your current tables.
|
|
48
48
|
4. Run `tailor deploy`. The migration label is set to `0000` on the deployed namespace.
|
|
49
49
|
|
|
50
50
|
### Adding migrations to an existing project
|
|
51
51
|
|
|
52
|
-
If you already have a deployed workspace whose schema matches your local
|
|
52
|
+
If you already have a deployed workspace whose schema matches your local table definitions:
|
|
53
53
|
|
|
54
54
|
1. Add the `migration` block to `tailor.config.ts`.
|
|
55
|
-
2. Run `tailor tailordb migration generate` to create `0000/schema.json` from current local
|
|
55
|
+
2. Run `tailor tailordb migration generate` to create `0000/schema.json` from current local tables.
|
|
56
56
|
3. Run `tailor deploy`. Because remote schema already matches, no script runs; only the migration label is set.
|
|
57
57
|
|
|
58
|
-
If your local
|
|
58
|
+
If your local tables and remote schema have **diverged**, reconcile them before introducing migrations — either update local tables to match remote, or accept that the first non-`0000` migration will reflect that gap.
|
|
59
59
|
|
|
60
60
|
### Resetting
|
|
61
61
|
|
|
62
|
-
`tailor tailordb migration generate --init` deletes the existing `migrations/` directory and
|
|
62
|
+
`tailor tailordb migration generate --init` deletes the existing `migrations/` directory and creates `0000` from the current local types. Use it only before the project is deployed. For a deployed migration history, use [`migration rebaseline`](#re-baselining-a-deployed-migration-history), which verifies the history and connected workspace before replacing any files.
|
|
63
63
|
|
|
64
64
|
## Migration Workflow
|
|
65
65
|
|
|
66
66
|
A typical change cycle:
|
|
67
67
|
|
|
68
|
-
1. **Modify a
|
|
68
|
+
1. **Modify a table definition.**
|
|
69
69
|
|
|
70
70
|
```typescript
|
|
71
71
|
// tailordb/user.ts
|
|
@@ -115,31 +115,91 @@ A typical change cycle:
|
|
|
115
115
|
|
|
116
116
|
### Warnings and optional migration scripts
|
|
117
117
|
|
|
118
|
-
Some non-breaking changes can still cause data loss — most notably removing a field (`field_removed`) or removing a
|
|
118
|
+
Some non-breaking changes can still cause data loss — most notably removing a field (`field_removed`) or removing a table (`table_removed`). `migration generate` reports these as **warnings**:
|
|
119
119
|
|
|
120
120
|
```
|
|
121
121
|
Warning: data loss possible:
|
|
122
122
|
|
|
123
|
-
- User.legacyParentId: Field removed (existing data will be
|
|
123
|
+
- User.legacyParentId: Field removed (existing data will no longer be accessible through the schema after the post-migration phase)
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
No `migrate.ts` is generated automatically because the schema change itself is non-breaking, but the existing data is
|
|
126
|
+
No `migrate.ts` is generated automatically because the schema change itself is non-breaking, but the existing data is no longer accessible through the active schema after the post-migration phase. The platform may retain a removed field's underlying stored value, so do not rely on removal to clear data before reusing the same field name. If you need to preserve, transform, or clear that data first, add a script with:
|
|
127
127
|
|
|
128
128
|
```bash
|
|
129
129
|
tailor tailordb migration script 0002
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
This writes `migrations/0002/migrate.ts` and `migrations/0002/db.ts` next to the existing `diff.json
|
|
132
|
+
This writes `migrations/0002/migrate.ts` and `migrations/0002/db.ts` next to the existing `diff.json` (add `--with-test` to also scaffold a `migrate.test.ts` — see [Testing Migrations Locally](#testing-migrations-locally)). The removed field stays readable inside `migrate.ts` because the pre-migration phase keeps it on the table until the script finishes (see [Per-migration phases](#per-migration-phases)). The next `tailor deploy` runs the script automatically — `migrate.ts` is executed whenever the file exists on disk, regardless of whether the diff itself required it.
|
|
133
|
+
|
|
134
|
+
If the data loss is intentional and no script is needed, record that decision the same way as for breaking changes (see [Breaking changes without a script](#breaking-changes-without-a-script)):
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
tailor tailordb migration script 0002 --no-script --reason "column no longer needed, data can be dropped"
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
In an interactive session, `migration generate` offers to record the reason on the spot when it detects warnings. The acknowledgment is stored in `diff.json`, so it is reviewable in the PR, and it satisfies `migration validate --strict` — useful for enforcing in CI that destructive changes are explicitly acknowledged before merge (see [Schema verification](#schema-verification)).
|
|
141
|
+
|
|
142
|
+
### Renaming a field
|
|
143
|
+
|
|
144
|
+
Renaming a field in a type definition looks like a removal plus an addition to the diff engine. Left as-is, that combination silently drops the old field's data: the removal is only a warning, so nothing forces a data copy.
|
|
145
|
+
|
|
146
|
+
To prevent that, when `migration generate` finds a removed field and an added field in the same type whose stored values can be copied without changing their meaning, it asks whether the change is a rename. Serial fields are never rename candidates, and an enum field only qualifies when it keeps every value of the removed field:
|
|
147
|
+
|
|
148
|
+
```
|
|
149
|
+
? User.fullName was removed and displayName was added with a compatible type. Was it renamed to displayName? (Y/n)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
In non-interactive environments (or with `--yes`), no prompt is shown and the command fails while a rename candidate is left unresolved — writing it as remove + add would silently drop the field's data at deploy. Resolve every candidate explicitly: pass the rename, or confirm a genuine removal with `--drop`:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
tailor tailordb migration generate --rename "User.fullName:displayName"
|
|
156
|
+
tailor tailordb migration generate --drop "User.fullName"
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Repeat `--rename` and `--drop` for multiple fields. A `--rename` that does not match a compatible removed + added pair, or a `--drop` that does not match a removed field, fails with an error.
|
|
160
|
+
|
|
161
|
+
A confirmed rename is recorded as a single `field_renamed` change and treated as **breaking**, so a migration script is required. The generated `migrate.ts` copies the old field into the new one with a single set-based update, and the generated `db.ts` exposes both the old field (readable) and the new field (writable). The copy intentionally overwrites every row without checking for existing values: values of removed fields are retained in storage, so a stale value could otherwise resurface under the new name later. If the new field adds a unique constraint, the script also includes a duplicate-resolution block to run before the constraint is enforced.
|
|
162
|
+
|
|
163
|
+
During deploy, the pre-migration phase keeps the old field and adds the new field with its constraints relaxed, the script copies the data, and the post-migration phase drops the old field and enforces the new field's constraints — all within a single `tailor deploy`.
|
|
164
|
+
|
|
165
|
+
If you decline the prompt (or confirm the removal with `--drop`), the change stays a plain removal + addition with the usual data-loss warning.
|
|
166
|
+
|
|
167
|
+
Renaming a member inside a **nested field** is not detected, and it is quieter: `User.address.zip` → `zipCode` becomes a single `field_modified` on `address` with no breaking change, no warning, and no generated script, so the member's values are not carried over. Copy them with a custom `tailordb migration script` if they must survive.
|
|
168
|
+
|
|
169
|
+
### Renaming a type
|
|
170
|
+
|
|
171
|
+
Renaming a whole type is detected the same way: when `migration generate` finds a removed type and an added type with a matching shape, it asks whether the change is a rename:
|
|
172
|
+
|
|
173
|
+
```
|
|
174
|
+
? User was removed and Person was added with a compatible schema. Was it renamed to Person? (Y/n)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
In non-interactive environments the command fails while a candidate is left unresolved, exactly like field renames. Resolve it with the type forms of the same flags (a value without a `.` targets a type):
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
tailor tailordb migration generate --rename "User:Person"
|
|
181
|
+
tailor tailordb migration generate --drop "User"
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Two types qualify as a rename pair only when copying every row preserves the data: every field must keep its name, type, array-ness, required/unique constraints, foreign key target, and decimal scale; enum fields may gain values but not lose them; indexes must match. A self-referential foreign key is compared against the new type name and must be optional. Types with serial fields (their values cannot be written by a script) or file fields (file contents are not copied) are never candidates. Name-derived and data-independent settings — `pluralForm`, description, type settings, permissions, hooks, and validations — may differ.
|
|
185
|
+
|
|
186
|
+
A confirmed rename is recorded as a single `table_renamed` change and treated as **breaking** for two reasons: existing records must be copied by the migration script, and the type's GraphQL API names (derived from the type name and `pluralForm`) change, which breaks API clients. The generated `migrate.ts` copies every row from the old type into the new one in id-ordered batches, preserving ids so stored foreign key references stay valid, and the generated `db.ts` exposes both the old table (readable) and the new table (writable). Self-referential foreign keys are inserted as null and backfilled after every row exists, so a reference to a row in a later batch cannot fail the copy.
|
|
187
|
+
|
|
188
|
+
Two caveats apply to the copy. The old type is not write-protected: rows written to it after the script's transaction commits — and before post-migration cleanup drops it — are not carried over, so pause writers to the renamed type for the duration of the deploy. And platform-managed record metadata (creation/update timestamps and actors) cannot be written by the script, so the new type's records carry the migration run's metadata instead of the original values.
|
|
189
|
+
|
|
190
|
+
Fields on other types that reference the renamed type via `foreignKeyType` must be retargeted at the new name in the same change. That retarget is recognized as part of the rename: it is not flagged as a breaking foreign-key change and needs no reference fixup, because record ids are preserved by the copy.
|
|
191
|
+
|
|
192
|
+
During deploy, the pre-migration phase creates the new type with its full constraints while the old type stays on the namespace, the script copies the rows, and the old type is dropped in post-migration cleanup after the checkpoint advances — all within a single `tailor deploy`.
|
|
133
193
|
|
|
134
194
|
### Breaking changes without a script
|
|
135
195
|
|
|
136
|
-
Breaking changes require `migrate.ts`. If it is missing at deploy time (for example, the generated script was deleted), `tailor deploy` fails before applying the migration or anything after it. When there is genuinely nothing to migrate — say, the affected
|
|
196
|
+
Breaking changes require `migrate.ts`. If it is missing at deploy time (for example, the generated script was deleted), `tailor deploy` fails before applying the migration or anything after it. When there is genuinely nothing to migrate — say, the affected table holds no data yet — record an explicit acknowledgment instead of keeping an empty script:
|
|
137
197
|
|
|
138
198
|
```bash
|
|
139
199
|
tailor tailordb migration script 0002 --no-script --reason "no data yet, safe to skip"
|
|
140
200
|
```
|
|
141
201
|
|
|
142
|
-
This stores the reason in `migrations/0002/diff.json` (commit the change). The next `tailor deploy` applies the schema change as usual, skips only the script step, and logs the recorded reason. The command refuses to record a skip while `migrate.ts` exists — delete the script first. If `migrate.ts` is added back later, the script
|
|
202
|
+
This stores the reason in `migrations/0002/diff.json` (commit the change). The next `tailor deploy` applies the schema change as usual, skips only the script step, and logs the recorded reason. The command refuses to record a skip while `migrate.ts` exists — delete the script first. If `migrate.ts` is added back later, `tailor deploy` fails rather than choosing between the script and the acknowledgment; run `tailor tailordb migration script 0002` again to clear the now-stale acknowledgment from `diff.json` (the script then runs on the next deploy), or delete `migrate.ts` to keep the skip.
|
|
143
203
|
|
|
144
204
|
## Configuration
|
|
145
205
|
|
|
@@ -167,15 +227,24 @@ export default defineConfig({
|
|
|
167
227
|
|
|
168
228
|
## Generated Files
|
|
169
229
|
|
|
170
|
-
| File
|
|
171
|
-
|
|
|
172
|
-
| `0000/schema.json`
|
|
173
|
-
| `XXXX/diff.json`
|
|
174
|
-
| `XXXX/migrate.ts`
|
|
175
|
-
| `XXXX/db.ts`
|
|
230
|
+
| File | When generated | Description |
|
|
231
|
+
| ---------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
|
|
232
|
+
| `0000/schema.json` | First `migration generate` | Full snapshot of all tables in the namespace. |
|
|
233
|
+
| `XXXX/diff.json` | Every subsequent migration | Field-level diff against the previous snapshot. |
|
|
234
|
+
| `XXXX/migrate.ts` | Auto-generated for breaking changes; added manually via `tailordb migration script` for warning-tier changes | Data transformation script. The `main` export receives a Kysely `Transaction`. |
|
|
235
|
+
| `XXXX/db.ts` | Generated once when `migrate.ts` is created | Kysely types reflecting the schema **before** this migration. Exports `Database`, `Transaction`, and `MigrationContext`. |
|
|
236
|
+
| `XXXX/migrate.test.ts` | Added via `tailordb migration script --with-test` | Unit-test scaffold for `migrate.ts` (see [Testing Migrations Locally](#testing-migrations-locally)). Never deployed. |
|
|
176
237
|
|
|
177
238
|
`db.ts` reflects the pre-migration schema because the script runs after the pre-migration phase has temporarily relaxed breaking constraints (e.g., a new `required` field is added as `optional` first), so the data being read still matches the previous shape.
|
|
178
239
|
|
|
240
|
+
### Migration file format compatibility
|
|
241
|
+
|
|
242
|
+
Migration files are versioned independently of the SDK package. This SDK writes format version `3` and reads versions `1` through `3`. It normalizes supported older formats in memory; it never rewrites applied migration files on disk.
|
|
243
|
+
|
|
244
|
+
If a future SDK can no longer replay an old migration format, re-baseline while using an SDK version that still supports the complete history, commit the new baseline, deploy it to every environment, and then upgrade the SDK. A file from a newer unsupported format instead requires upgrading the SDK first. The CLI rejects both cases with guidance rather than attempting a best-effort replay.
|
|
245
|
+
|
|
246
|
+
There is no migration-file conversion command. Keeping applied files unchanged preserves the record of what ran, while `migration rebaseline` provides the escape hatch when the supported replay window changes.
|
|
247
|
+
|
|
179
248
|
## Migration Script Anatomy
|
|
180
249
|
|
|
181
250
|
```typescript
|
|
@@ -196,6 +265,34 @@ export async function main(trx: Transaction): Promise<void> {
|
|
|
196
265
|
}
|
|
197
266
|
```
|
|
198
267
|
|
|
268
|
+
**Worked example: backfilling a new required enum field**
|
|
269
|
+
|
|
270
|
+
Adding a required field is a breaking change, so `migration generate` scaffolds `migrate.ts`. Given this table change:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
// tailordb/user.ts
|
|
274
|
+
export const user = db.table("User", {
|
|
275
|
+
name: db.string(),
|
|
276
|
+
email: db.string(),
|
|
277
|
+
role: db.enum(["MANAGER", "STAFF"]), // ← new required field
|
|
278
|
+
...db.fields.timestamps(),
|
|
279
|
+
});
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
existing `User` rows have no `role` value yet, so the script assigns one before the post-migration phase enforces the constraint:
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
import type { Transaction } from "./db";
|
|
286
|
+
|
|
287
|
+
export async function main(trx: Transaction): Promise<void> {
|
|
288
|
+
await trx.updateTable("User").set({ role: "MANAGER" }).where("role", "is", null).execute();
|
|
289
|
+
}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
The `where("role", "is", null)` guard keeps the script idempotent — rows that already have a value are untouched if the script re-runs.
|
|
293
|
+
|
|
294
|
+
Reference scripts for other breaking-change patterns live in the repository's [migration fixture templates](https://github.com/tailor-platform/sdk/tree/main/example/tests/migration-fixtures/templates): backfilling fields that become required and migrating rows off a removed enum value ([0005](https://github.com/tailor-platform/sdk/blob/main/example/tests/migration-fixtures/templates/0005/migrate.ts)), and de-duplicating values before a unique constraint is added ([0006](https://github.com/tailor-platform/sdk/blob/main/example/tests/migration-fixtures/templates/0006/migrate.ts)). They show the shape of each migration, not drop-in logic — adapt them to your data (the suffix strategy in `0006`, for example, assumes the suffixed names are not already taken).
|
|
295
|
+
|
|
199
296
|
**Accessing environment variables**
|
|
200
297
|
|
|
201
298
|
The migration `main` receives an optional second argument exposing the variables defined in `defineConfig({ env })` — the same values available via `context.env` in resolvers. The `MigrationContext` type is exported from the generated `./db`:
|
|
@@ -223,38 +320,207 @@ The `env` values are injected at bundle time (the same mechanism as resolvers/ex
|
|
|
223
320
|
|
|
224
321
|
## Supported Schema Changes
|
|
225
322
|
|
|
226
|
-
| Change Type
|
|
227
|
-
|
|
|
228
|
-
| Add optional field
|
|
229
|
-
| Add required field
|
|
230
|
-
| Remove field
|
|
231
|
-
|
|
|
232
|
-
| Change
|
|
233
|
-
|
|
|
234
|
-
| Add unique
|
|
235
|
-
|
|
|
236
|
-
|
|
|
237
|
-
|
|
|
238
|
-
|
|
|
239
|
-
|
|
|
240
|
-
|
|
|
241
|
-
|
|
|
242
|
-
|
|
|
243
|
-
|
|
|
244
|
-
|
|
|
245
|
-
|
|
|
246
|
-
| Change
|
|
247
|
-
| Change
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
323
|
+
| Change Type | Breaking? | Migration Script? | Notes |
|
|
324
|
+
| --------------------------------- | --------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
325
|
+
| Add optional field | No | No | Schema change only |
|
|
326
|
+
| Add required field | Yes | Yes | Script populates default values |
|
|
327
|
+
| Remove field | No | Optional | Warning tier — no script is auto-generated, but you can add one with `tailordb migration script` to preserve or clear data before the field leaves the active schema. The field stays readable from `migrate.ts` during Pre-migration. |
|
|
328
|
+
| Rename field | Yes | Yes | Confirmed interactively at generate time or via `--rename "Type.old:new"` — see [Renaming a field](#renaming-a-field). Auto-generated script copies values from the old field to the new one; both fields coexist during Pre-migration. |
|
|
329
|
+
| Change optional → required | Yes | Yes | Script sets defaults for null values |
|
|
330
|
+
| Change required → optional | No | No | Schema change only |
|
|
331
|
+
| Add index (non-unique) | No | No | Schema change only |
|
|
332
|
+
| Add unique index | Yes | Yes | Script must resolve duplicate value combinations across the index fields |
|
|
333
|
+
| Change unique index fields | Yes | Yes | Treated like adding a new unique constraint over the new field set |
|
|
334
|
+
| Remove index | No | No | Schema change only (removing the unique constraint from an index is also non-breaking) |
|
|
335
|
+
| Add unique constraint | Yes | Yes | Script must resolve duplicate values |
|
|
336
|
+
| Remove unique constraint | No | No | Schema change only |
|
|
337
|
+
| Change decimal scale | Yes | Yes | Auto-generated script re-saves existing rows under the new scale. Decreasing scale rounds values half-up and can lose precision. If the same change adds a unique constraint, duplicate handling runs after re-saving. |
|
|
338
|
+
| Add enum value | No | No | Schema change only |
|
|
339
|
+
| Remove enum value | Yes | Yes | Script migrates records with removed values |
|
|
340
|
+
| Add table | No | No | Schema change only |
|
|
341
|
+
| Remove table | No | Optional | Warning tier — no script is auto-generated, but you can add one with `tailordb migration script` to preserve data before the table leaves the active schema. The table stays readable from `migrate.ts` during Pre-migration. |
|
|
342
|
+
| Rename table | Yes | Yes | Confirmed interactively at generate time or via `--rename "OldType:NewType"` — see [Renaming a type](#renaming-a-type). Auto-generated script copies all rows preserving ids; both tables coexist until post-migration cleanup. |
|
|
343
|
+
| Change foreign key target table | Yes | Yes | Script updates references to the new target |
|
|
344
|
+
| Change field type (verified pair) | Yes | Yes | In-place for the pairs listed under [Field type changes](#field-type-changes); review the generated normalization scaffold and customize it only when existing values need transformation |
|
|
345
|
+
| Change field type (other pair) | Yes | Yes | Two migrations, generated together after you confirm — see [Converting a field type](#converting-a-field-type). Edit the conversion in the first; the second needs no changes. |
|
|
346
|
+
| Change array → single value | - | - | **Not supported** — see [Converting a field type](#converting-a-field-type) |
|
|
347
|
+
| Change single value → array | - | - | **Not supported** — see [Converting a field type](#converting-a-field-type) |
|
|
348
|
+
|
|
349
|
+
### Field type changes
|
|
350
|
+
|
|
351
|
+
These pairs change in place, in a single migration:
|
|
352
|
+
|
|
353
|
+
| From | To |
|
|
354
|
+
| --------- | ---------------------------- |
|
|
355
|
+
| `integer` | `string`, `float`, `decimal` |
|
|
356
|
+
| `float` | `string`, `decimal` |
|
|
357
|
+
| `decimal` | `string`, `float` |
|
|
358
|
+
| `boolean` | `string` |
|
|
359
|
+
| `uuid` | `string` |
|
|
360
|
+
| `enum` | `string` |
|
|
361
|
+
|
|
362
|
+
Every pair here accepts every value its source type allows, which is what lets the change happen in one migration: the field keeps its previous type until the migration finishes, so your application can keep writing to it throughout.
|
|
363
|
+
|
|
364
|
+
Every other scalar pair needs a temporary field. Eligible fields can use the generated [expand-contract pair](#converting-a-field-type); fields the generator rejects still need the manual three-step sequence described below. Three groups are worth calling out:
|
|
365
|
+
|
|
366
|
+
- Converting to a narrower type — `string` → `integer`, `string` → `uuid`, `integer` → `boolean` and similar — is excluded because values the source type still accepts, such as `"abc"` in a `string` field, cannot be cast. Your script could clean up the rows it sees, but the field goes on accepting new uncastable values until the migration completes.
|
|
367
|
+
- `boolean` → `integer`, `float` → `integer`, and `string` → `date` are excluded because the stored values cannot be cast to the new type.
|
|
368
|
+
- `date`, `datetime`, and `time` fields are not stored in the textual form you wrote them in, so converting them to or from another type reads back as a different instant. Convert them through a temporary field where your script controls the formatting.
|
|
369
|
+
|
|
370
|
+
Converting to `decimal` reformats values to the field's scale, so `42` reads back as `42.000000`. Values with more decimal places than the scale allows are rounded half-up, so `1.1234567` becomes `1.123457` at the default scale of 6.
|
|
371
|
+
|
|
372
|
+
A `float` field that is already unique cannot convert to `decimal` in place, because rounding can turn two distinct values into the same one and the existing constraint leaves no room to resolve the collision. Use the 3-step migration for those.
|
|
373
|
+
|
|
374
|
+
### Generated normalization script for field type changes
|
|
375
|
+
|
|
376
|
+
For example, changing `User.age` from `integer` to `float` generates a `migrate.ts` that scans non-null values in batches of 100:
|
|
377
|
+
|
|
378
|
+
```typescript
|
|
379
|
+
import type { Transaction } from "./db";
|
|
380
|
+
|
|
381
|
+
export async function main(trx: Transaction): Promise<void> {
|
|
382
|
+
// Normalize User.age from integer to float while the previous type is still active
|
|
383
|
+
{
|
|
384
|
+
let lastId: string | undefined;
|
|
385
|
+
while (true) {
|
|
386
|
+
let query = trx
|
|
387
|
+
.selectFrom("User")
|
|
388
|
+
.select(["id", "age"])
|
|
389
|
+
.where("age", "is not", null)
|
|
390
|
+
.orderBy("id", "asc")
|
|
391
|
+
.limit(100);
|
|
392
|
+
if (lastId) {
|
|
393
|
+
query = query.where("id", ">", lastId);
|
|
394
|
+
}
|
|
395
|
+
const rows = await query.execute();
|
|
396
|
+
if (rows.length === 0) break;
|
|
397
|
+
|
|
398
|
+
for (const row of rows) {
|
|
399
|
+
// TODO(tailor-migration-review): Remove this marker and the `never` annotation after reviewing the normalization.
|
|
400
|
+
// Keep the value accepted by the active integer type and castable to float.
|
|
401
|
+
const sourceValue = row.age;
|
|
402
|
+
if (sourceValue === null) continue;
|
|
403
|
+
const normalizedValue: never = sourceValue;
|
|
404
|
+
if (Object.is(normalizedValue, sourceValue)) continue;
|
|
405
|
+
await trx
|
|
406
|
+
.updateTable("User")
|
|
407
|
+
.set({ ["age"]: normalizedValue })
|
|
408
|
+
.where("id", "=", row.id)
|
|
409
|
+
.execute();
|
|
410
|
+
}
|
|
411
|
+
lastId = rows[rows.length - 1]!.id;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
The generated `never` annotation intentionally causes a TypeScript error until you review the normalization. If the existing values are already suitable for the target type, remove the annotation and review marker to accept the identity transformation; it does not write any rows. If values need application-specific normalization, replace the expression and remove the annotation and marker while keeping the result valid for both the active source type and the target type. The source field contract remains active until the script finishes; for example, an `integer` → `float` script cannot write fractional values during this phase.
|
|
418
|
+
|
|
419
|
+
### Converting a field type
|
|
420
|
+
|
|
421
|
+
A field type change outside the verified in-place pairs — `string` → `integer`, for example — cannot be applied in one step, because the field would have to hold both shapes at once. `migration generate` offers to carry the values through a temporary field instead:
|
|
422
|
+
|
|
423
|
+
```
|
|
424
|
+
User.price changes from string to integer, which cannot be applied in one step.
|
|
425
|
+
? Generate two migrations to convert User.price through a temporary field? (Y/n)
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
Confirming writes two migrations:
|
|
429
|
+
|
|
430
|
+
1. **The conversion.** Adds a temporary field (`priceMigrate`), converts each stored value into it, and clears and removes the original field. Edit the conversion expression before deploying: the generated `never` annotation fails your typecheck, and `tailordb migration validate` rejects the migration while the review marker is still there.
|
|
431
|
+
2. **The rename.** Renames the temporary field back to `price`. Its copy script is complete, but this migration also carries every other schema change the same run picked up, so review it as you would any generated migration.
|
|
432
|
+
|
|
433
|
+
`tailor deploy` applies both. Because the conversion only touches rows whose original value is still set, a re-run resumes where it stopped rather than converting a row twice.
|
|
434
|
+
|
|
435
|
+
The original field is removed in the first migration rather than the second, because the rename needs its name free. Your script can still read it while the conversion runs.
|
|
436
|
+
|
|
437
|
+
In a non-interactive run — `--yes`, or CI — name each field explicitly:
|
|
438
|
+
|
|
439
|
+
```bash
|
|
440
|
+
tailor tailordb migration generate --yes --expand-contract "User.price"
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
Without the flag the command fails rather than converting anything, so a scripted run cannot start a two-migration change by accident.
|
|
444
|
+
|
|
445
|
+
> **Why the conversion clears the original field.** Removing a field from the schema does not necessarily remove its stored value. Reusing the name for an incompatible type while a stale value remains can deploy successfully and then make subsequent reads fail. Clearing the original in the same update is what prevents that, which is why the generated script writes both fields at once.
|
|
446
|
+
|
|
447
|
+
> **Writes that land while the conversion runs are not carried across.** The original field keeps its old type until the conversion finishes, so an application can still write to it after the script has read the last row — and that value is dropped with the field rather than converted. Stop writes to the field, or accept the loss, before deploying a conversion on a live workspace.
|
|
448
|
+
|
|
449
|
+
Some changes are still rejected and need a temporary field you add yourself — add the new field, write a script that fills it and clears the old one, then remove the old field and rename the temporary one in a later migration:
|
|
450
|
+
|
|
451
|
+
- Array-to-scalar and scalar-to-array, since collapsing an array has no answer the generated script could choose for you.
|
|
452
|
+
- A field that is unique, or that an index, relationship, permission, or type-level script names. Those keep pointing at the original name, which the conversion removes.
|
|
453
|
+
|
|
454
|
+
## Testing Pending Migrations
|
|
455
|
+
|
|
456
|
+
`tailor tailordb migration test` runs every migration pending in the source workspace against an isolated workspace. The source workspace is selected by `--workspace-id` or the active profile and is never modified.
|
|
457
|
+
|
|
458
|
+
The command performs the following sequence:
|
|
459
|
+
|
|
460
|
+
1. Reads each migration-enabled namespace's `sdk-migration` checkpoint from the source workspace and reconstructs that exact snapshot from local migration history.
|
|
461
|
+
2. Creates a temporary workspace in the same region, organization, and folder as the source, unless `--target-workspace-id` names an existing throwaway workspace.
|
|
462
|
+
3. Deploys the checkpoint snapshots and writes their checkpoint labels.
|
|
463
|
+
4. Loads fixture data or clones source records.
|
|
464
|
+
5. Runs the normal deployment pipeline, including every pending pre-migration, `migrate.ts`, and post-migration phase.
|
|
465
|
+
6. Optionally runs an assertion script against the migrated data.
|
|
466
|
+
7. Deletes an automatically-created workspace after success or failure.
|
|
467
|
+
|
|
468
|
+
Both the pre-migration and final TailorDB schemas come from committed migration snapshots. Ungenerated changes in the current type source are not included in the rehearsal.
|
|
469
|
+
|
|
470
|
+
Executors are omitted from the baseline deployment so loading fixture or cloned records cannot trigger current event handlers against the older schema. Auth user profiles are also deferred until the pending migrations finish, while configured machine users remain available to run seed and migration scripts. The final deployment restores the configured executors and user profiles. Static websites are deployed so configuration references to their URLs resolve, but their workspace-bound custom domains are omitted from migration-test deployments.
|
|
471
|
+
|
|
472
|
+
### Seed mode
|
|
473
|
+
|
|
474
|
+
Seed mode is the default and uses the JSONL files produced by the configured `seedPlugin`. Run `tailor generate` after adding the plugin or changing seed types, then populate its `data/*.jsonl` files:
|
|
475
|
+
|
|
476
|
+
```bash
|
|
477
|
+
tailor tailordb migration test --data seed
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
Rows are loaded only for types present in the deployed pre-migration snapshots (and current schemas without migrations), in foreign-key dependency order. Fields introduced by pending migrations, including timestamp and nested fields, are removed before insertion so current fixtures can be loaded into the baseline schema. Missing type files are treated as empty. IdP `_User` fixtures are not loaded by this command.
|
|
481
|
+
|
|
482
|
+
Use `--machine-user` to override the seed plugin's `machineUserName`, the namespace migration setting, and the first configured Auth machine user for seed and assertion execution.
|
|
483
|
+
|
|
484
|
+
### Clone mode
|
|
485
|
+
|
|
486
|
+
Clone mode copies TailorDB records from the source workspace after the identical application, namespace names, and pre-migration schemas exist in the target. For namespaces without migration history, the command reproduces the deployed source schema rather than uncommitted local type changes:
|
|
487
|
+
|
|
488
|
+
```bash
|
|
489
|
+
tailor tailordb migration test --data clone
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
The platform clone API is feature-gated and requires editor access to both same-region workspaces. It copies TailorDB records only: IdP users, file blobs, and metadata labels are not copied. File fields therefore retain references whose blobs are absent. The command polls the asynchronous operation and reports platform failures; if clone is unavailable, use seed mode.
|
|
493
|
+
|
|
494
|
+
The source schema is re-verified immediately before cloning; if the source workspace was deployed or otherwise changed after the test started, the command aborts instead of cloning data that no longer matches the deployed baseline.
|
|
495
|
+
|
|
496
|
+
### Assertions and retained targets
|
|
497
|
+
|
|
498
|
+
Pass a TypeScript file with `--assert`. Its exported `main` function uses the same Kysely transaction signature as `migrate.ts`, runs after all pending migrations, and must throw when an invariant fails:
|
|
499
|
+
|
|
500
|
+
```bash
|
|
501
|
+
tailor tailordb migration test \
|
|
502
|
+
--data seed \
|
|
503
|
+
--assert ./tests/assert-customer-email.ts \
|
|
504
|
+
--assert-namespace tailordb
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
`--assert-namespace` is inferred when only one namespace has pending migrations and is required otherwise.
|
|
508
|
+
|
|
509
|
+
To inspect the result after a run, pass `--keep` so the automatically created workspace survives instead of being deleted, on success and on failure:
|
|
510
|
+
|
|
511
|
+
```bash
|
|
512
|
+
tailor tailordb migration test --keep
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
Alternatively, provide an empty designated throwaway workspace. This mode never deletes the target and requires explicit acknowledgment:
|
|
516
|
+
|
|
517
|
+
```bash
|
|
518
|
+
tailor tailordb migration test \
|
|
519
|
+
--target-workspace-id 00000000-0000-4000-8000-000000000000 \
|
|
520
|
+
--yes
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Do not target a shared development or production workspace: baseline deployment reconciles its managed resources and schemas before the migration test runs.
|
|
258
524
|
|
|
259
525
|
## Automatic Migration Execution
|
|
260
526
|
|
|
@@ -264,9 +530,10 @@ When you run `tailor deploy`, the SDK detects pending migrations (anything past
|
|
|
264
530
|
|
|
265
531
|
For each pending migration:
|
|
266
532
|
|
|
267
|
-
1. **Pre-migration**:
|
|
533
|
+
1. **Pre-migration**: Schema changes that would be breaking are applied in a relaxed form first. A verified in-place field type change keeps its complete previous field contract until Post-migration, including field and type-level hooks or validators changed by the same migration. Newly-required fields are added as optional; fields whose `optional → required` transition is breaking are temporarily kept optional. Fields that are being removed in this migration are temporarily kept on the table so that `migrate.ts` can still read them (for example, to `innerJoin` through a foreign key that is about to be dropped). For a renamed field, the old field is kept and the new field is added with its constraints relaxed, so the script can read the old field and write the new one. For a renamed type, the new type is created with its full constraints while the old type stays on the namespace until post-migration cleanup, so the script can copy rows between them. Breaking type-level index changes are relaxed the same way: a newly-added unique index is withheld, and an index gaining a unique constraint (or a unique index changing its field set) keeps its previous definition, so `migrate.ts` can resolve duplicates first. Non-breaking changes that are part of the same migration are also applied here.
|
|
268
534
|
2. **Script execution**: If `migrate.ts` exists on disk for this migration, it is bundled and sent to the platform via the script execution API and runs as the configured machine user inside a transaction. The script is hard-required for breaking changes (`diff.requiresMigrationScript`) — deploy fails if the file is missing, unless a `--no-script` acknowledgment was recorded (see [Breaking changes without a script](#breaking-changes-without-a-script)). It is also executed when present for warning-tier diffs — see [Warnings and optional migration scripts](#warnings-and-optional-migration-scripts).
|
|
269
|
-
3. **Post-migration**: Required constraints
|
|
535
|
+
3. **Post-migration schema**: Required constraints and the target field definitions are applied. Do not assume that removing a field clears its underlying stored JSON value.
|
|
536
|
+
4. **Checkpoint and cleanup**: The `sdk-migration` label is bumped to this migration's number, then removed GQL permissions and tables — including a renamed type's old table — are deleted. Advancing the checkpoint first prevents a failed checkpoint write from requiring the SDK to recreate irreversibly deleted records.
|
|
270
537
|
|
|
271
538
|
This split is what allows existing rows to be backfilled before the database starts rejecting nulls, and what lets `migrate.ts` traverse foreign-key fields that the same migration removes.
|
|
272
539
|
|
|
@@ -274,7 +541,7 @@ This split is what allows existing rows to be backfilled before the database sta
|
|
|
274
541
|
|
|
275
542
|
Before running migrations, `apply` performs two checks:
|
|
276
543
|
|
|
277
|
-
1. **Local schema check** — your current
|
|
544
|
+
1. **Local schema check** — your current table definitions must match the latest snapshot in `migrations/`. If they don't, you forgot to run `migration generate`.
|
|
278
545
|
2. **Remote schema check** — the deployed schema is reconstructed from migration history; the actual remote schema must match. Drift here means someone applied a different set of migrations or edited the schema out-of-band.
|
|
279
546
|
|
|
280
547
|
On drift you'll see something like:
|
|
@@ -290,7 +557,7 @@ Namespace: tailordb
|
|
|
290
557
|
|
|
291
558
|
The error also points you at `migration status`, `migration generate`, `migration sync`, and `migration set` — see [Remote schema drift detected](#remote-schema-drift-detected) for which one applies.
|
|
292
559
|
|
|
293
|
-
To run the same checks without deploying — plus migration file integrity (numbering, parseable contents,
|
|
560
|
+
To run the same checks without deploying — plus migration file integrity (numbering, parseable contents, a `migrate.ts` or a recorded `--no-script` acknowledgment for every migration that requires a script, and no unresolved generated normalization review markers):
|
|
294
561
|
|
|
295
562
|
```bash
|
|
296
563
|
tailor tailordb migration validate
|
|
@@ -298,6 +565,8 @@ tailor tailordb migration validate
|
|
|
298
565
|
|
|
299
566
|
It reports issues per namespace, exits with a non-zero code when any check fails, and supports `--json` for machine-readable output.
|
|
300
567
|
|
|
568
|
+
With `--strict`, validation additionally fails when a migration not yet applied to the remote has data-loss warnings (see [Warnings and optional migration scripts](#warnings-and-optional-migration-scripts)) but neither a `migrate.ts` nor a recorded `--no-script` acknowledgment. The failure names the affected type and field and prints the exact command to record the acknowledgment.
|
|
569
|
+
|
|
301
570
|
To bypass both checks during deploy (not recommended outside of recovery scenarios):
|
|
302
571
|
|
|
303
572
|
```bash
|
|
@@ -318,9 +587,31 @@ tailor deploy --no-schema-check
|
|
|
318
587
|
✔ Successfully applied changes.
|
|
319
588
|
```
|
|
320
589
|
|
|
590
|
+
## Re-baselining a deployed migration history
|
|
591
|
+
|
|
592
|
+
`tailor tailordb migration rebaseline` collapses the complete history into a new `0000/schema.json` in the current migration format. It does not modify the deployed schema or data.
|
|
593
|
+
|
|
594
|
+
Before running it:
|
|
595
|
+
|
|
596
|
+
1. Apply the latest migration to every environment. The CLI verifies the connected workspace, but it cannot inspect other workspaces.
|
|
597
|
+
2. Commit or otherwise preserve the existing migration history. Files after `0000`, including `migrate.ts` and `db.ts`, disappear from the working tree; Git history retains committed files.
|
|
598
|
+
3. Make sure local type changes have been captured with `tailor tailordb migration generate`.
|
|
599
|
+
|
|
600
|
+
Then re-baseline one namespace:
|
|
601
|
+
|
|
602
|
+
```bash
|
|
603
|
+
tailor tailordb migration rebaseline --namespace tailordb
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
The command validates the migration files, verifies that replaying the latest migration exactly reproduces the local types, and checks that the connected workspace is at that latest migration with no schema drift. After confirmation, it replaces the local history with the reconstructed baseline, records a new migration history ID in both `0000/schema.json` and remote metadata, and resets the connected workspace's `sdk-migration` label to `0000`. Use `--yes` only after arranging the same operational preconditions in non-interactive automation.
|
|
607
|
+
|
|
608
|
+
Commit the resulting `migrations/` change before generating any new migrations. For another environment still carrying the exact checkpoint and history ID that the new baseline replaced, the next `tailor deploy` checks whether its remote schema exactly matches the new `0000`. If it does, deploy offers to reset the checkpoint to `0000` and move the environment to the new history ID before applying any later local migrations. A markerless history is eligible only for the first rebaseline, at the exact migration recorded as replaced. Any other checkpoint or history ID is rejected without changing remote metadata, even if its schema happens to match the baseline.
|
|
609
|
+
|
|
610
|
+
Partial squashing is not supported: re-baselining always replaces the full history for one namespace.
|
|
611
|
+
|
|
321
612
|
## `migration set` Semantics
|
|
322
613
|
|
|
323
|
-
`tailor tailordb migration set <N>` updates the `sdk-migration` label on the deployed namespace's metadata. **It does not modify any data or schema.** It only changes which migrations the next `apply` will consider pending.
|
|
614
|
+
`tailor tailordb migration set <N>` updates the `sdk-migration` label on the deployed namespace's metadata. **It does not modify any data or schema.** It only changes which migrations the next `apply` will consider pending. The command also aligns the remote migration history ID with the local baseline, removing a stale ID when the local history predates re-baselining.
|
|
324
615
|
|
|
325
616
|
The migration number is validated before anything is sent to the remote: it must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the working tree's migration history, which is itself validated (a gapped history is rejected). `0` is always accepted as the baseline (even when no migrations directory exists yet), provided the history passes validation.
|
|
326
617
|
|
|
@@ -339,14 +630,14 @@ Use cases:
|
|
|
339
630
|
|
|
340
631
|
## `migration sync` Semantics
|
|
341
632
|
|
|
342
|
-
`tailor tailordb migration sync <N>` reconstructs the schema snapshot at migration `N` from the working tree's migration history and **overwrites the remote schema to match it**, then sets the `sdk-migration` label to `N
|
|
633
|
+
`tailor tailordb migration sync <N>` reconstructs the schema snapshot at migration `N` from the working tree's migration history and **overwrites the remote schema to match it**, then sets the `sdk-migration` label to `N` and aligns the remote migration history ID with the local baseline. Unlike `migration set`, it changes the remote schema as well as the bookkeeping. Like `set`, it never runs `migrate.ts` scripts itself — it only changes what the next `apply` considers pending:
|
|
343
634
|
|
|
344
|
-
| Movement | Effect on next `apply` | Effect on data
|
|
345
|
-
| -------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
346
|
-
| Backward (e.g., `0003` → `0001`) | Migrations `0002` and `0003` become pending and re-execute, including their `migrate.ts`. |
|
|
347
|
-
| Forward (e.g., `0001` → `0003`) | Migrations `0002` and `0003` are skipped — their `migrate.ts` scripts will not run. | Data the skipped scripts would have migrated stays as-is.
|
|
635
|
+
| Movement | Effect on next `apply` | Effect on data |
|
|
636
|
+
| -------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
637
|
+
| Backward (e.g., `0003` → `0001`) | Migrations `0002` and `0003` become pending and re-execute, including their `migrate.ts`. | Tables absent from snapshot `0001` are deleted along with their data; re-executed scripts may rewrite data. |
|
|
638
|
+
| Forward (e.g., `0001` → `0003`) | Migrations `0002` and `0003` are skipped — their `migrate.ts` scripts will not run. | Data the skipped scripts would have migrated stays as-is. |
|
|
348
639
|
|
|
349
|
-
Before anything is sent to the remote, `sync` verifies that replaying the full migration history reproduces the current local
|
|
640
|
+
Before anything is sent to the remote, `sync` verifies that replaying the full migration history reproduces the current local table definitions. If it does not — because migration files were edited and no longer match, or because a schema change has not been recorded with `migration generate` yet — the command fails without touching the remote. This means a rewritten migration history is validated before it can overwrite the deployed schema.
|
|
350
641
|
|
|
351
642
|
Because syncing backward causes already-applied scripts to re-execute on the next deploy, **write `migrate.ts` scripts to be idempotent** (see [Performance and Large Tables](#performance-and-large-tables) for resumable `where` clauses).
|
|
352
643
|
|
|
@@ -359,35 +650,40 @@ The main use case is recovering from drift after a `deploy --no-schema-check` fr
|
|
|
359
650
|
Migration numbers are assigned sequentially, so two developers branching off the same point and each generating `0005` will collide. Conventions that work:
|
|
360
651
|
|
|
361
652
|
- **Don't generate migrations on long-lived feature branches.** Generate them just before merge, after rebasing onto main.
|
|
362
|
-
- **Resolve collisions by re-generating.** If your branch has `0005` but main now has `0005` from another PR,
|
|
653
|
+
- **Resolve collisions by re-generating.** If your branch has `0005` but main now has `0005` from another PR, regenerate yours as `0006` — see [Resolving a migration number conflict](#resolving-a-migration-number-conflict).
|
|
363
654
|
- **Treat migration files as merge-conflict-prone.** They are committed JSON and TypeScript, so review them in PRs. The `diff.json` is the source of truth — if review focuses there, regenerating after rebase is straightforward.
|
|
364
655
|
|
|
656
|
+
### Resolving a migration number conflict
|
|
657
|
+
|
|
658
|
+
When your branch and main each generated the same number, merging or rebasing stops with an add/add conflict on `migrations/0005/diff.json`. Resolve it by re-generating your migration on top of main's:
|
|
659
|
+
|
|
660
|
+
1. **Save your script edits aside.** If you customized `0005/migrate.ts`, keep a copy before touching the directory — during a rebase, `git show ORIG_HEAD:migrations/0005/migrate.ts` prints the version from your pre-rebase branch tip.
|
|
661
|
+
2. **Take main's `0005/` directory in full.** Accept main's version of every conflicting file. Then check for files only your side added: if your migration has a `migrate.ts` and main's does not, that file never conflicts — it silently stays next to main's `diff.json`. Delete such leftovers explicitly.
|
|
662
|
+
3. **Finish the rebase or merge, then re-run `migration generate`.** With main's migration now part of local history, the diff is computed against the correct base — including main's changes — and your migration lands as the next number (`0006`).
|
|
663
|
+
4. **Port your script.** Copy the logic saved in step 1 into the newly scaffolded `0006/migrate.ts`. For a warning-tier change, `migration generate` does not scaffold a script — recreate it first with `tailor tailordb migration script 0006`.
|
|
664
|
+
|
|
665
|
+
**When a plain rename is enough.** If the two migrations touch disjoint tables and fields, renaming your directory to the next free number (keeping main's `0005/`) can be acceptable. Run `tailor tailordb migration validate` after the rename: if it reports a mismatch, the migrations were not disjoint — discard the rename and re-generate as above. A passing check covers only the schema history, not your script: `migrate.ts` now runs after main's migration, so confirm it does not read or write tables that migration touches — when in doubt, re-generate.
|
|
666
|
+
|
|
365
667
|
### CI / CD
|
|
366
668
|
|
|
367
669
|
- For non-interactive environments, pass `--yes` to `migration generate` and `--yes` to `apply`. `apply` runs migrations automatically when the `migrations/` directory is configured.
|
|
368
|
-
- Run `tailor tailordb migration validate` in CI to catch uncommitted migrations, broken migration files, and remote schema drift before deploying. It exits with a non-zero code when validation fails and supports `--json`.
|
|
369
|
-
- `tailor tailordb migration status` shows applied and pending migrations for a human-readable comparison. Its exit code is non-zero
|
|
670
|
+
- Run `tailor tailordb migration validate` in CI to catch uncommitted migrations, broken migration files, unreviewed generated normalization logic, and remote schema drift before deploying. It exits with a non-zero code when validation fails and supports `--json`. Add `--strict` to also require an explicit acknowledgment (a `migrate.ts` or a recorded `--no-script` reason) for every pending migration that can drop data, so destructive changes cannot merge unnoticed.
|
|
671
|
+
- `tailor tailordb migration status` validates file-format compatibility across the full local history, compares its history ID with the deployed namespace, and shows applied and pending migrations for a human-readable comparison. Its exit code is non-zero on incompatible files, migration history mismatches, and remote read errors, so check the output.
|
|
370
672
|
- Avoid running migrations in parallel against the same workspace — there is no locking. Serialize deploys per environment.
|
|
371
673
|
|
|
372
674
|
### Resetting a deployed project
|
|
373
675
|
|
|
374
|
-
`migration generate --init`
|
|
375
|
-
|
|
376
|
-
1. Run `migration generate --init` to start over from `0000`.
|
|
377
|
-
2. Run `tailor tailordb migration set 0` against the deployed namespace.
|
|
378
|
-
3. Run `tailor deploy` — the new `0000` becomes the baseline.
|
|
379
|
-
|
|
380
|
-
Coordinate this with your team because everyone else's local migrations will be invalidated.
|
|
676
|
+
Use `tailor tailordb migration rebaseline` rather than combining `migration generate --init` with a manual checkpoint change. See [Re-baselining a deployed migration history](#re-baselining-a-deployed-migration-history) for the required cross-environment coordination and verification.
|
|
381
677
|
|
|
382
678
|
## Failure Recovery
|
|
383
679
|
|
|
384
680
|
If the pre-migration phase or `migrate.ts` fails:
|
|
385
681
|
|
|
386
682
|
- **The transaction rolls back** for that migration's script. Database changes the script made are undone.
|
|
387
|
-
- **The pre-migration schema changes are rolled back** to the prior checkpoint:
|
|
683
|
+
- **The pre-migration schema changes are rolled back** to the prior checkpoint: tables that already existed are restored to their previous shape, and tables the migration newly introduced are dropped. The workspace is left at its prior checkpoint and prior schema — not half-applied.
|
|
388
684
|
- The whole `apply` aborts and the checkpoint label is not bumped. Subsequent migrations in the same run do not execute.
|
|
389
685
|
|
|
390
|
-
The rollback is best-effort per
|
|
686
|
+
The rollback is best-effort per table; if reverting a table fails, a warning is logged and the original migration error is still reported.
|
|
391
687
|
|
|
392
688
|
After a failure:
|
|
393
689
|
|
|
@@ -395,13 +691,17 @@ After a failure:
|
|
|
395
691
|
2. Fix `migrate.ts` (or the data it depends on).
|
|
396
692
|
3. Re-run `tailor deploy`. The same migration runs again because its label was never bumped, and the prior-checkpoint schema is a clean baseline to retry against.
|
|
397
693
|
|
|
398
|
-
If a migration **succeeds in script** but
|
|
694
|
+
If a migration **succeeds in script** but its reversible **post-migration schema update** fails (rare; usually a constraint violation the script should have prevented), the SDK makes the same best-effort restoration to the prior-checkpoint schema. The script's committed data changes remain, so write migration scripts to tolerate re-execution.
|
|
695
|
+
|
|
696
|
+
The checkpoint is advanced only after the reversible post-migration schema updates succeed. If the checkpoint write reports an error, the SDK reads it back: a matching value is treated as committed. Any other observed value leaves the post-migration schema unchanged rather than risk rolling back a concurrent deployment; a value beyond the current migration confirms a concurrent deploy, while an older or missing value means the checkpoint must be repaired before retrying. If read-back also fails, the SDK likewise leaves the post-migration schema unchanged; verify the remote checkpoint before retrying.
|
|
697
|
+
|
|
698
|
+
Removed tables are deleted only after the checkpoint is committed. If that cleanup fails, the checkpoint remains at the new migration and the SDK fails closed: the leftover table is reported as remote schema drift on the next deploy. Remove the leftover GQL permission and table manually, verify the remote schema, and then retry. The SDK does not automatically ignore or delete a same-named remote table because it cannot distinguish failed cleanup from a table recreated after cleanup completed.
|
|
399
699
|
|
|
400
700
|
## Rollback Strategy
|
|
401
701
|
|
|
402
702
|
There is no automatic down-migration. To roll back a schema/data change in production, write a new forward migration that reverses the previous one. For example, to undo a `0005` that added a required `email` field:
|
|
403
703
|
|
|
404
|
-
1. Edit your
|
|
704
|
+
1. Edit your table definitions to remove the field.
|
|
405
705
|
2. `migration generate --name "rollback 0005 email"` produces `0006` with a removal diff.
|
|
406
706
|
3. Apply.
|
|
407
707
|
|
|
@@ -418,7 +718,7 @@ The CLI logs the selected user before running scripts (`Using machine user: ...`
|
|
|
418
718
|
|
|
419
719
|
**Permissions required**
|
|
420
720
|
|
|
421
|
-
The machine user needs read/write access to every
|
|
721
|
+
The machine user needs read/write access to every table the migration script touches. If your migrations alter data across multiple tables, the simplest path is to give the migration user broad access (e.g., an `ADMIN` role) and restrict day-to-day machine users separately. If the user lacks permission, the script fails with a permission error in `Logs:`.
|
|
422
722
|
|
|
423
723
|
If you see `No machine user available for migration execution`, either:
|
|
424
724
|
|
|
@@ -445,10 +745,105 @@ The migration script runs in a single transaction. For tables with many rows:
|
|
|
445
745
|
|
|
446
746
|
## Testing Migrations Locally
|
|
447
747
|
|
|
448
|
-
|
|
748
|
+
### Unit-testing migrate.ts
|
|
749
|
+
|
|
750
|
+
`main` is a plain function, so you can unit-test it with Vitest before the first deploy ever runs it. `createKyselyMock` from `@tailor-platform/sdk/vitest` compiles queries to the same SQL as the deployed migration, so a test verifies the exact statements the script issues — SQL, parameters, and order. Type the mock with the `Database` interface exported from the generated `db.ts`.
|
|
751
|
+
|
|
752
|
+
Scaffold a ready-to-fill test next to the script with:
|
|
753
|
+
|
|
754
|
+
```bash
|
|
755
|
+
tailor tailordb migration script 0005 --with-test
|
|
756
|
+
```
|
|
757
|
+
|
|
758
|
+
When `migrate.ts` already exists (the usual case for breaking changes, where `migration generate` creates it), the command adds only `migrate.test.ts`. Or write the test by hand:
|
|
759
|
+
|
|
760
|
+
```typescript
|
|
761
|
+
// migrations/0005/migrate.test.ts
|
|
762
|
+
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
|
|
763
|
+
import { describe, expect, test } from "vitest";
|
|
764
|
+
import type { Database } from "./db";
|
|
765
|
+
import { main } from "./migrate";
|
|
766
|
+
|
|
767
|
+
describe("0005 add required email", () => {
|
|
768
|
+
test("backfills null emails", async () => {
|
|
769
|
+
const mock = createKyselyMock<Database>();
|
|
770
|
+
|
|
771
|
+
await mock.withTx((trx) => main(trx));
|
|
772
|
+
|
|
773
|
+
expect(mock.updates).toHaveLength(1);
|
|
774
|
+
expect(mock.updates[0]?.updateValues()).toEqual({ email: "unknown@example.com" });
|
|
775
|
+
expect(mock.updates[0]?.sql).toContain('where "email" is null');
|
|
776
|
+
});
|
|
777
|
+
});
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
Stage the rows each query returns with `mock.enqueueResult(...)` or `mock.setQueryResolver(...)` when the script reads before writing; call `main(trx, { env: { ... } })` when the script takes a `MigrationContext`. See [Kysely-layer mock](../testing.md#kysely-layer-mock-createkyselymock) for the full mock API.
|
|
781
|
+
|
|
782
|
+
These tests need no platform connection and no `tailor-runtime` environment — they run in a plain Vitest setup. Vitest's default `include` pattern already picks up `migrations/**/migrate.test.ts`; if your config narrows `include`, add the migrations directory. The test file is ignored by `tailor deploy` and never ships to the platform.
|
|
449
783
|
|
|
450
|
-
|
|
451
|
-
|
|
784
|
+
### Executing migrate.ts against a local Postgres (PGlite)
|
|
785
|
+
|
|
786
|
+
A statement-level test verifies what the script issues, not what it does to data (e.g., whether a `where` clause matches the rows you intended). To run `main` against real rows locally, back Kysely with [`@electric-sql/pglite`](https://pglite.dev/) — an in-memory PostgreSQL — via `createKyselyPGlite` from `@tailor-platform/sdk/vitest`:
|
|
787
|
+
|
|
788
|
+
```bash
|
|
789
|
+
npm install -D @electric-sql/pglite
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
Create the tables the script touches (matching the shape in the generated `db.ts`), stage rows, then run the script in a transaction:
|
|
793
|
+
|
|
794
|
+
```typescript
|
|
795
|
+
// migrations/0005/migrate.pglite.test.ts
|
|
796
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
797
|
+
import { sql } from "@tailor-platform/sdk/kysely";
|
|
798
|
+
import { createKyselyPGlite } from "@tailor-platform/sdk/vitest";
|
|
799
|
+
import { afterAll, beforeAll, describe, expect, test } from "vitest";
|
|
800
|
+
import type { Database } from "./db";
|
|
801
|
+
import { main } from "./migrate";
|
|
802
|
+
|
|
803
|
+
const db = createKyselyPGlite<Database>(new PGlite());
|
|
804
|
+
|
|
805
|
+
beforeAll(async () => {
|
|
806
|
+
await sql`
|
|
807
|
+
CREATE TABLE "User" (
|
|
808
|
+
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
809
|
+
"name" text NOT NULL,
|
|
810
|
+
"email" text
|
|
811
|
+
)
|
|
812
|
+
`.execute(db);
|
|
813
|
+
});
|
|
814
|
+
|
|
815
|
+
afterAll(async () => {
|
|
816
|
+
await db.destroy();
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
describe("0005 add required email", () => {
|
|
820
|
+
test("backfills null emails and keeps existing ones", async () => {
|
|
821
|
+
await sql`
|
|
822
|
+
INSERT INTO "User" ("name", "email")
|
|
823
|
+
VALUES ('a', NULL), ('b', 'b@example.com')
|
|
824
|
+
`.execute(db);
|
|
825
|
+
|
|
826
|
+
await db.transaction().execute((trx) => main(trx));
|
|
827
|
+
|
|
828
|
+
const rows = await db.selectFrom("User").select(["name", "email"]).orderBy("name").execute();
|
|
829
|
+
expect(rows).toEqual([
|
|
830
|
+
{ name: "a", email: "unknown@example.com" },
|
|
831
|
+
{ name: "b", email: "b@example.com" },
|
|
832
|
+
]);
|
|
833
|
+
});
|
|
834
|
+
});
|
|
835
|
+
```
|
|
836
|
+
|
|
837
|
+
Two caveats keep this from replacing a scratch workspace:
|
|
838
|
+
|
|
839
|
+
- PGlite runs full PostgreSQL, while TailorDB supports [a subset of it](https://docs.tailor.tech/guides/function/accessing-tailordb#supported-sql-queries) — a statement that passes here can still be rejected on deploy.
|
|
840
|
+
- The `CREATE TABLE` statements are yours, so they can drift from the schema the platform actually has.
|
|
841
|
+
|
|
842
|
+
### Beyond unit tests
|
|
843
|
+
|
|
844
|
+
A unit test verifies which statements the script issues; a PGlite test verifies what they do to the rows you staged. Neither runs against your actual data. To cover that:
|
|
845
|
+
|
|
846
|
+
- Run `migration generate` on a clean working copy first, review `diff.json`, then run again after editing tables to ensure the diff matches what you intended.
|
|
452
847
|
- For non-trivial migrations, apply against a scratch workspace before promoting to staging or production.
|
|
453
848
|
|
|
454
849
|
## Environment-Specific Strategies
|
|
@@ -481,6 +876,12 @@ For genuinely different schemas across environments, prefer separate workspaces
|
|
|
481
876
|
2. Restore the file from version control (`git checkout -- <path>`), or regenerate migration files with `migration generate` / `migration script`.
|
|
482
877
|
3. Do not hand-edit `schema.json` or `diff.json`; they are managed by the CLI.
|
|
483
878
|
|
|
879
|
+
### "Unsupported migration file format version" error
|
|
880
|
+
|
|
881
|
+
**Cause:** A `schema.json` or `diff.json` file is older or newer than the format versions supported by the installed SDK.
|
|
882
|
+
|
|
883
|
+
**Resolution:** Follow the ordering in the error message. For an older history, restore an SDK version that can read every file, run `migration rebaseline`, commit and deploy the new baseline everywhere, and then upgrade. For a file produced by a newer SDK, upgrade the SDK that is reading it. Do not hand-edit the version field.
|
|
884
|
+
|
|
484
885
|
### "No machine user available for migration execution"
|
|
485
886
|
|
|
486
887
|
**Cause:** Neither `migration.machineUser` is set nor are there any machine users in `auth.machineUsers`.
|
|
@@ -495,7 +896,7 @@ For genuinely different schemas across environments, prefer separate workspaces
|
|
|
495
896
|
|
|
496
897
|
### Migration script execution fails
|
|
497
898
|
|
|
498
|
-
**Cause:** Runtime error in your `migrate.ts`, a permission error from the machine user, or a constraint violation when post-migration tightens
|
|
899
|
+
**Cause:** Runtime error in your `migrate.ts`, a permission error from the machine user, or a constraint violation when post-migration tightens tables.
|
|
499
900
|
|
|
500
901
|
**Resolution:** Read the `Logs:` block. Fix the script or the data assumption it relies on, and re-run `tailor deploy`. The label is not bumped on failure, so the same migration retries.
|
|
501
902
|
|