masterrecord 1.2.3 → 1.2.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.
package/CHANGES.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.2.5 — documentation catch-up
4
+
5
+ Docs-only. Brought `docs/MIGRATIONS_GUIDE.md` up to date with the 1.2.x work that was previously only in this changelog:
6
+
7
+ - New **Indexes** section (`createIndex` / `createCompositeIndex`, incl. `unique`).
8
+ - New **Partial / filtered indexes** section (`where`) with the per-engine matrix (Postgres/SQLite native, MySQL throws).
9
+ - 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).
10
+
11
+ No code changes.
12
+
13
+ ## v1.2.4 — partial / filtered indexes (enterprise parity)
14
+
15
+ 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:
16
+
17
+ ```javascript
18
+ // declarative (context)
19
+ this.compositeIndex(Setting, ['scope_id'], { unique: true, where: 'is_default = 1' });
20
+
21
+ // or in a migration
22
+ await this.createCompositeIndex({ tableName: 'Setting', columns: ['scope_id'], indexName: 'one_default', unique: true, where: 'is_default = 1' });
23
+ // single-column: await this.createIndex({ tableName, columnName, indexName, unique: true, where });
24
+ ```
25
+
26
+ - **PostgreSQL / SQLite:** native partial index (`CREATE [UNIQUE] INDEX … WHERE <predicate>`).
27
+ - **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.
28
+ - `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.
29
+ - `createIndex` (single column) gained `unique` support along the way.
30
+ - `where` is a raw, developer-authored SQL predicate (like identifiers) — not for user input.
31
+
32
+ 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.
33
+
3
34
  ## v1.2.3 — self-contained incremental migrations (fixes silent addColumn no-op across DBs)
4
35
 
5
36
  **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.
@@ -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){
@@ -119,12 +119,14 @@ export default ${this.name};
119
119
  }
120
120
 
121
121
  createCompositeIndex(type, indexInfo){
122
- const indexInfoStr = JSON.stringify({
122
+ const baked = {
123
123
  tableName: indexInfo.tableName,
124
124
  columns: indexInfo.columns,
125
125
  indexName: indexInfo.indexName,
126
126
  unique: indexInfo.unique
127
- });
127
+ };
128
+ if (indexInfo.where) baked.where = indexInfo.where; // partial/filtered index
129
+ const indexInfoStr = JSON.stringify(baked);
128
130
 
129
131
  if(type === "up"){
130
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
  }
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) {
@@ -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,69 @@ 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
+ - **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.
308
+ - **Observable DDL.** Every statement run by a migration is logged as `[masterrecord:migration] …`, **including in production**. Set `MR_SILENT_MIGRATIONS=true` to suppress it.
309
+
244
310
  ## Seed Data
245
311
 
246
312
  ### Single-row seeding
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
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