masterrecord 1.3.3 → 1.5.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/Entity/entityTrackerModel.js +202 -149
- package/Migrations/cli.js +152 -36
- package/Migrations/migrationMySQLQuery.js +21 -13
- package/Migrations/migrationPostgresQuery.js +21 -12
- package/Migrations/migrationSQLiteQuery.js +5 -1
- package/Migrations/migrationTemplate.js +11 -0
- package/Migrations/migrations.js +16 -0
- package/Migrations/schema.js +108 -28
- package/QueryLanguage/queryMethods.js +34 -5
- package/SQLLiteEngine.js +67 -10
- package/Tools.js +76 -0
- package/context.js +345 -63
- package/mySQLEngine.js +0 -0
- package/package.json +11 -14
- package/postgresEngine.js +97 -10
- package/readme.md +61 -11
- package/CHANGES.md +0 -421
- package/docs/ACTIVE_RECORD_PATTERN.md +0 -477
- package/docs/DETACHED_ENTITIES_GUIDE.md +0 -445
- package/docs/FULL_TEXT_SEARCH.md +0 -219
- package/docs/INCLUDES_CLARIFICATION.md +0 -202
- package/docs/METHODS_REFERENCE.md +0 -199
- package/docs/MIGRATIONS_GUIDE.md +0 -508
- package/docs/POSTGRESQL_SETUP.md +0 -441
- package/docs/QUERY_CACHING_GUIDE.md +0 -446
- package/docs/TROUBLESHOOTING.md +0 -348
- package/docs/belongsTo-relationships.md +0 -222
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"./package.json": "./package.json"
|
|
31
31
|
},
|
|
32
32
|
"bin": {
|
|
33
|
-
"masterrecord": "
|
|
33
|
+
"masterrecord": "Migrations/cli.js"
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"*.js",
|
|
@@ -41,12 +41,10 @@
|
|
|
41
41
|
"!**/*.test.js",
|
|
42
42
|
"!eslint.config.js",
|
|
43
43
|
"!prettier.config.js",
|
|
44
|
-
"docs/**/*.md",
|
|
45
|
-
"CHANGES.md",
|
|
46
44
|
"LICENSE"
|
|
47
45
|
],
|
|
48
46
|
"engines": {
|
|
49
|
-
"node": ">=
|
|
47
|
+
"node": ">=22.12.0"
|
|
50
48
|
},
|
|
51
49
|
"scripts": {
|
|
52
50
|
"test": "node --test test/*.test.js test/integration/*.test.js Migrations/pathUtils.test.js",
|
|
@@ -71,17 +69,16 @@
|
|
|
71
69
|
"masterrecord"
|
|
72
70
|
],
|
|
73
71
|
"dependencies": {
|
|
74
|
-
"
|
|
75
|
-
"
|
|
72
|
+
"better-sqlite3": ">=12.6.2 <14",
|
|
73
|
+
"commander": "^15.0.0",
|
|
76
74
|
"deep-object-diff": "^1.1.9",
|
|
77
|
-
"
|
|
78
|
-
"mysql2": "^3.
|
|
79
|
-
"
|
|
80
|
-
"better-sqlite3": "^12.6.2"
|
|
75
|
+
"glob": "^13.0.6",
|
|
76
|
+
"mysql2": "^3.23.2",
|
|
77
|
+
"pg": "^8.22.0"
|
|
81
78
|
},
|
|
82
79
|
"devDependencies": {
|
|
83
|
-
"@eslint/js": "^
|
|
84
|
-
"eslint": "^
|
|
85
|
-
"globals": "^
|
|
80
|
+
"@eslint/js": "^10.0.1",
|
|
81
|
+
"eslint": "^10.8.0",
|
|
82
|
+
"globals": "^17.9.0"
|
|
86
83
|
}
|
|
87
84
|
}
|
package/postgresEngine.js
CHANGED
|
@@ -12,6 +12,9 @@ class postgresEngine {
|
|
|
12
12
|
this.db = null;
|
|
13
13
|
this.dbType = 'postgres';
|
|
14
14
|
this.unsupportedWords = ["order"];
|
|
15
|
+
// Holds a dedicated pooled client while a transaction is open so every
|
|
16
|
+
// statement in saveChanges() runs on the same client (BEGIN..COMMIT).
|
|
17
|
+
this._txnClient = null;
|
|
15
18
|
}
|
|
16
19
|
|
|
17
20
|
/**
|
|
@@ -220,8 +223,10 @@ class postgresEngine {
|
|
|
220
223
|
}
|
|
221
224
|
return null;
|
|
222
225
|
} catch (err) {
|
|
223
|
-
|
|
224
|
-
|
|
226
|
+
// Loud failure: never swallow a query error into a silent null.
|
|
227
|
+
const missing = tools.missingTableError(err);
|
|
228
|
+
if (missing) { throw missing; }
|
|
229
|
+
throw err;
|
|
225
230
|
}
|
|
226
231
|
}
|
|
227
232
|
|
|
@@ -253,8 +258,10 @@ class postgresEngine {
|
|
|
253
258
|
}
|
|
254
259
|
return null;
|
|
255
260
|
} catch (err) {
|
|
256
|
-
|
|
257
|
-
|
|
261
|
+
// Loud failure: never swallow a query error into a silent null.
|
|
262
|
+
const missing = tools.missingTableError(err);
|
|
263
|
+
if (missing) { throw missing; }
|
|
264
|
+
throw err;
|
|
258
265
|
}
|
|
259
266
|
}
|
|
260
267
|
|
|
@@ -276,8 +283,10 @@ class postgresEngine {
|
|
|
276
283
|
}
|
|
277
284
|
return [];
|
|
278
285
|
} catch (err) {
|
|
279
|
-
|
|
280
|
-
|
|
286
|
+
// Loud failure: never swallow a query error into a silent empty set.
|
|
287
|
+
const missing = tools.missingTableError(err);
|
|
288
|
+
if (missing) { throw missing; }
|
|
289
|
+
throw err;
|
|
281
290
|
}
|
|
282
291
|
}
|
|
283
292
|
|
|
@@ -521,6 +530,7 @@ class postgresEngine {
|
|
|
521
530
|
}
|
|
522
531
|
|
|
523
532
|
if (arg === "null") {
|
|
533
|
+
tools.assertSafeOperator(func);
|
|
524
534
|
expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
525
535
|
} else {
|
|
526
536
|
// Check if arg is a parameterized placeholder
|
|
@@ -528,7 +538,9 @@ class postgresEngine {
|
|
|
528
538
|
if (isPlaceholder || func === "IN") {
|
|
529
539
|
expressions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
530
540
|
} else {
|
|
531
|
-
|
|
541
|
+
tools.assertSafeOperator(func);
|
|
542
|
+
// Escape the single quote so a literal can't break out.
|
|
543
|
+
expressions.push(`${entityRef}.${$that._q(field)} ${func} '${tools.escapeSqlLiteral(arg)}'`);
|
|
532
544
|
}
|
|
533
545
|
}
|
|
534
546
|
}
|
|
@@ -580,16 +592,19 @@ class postgresEngine {
|
|
|
580
592
|
}
|
|
581
593
|
|
|
582
594
|
if (arg === "null") {
|
|
595
|
+
tools.assertSafeOperator(func);
|
|
583
596
|
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
584
597
|
} else if (func === "IN") {
|
|
585
598
|
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
586
599
|
} else {
|
|
600
|
+
tools.assertSafeOperator(func);
|
|
587
601
|
// Check if arg is a parameterized placeholder ($1, $2, etc.)
|
|
588
602
|
const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
|
|
589
603
|
if (isPlaceholder) {
|
|
590
604
|
conditions.push(`${entityRef}.${$that._q(field)} ${func} ${arg}`);
|
|
591
605
|
} else {
|
|
592
|
-
|
|
606
|
+
// Escape the single quote so a literal can't break out.
|
|
607
|
+
conditions.push(`${entityRef}.${$that._q(field)} ${func} '${tools.escapeSqlLiteral(arg)}'`);
|
|
593
608
|
}
|
|
594
609
|
}
|
|
595
610
|
}
|
|
@@ -604,7 +619,9 @@ class postgresEngine {
|
|
|
604
619
|
|
|
605
620
|
buildLimit(query) {
|
|
606
621
|
if (query.take) {
|
|
607
|
-
|
|
622
|
+
// Defense-in-depth: LIMIT cannot be parameterized, so coerce to an
|
|
623
|
+
// integer at the SQL boundary (matches MySQL; SQLite does the same).
|
|
624
|
+
return `LIMIT ${this._safeRowCount(query.take, 'take')}`;
|
|
608
625
|
}
|
|
609
626
|
return "";
|
|
610
627
|
}
|
|
@@ -613,11 +630,22 @@ class postgresEngine {
|
|
|
613
630
|
if (query.skip) {
|
|
614
631
|
// Unlike SQLite/MySQL, Postgres accepts a bare OFFSET with no LIMIT,
|
|
615
632
|
// so a .skip() without .take() is valid as-is — no sentinel needed.
|
|
616
|
-
return `OFFSET ${query.skip}`;
|
|
633
|
+
return `OFFSET ${this._safeRowCount(query.skip, 'skip')}`;
|
|
617
634
|
}
|
|
618
635
|
return "";
|
|
619
636
|
}
|
|
620
637
|
|
|
638
|
+
// Coerce a LIMIT/OFFSET value to a non-negative integer or throw. These
|
|
639
|
+
// clauses are not parameterizable, so this is the last defense against a
|
|
640
|
+
// non-numeric (injection) pagination value reaching the SQL string.
|
|
641
|
+
_safeRowCount(value, label){
|
|
642
|
+
const n = typeof value === 'number' ? value : Number(value);
|
|
643
|
+
if(!Number.isInteger(n) || n < 0 || !Number.isSafeInteger(n)){
|
|
644
|
+
throw new Error(`Invalid ${label} value for LIMIT/OFFSET: ${JSON.stringify(value)} (expected a non-negative integer)`);
|
|
645
|
+
}
|
|
646
|
+
return n;
|
|
647
|
+
}
|
|
648
|
+
|
|
621
649
|
/**
|
|
622
650
|
* Build ORDER BY clause from query.orderBy or query.orderByDesc.
|
|
623
651
|
* Both are objects shaped like `{ selectFields: ['col1', 'col2'], ... }`
|
|
@@ -1037,6 +1065,13 @@ class postgresEngine {
|
|
|
1037
1065
|
if (params && params.length) console.log(isMigration ? "[masterrecord:migration] params" : "[Params]", params);
|
|
1038
1066
|
}
|
|
1039
1067
|
|
|
1068
|
+
// Inside a transaction, reuse the transaction's client so every
|
|
1069
|
+
// statement is part of the same BEGIN..COMMIT unit (and don't
|
|
1070
|
+
// release it — endTransaction/errorTransaction owns its lifecycle).
|
|
1071
|
+
if (this._txnClient) {
|
|
1072
|
+
return await this._txnClient.query(query, params);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1040
1075
|
const client = await this.pool.connect();
|
|
1041
1076
|
try {
|
|
1042
1077
|
const result = await client.query(query, params);
|
|
@@ -1050,6 +1085,58 @@ class postgresEngine {
|
|
|
1050
1085
|
}
|
|
1051
1086
|
}
|
|
1052
1087
|
|
|
1088
|
+
// --- Transactions -----------------------------------------------------
|
|
1089
|
+
// saveChanges() brackets all inserts/updates/deletes so a partial failure
|
|
1090
|
+
// rolls the whole batch back. Without this, Postgres writes were
|
|
1091
|
+
// autocommitted per statement and a mid-batch error left partial data.
|
|
1092
|
+
|
|
1093
|
+
async startTransaction(){
|
|
1094
|
+
if(this._txnClient){ return; }
|
|
1095
|
+
this._txnClient = await this.pool.connect();
|
|
1096
|
+
await this._txnClient.query('BEGIN');
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
async endTransaction(){
|
|
1100
|
+
if(!this._txnClient){ return; }
|
|
1101
|
+
const client = this._txnClient;
|
|
1102
|
+
this._txnClient = null;
|
|
1103
|
+
try {
|
|
1104
|
+
await client.query('COMMIT');
|
|
1105
|
+
} finally {
|
|
1106
|
+
client.release();
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
async errorTransaction(){
|
|
1111
|
+
if(!this._txnClient){ return; }
|
|
1112
|
+
const client = this._txnClient;
|
|
1113
|
+
this._txnClient = null;
|
|
1114
|
+
try {
|
|
1115
|
+
await client.query('ROLLBACK');
|
|
1116
|
+
} finally {
|
|
1117
|
+
client.release();
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
inTransaction(){
|
|
1122
|
+
return !!this._txnClient;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// Nested rollback points so a failed bulk write can be undone without
|
|
1126
|
+
// aborting (Postgres marks a transaction "aborted" after any statement
|
|
1127
|
+
// error) the enclosing transaction. `name` is an internal identifier.
|
|
1128
|
+
async savepoint(name){
|
|
1129
|
+
return this._txnClient.query(`SAVEPOINT ${name}`);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
async releaseSavepoint(name){
|
|
1133
|
+
return this._txnClient.query(`RELEASE SAVEPOINT ${name}`);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
async rollbackToSavepoint(name){
|
|
1137
|
+
return this._txnClient.query(`ROLLBACK TO SAVEPOINT ${name}`);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1053
1140
|
/**
|
|
1054
1141
|
* Sanitize single quotes (legacy, prefer parameterized queries)
|
|
1055
1142
|
*/
|
package/readme.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/masterrecord)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
> **ESM only.** As of v1.0, MasterRecord is a pure ESM package. Requires **Node.js
|
|
6
|
+
> **ESM only.** As of v1.0, MasterRecord is a pure ESM package. Requires **Node.js 22.12+** and a host project with `"type": "module"` in `package.json`. There is no CommonJS build.
|
|
7
7
|
|
|
8
8
|
**MasterRecord** is a lightweight, code-first ORM for Node.js with a fluent query API, comprehensive migrations, and multi-database support. Build type-safe queries with lambda expressions, manage schema changes with CLI-driven migrations, and work seamlessly across MySQL, PostgreSQL, and SQLite.
|
|
9
9
|
|
|
@@ -201,9 +201,26 @@ npm install masterrecord better-sqlite3 # SQLite
|
|
|
201
201
|
### Dependencies
|
|
202
202
|
|
|
203
203
|
MasterRecord includes the following database drivers by default:
|
|
204
|
-
- `pg@^8.
|
|
205
|
-
- `mysql2@^3.
|
|
206
|
-
- `better-sqlite3@^
|
|
204
|
+
- `pg@^8.22.0` - PostgreSQL (async)
|
|
205
|
+
- `mysql2@^3.23.2` - MySQL (async with connection pooling)
|
|
206
|
+
- `better-sqlite3@^13.0.2` - SQLite (async API wrapper for consistency)
|
|
207
|
+
|
|
208
|
+
### npm v12+ install note (native SQLite build)
|
|
209
|
+
|
|
210
|
+
`better-sqlite3` is a native module — it runs a `node-gyp` build in its install
|
|
211
|
+
script. As of **npm v12**, dependency lifecycle scripts (`preinstall` / `install` /
|
|
212
|
+
`postinstall`) are **off by default** (`allowScripts` is opt-in). If you install
|
|
213
|
+
MasterRecord with npm v12+ and SQLite fails to load with a "did not self-register"
|
|
214
|
+
or missing-binding error, approve the build scripts once:
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
npm approve-scripts --allow-scripts-pending # review, then approve the trusted build scripts
|
|
218
|
+
# commit the resulting allowlist in your package.json
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Older npm (≤11) builds native modules automatically and needs no action. If you
|
|
222
|
+
only use MySQL or Postgres, you can drop `better-sqlite3` entirely and this doesn't
|
|
223
|
+
apply.
|
|
207
224
|
|
|
208
225
|
## Two Patterns: Entity Framework & Active Record
|
|
209
226
|
|
|
@@ -454,7 +471,8 @@ class User {
|
|
|
454
471
|
// Unique constraint
|
|
455
472
|
email(db) { db.string().unique(); }
|
|
456
473
|
|
|
457
|
-
// Timestamp (stored as TEXT on
|
|
474
|
+
// Timestamp (stored as TEXT on every engine; write an epoch-millis or ISO
|
|
475
|
+
// string in app code or a beforeSave hook)
|
|
458
476
|
created_at(db) { db.datetime(); }
|
|
459
477
|
}
|
|
460
478
|
```
|
|
@@ -474,15 +492,23 @@ class User {
|
|
|
474
492
|
| `float` | REAL | FLOAT | REAL |
|
|
475
493
|
| `decimal` | DECIMAL | DECIMAL | REAL |
|
|
476
494
|
| `boolean` | BOOLEAN | TINYINT | INTEGER |
|
|
477
|
-
| `date` |
|
|
478
|
-
| `time` |
|
|
479
|
-
| `datetime` |
|
|
480
|
-
| `timestamp` |
|
|
495
|
+
| `date` | TEXT | TEXT | TEXT |
|
|
496
|
+
| `time` | TEXT | TEXT | TEXT |
|
|
497
|
+
| `datetime` | TEXT | TEXT | TEXT |
|
|
498
|
+
| `timestamp` | TEXT | TEXT | TEXT |
|
|
481
499
|
| `json` | JSON | JSON | TEXT |
|
|
482
500
|
| `jsonb` | JSONB | JSON | TEXT |
|
|
483
501
|
| `uuid` | UUID | VARCHAR(36) | TEXT |
|
|
484
502
|
| `binary` | BYTEA | BLOB | BLOB |
|
|
485
503
|
|
|
504
|
+
> **Temporal types are TEXT everywhere.** `date`, `time`, `datetime`, and
|
|
505
|
+
> `timestamp` are stored as `TEXT` on **all three engines** (not native
|
|
506
|
+
> `DATE`/`TIME`/`TIMESTAMP`/`DATETIME`) so the same model runs unchanged across
|
|
507
|
+
> SQLite, MySQL, and PostgreSQL. Write epoch-millis or ISO-8601 strings — a
|
|
508
|
+
> native temporal column would reject those values at INSERT. Set them in app
|
|
509
|
+
> code or a `beforeSave` hook rather than via a DB-side `CURRENT_TIMESTAMP`
|
|
510
|
+
> default.
|
|
511
|
+
|
|
486
512
|
### Relationships
|
|
487
513
|
|
|
488
514
|
Relationships are declared with the `hasMany` / `hasOne` / `belongsTo` builder
|
|
@@ -1845,7 +1871,10 @@ class User {
|
|
|
1845
1871
|
}
|
|
1846
1872
|
|
|
1847
1873
|
created_at(db) {
|
|
1848
|
-
|
|
1874
|
+
// Temporal columns are TEXT on every engine — set the value in app
|
|
1875
|
+
// code or a beforeSave hook (a DB-side CURRENT_TIMESTAMP default is not
|
|
1876
|
+
// portable). Write epoch-millis or an ISO string.
|
|
1877
|
+
db.datetime();
|
|
1849
1878
|
}
|
|
1850
1879
|
}
|
|
1851
1880
|
```
|
|
@@ -1946,7 +1975,10 @@ class CreditLedger {
|
|
|
1946
1975
|
}
|
|
1947
1976
|
|
|
1948
1977
|
created_at(db) {
|
|
1949
|
-
|
|
1978
|
+
// Temporal columns are TEXT on every engine — set the value in app
|
|
1979
|
+
// code or a beforeSave hook (a DB-side CURRENT_TIMESTAMP default is not
|
|
1980
|
+
// portable). Write epoch-millis or an ISO string.
|
|
1981
|
+
db.datetime();
|
|
1950
1982
|
}
|
|
1951
1983
|
|
|
1952
1984
|
resource_type(db) {
|
|
@@ -3336,6 +3368,24 @@ All operations use parameterized queries:
|
|
|
3336
3368
|
- IN clauses
|
|
3337
3369
|
- LIKE patterns
|
|
3338
3370
|
|
|
3371
|
+
### Pagination is validated
|
|
3372
|
+
|
|
3373
|
+
`LIMIT` / `OFFSET` can't be parameterized, so `.take()` / `.skip()` validate their input — a non-negative integer (or a clean numeric string) is accepted; anything else (e.g. a value that tries to smuggle extra SQL in after the number) throws before it can reach the SQL string. Pass request values straight through safely:
|
|
3374
|
+
|
|
3375
|
+
```javascript
|
|
3376
|
+
await db.User.take(req.query.limit).skip(req.query.offset).toList();
|
|
3377
|
+
```
|
|
3378
|
+
|
|
3379
|
+
### Atomic writes
|
|
3380
|
+
|
|
3381
|
+
`saveChanges()` wraps all tracked inserts/updates/deletes in a single transaction on **every** engine (SQLite, MySQL, Postgres). A mid-batch failure rolls the whole batch back — you never get partial data.
|
|
3382
|
+
|
|
3383
|
+
### Transport encryption (production)
|
|
3384
|
+
|
|
3385
|
+
MySQL and Postgres connect in **plaintext unless you provide an `ssl` option** in your environment config. Enable TLS for any non-local database (MasterRecord never disables certificate verification for you). See the full guide:
|
|
3386
|
+
|
|
3387
|
+
👉 **[docs/SECURITY.md](./docs/SECURITY.md)** — parameterization, the safe raw-SQL path (`ctx.query(sql, params)`) vs. the verbatim `.raw()` hatch, TLS setup, credentials, and schema-identifier caveats.
|
|
3388
|
+
|
|
3339
3389
|
### Input Validation
|
|
3340
3390
|
|
|
3341
3391
|
While SQL injection is prevented, always validate business logic:
|