masterrecord 1.2.2 → 1.2.4

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,41 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.2.4 — partial / filtered indexes (enterprise parity)
4
+
5
+ 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:
6
+
7
+ ```javascript
8
+ // declarative (context)
9
+ this.compositeIndex(Setting, ['scope_id'], { unique: true, where: 'is_default = 1' });
10
+
11
+ // or in a migration
12
+ await this.createCompositeIndex({ tableName: 'Setting', columns: ['scope_id'], indexName: 'one_default', unique: true, where: 'is_default = 1' });
13
+ // single-column: await this.createIndex({ tableName, columnName, indexName, unique: true, where });
14
+ ```
15
+
16
+ - **PostgreSQL / SQLite:** native partial index (`CREATE [UNIQUE] INDEX … WHERE <predicate>`).
17
+ - **MySQL:** has no partial indexes — masterrecord **throws** at migration time with a clear message (rather than silently emitting a non-filtered index that would enforce the wrong constraint). Enforce the invariant in the write path or via a generated column. This matches how EF Core / Rails / Django behave on MySQL.
18
+ - `where` flows through the full pipeline: entity `static compositeIndexes`, `context.compositeIndex()`, the snapshot diff, and the generated (self-contained) migration. `compositeIndex()` now also accepts a single column.
19
+ - `createIndex` (single column) gained `unique` support along the way.
20
+ - `where` is a raw, developer-authored SQL predicate (like identifiers) — not for user input.
21
+
22
+ New tests: `test/partial-index.test.js` — builder output (PG/SQLite emit `WHERE`, MySQL throws), an end-to-end SQLite test proving a second default per scope is rejected, and a declarative round-trip. Suite green; 0 lint errors.
23
+
24
+ ## v1.2.3 — self-contained incremental migrations (fixes silent addColumn no-op across DBs)
25
+
26
+ **Bug:** an incremental `addColumn` migration could silently no-op on a second database (column never added, migration still recorded as applied). Reproduced and root-caused on prod MySQL.
27
+
28
+ **Mechanism:** `update-database` does not run the literal op in the migration file — it calls `buildUpObject(committedSnapshot.schema, currentEntities)` and passes the result as `table` to `up(table)`. The generated `await this.addColumn(table.public_token)` therefore depended on `table.public_token` being populated, which only happens when that column is in the **snapshot↔entities diff** (`item.newColumns`). The committed snapshot is shared and gets advanced by whichever DB you migrate first (e.g. dev); every subsequent DB (e.g. prod) then diffs to **empty** for that column → `table.public_token` is `undefined` → `schema.addColumn(undefined)` hit its silent `if(table){…}` guard → nothing ran, migration marked applied. `createTable` was immune because `buildUpObject` populates every table regardless of diff; only incremental column ops were affected.
29
+
30
+ **Fixes:**
31
+ 1. **Self-contained generation.** `add-migration` now bakes the full column spec inline — `await this.addColumn({ tableName, name, type, … })` instead of `await this.addColumn(table.public_token)`. Migrations replay deterministically on every database, independent of snapshot state (the standard Rails/Knex/TypeORM model). Applies to `addColumn` and the symmetric `dropColumn` (incl. up/down).
32
+ 2. **Fail loudly.** `schema.addColumn` / `dropColumn` now throw a descriptive error on an incomplete/undefined operand ("…snapshot is ahead of this database…") instead of silently skipping — so legacy `table.<col>`-style migrations can never silently lose a column again.
33
+ 3. **Readiness symmetry.** `addColumn` / `dropColumn` now `await this._ensureReady()` (like `createTable`), and throw if no dialect is active — closing the related (theoretical) async-init gap.
34
+
35
+ New tests: `test/migration-self-contained.test.js` (generation bakes a literal; self-contained add applies despite an empty diff; loud throw on incomplete operand). Suite green (same single pre-existing failure); 0 lint errors.
36
+
37
+ > Existing already-generated migrations keep working; if one uses the old `table.<col>` form and hits the empty-diff case, it now **throws loudly** (fix #2) instead of silently skipping — regenerate it to get the self-contained form.
38
+
3
39
  ## v1.2.2 — deterministic migration snapshots (no transient `tableName` leak)
4
40
 
5
41
  The generated `*_contextSnapShot.json` could differ run-to-run for an unchanged schema, producing noisy git diffs and occasional spurious "schema changed" detections.
@@ -84,7 +84,7 @@ class EntityModelBuilder {
84
84
  };
85
85
  }
