masterrecord 1.2.4 → 1.2.6

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/CHANGES.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.2.6 — idempotent addColumn (skip-if-exists)
4
+
5
+ `schema.addColumn` now **skips if the column already exists**, symmetric with `dropColumn`'s skip-if-gone and `createTable`'s `IF NOT EXISTS`. None of SQLite/MySQL support `ADD COLUMN IF NOT EXISTS`, so it probes the live schema via `getTableInfo` (which throws on a real introspection error — so a genuine failure still aborts loudly; only a clean "already present" result short-circuits, with a `[masterrecord:migration]` skip log).
6
+
7
+ Effect: re-running a migration, or applying one to a database that already has part of the schema, is now safe — the per-migration guards added in 1.2.3 become belt-and-suspenders rather than load-bearing. (belongsTo FK columns are matched by their `foreignKey` name.)
8
+
9
+ New test: idempotent-addColumn case in `test/migration-self-contained.test.js`. Suite green; 0 lint errors.
10
+
11
+ ## v1.2.5 — documentation catch-up
12
+
13
+ Docs-only. Brought `docs/MIGRATIONS_GUIDE.md` up to date with the 1.2.x work that was previously only in this changelog:
14
+
15
+ - New **Indexes** section (`createIndex` / `createCompositeIndex`, incl. `unique`).
16
+ - New **Partial / filtered indexes** section (`where`) with the per-engine matrix (Postgres/SQLite native, MySQL throws).
17
+ - New **Reliability & observability** section: self-contained generated migrations, loud-failure semantics (no silent no-ops), and the `[masterrecord:migration]` DDL logging + `MR_SILENT_MIGRATIONS` env var (which was undocumented).
18
+
19
+ No code changes.
20
+
3
21
  ## v1.2.4 — partial / filtered indexes (enterprise parity)
4
22
 
5
23
  Adds a `where` option to `createIndex` and `createCompositeIndex`, bringing masterrecord to parity with EF Core (`HasFilter`), TypeORM/Sequelize (`where`), Rails (`:where`) and Django (`condition`). The canonical use is **one-default-per-scope** — at most one `is_default = 1` per `scope_id`, enforced by the database:
@@ -239,6 +239,27 @@ class schema{
239
239
  throw new Error('masterrecord: addColumn — no database dialect is active (context not initialized).');
240
240
  }
241
241
 
242
+ // Idempotency: skip if the column already exists — symmetric with
243
+ // dropColumn's skip-if-gone and createTable's IF NOT EXISTS. None of
244
+ // SQLite/MySQL support `ADD COLUMN IF NOT EXISTS`, so probe the live
245
+ // schema instead. getTableInfo throws on a real introspection error
246
+ // (1.2.0), so a genuine failure still aborts loudly; only a clean
247
+ // "column already present" result short-circuits. This makes
248
+ // re-running a migration safe and reduces the per-migration guards to
249
+ // belt-and-suspenders.
250
+ const _engine = this.context._SQLEngine;
251
+ if (_engine && typeof _engine.getTableInfo === 'function') {
252
+ const dbColumn = (table.relationshipType === 'belongsTo' && table.foreignKey) ? table.foreignKey : table.name;
253
+ const existingCols = await _engine.getTableInfo(table.tableName);
254
+ const alreadyExists = Array.isArray(existingCols) && existingCols.some(c => c && c.name === dbColumn);
255
+ if (alreadyExists) {
256
+ if (process.env.MR_SILENT_MIGRATIONS !== 'true') {
257
+ console.log(`[masterrecord:migration] addColumn skipped — ${table.tableName}.${dbColumn} already exists`);
258
+ }
259
+ return;
260
+ }
261
+ }
262
+
242
263
  if(this.context.isSQLite){
243
264
  var queryBuilder = new sqliteQuery();
244
265
  var query = queryBuilder.addColum(table);
@@ -9,6 +9,9 @@ Complete guide for database migrations and seed data with MySQL, SQLite, and Pos
9
9
  - [Quick Start](#quick-start)
10
10
  - [Database Support](#database-support)
11
11
  - [Creating Migrations](#creating-migrations)
12
+ - [Indexes](#indexes)
13
+ - [Partial / filtered indexes](#partial--filtered-indexes-where)
14
+ - [Reliability & observability](#reliability--observability)
12
15
  - [Seed Data](#seed-data)
13
16
  - [Migration Commands](#migration-commands)
14
17
  - [Examples](#examples)
@@ -241,6 +244,70 @@ class RenameUsernameColumn extends masterrecord.schema {
241
244
  export default RenameUsernameColumn;
242
245
  ```
243
246
 
247
+ ### Indexes
248
+
249
+ ```javascript
250
+ import masterrecord from 'masterrecord';
251
+
252
+ class AddIndexes extends masterrecord.schema {
253
+ async up(table) {
254
+ await this.init(table);
255
+
256
+ // Single-column index (add `unique: true` for a unique index)
257
+ await this.createIndex({ tableName: 'User', columnName: 'email', indexName: 'idx_user_email', unique: true });
258
+
259
+ // Composite index
260
+ await this.createCompositeIndex({ tableName: 'Order', columns: ['organization_id', 'created_at'], indexName: 'idx_org_created' });
261
+ }
262
+
263
+ async down(table) {
264
+ await this.init(table);
265
+ await this.dropIndex({ tableName: 'User', indexName: 'idx_user_email' });
266
+ await this.dropCompositeIndex({ tableName: 'Order', indexName: 'idx_org_created' });
267
+ }
268
+ }
269
+
270
+ export default AddIndexes;
271
+ ```
272
+
273
+ #### Partial / filtered indexes (`where`)
274
+
275
+ 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:
276
+
277
+ ```javascript
278
+ // at most one is_default = 1 per scope_id (DB-enforced)
279
+ await this.createCompositeIndex({
280
+ tableName: 'Setting',
281
+ columns: ['scope_id'],
282
+ indexName: 'one_default_per_scope',
283
+ unique: true,
284
+ where: 'is_default = 1', // raw SQL predicate (not user input)
285
+ });
286
+
287
+ // unique email only among rows that aren't soft-deleted
288
+ await this.createIndex({
289
+ tableName: 'User', columnName: 'email', indexName: 'uniq_active_email',
290
+ unique: true, where: 'deleted_at IS NULL',
291
+ });
292
+ ```
293
+
294
+ | Engine | `where` support |
295
+ | --- | --- |
296
+ | PostgreSQL | native partial index |
297
+ | SQLite | native partial index (3.8+) |
298
+ | 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. |
299
+
300
+ 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.
301
+
302
+ ## Reliability & observability
303
+
304
+ Migrations are designed to fail loudly and be observable — there are no silent no-ops:
305
+
306
+ - **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.
307
+ - **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.
308
+ - **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.
309
+ - **Observable DDL.** Every statement run by a migration is logged as `[masterrecord:migration] …`, **including in production**. Set `MR_SILENT_MIGRATIONS=true` to suppress it.
310
+
244
311
  ## Seed Data
245
312
 
246
313
  ### Single-row seeding
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",