masterrecord 1.3.3 → 1.5.6
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 +210 -0
- 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/docs/DETACHED_ENTITIES_GUIDE.md +12 -4
- package/docs/MIGRATIONS_GUIDE.md +25 -1
- package/docs/POSTGRESQL_SETUP.md +7 -3
- package/docs/SECURITY.md +95 -0
- package/mySQLEngine.js +0 -0
- package/package.json +11 -12
- package/postgresEngine.js +97 -10
- package/readme.md +61 -11
package/docs/SECURITY.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Security & Production Guide
|
|
2
|
+
|
|
3
|
+
MasterRecord is designed to be safe by default. This page documents the guarantees, the sharp edges, and the settings you should turn on for a production / enterprise deployment across SQLite, MySQL, and Postgres.
|
|
4
|
+
|
|
5
|
+
## 1. Query parameterization (SQL injection)
|
|
6
|
+
|
|
7
|
+
**Always pass runtime values through the `$$` (or `$`) placeholder** — never interpolate them into the lambda string yourself.
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
// ✅ SAFE — the value is bound as a parameter (?, $1) on every engine
|
|
11
|
+
ctx.User.where(u => u.email == $$, req.body.email).toList();
|
|
12
|
+
ctx.User.where(u => $$.includes(u.id), req.query.ids).toList(); // IN (...)
|
|
13
|
+
ctx.User.where(u => u.name.like($$), `${term}%`).toList(); // LIKE
|
|
14
|
+
|
|
15
|
+
// ❌ UNSAFE — you built SQL from untrusted input by hand
|
|
16
|
+
ctx.User.where(`u => u.email == '${req.body.email}'`).toList();
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Values bound via `$$` / `$` go through prepared-statement parameters (`?` on SQLite/MySQL, `$1,$2,…` on Postgres) and are type-validated (`only primitives, null, Date, Buffer`). The lambda parser also restricts column names to word characters and operators to a fixed set, and every engine re-asserts the operator against an allowlist before emitting SQL.
|
|
20
|
+
|
|
21
|
+
Inline literals (e.g. `u => u.status == "active"`) are single-quote-escaped (`'` → `''`) as defense-in-depth, but the placeholder path above is the contract for anything user-supplied.
|
|
22
|
+
|
|
23
|
+
## 2. Pagination values (`.take()` / `.skip()`)
|
|
24
|
+
|
|
25
|
+
`LIMIT` / `OFFSET` **cannot** be parameterized on any engine, so pagination is a classic injection point. MasterRecord validates these for you:
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
ctx.User.take(req.query.limit).skip(req.query.offset).toList();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- A non-negative integer (or a clean numeric string like `'25'`) is accepted.
|
|
32
|
+
- Anything else (a value that appends extra SQL after the number, `-1`, `1.5`, `NaN`) **throws** before it can reach the SQL string — both at the `.take()`/`.skip()` setter and again at the engine boundary.
|
|
33
|
+
|
|
34
|
+
Clamp `limit` to a sane maximum in your own code to avoid unbounded result sets.
|
|
35
|
+
|
|
36
|
+
## 3. Raw SQL
|
|
37
|
+
|
|
38
|
+
There are two raw escape hatches — know which one you're using:
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
// ✅ Parameterized and portable — prefer this for anything with user input.
|
|
42
|
+
await ctx.query('SELECT * FROM "User" WHERE email = $1', [email]); // Postgres
|
|
43
|
+
await ctx.query('SELECT * FROM User WHERE email = ?', [email]); // SQLite/MySQL
|
|
44
|
+
|
|
45
|
+
// ⚠️ Verbatim — the string is executed as-is (no binding). NEVER interpolate
|
|
46
|
+
// untrusted input into it.
|
|
47
|
+
ctx.User.raw('SELECT * FROM User WHERE active = 1').toList();
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`ctx.query(sql, params)` / `ctx.execute(sql, params)` bind their parameters. The query-builder `.raw(sql)` runs the string verbatim — treat it like writing SQL by hand.
|
|
51
|
+
|
|
52
|
+
## 4. Atomic writes
|
|
53
|
+
|
|
54
|
+
`saveChanges()` wraps **all** tracked inserts/updates/deletes in a single transaction on every engine (SQLite, MySQL, Postgres). If any statement fails, the entire batch is rolled back — you never get partial data. No extra code required:
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
ctx.Order.add(order);
|
|
58
|
+
ctx.LineItem.add(item1);
|
|
59
|
+
ctx.LineItem.add(item2);
|
|
60
|
+
await ctx.saveChanges(); // all-or-nothing
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
(Internally, the bulk-write fast paths are savepoint-protected so a fallback to per-row writes still works inside the enclosing transaction.)
|
|
64
|
+
|
|
65
|
+
## 5. Transport encryption (TLS/SSL)
|
|
66
|
+
|
|
67
|
+
**MySQL and Postgres connect in plaintext unless you supply an `ssl` option.** For any non-local database, enable TLS in your environment config:
|
|
68
|
+
|
|
69
|
+
```jsonc
|
|
70
|
+
// Postgres — managed provider with a CA cert
|
|
71
|
+
{ "AppCtx": { "type": "pg", "host": "…", "database": "…", "user": "…", "password": "…",
|
|
72
|
+
"ssl": { "rejectUnauthorized": true, "ca": "<PEM>" } } }
|
|
73
|
+
|
|
74
|
+
// MySQL — verify the server certificate
|
|
75
|
+
{ "AppCtx": { "type": "mysql", "host": "…", "database": "…", "user": "…", "password": "…",
|
|
76
|
+
"ssl": { "rejectUnauthorized": true } } }
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
MasterRecord never forces `rejectUnauthorized: false`; whatever you pass in `ssl` is handed to the underlying driver (`mysql2` / `pg`) unchanged. Do **not** disable certificate verification in production.
|
|
80
|
+
|
|
81
|
+
SQLite is a local file — protect it with filesystem permissions and disk encryption.
|
|
82
|
+
|
|
83
|
+
## 6. Credentials
|
|
84
|
+
|
|
85
|
+
- Connection passwords are never logged. `getConnectionInfo()` deliberately omits the password.
|
|
86
|
+
- Keep DB credentials in environment config / secrets, not in source.
|
|
87
|
+
- In production set `NODE_ENV=production` to silence per-query SQL logging (runtime SQL is only logged outside production or when `LOG_SQL=true`).
|
|
88
|
+
|
|
89
|
+
## 7. Schema / migration identifiers
|
|
90
|
+
|
|
91
|
+
DDL identifiers (table, column, index names) can't be parameterized, and migrations are developer-authored code, so MasterRecord treats them as trusted. **Do not build entity, table, column, or index names — or index `where` predicates — from untrusted input.** Database names passed to the auto-create bootstrap are validated against a strict pattern before use.
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
Found a security issue? Please report it privately to the maintainer rather than opening a public issue.
|
package/mySQLEngine.js
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.6",
|
|
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",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"LICENSE"
|
|
47
47
|
],
|
|
48
48
|
"engines": {
|
|
49
|
-
"node": ">=
|
|
49
|
+
"node": ">=22.12.0"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
52
|
"test": "node --test test/*.test.js test/integration/*.test.js Migrations/pathUtils.test.js",
|
|
@@ -71,17 +71,16 @@
|
|
|
71
71
|
"masterrecord"
|
|
72
72
|
],
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"
|
|
75
|
-
"
|
|
74
|
+
"better-sqlite3": ">=12.6.2 <14",
|
|
75
|
+
"commander": "^15.0.0",
|
|
76
76
|
"deep-object-diff": "^1.1.9",
|
|
77
|
-
"
|
|
78
|
-
"mysql2": "^3.
|
|
79
|
-
"
|
|
80
|
-
"better-sqlite3": "^12.6.2"
|
|
77
|
+
"glob": "^13.0.6",
|
|
78
|
+
"mysql2": "^3.23.2",
|
|
79
|
+
"pg": "^8.22.0"
|
|
81
80
|
},
|
|
82
81
|
"devDependencies": {
|
|
83
|
-
"@eslint/js": "^
|
|
84
|
-
"eslint": "^
|
|
85
|
-
"globals": "^
|
|
82
|
+
"@eslint/js": "^10.0.1",
|
|
83
|
+
"eslint": "^10.8.0",
|
|
84
|
+
"globals": "^17.9.0"
|
|
86
85
|
}
|
|
87
86
|
}
|
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:
|