86
86
 
87
- // Object: { columns: [...], name?, unique? }
87
+ // Object: { columns: [...], name?, unique?, where? }
88
88
  if (!index.columns || !Array.isArray(index.columns)) {
89
89
  throw new Error(`Composite index must have 'columns' array`);
90
90
  }
@@ -92,11 +92,15 @@ class EntityModelBuilder {
92
92
  const name = index.name ||
93
93
  `idx_${tableName.toLowerCase()}_${index.columns.join('_')}`;
94
94
 
95
- return {
95
+ const normalized = {
96
96
  columns: index.columns,
97
97
  name: name,
98
98
  unique: index.unique || false
99
99
  };
100
+ // Partial/filtered index predicate (Postgres/SQLite). Raw SQL,
101
+ // developer-authored. Carried through to migration generation.
102
+ if (index.where) normalized.where = index.where;
103
+ return normalized;
100
104
  });
101
105
  }
102
106
 
@@ -246,10 +246,18 @@ class migrationMySQLQuery {
246
246
  }
247
247
 
248
248
  createIndex(indexInfo){
249
+ // MySQL has no partial/filtered indexes — fail loudly rather than
250
+ // silently emit a non-filtered index (which would enforce the wrong
251
+ // constraint). Enforce the invariant in the write path, or use a
252
+ // generated column. Postgres and SQLite support `where` natively.
253
+ if (indexInfo.where) {
254
+ throw new Error(`masterrecord: MySQL does not support partial/filtered indexes (the \`where\` option on index '${indexInfo.indexName}'). Enforce this invariant in the write path (e.g. a transactional clear-then-set), or use a generated column. Postgres and SQLite support partial indexes natively.`);
255
+ }
249
256
  const indexName = indexInfo.indexName === true
250
257
  ? `idx_${indexInfo.tableName.toLowerCase()}_${indexInfo.columnName.toLowerCase()}`
251
258
  : indexInfo.indexName;
252
- return `CREATE INDEX \`${indexName}\` ON \`${indexInfo.tableName}\`(\`${indexInfo.columnName}\`)`;
259
+ const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
260
+ return `CREATE ${uniqueKeyword}INDEX \`${indexName}\` ON \`${indexInfo.tableName}\`(\`${indexInfo.columnName}\`)`;
253
261
  }
254
262
 
