masterrecord 1.1.8 → 1.2.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/CHANGES.md +24 -0
- package/Migrations/schema.js +3 -1
- package/SQLLiteEngine.js +33 -20
- package/mySQLEngine.js +25 -12
- package/package.json +1 -1
- package/postgresEngine.js +25 -11
- package/readme.md +38 -52
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.2.0 — reliable schema introspection + observable migrations (fixes silent column-skip)
|
|
4
|
+
|
|
5
|
+
**Bug:** adding a column to an existing table could silently no-op on MySQL/Postgres — the column was never added, with no error. Root cause: `tableExists()` and `getTableInfo()` wrapped everything in `catch (_) { return false / [] }`. Any real introspection failure (a connection/permission/`INFORMATION_SCHEMA` error, or — on Postgres — a `search_path` mismatch) was disguised as *"table absent."* `schema.createTable()` then took its blind `CREATE TABLE IF NOT EXISTS` branch, which is a no-op on an existing table, so `syncTable()` (the code that adds the missing column) never ran. Compounded by migration DDL only being logged when `NODE_ENV !== 'production'`, the whole thing was invisible in prod. SQLite was unaffected in practice because its introspection is a local `PRAGMA` that essentially never errors.
|
|
6
|
+
|
|
7
|
+
**Fix (all three engines + shared schema layer):**
|
|
8
|
+
- **Introspection no longer lies.** `tableExists()` / `getTableInfo()` now distinguish a *genuinely-absent* table (zero rows → `false` / `[]`) from a *real failure* (now **throws** with a descriptive `masterrecord: … introspection failed: …` message). A failed introspection therefore aborts the migration loudly instead of silently routing to a no-op create.
|
|
9
|
+
- **Migrations are observable in production.** DDL run via `_execute` is always logged as `[masterrecord:migration] …` (independent of `NODE_ENV`; set `MR_SILENT_MIGRATIONS=true` to opt out). Runtime queries keep their existing dev-only `[SQL]` logging.
|
|
10
|
+
- Removed the stale `// todo need to work on add column for mysql` — `addColumn()` already works on every engine and now fails loudly on error.
|
|
11
|
+
|
|
12
|
+
**Postgres note:** introspection is scoped to the connection's `search_path` (`current_schemas(false)`); a table in a schema outside the search_path still reads as absent. Surfacing/handling non-default schemas is a separate feature, but real errors now throw rather than masquerading as absence.
|
|
13
|
+
|
|
14
|
+
New tests: `test/schema-sync-introspection.test.js` (createTable syncs a missing column on an existing table; introspection throws on real failure vs `[]`/`false` on genuine absence). Verified on SQLite; the same code paths apply to MySQL/Postgres.
|
|
15
|
+
|
|
16
|
+
## v1.1.9 — docs: correct the seed-data section
|
|
17
|
+
|
|
18
|
+
README "Seed Data" docs described a code path that doesn't exist. Corrected to match what `add-migration` actually generates (verified against `Migrations/migrationTemplate.js`):
|
|
19
|
+
|
|
20
|
+
- Context-level `this.dbset(T).seed({…})` compiles to idempotent **`this.seed('T', …)`** calls — not `table.T.create({…})` (which is not a real method and never emitted).
|
|
21
|
+
- **Both** routes (context-level and hand-written `this.seed()`) are idempotent (`INSERT OR IGNORE` / `INSERT IGNORE` / `ON CONFLICT DO NOTHING`); the old docs wrongly claimed context-level seeds were non-idempotent and had to be removed after the first run.
|
|
22
|
+
- Removed the false "triggers lifecycle hooks / validators" benefit — generated seeds are raw parameterized INSERTs and do **not** run `beforeSave`/`afterSave`/validators (added a note to use `context.Entity.new()` + `save()` when you need those).
|
|
23
|
+
- Fixed the upsert example to the real generated form (`this.context.T.where(...).single()` + `existing.save()` + `this.seed(...)`).
|
|
24
|
+
|
|
25
|
+
Docs-only; no code changes.
|
|
26
|
+
|
|
3
27
|
## v1.1.8 — entity internals/methods are non-enumerable (fixes spread/JSON data loss)
|
|
4
28
|
|
|
5
29
|
**Bug:** entity instances exposed their internals (`__entity`, `__context`, `__ID`, `__dirtyFields`, `__state`, `__name`) and helper methods (`toJSON`, `toObject`, `save`, `delete`, `reload`, `clone`) as **enumerable** own properties (attached by object literal / plain assignment). So spreading or `Object.assign`-ing an entity:
|
package/Migrations/schema.js
CHANGED
|
@@ -215,7 +215,9 @@ class schema{
|
|
|
215
215
|
|
|
216
216
|
// create obj to convert into create sql
|
|
217
217
|
async addColumn(table){
|
|
218
|
-
//
|
|
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.
|
|
219
221
|
if(table){
|
|
220
222
|
if(this.context.isSQLite){
|
|
221
223
|
var queryBuilder = new sqliteQuery();
|
package/SQLLiteEngine.js
CHANGED
|
@@ -143,29 +143,40 @@ class SQLLiteEngine {
|
|
|
143
143
|
|
|
144
144
|
// Introspection helpers
|
|
145
145
|
async tableExists(tableName){
|
|
146
|
+
// A genuinely-absent table returns no row -> false. A real failure
|
|
147
|
+
// (locked/corrupt db, etc.) MUST throw — never disguise an error as
|
|
148
|
+
// "table absent", or schema.createTable() silently blind-creates and
|
|
149
|
+
// skips column syncs with no error.
|
|
146
150
|
try{
|
|
147
151
|
// Use parameterized query to prevent SQL injection
|
|
148
152
|
const sql = `SELECT name FROM sqlite_master WHERE type='table' AND name=?`;
|
|
149
153
|
const row = this.db.prepare(sql).get(tableName);
|
|
150
|
-
return
|
|
151
|
-
}catch(
|
|
154
|
+
return !!row;
|
|
155
|
+
}catch(err){
|
|
156
|
+
throw new Error(`masterrecord: could not determine whether table '${tableName}' exists (SQLite introspection failed): ${err.message}`);
|
|
157
|
+
}
|
|
152
158
|
}
|
|
153
159
|
|
|
154
160
|
async getTableInfo(tableName){
|
|
161
|
+
// Security: Validate table name to prevent SQL injection — PRAGMA
|
|
162
|
+
// can't be parameterized. An invalid name is a programming error and
|
|
163
|
+
// must throw, not be swallowed into an empty column list.
|
|
164
|
+
if (!tableName || typeof tableName !== 'string') {
|
|
165
|
+
throw new Error('Invalid table name: must be a non-empty string');
|
|
166
|
+
}
|
|
167
|
+
// Allow only alphanumeric characters, underscores; must start with letter/underscore
|
|
168
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {
|
|
169
|
+
throw new Error(`Invalid table name format: ${tableName}`);
|
|
170
|
+
}
|
|
155
171
|
try{
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
const sql = `PRAGMA table_info(${tableName})`;
|
|
166
|
-
const rows = this.db.prepare(sql).all();
|
|
167
|
-
return Promise.resolve(rows || []);
|
|
168
|
-
}catch(_){ return Promise.resolve([]); }
|
|
172
|
+
// PRAGMA on a non-existent table returns an empty list (not an
|
|
173
|
+
// error), so a genuinely-absent table is [] — only real failures
|
|
174
|
+
// throw.
|
|
175
|
+
const rows = this.db.prepare(`PRAGMA table_info(${tableName})`).all();
|
|
176
|
+
return rows || [];
|
|
177
|
+
}catch(err){
|
|
178
|
+
throw new Error(`masterrecord: could not read columns for table '${tableName}' (SQLite introspection failed): ${err.message}`);
|
|
179
|
+
}
|
|
169
180
|
}
|
|
170
181
|
|
|
171
182
|
async getCount(queryObject, entity, _context){
|
|
@@ -1300,16 +1311,18 @@ class SQLLiteEngine {
|
|
|
1300
1311
|
if (params && params.length > 0) {
|
|
1301
1312
|
return this._executeWithParams(query, params);
|
|
1302
1313
|
}
|
|
1303
|
-
|
|
1304
|
-
|
|
1314
|
+
// Migration/DDL path — always log so migrations are observable in
|
|
1315
|
+
// production (the gated [SQL] debug log only fires in dev).
|
|
1316
|
+
if (process.env.MR_SILENT_MIGRATIONS !== 'true') {
|
|
1317
|
+
console.log("[masterrecord:migration]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
|
|
1305
1318
|
}
|
|
1306
1319
|
return this.db.exec(query);
|
|
1307
1320
|
}
|
|
1308
1321
|
|
|
1309
1322
|
_executeWithParams(query, params = []){
|
|
1310
|
-
if (process.env.
|
|
1311
|
-
console.
|
|
1312
|
-
console.
|
|
1323
|
+
if (process.env.MR_SILENT_MIGRATIONS !== 'true') {
|
|
1324
|
+
console.log("[masterrecord:migration]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
|
|
1325
|
+
if (params && params.length) console.log("[masterrecord:migration] params", params);
|
|
1313
1326
|
}
|
|
1314
1327
|
return this.db.prepare(query).run(...params);
|
|
1315
1328
|
}
|
package/mySQLEngine.js
CHANGED
|
@@ -237,25 +237,31 @@ class MySQLEngine {
|
|
|
237
237
|
* Introspection: Check if table exists
|
|
238
238
|
*/
|
|
239
239
|
async tableExists(tableName) {
|
|
240
|
+
// A genuinely-absent table yields zero rows -> false. A real failure
|
|
241
|
+
// (connection/permission/INFORMATION_SCHEMA error) MUST throw — never
|
|
242
|
+
// disguise an error as "table absent", or schema.createTable() silently
|
|
243
|
+
// blind-creates (a no-op on an existing table) and skips column syncs.
|
|
244
|
+
let res;
|
|
240
245
|
try {
|
|
241
246
|
const sql = `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`;
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
return false;
|
|
247
|
+
res = await this._runWithParams(sql, [tableName]);
|
|
248
|
+
} catch (err) {
|
|
249
|
+
throw new Error(`masterrecord: could not determine whether table '${tableName}' exists (MySQL introspection failed): ${err.message}`);
|
|
246
250
|
}
|
|
251
|
+
return Array.isArray(res) ? res.length > 0 : !!res?.length;
|
|
247
252
|
}
|
|
248
253
|
|
|
249
254
|
/**
|
|
250
|
-
* Introspection: Get table column information
|
|
255
|
+
* Introspection: Get table column information.
|
|
256
|
+
* Genuinely-absent table -> [] (zero rows); real failures throw.
|
|
251
257
|
*/
|
|
252
258
|
async getTableInfo(tableName) {
|
|
253
259
|
try {
|
|
254
260
|
const sql = `SELECT COLUMN_NAME as name, COLUMN_DEFAULT as dflt_value, IS_NULLABLE as is_nullable, DATA_TYPE as data_type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`;
|
|
255
261
|
const res = await this._runWithParams(sql, [tableName]);
|
|
256
262
|
return res || [];
|
|
257
|
-
} catch (
|
|
258
|
-
|
|
263
|
+
} catch (err) {
|
|
264
|
+
throw new Error(`masterrecord: could not read columns for table '${tableName}' (MySQL introspection failed): ${err.message}`);
|
|
259
265
|
}
|
|
260
266
|
}
|
|
261
267
|
|
|
@@ -999,17 +1005,24 @@ class MySQLEngine {
|
|
|
999
1005
|
* Used by migration schema for non-parameterized DDL queries.
|
|
1000
1006
|
*/
|
|
1001
1007
|
_execute(query, params) {
|
|
1002
|
-
|
|
1008
|
+
// Migration/DDL path — flag it so the statement is always logged
|
|
1009
|
+
// (migrations must be observable in production).
|
|
1010
|
+
return this._runWithParams(query, params || [], { migration: true });
|
|
1003
1011
|
}
|
|
1004
1012
|
|
|
1005
1013
|
/**
|
|
1006
1014
|
* Execute parameterized query with mysql2/promise
|
|
1007
1015
|
*/
|
|
1008
|
-
async _runWithParams(query, params = []) {
|
|
1016
|
+
async _runWithParams(query, params = [], opts = {}) {
|
|
1009
1017
|
try {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1018
|
+
// Migration DDL (opts.migration) is always logged so production
|
|
1019
|
+
// migrations are observable; runtime queries stay behind the
|
|
1020
|
+
// dev/LOG_SQL gate to avoid noise.
|
|
1021
|
+
const isMigration = opts.migration === true;
|
|
1022
|
+
if (isMigration ? process.env.MR_SILENT_MIGRATIONS !== 'true'
|
|
1023
|
+
: (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production')) {
|
|
1024
|
+
console.log(isMigration ? "[masterrecord:migration]" : "[SQL]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
|
|
1025
|
+
if (params && params.length) console.log(isMigration ? "[masterrecord:migration] params" : "[Params]", params);
|
|
1013
1026
|
}
|
|
1014
1027
|
|
|
1015
1028
|
const [results] = await this.pool.execute(query, params);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
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/postgresEngine.js
CHANGED
|
@@ -281,13 +281,20 @@ class postgresEngine {
|
|
|
281
281
|
* migration tracker can call it uniformly across all three drivers.
|
|
282
282
|
*/
|
|
283
283
|
async tableExists(tableName) {
|
|
284
|
+
// A genuinely-absent table yields zero rows -> false. A real failure
|
|
285
|
+
// (connection/permission/information_schema error) MUST throw — never
|
|
286
|
+
// disguise an error as "table absent", or schema.createTable() silently
|
|
287
|
+
// blind-creates (a no-op on an existing table) and skips column syncs.
|
|
288
|
+
// NOTE: scoped to the connection's search_path via current_schemas();
|
|
289
|
+
// a table living in a schema outside the search_path reads as absent.
|
|
290
|
+
let result;
|
|
284
291
|
try {
|
|
285
292
|
const sql = `SELECT 1 FROM information_schema.tables WHERE table_schema = ANY(current_schemas(false)) AND table_name = $1 LIMIT 1`;
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
return false;
|
|
293
|
+
result = await this._runWithParams(sql, [tableName]);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
throw new Error(`masterrecord: could not determine whether table '${tableName}' exists (PostgreSQL introspection failed): ${err.message}`);
|
|
290
296
|
}
|
|
297
|
+
return !!(result && result.rows && result.rows.length > 0);
|
|
291
298
|
}
|
|
292
299
|
|
|
293
300
|
/**
|
|
@@ -317,8 +324,8 @@ class postgresEngine {
|
|
|
317
324
|
`;
|
|
318
325
|
const result = await this._runWithParams(sql, [tableName]);
|
|
319
326
|
return (result && result.rows) ? result.rows : [];
|
|
320
|
-
} catch (
|
|
321
|
-
|
|
327
|
+
} catch (err) {
|
|
328
|
+
throw new Error(`masterrecord: could not read columns for table '${tableName}' (PostgreSQL introspection failed): ${err.message}`);
|
|
322
329
|
}
|
|
323
330
|
}
|
|
324
331
|
|
|
@@ -977,14 +984,21 @@ class postgresEngine {
|
|
|
977
984
|
* Used by migration schema for non-parameterized DDL queries.
|
|
978
985
|
*/
|
|
979
986
|
_execute(query, params) {
|
|
980
|
-
|
|
987
|
+
// Migration/DDL path — flag it so the statement is always logged
|
|
988
|
+
// (migrations must be observable in production).
|
|
989
|
+
return this._runWithParams(query, params || [], { migration: true });
|
|
981
990
|
}
|
|
982
991
|
|
|
983
|
-
async _runWithParams(query, params = []) {
|
|
992
|
+
async _runWithParams(query, params = [], opts = {}) {
|
|
984
993
|
try {
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
994
|
+
// Migration DDL (opts.migration) is always logged so production
|
|
995
|
+
// migrations are observable; runtime queries stay behind the
|
|
996
|
+
// dev/LOG_SQL gate.
|
|
997
|
+
const isMigration = opts.migration === true;
|
|
998
|
+
if (isMigration ? process.env.MR_SILENT_MIGRATIONS !== 'true'
|
|
999
|
+
: (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production')) {
|
|
1000
|
+
console.log(isMigration ? "[masterrecord:migration]" : "[SQL]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
|
|
1001
|
+
if (params && params.length) console.log(isMigration ? "[masterrecord:migration] params" : "[Params]", params);
|
|
988
1002
|
}
|
|
989
1003
|
|
|
990
1004
|
const client = await this.pool.connect();
|
package/readme.md
CHANGED
|
@@ -2215,16 +2215,17 @@ class AppContext extends context {
|
|
|
2215
2215
|
|
|
2216
2216
|
### Automatic Migration Generation
|
|
2217
2217
|
|
|
2218
|
-
When you define seed data
|
|
2218
|
+
When you define seed data on the context, `add-migration` compiles it into idempotent `this.seed(...)` calls in the generated migration:
|
|
2219
2219
|
|
|
2220
2220
|
```javascript
|
|
2221
2221
|
// Your context definition triggers this migration
|
|
2222
2222
|
class Migration_20250205_123456 extends masterrecord.schema {
|
|
2223
2223
|
async up(table) {
|
|
2224
|
-
this.init(table);
|
|
2224
|
+
await this.init(table);
|
|
2225
2225
|
|
|
2226
|
-
// Generated
|
|
2227
|
-
|
|
2226
|
+
// Generated idempotent seed calls — INSERT OR IGNORE (SQLite) /
|
|
2227
|
+
// INSERT IGNORE (MySQL) / ON CONFLICT DO NOTHING (PostgreSQL)
|
|
2228
|
+
await this.seed('User', {
|
|
2228
2229
|
user_name: 'admin',
|
|
2229
2230
|
first_name: 'System',
|
|
2230
2231
|
last_name: 'Administrator',
|
|
@@ -2235,32 +2236,24 @@ class Migration_20250205_123456 extends masterrecord.schema {
|
|
|
2235
2236
|
availability_status: 'online'
|
|
2236
2237
|
});
|
|
2237
2238
|
|
|
2238
|
-
await
|
|
2239
|
-
|
|
2240
|
-
content: 'Hello world',
|
|
2241
|
-
author_id: 1
|
|
2242
|
-
});
|
|
2243
|
-
|
|
2244
|
-
await table.Post.create({
|
|
2245
|
-
title: 'Getting Started',
|
|
2246
|
-
content: 'Tutorial',
|
|
2247
|
-
author_id: 1
|
|
2248
|
-
});
|
|
2239
|
+
await this.seed('Post', { title: 'Welcome', content: 'Hello world', author_id: 1 });
|
|
2240
|
+
await this.seed('Post', { title: 'Getting Started', content: 'Tutorial', author_id: 1 });
|
|
2249
2241
|
}
|
|
2250
2242
|
|
|
2251
2243
|
async down(table) {
|
|
2252
|
-
this.init(table);
|
|
2244
|
+
await this.init(table);
|
|
2253
2245
|
// Seed data typically not removed in down migrations
|
|
2254
2246
|
}
|
|
2255
2247
|
}
|
|
2256
2248
|
```
|
|
2257
2249
|
|
|
2258
|
-
### Benefits of
|
|
2250
|
+
### Benefits of context-level seed
|
|
2251
|
+
|
|
2252
|
+
1. **Declarative**: seed data lives with your context definition and is versioned alongside the schema.
|
|
2253
|
+
2. **Idempotent**: the generated `this.seed()` calls use the engine's insert-or-ignore form, so re-running migrations never duplicates rows or errors on an existing key.
|
|
2254
|
+
3. **Environment-aware**: scope seeds with `.when(env)`, and use upsert / `seedFactory` for generated data.
|
|
2259
2255
|
|
|
2260
|
-
|
|
2261
|
-
2. **Validation**: Uses entity field definitions and validators
|
|
2262
|
-
3. **Type Safety**: Ensures fields match entity schema
|
|
2263
|
-
4. **Maintainable**: Changes to entity structure reflected automatically
|
|
2256
|
+
> **Note:** generated seeds are raw parameterized INSERTs (via `this.seed()`), so they do **not** run entity lifecycle hooks (`beforeSave`/`afterSave`) or validators. If you need those to run on seeded rows, insert them through `context.Entity.new()` + `save()` in application code instead.
|
|
2264
2257
|
|
|
2265
2258
|
### Manual Seed Methods (Advanced)
|
|
2266
2259
|
|
|
@@ -2294,44 +2287,37 @@ class Migration_20250205_123456 extends masterrecord.schema {
|
|
|
2294
2287
|
|
|
2295
2288
|
### Idempotency
|
|
2296
2289
|
|
|
2297
|
-
**
|
|
2298
|
-
- Generates plain `create()` calls
|
|
2299
|
-
- Fails if primary key exists (user must remove seed data after first migration)
|
|
2300
|
-
- Best for one-time initial setup data
|
|
2301
|
-
|
|
2302
|
-
**Manual approach** (idempotent):
|
|
2303
|
-
- Uses database-specific INSERT OR IGNORE syntax
|
|
2290
|
+
**Both** routes are idempotent — context-level seed compiles to `this.seed()`, and `this.seed()` emits the engine's insert-or-ignore form:
|
|
2304
2291
|
- SQLite: `INSERT OR IGNORE INTO`
|
|
2305
2292
|
- MySQL: `INSERT IGNORE INTO`
|
|
2306
2293
|
- PostgreSQL: `INSERT ... ON CONFLICT DO NOTHING`
|
|
2307
|
-
- Best for repeatable migrations and re-seeding
|
|
2308
2294
|
|
|
2309
|
-
|
|
2295
|
+
Re-running a migration never creates duplicates or throws on an existing primary key, so you do **not** need to remove seed data after the first run.
|
|
2296
|
+
|
|
2310
2297
|
```javascript
|
|
2311
|
-
// Context-level (
|
|
2298
|
+
// Context-level (declarative) — generated into a this.seed() migration
|
|
2312
2299
|
this.dbset(User).seed({ id: 1, name: 'admin' });
|
|
2313
|
-
// After first migration, remove or comment out seed data
|
|
2314
2300
|
|
|
2315
|
-
// Manual (
|
|
2301
|
+
// Manual (in a migration) — identical idempotent behavior
|
|
2316
2302
|
class Migration_xyz extends masterrecord.schema {
|
|
2317
2303
|
async up(table) {
|
|
2318
|
-
this.init(table);
|
|
2319
|
-
|
|
2320
|
-
this.seed('User', { id: 1, name: 'admin' });
|
|
2304
|
+
await this.init(table);
|
|
2305
|
+
await this.seed('User', { id: 1, name: 'admin' }); // safe to re-run
|
|
2321
2306
|
}
|
|
2322
2307
|
}
|
|
2323
2308
|
```
|
|
2324
2309
|
|
|
2310
|
+
Idempotency relies on a primary key or unique constraint on the target table — that's what the engine's ignore/conflict clause keys on.
|
|
2311
|
+
|
|
2325
2312
|
### Best Practices
|
|
2326
2313
|
|
|
2327
|
-
1. **Use context-level seed** for
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
6. **Don't delete seed data** in down migrations (can cause referential integrity issues)
|
|
2314
|
+
1. **Use context-level seed** for declarative bootstrap data (admin users, default categories, lookup tables) you want versioned with the schema.
|
|
2315
|
+
2. **Use manual `this.seed()` / `this.bulkSeed()`** when you want the seed written explicitly in a specific migration; `bulkSeed` is one INSERT, so prefer it for large datasets.
|
|
2316
|
+
3. **Both are idempotent** — safe to leave in place and re-run; no need to delete after the first deploy.
|
|
2317
|
+
4. **Keep seed data minimal** - only essential bootstrap data.
|
|
2318
|
+
5. **Use fixtures/factories** for test data, not seed methods.
|
|
2319
|
+
6. **Don't delete seed data** in down migrations (can cause referential integrity issues).
|
|
2320
|
+
7. If you need lifecycle hooks/validators to run on seeded rows, insert via `context.Entity.new()` + `save()` in app code rather than `seed()`.
|
|
2335
2321
|
|
|
2336
2322
|
### Example: Multi-Tenant Seed Data
|
|
2337
2323
|
|
|
@@ -2394,15 +2380,15 @@ class AppContext extends context {
|
|
|
2394
2380
|
**Generated Migration:**
|
|
2395
2381
|
```javascript
|
|
2396
2382
|
async up(table) {
|
|
2397
|
-
this.init(table);
|
|
2398
|
-
await
|
|
2383
|
+
await this.init(table);
|
|
2384
|
+
await this.seed('User', { id: 1, name: 'admin', email: 'admin@example.com' });
|
|
2399
2385
|
}
|
|
2400
2386
|
|
|
2401
2387
|
async down(table) {
|
|
2402
|
-
this.init(table);
|
|
2388
|
+
await this.init(table);
|
|
2403
2389
|
// Auto-generated rollback (reverse order for FK safety)
|
|
2404
2390
|
try {
|
|
2405
|
-
const record = await
|
|
2391
|
+
const record = await this.context.User.findById(1);
|
|
2406
2392
|
if (record) await record.delete();
|
|
2407
2393
|
} catch (e) {
|
|
2408
2394
|
console.warn('Seed rollback: User id=1 not found');
|
|
@@ -2554,7 +2540,7 @@ const factoryRecords = [
|
|
|
2554
2540
|
// ... 8 more
|
|
2555
2541
|
];
|
|
2556
2542
|
for (const record of factoryRecords) {
|
|
2557
|
-
await
|
|
2543
|
+
await this.seed('User', record);
|
|
2558
2544
|
}
|
|
2559
2545
|
```
|
|
2560
2546
|
|
|
@@ -2613,16 +2599,16 @@ class AppContext extends context {
|
|
|
2613
2599
|
**Generated Migration:**
|
|
2614
2600
|
```javascript
|
|
2615
2601
|
async up(table) {
|
|
2616
|
-
this.init(table);
|
|
2602
|
+
await this.init(table);
|
|
2617
2603
|
|
|
2618
2604
|
// Check-then-update pattern (database-agnostic)
|
|
2619
2605
|
{
|
|
2620
|
-
const existing = await
|
|
2606
|
+
const existing = await this.context.User.where(r => r.email == 'admin@example.com').single();
|
|
2621
2607
|
if (existing) {
|
|
2622
2608
|
existing.name = 'Administrator';
|
|
2623
2609
|
await existing.save();
|
|
2624
2610
|
} else {
|
|
2625
|
-
await
|
|
2611
|
+
await this.seed('User', { email: 'admin@example.com', name: 'Administrator' });
|
|
2626
2612
|
}
|
|
2627
2613
|
}
|
|
2628
2614
|
}
|