masterrecord 1.3.3 → 1.5.5

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.
@@ -1,508 +0,0 @@
1
- # MasterRecord Migrations Guide
2
-
3
- Complete guide for database migrations and seed data with MySQL, SQLite, and PostgreSQL.
4
-
5
- > **ESM only.** MasterRecord v1.0+ is a pure ESM package. Every example below uses `import`/`export default` syntax. Your host project must have `"type": "module"` in its `package.json`.
6
-
7
- ## Table of Contents
8
- - [Overview](#overview)
9
- - [Quick Start](#quick-start)
10
- - [Database Support](#database-support)
11
- - [Creating Migrations](#creating-migrations)
12
- - [Indexes](#indexes)
13
- - [Partial / filtered indexes](#partial--filtered-indexes-where)
14
- - [Reliability & observability](#reliability--observability)
15
- - [Seed Data](#seed-data)
16
- - [Migration Commands](#migration-commands)
17
- - [Examples](#examples)
18
-
19
- ## Overview
20
-
21
- MasterRecord migrations let you:
22
- - Create and modify database tables from code-first entity definitions
23
- - Track schema changes over time with automatic snapshots
24
- - Seed initial or test data with idempotent inserts
25
- - Roll back changes when needed
26
- - Work consistently across MySQL, SQLite, and PostgreSQL
27
-
28
- ## Quick Start
29
-
30
- ### 1. Set up your context
31
-
32
- ```javascript
33
- // app/models/AppContext.js
34
- // Name the file after the context class so `masterrecord enable-migrations AppContext`
35
- // can find it (the CLI resolves the context by file name: *AppContext.js).
36
- import context from 'masterrecord/context';
37
- import User from './User.js';
38
- import Post from './Post.js';
39
-
40
- class AppContext extends context {
41
- constructor() {
42
- super();
43
- this.env('config/environments');
44
- this.dbset(User);
45
- this.dbset(Post);
46
- }
47
- }
48
-
49
- export default AppContext;
50
- ```
51
-
52
- ### 2. Enable migrations (one-time)
53
-
54
- ```bash
55
- masterrecord enable-migrations AppContext
56
- ```
57
-
58
- This creates a snapshot file at `app/models/db/migrations/appcontext_contextSnapShot.json`.
59
-
60
- ### 3. Generate a migration
61
-
62
- ```bash
63
- masterrecord add-migration InitialCreate AppContext
64
- ```
65
-
66
- MasterRecord diffs the current entity definitions against the snapshot and emits a migration file at `app/models/db/migrations/<timestamp>_InitialCreate_migration.js`.
67
-
68
- ### 4. Review the generated migration
69
-
70
- ```javascript
71
- // app/models/db/migrations/1700000000000_InitialCreate_migration.js
72
- import masterrecord from 'masterrecord';
73
-
74
- class InitialCreate extends masterrecord.schema {
75
- constructor(context) {
76
- super(context);
77
- }
78
-
79
- async up(table) {
80
- await this.init(table);
81
- await this.createTable(table.User);
82
- await this.createTable(table.Post);
83
- }
84
-
85
- async down(table) {
86
- await this.init(table);
87
- await this.dropTable(table.Post);
88
- await this.dropTable(table.User);
89
- }
90
- }
91
-
92
- export default InitialCreate;
93
- ```
94
-
95
- ### 5. Apply migrations
96
-
97
- ```bash
98
- masterrecord update-database AppContext
99
- ```
100
-
101
- ## Database Support
102
-
103
- ### PostgreSQL
104
- - SERIAL / BIGSERIAL auto-increment
105
- - Native BOOLEAN, UUID, JSONB
106
- - Parameterized queries (`$1`, `$2`, …)
107
- - `ON CONFLICT DO NOTHING` for idempotent seeds
108
-
109
- ### MySQL
110
- - `AUTO_INCREMENT` primary keys
111
- - TINYINT for booleans (0/1)
112
- - JSON column type
113
- - `INSERT IGNORE` for idempotent seeds
114
-
115
- ### SQLite
116
- - `AUTOINCREMENT` primary keys
117
- - INTEGER for booleans (0/1)
118
- - `INSERT OR IGNORE` for idempotent seeds
119
-
120
- ## Creating Migrations
121
-
122
- Migration files are classes that extend `masterrecord.schema`. They must implement `async up(table)` and `async down(table)` methods. Always call `await this.init(table)` first inside each method.
123
-
124
- ### Creating a table
125
-
126
- ```javascript
127
- import masterrecord from 'masterrecord';
128
-
129
- class CreateUsers extends masterrecord.schema {
130
- async up(table) {
131
- await this.init(table);
132
- await this.createTable(table.User);
133
- }
134
-
135
- async down(table) {
136
- await this.init(table);
137
- await this.dropTable(table.User);
138
- }
139
- }
140
-
141
- export default CreateUsers;
142
- ```
143
-
144
- ### Adding columns
145
-
146
- ```javascript
147
- import masterrecord from 'masterrecord';
148
-
149
- class AddPhoneToUser extends masterrecord.schema {
150
- async up(table) {
151
- await this.init(table);
152
- await this.addColumn({
153
- tableName: 'User',
154
- name: 'phone_number',
155
- type: 'string',
156
- });
157
- }
158
-
159
- async down(table) {
160
- await this.init(table);
161
- await this.dropColumn({ tableName: 'User', name: 'phone_number' });
162
- }
163
- }
164
-
165
- export default AddPhoneToUser;
166
- ```
167
-
168
- ### Modifying columns
169
-
170
- ```javascript
171
- import masterrecord from 'masterrecord';
172
-
173
- class MakeAgeRequired extends masterrecord.schema {
174
- async up(table) {
175
- await this.init(table);
176
- await this.alterColumn({
177
- tableName: 'User',
178
- table: { name: 'age', type: 'integer', nullable: false, default: 0 },
179
- });
180
- }
181
-
182
- async down(table) {
183
- await this.init(table);
184
- await this.alterColumn({
185
- tableName: 'User',
186
- table: { name: 'age', type: 'integer', nullable: true },
187
- });
188
- }
189
- }
190
-
191
- export default MakeAgeRequired;
192
- ```
193
-
194
- ### Full-text search indexes
195
-
196
- Create and drop portable FTS indexes. Each engine emits its native equivalent — FTS5 virtual table + triggers on SQLite, `tsvector` column + GIN index + maintenance trigger on PostgreSQL, `FULLTEXT INDEX` on MySQL.
197
-
198
- ```javascript
199
- import masterrecord from 'masterrecord';
200
-
201
- class AddMemoryDocFts extends masterrecord.schema {
202
- async up(table) {
203
- await this.init(table);
204
- await this.createTable(table.MemoryDoc);
205
- await this.createFullTextIndex({
206
- tableName: 'MemoryDoc',
207
- columns: ['title', 'body'],
208
- });
209
- }
210
-
211
- async down(table) {
212
- await this.init(table);
213
- await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
214
- await this.dropTable(table.MemoryDoc);
215
- }
216
- }
217
-
218
- export default AddMemoryDocFts;
219
- ```
220
-
221
- `createFullTextIndex(info)` accepts:
222
- - `tableName` (string, required)
223
- - `columns` (string[], required) — columns to index
224
- - `indexName` (string, optional) — overrides the generated name (`idx_<table>_fts`)
225
- - `config` (string, optional) — Postgres-only `to_tsvector` config (defaults to `'english'`)
226
-
227
- Runtime querying uses the matching `.search({ in, query })` dbset method — see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md) for engine-specific query syntax and ranking caveats.
228
-
229
- ### Renaming columns
230
-
231
- ```javascript
232
- import masterrecord from 'masterrecord';
233
-
234
- class RenameUsernameColumn extends masterrecord.schema {
235
- async up(table) {
236
- await this.init(table);
237
- await this.renameColumn({ tableName: 'User', name: 'username', newName: 'user_name' });
238
- }
239
-
240
- async down(table) {
241
- await this.init(table);
242
- await this.renameColumn({ tableName: 'User', name: 'user_name', newName: 'username' });
243
- }
244
- }
245
-
246
- export default RenameUsernameColumn;
247
- ```
248
-
249
- ### Indexes
250
-
251
- ```javascript
252
- import masterrecord from 'masterrecord';
253
-
254
- class AddIndexes extends masterrecord.schema {
255
- async up(table) {
256
- await this.init(table);
257
-
258
- // Single-column index (add `unique: true` for a unique index)
259
- await this.createIndex({ tableName: 'User', columnName: 'email', indexName: 'idx_user_email', unique: true });
260
-
261
- // Composite index
262
- await this.createCompositeIndex({ tableName: 'Order', columns: ['organization_id', 'created_at'], indexName: 'idx_org_created' });
263
- }
264
-
265
- async down(table) {
266
- await this.init(table);
267
- await this.dropIndex({ tableName: 'User', indexName: 'idx_user_email' });
268
- await this.dropCompositeIndex({ tableName: 'Order', indexName: 'idx_org_created' });
269
- }
270
- }
271
-
272
- export default AddIndexes;
273
- ```
274
-
275
- #### Partial / filtered indexes (`where`)
276
-
277
- Add a `where` predicate to index/enforce uniqueness over only the matching rows — e.g. **one default per scope**, or unique email among non-deleted rows:
278
-
279
- ```javascript
280
- // at most one is_default = 1 per scope_id (DB-enforced)
281
- await this.createCompositeIndex({
282
- tableName: 'Setting',
283
- columns: ['scope_id'],
284
- indexName: 'one_default_per_scope',
285
- unique: true,
286
- where: 'is_default = 1', // raw SQL predicate (not user input)
287
- });
288
-
289
- // unique email only among rows that aren't soft-deleted
290
- await this.createIndex({
291
- tableName: 'User', columnName: 'email', indexName: 'uniq_active_email',
292
- unique: true, where: 'deleted_at IS NULL',
293
- });
294
- ```
295
-
296
- | Engine | `where` support |
297
- | --- | --- |
298
- | PostgreSQL | native partial index |
299
- | SQLite | native partial index (3.8+) |
300
- | MySQL | **not supported** — masterrecord throws at migration time (MySQL has no partial indexes). Enforce the invariant in the write path or via a generated column. |
301
-
302
- You can also declare these on the entity/context (`this.compositeIndex(Model, ['scope_id'], { unique: true, where: 'is_default = 1' })`) and `add-migration` will generate the call for you.
303
-
304
- ## Reliability & observability
305
-
306
- Migrations are designed to fail loudly and be observable — there are no silent no-ops:
307
-
308
- - **Generated migrations are self-contained.** `add-migration` bakes the full column spec into each `addColumn`/`dropColumn` (`await this.addColumn({ tableName, name, type, … })`), so a migration replays deterministically on every database regardless of how far the committed snapshot has advanced.
309
- - **Idempotent column ops.** `addColumn` skips if the column already exists (symmetric with `dropColumn`'s skip-if-gone and `createTable`'s `IF NOT EXISTS`), so re-running a migration — or applying one to a database that already has part of the schema — is safe. The existence check uses live introspection, which throws on a real error, so a genuine failure still aborts loudly.
310
- - **Loud failures.** `addColumn`/`dropColumn` throw on an incomplete operand; introspection (`tableExists`/`getTableInfo`) throws on a real error instead of masquerading as “table absent”; MySQL throws on partial-index `where`. A failed step aborts the migration rather than marking it applied.
311
- - **Observable DDL.** Every statement run by a migration is logged as `[masterrecord:migration] …`, **including in production**. Set `MR_SILENT_MIGRATIONS=true` to suppress it.
312
-
313
- ## Seed Data
314
-
315
- ### Single-row seeding
316
-
317
- ```javascript
318
- import masterrecord from 'masterrecord';
319
-
320
- class SeedRoles extends masterrecord.schema {
321
- async up(table) {
322
- await this.init(table);
323
- await this.createTable(table.Role);
324
-
325
- this.seed('Role', { name: 'Admin', description: 'Administrator role' });
326
- this.seed('Role', { name: 'User', description: 'Regular user role' });
327
- }
328
-
329
- async down(table) {
330
- await this.init(table);
331
- await this.dropTable(table.Role);
332
- }
333
- }
334
-
335
- export default SeedRoles;
336
- ```
337
-
338
- ### Bulk seeding (preferred)
339
-
340
- ```javascript
341
- import masterrecord from 'masterrecord';
342
-
343
- class SeedUsers extends masterrecord.schema {
344
- async up(table) {
345
- await this.init(table);
346
- await this.createTable(table.User);
347
-
348
- this.bulkSeed('User', [
349
- { name: 'Alice', email: 'alice@example.com', age: 25 },
350
- { name: 'Bob', email: 'bob@example.com', age: 30 },
351
- { name: 'Charlie', email: 'charlie@example.com', age: 35 },
352
- ]);
353
- }
354
-
355
- async down(table) {
356
- await this.init(table);
357
- await this.dropTable(table.User);
358
- }
359
- }
360
-
361
- export default SeedUsers;
362
- ```
363
-
364
- Seeds are idempotent — re-running a migration won't create duplicate rows, because MasterRecord emits the database-native "insert or ignore" form (`INSERT OR IGNORE`, `INSERT IGNORE`, or `ON CONFLICT DO NOTHING`). This requires a unique constraint or primary key on the target table.
365
-
366
- ### Conditional seeding by database
367
-
368
- ```javascript
369
- import masterrecord from 'masterrecord';
370
-
371
- class SeedSettings extends masterrecord.schema {
372
- async up(table) {
373
- await this.init(table);
374
- await this.createTable(table.Setting);
375
-
376
- if (this.context.isPostgres) {
377
- this.seed('Setting', { key: 'postgres_feature', value: 'enabled' });
378
- }
379
- if (this.context.isMySQL) {
380
- this.seed('Setting', { key: 'mysql_feature', value: 'enabled' });
381
- }
382
- }
383
-
384
- async down(table) {
385
- await this.init(table);
386
- await this.dropTable(table.Setting);
387
- }
388
- }
389
-
390
- export default SeedSettings;
391
- ```
392
-
393
- ## Migration Commands
394
-
395
- ```bash
396
- # Enable migrations for a context (creates snapshot)
397
- masterrecord enable-migrations <ContextName>
398
-
399
- # Generate a new migration from a diff of current entities vs snapshot
400
- masterrecord add-migration <MigrationName> <ContextName>
401
-
402
- # Apply all pending migrations
403
- masterrecord update-database <ContextName>
404
-
405
- # Operate on every context in the project at once
406
- masterrecord enable-migrations-all
407
- masterrecord add-migration-all <MigrationName>
408
- masterrecord update-database-all
409
- ```
410
-
411
- Migration state is tracked in `<contextname>_contextSnapShot.json` alongside the migration files.
412
-
413
- ## Examples
414
-
415
- ### Example: E-commerce schema
416
-
417
- ```javascript
418
- // app/models/db/migrations/1700000000000_CreateECommerce_migration.js
419
- import masterrecord from 'masterrecord';
420
-
421
- class CreateECommerce extends masterrecord.schema {
422
- async up(table) {
423
- await this.init(table);
424
-
425
- await this.createTable(table.User);
426
- await this.createTable(table.Category);
427
- await this.createTable(table.Product);
428
- await this.createTable(table.Order);
429
- await this.createTable(table.OrderItem);
430
-
431
- this.bulkSeed('Category', [
432
- { name: 'Electronics', slug: 'electronics' },
433
- { name: 'Clothing', slug: 'clothing' },
434
- { name: 'Books', slug: 'books' },
435
- ]);
436
-
437
- this.seed('User', {
438
- name: 'Admin',
439
- email: 'admin@shop.com',
440
- role: 'admin',
441
- });
442
-
443
- this.bulkSeed('Product', [
444
- { name: 'Laptop', price: 999.99, category_id: 1, stock: 50 },
445
- { name: 'T-Shirt', price: 19.99, category_id: 2, stock: 200 },
446
- ]);
447
- }
448
-
449
- async down(table) {
450
- await this.init(table);
451
- await this.dropTable(table.OrderItem);
452
- await this.dropTable(table.Order);
453
- await this.dropTable(table.Product);
454
- await this.dropTable(table.Category);
455
- await this.dropTable(table.User);
456
- }
457
- }
458
-
459
- export default CreateECommerce;
460
- ```
461
-
462
- ### Example: Multi-database-aware migration
463
-
464
- ```javascript
465
- import masterrecord from 'masterrecord';
466
-
467
- class AddUserPreferences extends masterrecord.schema {
468
- async up(table) {
469
- await this.init(table);
470
-
471
- // Works across all databases
472
- await this.addColumn({
473
- tableName: 'User',
474
- name: 'preferences',
475
- type: 'text',
476
- });
477
-
478
- // PostgreSQL: upgrade to native JSONB
479
- if (this.context.isPostgres) {
480
- await this.alterColumn({
481
- tableName: 'User',
482
- table: { name: 'preferences', type: 'jsonb' },
483
- });
484
- }
485
-
486
- this.seed('User', {
487
- name: 'Demo User',
488
- email: 'demo@example.com',
489
- preferences: JSON.stringify({ theme: 'light', notifications: true, language: 'en' }),
490
- });
491
- }
492
-
493
- async down(table) {
494
- await this.init(table);
495
- await this.dropColumn({ tableName: 'User', name: 'preferences' });
496
- }
497
- }
498
-
499
- export default AddUserPreferences;
500
- ```
501
-
502
- ## Best practices
503
-
504
- 1. **Always provide a `down` migration.** Even if it just reverses `createTable` with `dropTable`. It pays off the first time a migration needs to be rolled back.
505
- 2. **Prefer `bulkSeed` over multiple `seed` calls.** It's one INSERT instead of N.
506
- 3. **Test migrations on every target database.** If your app supports MySQL and Postgres, run both sets of migrations in CI.
507
- 4. **Keep migrations small and focused.** One logical change per migration file.
508
- 5. **Never edit an already-applied migration.** Create a new migration that corrects or rolls back the earlier one.