255
263
  dropIndex(indexInfo){
@@ -260,6 +268,9 @@ class migrationMySQLQuery {
260
268
  }
261
269
 
262
270
  createCompositeIndex(indexInfo){
271
+ if (indexInfo.where) {
272
+ throw new Error(`masterrecord: MySQL does not support partial/filtered indexes (the \`where\` option on index '${indexInfo.indexName}'). Enforce this invariant in the write path (e.g. a transactional clear-then-set), or use a generated column. Postgres and SQLite support partial indexes natively.`);
273
+ }
263
274
  const columns = indexInfo.columns.map(c => `\`${c}\``).join(', ');
264
275
  const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
265
276
  return `CREATE ${uniqueKeyword}INDEX \`${indexInfo.indexName}\` ON \`${indexInfo.tableName}\`(${columns})`;
@@ -243,7 +243,11 @@ class migrationPostgresQuery {
243
243
  const indexName = indexInfo.indexName === true
244
244
  ? `idx_${indexInfo.tableName.toLowerCase()}_${indexInfo.columnName.toLowerCase()}`
245
245
  : indexInfo.indexName;
246
- return `CREATE INDEX IF NOT EXISTS "${indexName}" ON "${indexInfo.tableName}"("${indexInfo.columnName}")`;
246
+ const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
247
+ // Partial/filtered index — Postgres supports `WHERE <predicate>`.
248
+ // `where` is a raw, developer-authored SQL predicate (not user input).
249
+ const whereClause = indexInfo.where ? ` WHERE ${indexInfo.where}` : '';
250
+ return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS "${indexName}" ON "${indexInfo.tableName}"("${indexInfo.columnName}")${whereClause}`;
247
251
  }
248
252
 
249
253
  dropIndex(indexInfo){
@@ -256,7 +260,8 @@ class migrationPostgresQuery {
256
260
  createCompositeIndex(indexInfo){
257
261
  const columns = indexInfo.columns.map(c => `"${c}"`).join(', ');
258
262
  const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
259
- return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS "${indexInfo.indexName}" ON "${indexInfo.tableName}"(${columns})`;
263
+ const whereClause = indexInfo.where ? ` WHERE ${indexInfo.where}` : '';
264
+ return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS "${indexInfo.indexName}" ON "${indexInfo.tableName}"(${columns})${whereClause}`;
260
265
  }
261
266
 
262
267
  dropCompositeIndex(indexInfo){
@@ -221,7 +221,12 @@ class migrationSQLiteQuery {
221
221
  const indexName = indexInfo.indexName === true
222
222
  ? `idx_${indexInfo.tableName.toLowerCase()}_${indexInfo.columnName.toLowerCase()}`
223
223
  : indexInfo.indexName;
224
- return `CREATE INDEX IF NOT EXISTS ${indexName} ON ${indexInfo.tableName}(${indexInfo.columnName})`;
224
+ const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
225
+ // Partial/filtered index — SQLite supports `WHERE <predicate>` (3.8+).
226
+ // `where` is a raw, developer-authored SQL predicate (like the table/
227
+ // column identifiers), not user input.
228
+ const whereClause = indexInfo.where ? ` WHERE ${indexInfo.where}` : '';
229
+ return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS ${indexName} ON ${indexInfo.tableName}(${indexInfo.columnName})${whereClause}`;
225
230
  }
226
231
 
227
232
  dropIndex(indexInfo){
@@ -234,7 +239,8 @@ class migrationSQLiteQuery {
234
239
  createCompositeIndex(indexInfo){
235
240
  const columns = indexInfo.columns.join(', ');
236
241
  const uniqueKeyword = indexInfo.unique ? 'UNIQUE ' : '';
237
- return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS ${indexInfo.indexName} ON ${indexInfo.tableName}(${columns})`;
242
+ const whereClause = indexInfo.where ? ` WHERE ${indexInfo.where}` : '';
243
+ return `CREATE ${uniqueKeyword}INDEX IF NOT EXISTS ${indexInfo.indexName} ON ${indexInfo.tableName}(${columns})${whereClause}`;
238
244
  }
239
245
 
240
246
  dropCompositeIndex(indexInfo){
@@ -54,16 +54,17 @@ export default ${this.name};
54
54
  }
55
55
  }
56
56
 
57
- addColumn(type, name, _parent){
58
- if(type === "up"){
59
- this.#up += os.EOL + ` await this.addColumn(table.${name});`
60
- }
61
- else{
62
- this.#down += os.EOL + ` await this.addColumn(table.${name});`
63
- }
57
+ // Bake the resolved column spec inline so the migration is self-contained
58
+ // and replays deterministically on every database — independent of the
59
+ // committed snapshot's state at apply time. (Previously emitted
60
+ // `table.<col>`, re-derived from a live diff, which silently no-op'd when
61
+ // the snapshot was already ahead of the target DB.)
62
+ addColumn(type, spec){
63
+ const stmt = ` await this.addColumn(${JSON.stringify(spec)});`;
64
+ if(type === "up"){ this.#up += os.EOL + stmt; }
65
+ else{ this.#down += os.EOL + stmt; }
64
66
  }
65
- //this.addColumn(table.${parent}.${name});`
66
-
67
+
67
68
  dropTable(type, name){
68
69
  if(type === "up"){
69
70
  this.#down += os.EOL + ` await this.dropTable(table.${name});`
@@ -73,13 +74,10 @@ export default ${this.name};
73
74
  }
74
75
  }
75
76
 
76
- dropColumn(type, name, _parent){
77
- if(type === "up"){
78
- this.#up += os.EOL + ` await this.dropColumn(table.${name});`
79
- }
80
- else{
81
- this.#down += os.EOL + ` await this.dropColumn(table.${name});`
82
- }
77
+ dropColumn(type, spec){
78
+ const stmt = ` await this.dropColumn(${JSON.stringify(spec)});`;
79
+ if(type === "up"){ this.#up += os.EOL + stmt; }
80
+ else{ this.#down += os.EOL + stmt; }
83
81
  }
84
82
 
85
83
  createIndex(type, indexInfo){
@@ -121,12 +119,14 @@ export default ${this.name};
121
119
  }
122
120
 
123
121
  createCompositeIndex(type, indexInfo){
124
- const indexInfoStr = JSON.stringify({
122
+ const baked = {
125
123
  tableName: indexInfo.tableName,
126
124
  columns: indexInfo.columns,
127
125
  indexName: indexInfo.indexName,
128
126
  unique: indexInfo.unique
129
- });
127
+ };
128
+ if (indexInfo.where) baked.where = indexInfo.where; // partial/filtered index
129
+ const indexInfoStr = JSON.stringify(baked);
130
130
 
131
131
  if(type === "up"){
132
132
  this.#up += os.EOL + ` await this.createCompositeIndex(${indexInfoStr});`
@@ -306,12 +306,14 @@ class Migrations{
306
306
  );
307
307
 
308
308
  if (!exists) {
309
- item.newCompositeIndexes.push({
309
+ const info = {
310
310
  tableName: item.name,
311
311
  columns: newIdx.columns,
312
312
  indexName: newIdx.name,
313
313
  unique: newIdx.unique
314
- });
314
+ };
315
+ if (newIdx.where) info.where = newIdx.where; // partial/filtered index
316
+ item.newCompositeIndexes.push(info);
315
317
  }
316
318
  });
317
319
  }
@@ -550,6 +552,33 @@ class Migrations{
550
552
  return false;
551
553
  }
552
554
 
555
+ // Resolve a column's full, JSON-safe definition (for baking a
556
+ // self-contained add/drop into a generated migration). Looks the column
557
+ // up by its DB name (or belongsTo foreignKey) in the entity and copies
558
+ // the DDL-relevant fields plus an explicit tableName. Functions
559
+ // (transform/validators/get/set) are intentionally omitted — they aren't
560
+ // needed for DDL and aren't serializable.
561
+ #columnLiteral(entity, columnName, tableName){
562
+ let def = null;
563
+ for (const key of Object.keys(entity || {})) {
564
+ const d = entity[key];
565
+ if (d && typeof d === 'object') {
566
+ if (d.name === columnName) { def = d; break; }
567
+ if (d.relationshipType === 'belongsTo' && d.foreignKey === columnName) { def = d; break; }
568
+ }
569
+ }
570
+ if (!def) {
571
+ // Should not happen for a detected column; keep minimal + let the
572
+ // schema layer's loud guard catch any incompleteness at apply time.
573
+ return { tableName, name: columnName };
574
+ }
575
+ const spec = { tableName, name: def.name, type: def.type };
576
+ for (const k of ['nullable', 'default', 'unique', 'auto', 'primary', 'typeSize', 'relationshipType', 'foreignKey', 'foreignTable']) {
577
+ if (def[k] !== undefined && def[k] !== null) spec[k] = def[k];
578
+ }
579
+ return spec;
580
+ }
581
+
553
582
  template(name, oldSchema, newSchema, newSeedData = {}, seedConfig = {}, currentEnv = null){
554
583
  const MT = new MigrationTemplate(name);
555
584
  // Determine current environment if not provided
@@ -557,6 +586,7 @@ class Migrations{
557
586
  currentEnv = process.env.NODE_ENV || process.env.master || 'development';
558
587
  }
559
588
  const tables = this.#buildMigrationObject(oldSchema, newSchema, newSeedData);
589
+ const self = this;
560
590
 
561
591
  tables.forEach(function (item, _index) {
562
592
  // (Whole-table create/drop is handled below via item.newTables /
@@ -570,15 +600,21 @@ class Migrations{
570
600
  MT.dropTable("down", item.name);
571
601
  });
572
602
 
573
- // add new columns for table
603
+ // Add new columns. Bake the FULL column spec into the generated
604
+ // migration (self-contained) instead of `table.<col>`, which was
605
+ // re-derived from a live snapshot↔entities diff at apply time and
606
+ // silently no-op'd on any database whose diff was empty (snapshot
607
+ // already advanced by the first DB migrated).
574
608
  item.newColumns.forEach(function (column, _index) {
575
- MT.addColumn("up", column, item.name);
576
- MT.dropColumn("down", column, item.name);
609
+ const spec = self.#columnLiteral(item.new, column, item.name);
610
+ MT.addColumn("up", spec);
611
+ MT.dropColumn("down", spec);
577
612
  });
578
613
 
579
614
  item.deletedColumns.forEach(function (column, _index) {
580
- MT.dropColumn("up", column, item.name);
581
- MT.addColumn("down",column, item.name);
615
+ const spec = self.#columnLiteral(item.old, column, item.name);
616
+ MT.dropColumn("up", spec);
617
+ MT.addColumn("down", spec);
582
618
  });
583
619
 
584
620
  item.updatedColumns.forEach(function (column, _index) {
@@ -215,38 +215,63 @@ class schema{
215
215
 
216
216
  // create obj to convert into create sql
217
217
  async addColumn(table){
218
- // Adds a column on all three engines. Each engine's _execute throws on
219
- // failure (no silent swallow), so a failed ADD COLUMN aborts the
220
- // migration loudly rather than being skipped.
221
- if(table){
222
- if(this.context.isSQLite){
218
+ // Ensure the async DB init (MySQL/Postgres) has completed before we
219
+ // read dialect flags / run DDL — matches createTable(), which always
220
+ // did this. (addColumn/dropColumn previously skipped it.)
221
+ await this._ensureReady();
222
+
223
+ // FAIL LOUDLY instead of silently skipping. An older generated
224
+ // migration re-derives its column from a live diff (`table.<col>`) at
225
+ // apply time; when the committed snapshot is already AHEAD of THIS
226
+ // database the diff is empty and `table` is undefined — which used to
227
+ // hit a silent `if(table){…}` guard, mark the migration applied, and
228
+ // never add the column. (Newer migrations bake the full spec inline,
229
+ // so this only guards legacy/edge cases.)
230
+ if(!table || !table.tableName || !table.name || !table.type){
231
+ throw new Error(
232
+ `masterrecord: addColumn received an incomplete column definition (${JSON.stringify(table)}). ` +
233
+ `This usually means the committed snapshot is already ahead of this database, so the migration ` +
234
+ `could not re-derive the column from the diff. Regenerate the migration (it now bakes the full ` +
235
+ `column spec inline) or apply it against a database whose snapshot matches.`
236
+ );
237
+ }
238
+ if(!this.context.isSQLite && !this.context.isMySQL && !this.context.isPostgres){
239
+ throw new Error('masterrecord: addColumn — no database dialect is active (context not initialized).');
240
+ }
241
+
242
+ if(this.context.isSQLite){
223
243
  var queryBuilder = new sqliteQuery();
224
- // Fixed: Use addColum (consistent with MySQL/PostgreSQL) instead of alterColumn
225
- // This allows explicit column definitions to work, not just CLI-generated migrations
226
- // Note: No need to set table.realDataType - columnMapping handles type conversion internally
227
244
  var query = queryBuilder.addColum(table);
228
245
  await this.context._execute(query);
229
246
  }
230
247
 
231
248
  if(this.context.isMySQL){
232
249
  var queryBuilder = new sqlquery();
233
- // Note: No need to set table.realDataType - columnMapping handles type conversion internally
234
250
  var query = queryBuilder.addColum(table);
235
251
  await this.context._execute(query);
236
252
  }
237
253
 
238
254
  if(this.context.isPostgres){
239
255
  var queryBuilder = new postgresQuery();
240
- // Note: No need to set table.realDataType - columnMapping handles type conversion internally
241
256
  var query = queryBuilder.addColum(table);
242
257
  await this.context._execute(query);
243
258
  }
244
- }
245
259
 
246
260
  // add column to database
247
261
  }
248
262
 
249
263
  async dropColumn(table){
264
+ await this._ensureReady();
265
+ // Fail loudly rather than silently skipping (see addColumn) — a drift
266
+ // between the committed snapshot and this database can leave the
267
+ // migration's re-derived `table.<col>` undefined.
268
+ if(!table || !table.tableName || !table.name){
269
+ throw new Error(
270
+ `masterrecord: dropColumn received an incomplete column definition (${JSON.stringify(table)}). ` +
271
+ `The committed snapshot may be ahead of this database. Regenerate the migration (it now bakes the ` +
272
+ `full column spec inline) or apply it against a database whose snapshot matches.`
273
+ );
274
+ }
250
275
  if(table){
251
276
  if(this.fullTable){
252
277
  // SQLite doesn't support `IF EXISTS` on DROP COLUMN, so
package/context.js CHANGED
@@ -1369,9 +1369,12 @@ class context {
1369
1369
  throw new Error('compositeIndex: model must be entity class or table name');
1370
1370
  }
1371
1371
 
1372
- // Validate columns
1373
- if (!Array.isArray(columns) || columns.length < 2) {
1374
- throw new Error('compositeIndex: columns must be array with at least 2 columns');
1372
+ // Validate columns. A single column is allowed when a partial/unique
1373
+ // filter is in play (e.g. one-default-per-scope: unique on [scope_id]
1374
+ // WHERE is_default) — that's a legitimate filtered index, matching
1375
+ // EF Core's HasIndex(...).HasFilter(...).IsUnique().
1376
+ if (!Array.isArray(columns) || columns.length < 1) {
1377
+ throw new Error('compositeIndex: columns must be a non-empty array');
1375
1378
  }
1376
1379
 
1377
1380
  // Auto-generate name if not provided
@@ -1383,6 +1386,9 @@ class context {
1383
1386
  name: indexName,
1384
1387
  unique: options.unique || false
1385
1388
  };
1389
+ // Partial/filtered index predicate (Postgres/SQLite); raw SQL.
1390
+ // MySQL throws at migration time (no partial-index support).
1391
+ if (options.where) indexDef.where = options.where;
1386
1392
 
1387
1393
  // Store in context for later merging with entity-defined indexes
1388
1394
  if (!this.__contextCompositeIndexes) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
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",
package/readme.md CHANGED
@@ -2175,6 +2175,46 @@ class User {
2175
2175
  - **Single index**: Column queried independently (`WHERE email = ?`)
2176
2176
  - **Composite index**: Columns queried together (`WHERE last_name = ? AND first_name = ?`)
2177
2177
 
2178
+ ### Partial / Filtered Indexes
2179
+
2180
+ Add a `where` predicate to index on (and enforce uniqueness over) only the rows that match — the same capability as EF Core's `HasFilter`, TypeORM/Sequelize `where`, Rails `:where`, and Django `condition`.
2181
+
2182
+ The canonical use is **one-default-per-scope** — at most one `is_default = 1` row per `scope_id`, enforced by the database:
2183
+
2184
+ ```javascript
2185
+ // Declaratively, on the context:
2186
+ class AppContext extends context {
2187
+ onConfig() {
2188
+ this.dbset(Setting);
2189
+ this.compositeIndex(Setting, ['scope_id'], {
2190
+ unique: true,
2191
+ where: 'is_default = 1', // raw SQL predicate
2192
+ name: 'one_default_per_scope',
2193
+ });
2194
+ }
2195
+ }
2196
+
2197
+ // Or in a hand-written migration:
2198
+ await this.createCompositeIndex({
2199
+ tableName: 'Setting',
2200
+ columns: ['scope_id'],
2201
+ indexName: 'one_default_per_scope',
2202
+ unique: true,
2203
+ where: 'is_default = 1',
2204
+ });
2205
+ // single-column form: this.createIndex({ tableName, columnName, indexName, unique: true, where })
2206
+ ```
2207
+
2208
+ Other common uses: unique email among non-deleted rows (`where: 'deleted_at IS NULL'`), indexing only active records (`where: 'status = \'active\''`).
2209
+
2210
+ | Engine | Behavior |
2211
+ | --- | --- |
2212
+ | PostgreSQL | native partial index (`CREATE UNIQUE INDEX … WHERE …`) |
2213
+ | SQLite | native partial index (3.8+) |
2214
+ | MySQL | **not supported** — MySQL has no partial indexes. masterrecord **throws** at migration time (rather than silently creating a non-filtered index that would enforce the wrong constraint). Enforce the invariant in the write path (a transactional clear-then-set) or use a generated column. |
2215
+
2216
+ > `where` is a **raw SQL predicate** authored by you (like table/column names), not a place for user input.
2217
+
2178
2218
  ---
2179
2219
 
2180
2220
  ## Seed Data