masterrecord 1.2.5 → 1.2.7
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 +21 -0
- package/Migrations/schema.js +21 -0
- package/SQLLiteEngine.js +14 -0
- package/context.js +77 -4
- package/docs/MIGRATIONS_GUIDE.md +1 -0
- package/docs/TROUBLESHOOTING.md +16 -1
- package/mySQLEngine.js +7 -0
- package/package.json +1 -1
- package/postgresEngine.js +8 -0
- package/readme.md +16 -13
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.2.7 — public engine-agnostic raw-SQL escape hatch (`ctx.query` / `ctx.execute`)
|
|
4
|
+
|
|
5
|
+
Adds a public, portable raw-SQL API so apps stop reaching into `ctx.db` (the raw, engine-specific driver). `ctx.db.prepare()` is better-sqlite3's synchronous API; mysql2/pg have no `.prepare()`, so code written against `ctx.db` "works on SQLite, breaks on MySQL." The only engine-agnostic path was the private `context._execute` (the migration/DDL path, which logs as a migration and doesn't return rows on SQLite).
|
|
6
|
+
|
|
7
|
+
- **`ctx.query(sql, params)`** (alias **`ctx.execute(sql, params)`**) — runs raw SQL on SQLite/MySQL/Postgres and returns an **array of row objects** for row-returning statements; executes writes (returns the driver's write result). Placeholders are engine-native (`?` for SQLite/MySQL, `$1,$2,…` for Postgres). Each engine gained a matching `query()` method (SQLite uses `stmt.reader` to pick `all()` vs `run()`; pg normalizes `result.rows`).
|
|
8
|
+
- **DX guard (loud-failure parity):** on MySQL/Postgres, `ctx.db.prepare()` (and `.pragma()`) now throw a descriptive error pointing to `ctx.query()` instead of the generic "is not a function". `ctx.db` is never used internally (the engines hold their own pool), so this only affects user-facing access; every real driver method is forwarded untouched. SQLite's `ctx.db` is the real better-sqlite3 handle and is unaffected.
|
|
9
|
+
|
|
10
|
+
This closes the entire "works on SQLite, breaks on MySQL" class for legitimate raw-SQL cases (e.g. cross-context FK updates the query builder can't express). Prefer the ORM where possible; `ctx.query()` is the escape hatch.
|
|
11
|
+
|
|
12
|
+
New test: `test/raw-query-escape-hatch.test.js`. Docs: README "Raw SQL Queries" + API reference updated; TROUBLESHOOTING gains a "`ctx.db.prepare is not a function`" entry. Suite green; 0 lint errors.
|
|
13
|
+
|
|
14
|
+
> Verified executing on SQLite (rows/writes/params). The MySQL/Postgres `query()` and the `ctx.db` guard share the same code shape but aren't run against live servers here.
|
|
15
|
+
|
|
16
|
+
## v1.2.6 — idempotent addColumn (skip-if-exists)
|
|
17
|
+
|
|
18
|
+
`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).
|
|
19
|
+
|
|
20
|
+
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.)
|
|
21
|
+
|
|
22
|
+
New test: idempotent-addColumn case in `test/migration-self-contained.test.js`. Suite green; 0 lint errors.
|
|
23
|
+
|
|
3
24
|
## v1.2.5 — documentation catch-up
|
|
4
25
|
|
|
5
26
|
Docs-only. Brought `docs/MIGRATIONS_GUIDE.md` up to date with the 1.2.x work that was previously only in this changelog:
|
package/Migrations/schema.js
CHANGED
|
@@ -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);
|
package/SQLLiteEngine.js
CHANGED
|
@@ -1342,6 +1342,20 @@ class SQLLiteEngine {
|
|
|
1342
1342
|
return this.db.prepare(query).run(...params);
|
|
1343
1343
|
}
|
|
1344
1344
|
|
|
1345
|
+
// Engine-agnostic raw query backing the public ctx.query()/ctx.execute().
|
|
1346
|
+
// Returns an array of rows for row-returning statements (SELECT / PRAGMA /
|
|
1347
|
+
// RETURNING); for writes returns better-sqlite3's run info
|
|
1348
|
+
// ({ changes, lastInsertRowid }). `stmt.reader` tells the two apart.
|
|
1349
|
+
query(query, params = []){
|
|
1350
|
+
if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
|
|
1351
|
+
console.debug("[SQL]", query);
|
|
1352
|
+
if (params && params.length) console.debug("[Params]", params);
|
|
1353
|
+
}
|
|
1354
|
+
const stmt = this.db.prepare(query);
|
|
1355
|
+
const args = Array.isArray(params) ? params : (params === undefined ? [] : [params]);
|
|
1356
|
+
return stmt.reader ? stmt.all(...args) : stmt.run(...args);
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1345
1359
|
setDB(db, type){
|
|
1346
1360
|
this.db = db;
|
|
1347
1361
|
this.dbType = type; // this will let us know which type of sqlengine to use.
|
package/context.js
CHANGED
|
@@ -887,8 +887,8 @@ class context {
|
|
|
887
887
|
// MySQL is async - caller must await env()
|
|
888
888
|
// Store promise so migration schema can await it
|
|
889
889
|
this._initPromise = (async () => {
|
|
890
|
-
this.db = await this.__mysqlInit(options, 'mysql2');
|
|
891
|
-
// Note: engine is already set in __mysqlInit
|
|
890
|
+
this.db = this.#guardRawDriverHandle(await this.__mysqlInit(options, 'mysql2'), 'MySQL');
|
|
891
|
+
// Note: engine is already set in __mysqlInit (uses the real pool)
|
|
892
892
|
return this;
|
|
893
893
|
})();
|
|
894
894
|
// Prevent unhandled rejection crash — _ensureReady() will re-throw on query
|
|
@@ -910,8 +910,8 @@ class context {
|
|
|
910
910
|
// PostgreSQL is async - caller must await env()
|
|
911
911
|
// Store promise so migration schema can await it
|
|
912
912
|
this._initPromise = (async () => {
|
|
913
|
-
this.db = await this.__postgresInit(options, 'pg');
|
|
914
|
-
// Note: engine is already set in __postgresInit
|
|
913
|
+
this.db = this.#guardRawDriverHandle(await this.__postgresInit(options, 'pg'), 'PostgreSQL');
|
|
914
|
+
// Note: engine is already set in __postgresInit (uses the real pool)
|
|
915
915
|
return this;
|
|
916
916
|
})();
|
|
917
917
|
// Prevent unhandled rejection crash — _ensureReady() will re-throw on query
|
|
@@ -2004,6 +2004,79 @@ class context {
|
|
|
2004
2004
|
return this._SQLEngine._execute(query);
|
|
2005
2005
|
}
|
|
2006
2006
|
|
|
2007
|
+
/**
|
|
2008
|
+
* Engine-agnostic raw-SQL escape hatch.
|
|
2009
|
+
*
|
|
2010
|
+
* Prefer the ORM (`ctx.Model.where(...).toList()`, `.add()`,
|
|
2011
|
+
* `saveChanges()`) — it's portable across SQLite/MySQL/Postgres. Use this
|
|
2012
|
+
* only for SQL the query builder can't express. Unlike reaching into
|
|
2013
|
+
* `ctx.db` (which is the raw, engine-specific driver — e.g. better-sqlite3's
|
|
2014
|
+
* synchronous `prepare()`, which doesn't exist on mysql2/pg), `query()`
|
|
2015
|
+
* works the same on every engine.
|
|
2016
|
+
*
|
|
2017
|
+
* Returns an array of row objects for row-returning statements
|
|
2018
|
+
* (SELECT / RETURNING) on all three engines. For write statements
|
|
2019
|
+
* (INSERT/UPDATE/DELETE/DDL) it executes and returns the driver's write
|
|
2020
|
+
* result (shape varies by engine — prefer the ORM when you need a portable
|
|
2021
|
+
* result). Use `?` placeholders for SQLite/MySQL and `$1,$2,…` for Postgres.
|
|
2022
|
+
*
|
|
2023
|
+
* @param {string} sql - SQL with parameter placeholders
|
|
2024
|
+
* @param {Array} [params] - Bind values
|
|
2025
|
+
* @returns {Promise<Array<object>|*>}
|
|
2026
|
+
*
|
|
2027
|
+
* @example
|
|
2028
|
+
* const rows = await ctx.query('SELECT * FROM "User" WHERE age > $1', [25]); // pg
|
|
2029
|
+
* await ctx.execute('UPDATE Step SET run_id = ? WHERE id = ?', ['run_x', 1]); // sqlite/mysql
|
|
2030
|
+
*/
|
|
2031
|
+
async query(sql, params = []) {
|
|
2032
|
+
if (this._initPromise) { await this._initPromise; } // MySQL/Postgres async init
|
|
2033
|
+
if (!this._SQLEngine) {
|
|
2034
|
+
throw new DatabaseConnectionError(
|
|
2035
|
+
'Cannot run query: database engine not initialized. Ensure you have awaited env() before querying.',
|
|
2036
|
+
this.isMySQL ? 'MySQL' : this.isPostgres ? 'PostgreSQL' : 'SQLite'
|
|
2037
|
+
);
|
|
2038
|
+
}
|
|
2039
|
+
return this._SQLEngine.query(sql, params || []);
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/**
|
|
2043
|
+
* Alias of {@link query} — read naturally for write statements
|
|
2044
|
+
* (`await ctx.execute('UPDATE …', [...])`). Both run raw SQL on any engine.
|
|
2045
|
+
*/
|
|
2046
|
+
async execute(sql, params = []) {
|
|
2047
|
+
return this.query(sql, params);
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Wrap a non-SQLite raw driver handle (mysql2 / pg pool) so that calling
|
|
2052
|
+
* a SQLite-only method on `ctx.db` fails with guidance instead of the
|
|
2053
|
+
* generic "X is not a function". Apps commonly reach for
|
|
2054
|
+
* `ctx.db.prepare()` (better-sqlite3's API); on MySQL/Postgres `ctx.db`
|
|
2055
|
+
* is the raw driver/pool and has no such method.
|
|
2056
|
+
*
|
|
2057
|
+
* The Proxy forwards every real pool method (bound to the real pool, so
|
|
2058
|
+
* driver internals keep working) and only intercepts the SQLite-specific
|
|
2059
|
+
* names. `ctx.db` is never used internally — the engines hold their own
|
|
2060
|
+
* pool reference — so this only affects user-facing access.
|
|
2061
|
+
* @private
|
|
2062
|
+
*/
|
|
2063
|
+
#guardRawDriverHandle(pool, engineLabel) {
|
|
2064
|
+
if (!pool || typeof pool !== 'object') return pool;
|
|
2065
|
+
const sqliteOnly = new Set(['prepare', 'pragma']);
|
|
2066
|
+
return new Proxy(pool, {
|
|
2067
|
+
get(target, prop) {
|
|
2068
|
+
if (typeof prop === 'string' && sqliteOnly.has(prop)) {
|
|
2069
|
+
throw new Error(
|
|
2070
|
+
`masterrecord: ctx.db on ${engineLabel} is the raw ${engineLabel} driver, which has no .${prop}() — that's SQLite-only. ` +
|
|
2071
|
+
`Use the engine-agnostic ctx.query(sql, params) / ctx.execute(sql, params), or the ORM (ctx.Model.where()…).`
|
|
2072
|
+
);
|
|
2073
|
+
}
|
|
2074
|
+
const value = target[prop];
|
|
2075
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
2076
|
+
}
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2007
2080
|
/**
|
|
2008
2081
|
* Get query cache statistics
|
|
2009
2082
|
*
|
package/docs/MIGRATIONS_GUIDE.md
CHANGED
|
@@ -304,6 +304,7 @@ You can also declare these on the entity/context (`this.compositeIndex(Model, ['
|
|
|
304
304
|
Migrations are designed to fail loudly and be observable — there are no silent no-ops:
|
|
305
305
|
|
|
306
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.
|
|
307
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.
|
|
308
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.
|
|
309
310
|
|
package/docs/TROUBLESHOOTING.md
CHANGED
|
@@ -305,4 +305,19 @@ step.created_at = String(Date.now()); // ← stored as a plain JS prop, INSERT
|
|
|
305
305
|
|
|
306
306
|
**Fix:** restart the Node process. There is no library-level fix; this is how Node module loading works.
|
|
307
307
|
|
|
308
|
-
Until restart, the workaround is to set the field via raw
|
|
308
|
+
Until restart, the workaround is to set the field via the engine-agnostic raw escape hatch — `await ctx.execute('INSERT INTO Step (...) VALUES (?, ?)', [...])` (works on every engine) — or, for fields that exist in the DB but not the class definition, lazy-load the entity (which iterates the DB row's actual columns and creates setters for them on the instance, even if the class doesn't declare them).
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## `TypeError: ctx.db.prepare is not a function` (MySQL / Postgres)
|
|
313
|
+
|
|
314
|
+
`ctx.db` is the **raw, engine-specific driver**. On SQLite it's a better-sqlite3 database (which has `.prepare()/.get()/.run()/.all()`); on MySQL it's a mysql2 pool and on Postgres a pg pool — neither has `.prepare()`. Code written against `ctx.db.prepare(...)` therefore works on SQLite and throws on MySQL/Postgres.
|
|
315
|
+
|
|
316
|
+
**Fix:** use the engine-agnostic raw-SQL escape hatch (since v1.2.7):
|
|
317
|
+
|
|
318
|
+
```javascript
|
|
319
|
+
const rows = await ctx.query('SELECT * FROM "User" WHERE id = $1', [id]); // returns rows, all engines
|
|
320
|
+
await ctx.execute('UPDATE "User" SET name = ? WHERE id = ?', ['Alice', id]);
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Better still, prefer the ORM (`ctx.User.where(u => u.id == $$, id).single()`), which is portable by construction. On a non-SQLite engine, `ctx.db.prepare()` now throws a descriptive error pointing you to `ctx.query()`.
|
package/mySQLEngine.js
CHANGED
|
@@ -233,6 +233,13 @@ class MySQLEngine {
|
|
|
233
233
|
return await this._runWithParams(query, params);
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
+
// Engine-agnostic raw query backing the public ctx.query()/ctx.execute().
|
|
237
|
+
// mysql2 returns an array of rows for SELECT and a ResultSetHeader for
|
|
238
|
+
// writes.
|
|
239
|
+
async query(query, params = []) {
|
|
240
|
+
return await this._runWithParams(query, params);
|
|
241
|
+
}
|
|
242
|
+
|
|
236
243
|
/**
|
|
237
244
|
* Introspection: Check if table exists
|
|
238
245
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.7",
|
|
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
|
@@ -275,6 +275,14 @@ class postgresEngine {
|
|
|
275
275
|
return await this._runWithParams(query, params);
|
|
276
276
|
}
|
|
277
277
|
|
|
278
|
+
// Engine-agnostic raw query backing the public ctx.query()/ctx.execute().
|
|
279
|
+
// Normalizes pg's result object to an array of rows for row-returning
|
|
280
|
+
// statements; for writes returns the driver result.
|
|
281
|
+
async query(query, params = []) {
|
|
282
|
+
const result = await this._runWithParams(query, params);
|
|
283
|
+
return (result && Array.isArray(result.rows)) ? result.rows : result;
|
|
284
|
+
}
|
|
285
|
+
|
|
278
286
|
/**
|
|
279
287
|
* Introspection: Check if a table exists in the current Postgres schema.
|
|
280
288
|
* Mirrors the SQLite/MySQL engines so migration code and the CLI's
|
package/readme.md
CHANGED
|
@@ -1368,26 +1368,25 @@ masterrecord update-database-all
|
|
|
1368
1368
|
|
|
1369
1369
|
### Raw SQL Queries
|
|
1370
1370
|
|
|
1371
|
-
|
|
1371
|
+
For SQL the query builder can't express, use the **engine-agnostic** escape hatch `db.query(sql, params)` (alias `db.execute(sql, params)`). It works the same on SQLite, MySQL, and PostgreSQL and returns an **array of row objects** for row-returning statements:
|
|
1372
1372
|
|
|
1373
1373
|
```javascript
|
|
1374
|
-
//
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
// PostgreSQL parameterized query
|
|
1379
|
-
const users = await db._SQLEngine.exec(
|
|
1380
|
-
'SELECT * FROM "User" WHERE age > $1 AND status = $2',
|
|
1374
|
+
// SELECT → array of rows (all engines)
|
|
1375
|
+
const users = await db.query(
|
|
1376
|
+
'SELECT * FROM "User" WHERE age > $1 AND status = $2', // Postgres: $1,$2
|
|
1381
1377
|
[25, 'active']
|
|
1382
1378
|
);
|
|
1379
|
+
// SQLite / MySQL use ? placeholders:
|
|
1380
|
+
const users = await db.query('SELECT * FROM User WHERE age > ? AND status = ?', [25, 'active']);
|
|
1383
1381
|
|
|
1384
|
-
//
|
|
1385
|
-
|
|
1386
|
-
'SELECT * FROM User WHERE age > ? AND status = ?',
|
|
1387
|
-
[25, 'active']
|
|
1388
|
-
);
|
|
1382
|
+
// Writes — reads naturally as execute() (works on every engine)
|
|
1383
|
+
await db.execute('UPDATE Step SET run_id = ? WHERE id = ?', ['run_x', 1]);
|
|
1389
1384
|
```
|
|
1390
1385
|
|
|
1386
|
+
> **Do not reach into `db.db`.** That is the *raw, engine-specific driver* — `db.db.prepare()` is better-sqlite3's synchronous API and does **not** exist on mysql2/pg, so code written against it works on SQLite and breaks on MySQL/Postgres. (On a non-SQLite engine, `db.db.prepare()` now throws a descriptive error pointing you here.) Prefer the ORM (`db.User.where(...).toList()`); use `db.query()` only when you must.
|
|
1387
|
+
|
|
1388
|
+
Placeholders are engine-native (`?` for SQLite/MySQL, `$1,$2,…` for Postgres) — `query()` passes them straight through, so a raw statement is as portable as the SQL you write. For fully portable code, prefer the query builder.
|
|
1389
|
+
|
|
1391
1390
|
## API Reference
|
|
1392
1391
|
|
|
1393
1392
|
### Context Methods
|
|
@@ -1410,6 +1409,10 @@ context.attach(entity, { field: value }) // Attach with specific changes
|
|
|
1410
1409
|
context.attachAll([entity1, entity2]) // Attach multiple entities
|
|
1411
1410
|
await context.update('Entity', id, changes) // Update by primary key
|
|
1412
1411
|
|
|
1412
|
+
// Engine-agnostic raw SQL (escape hatch — prefer the query builder)
|
|
1413
|
+
await context.query(sql, params) // raw SQL → array of rows (all engines)
|
|
1414
|
+
await context.execute(sql, params) // alias; reads naturally for writes
|
|
1415
|
+
|
|
1413
1416
|
// Cache management
|
|
1414
1417
|
context.getCacheStats() // Get cache statistics
|
|
1415
1418
|
context.clearQueryCache() // Clear all cached queries
|