masterrecord 0.3.68 → 1.0.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/.claude/settings.local.json +3 -1
- package/CHANGES.md +31 -2
- package/Cache/QueryCache.js +10 -4
- package/Cache/RedisQueryCache.js +3 -2
- package/Entity/entityModel.js +1 -1
- package/Entity/entityModelBuilder.js +2 -2
- package/Entity/entityTrackerModel.js +3 -3
- package/Entity/fieldTransformer.js +1 -1
- package/FOREIGN_KEY_STRING_FIX.md +2 -2
- package/MasterRecord.js +6 -43
- package/Migrations/cli.js +44 -113
- package/Migrations/dependencyGraph.js +1 -1
- package/Migrations/migrationMySQLQuery.js +1 -1
- package/Migrations/migrationPostgresQuery.js +1 -1
- package/Migrations/migrationSQLiteQuery.js +1 -1
- package/Migrations/migrationTemplate.js +8 -39
- package/Migrations/migrations.js +16 -14
- package/Migrations/pathUtils.js +2 -5
- package/Migrations/pathUtils.test.js +33 -49
- package/Migrations/schema.js +52 -89
- package/QueryLanguage/queryMethods.js +4 -4
- package/QueryLanguage/queryParameters.js +1 -1
- package/QueryLanguage/queryScript.js +4 -3
- package/SQLLiteEngine.js +26 -7
- package/Tools.js +10 -8
- package/context.js +43 -42
- package/deleteManager.js +2 -2
- package/docs/MIGRATIONS_GUIDE.md +237 -532
- package/docs/POSTGRESQL_SETUP.md +4 -4
- package/docs/QUERY_CACHING_GUIDE.md +8 -7
- package/eslint.config.js +40 -0
- package/insertManager.js +28 -20
- package/mySQLConnect.js +2 -2
- package/mySQLEngine.js +26 -6
- package/package.json +34 -5
- package/postgresEngine.js +29 -8
- package/postgresSyncConnect.js +5 -3
- package/prettier.config.js +22 -0
- package/readme.md +35 -27
- package/test/context-errors.test.js +43 -0
- package/test/esm-imports.test.js +110 -0
- package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +1 -0
- package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
- package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +1 -0
- package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
- package/test/migration-template.test.js +47 -0
- package/test/new-setter-large-string.test.js +191 -0
- package/test/pool-key.test.js +43 -0
- package/test/sqlite-lifecycle.test.js +76 -0
- package/.eslintrc.js +0 -290
- package/.prettierrc.js +0 -109
- package/test/anyCommaStringTest.js +0 -237
- package/test/anyMethodTest.js +0 -176
- package/test/attachDetached.test.js +0 -303
- package/test/bulk-operations-test.js +0 -235
- package/test/cache-toObject-test.js +0 -105
- package/test/cacheIntegration.test.js +0 -319
- package/test/config-glob-pattern-test.js +0 -232
- package/test/double-where-bug-test.js +0 -71
- package/test/ensure-ready-test.js +0 -251
- package/test/entity-deduplication-test.js +0 -174
- package/test/entity-methods-test.js +0 -269
- package/test/findByIdTest.js +0 -227
- package/test/foreign-key-string-value-test.js +0 -406
- package/test/global-model-registry-test.js +0 -538
- package/test/id-setting-validation.js +0 -202
- package/test/includesFeatureTest.js +0 -183
- package/test/includesTransformTest.js +0 -110
- package/test/index-bug-fix-test.js +0 -188
- package/test/insert-return-test.js +0 -39
- package/test/lifecycle-hooks-test.js +0 -258
- package/test/multiContextCache.test.js +0 -230
- package/test/new-entity-migration-test.js +0 -162
- package/test/newMethodTest.js +0 -330
- package/test/newMethodUnitTest.js +0 -320
- package/test/optInCache.test.js +0 -221
- package/test/parameterizedPlaceholderTest.js +0 -159
- package/test/pool-registry-test.js +0 -303
- package/test/post-insert-tracking-test.js +0 -258
- package/test/postgresEngineTest.js +0 -463
- package/test/postgresIntegrationTest.js +0 -381
- package/test/promise-detection-test.js +0 -290
- package/test/qa-context-pattern-test.js +0 -319
- package/test/query-helpers-test.js +0 -258
- package/test/query-isolation-test.js +0 -59
- package/test/queryCache.test.js +0 -148
- package/test/securityTest.js +0 -268
- package/test/seed-data-test.js +0 -212
- package/test/seed-deduplication-test.js +0 -313
- package/test/seed-features-integration-test.js +0 -418
- package/test/seed-migration-template-test.js +0 -220
- package/test/singleDollarPlaceholderTest.js +0 -238
- package/test/tablePrefixTest.js +0 -100
- package/test/transformerTest.js +0 -287
- package/test/v0.3.34-bug-fixes-test.js +0 -428
- package/test/validation-test.js +0 -302
- package/test/whereChainingTest.js +0 -88
package/docs/POSTGRESQL_SETUP.md
CHANGED
|
@@ -13,7 +13,7 @@ npm install pg@^8.16.3
|
|
|
13
13
|
### 1. Initialize PostgreSQL Connection
|
|
14
14
|
|
|
15
15
|
```javascript
|
|
16
|
-
|
|
16
|
+
import context from 'masterrecord/context';
|
|
17
17
|
|
|
18
18
|
// Create a new context
|
|
19
19
|
const db = new context();
|
|
@@ -105,7 +105,7 @@ await db.saveChanges();
|
|
|
105
105
|
### Transactions
|
|
106
106
|
|
|
107
107
|
```javascript
|
|
108
|
-
|
|
108
|
+
import PostgresSyncConnect from 'masterrecord/postgresSyncConnect';
|
|
109
109
|
|
|
110
110
|
const connection = new PostgresSyncConnect();
|
|
111
111
|
await connection.connect(config);
|
|
@@ -347,12 +347,12 @@ node test/postgresIntegrationTest.js
|
|
|
347
347
|
- **MasterRecord**: 0.3.0+
|
|
348
348
|
- **pg (node-postgres)**: 8.16.3+
|
|
349
349
|
- **PostgreSQL Server**: 9.6+ (tested with 12+, 13+, 14+)
|
|
350
|
-
- **Node.js**:
|
|
350
|
+
- **Node.js**: 20+ (ESM-only package)
|
|
351
351
|
|
|
352
352
|
## Complete Example
|
|
353
353
|
|
|
354
354
|
```javascript
|
|
355
|
-
|
|
355
|
+
import context from 'masterrecord/context';
|
|
356
356
|
|
|
357
357
|
async function main() {
|
|
358
358
|
// Initialize
|
|
@@ -12,8 +12,8 @@ MasterRecord's query caching works like **Active Record** in Rails:
|
|
|
12
12
|
### 1. Express Middleware (Recommended)
|
|
13
13
|
|
|
14
14
|
```javascript
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
import express from 'express';
|
|
16
|
+
import AppContext from './models/AppContext.js';
|
|
17
17
|
|
|
18
18
|
const app = express();
|
|
19
19
|
|
|
@@ -30,9 +30,9 @@ app.use((req, res, next) => {
|
|
|
30
30
|
});
|
|
31
31
|
|
|
32
32
|
// Routes
|
|
33
|
-
app.get('/api/categories', (req, res) => {
|
|
33
|
+
app.get('/api/categories', async (req, res) => {
|
|
34
34
|
// Opt-in caching with .cache()
|
|
35
|
-
const categories = req.db.Categories.cache().toList();
|
|
35
|
+
const categories = await req.db.Categories.cache().toList();
|
|
36
36
|
res.json(categories);
|
|
37
37
|
// Cache auto-cleared after response
|
|
38
38
|
});
|
|
@@ -130,8 +130,8 @@ const transactions = db.Transactions
|
|
|
130
130
|
### Example 1: E-Commerce API
|
|
131
131
|
|
|
132
132
|
```javascript
|
|
133
|
-
|
|
134
|
-
|
|
133
|
+
import express from 'express';
|
|
134
|
+
import AppContext from './models/AppContext.js';
|
|
135
135
|
|
|
136
136
|
const app = express();
|
|
137
137
|
|
|
@@ -322,7 +322,8 @@ const cats = db.Categories.cache().toList();
|
|
|
322
322
|
### Unit Tests
|
|
323
323
|
|
|
324
324
|
```javascript
|
|
325
|
-
|
|
325
|
+
import { describe, test, beforeEach, afterEach } from 'node:test';
|
|
326
|
+
import AppContext from '../models/AppContext.js';
|
|
326
327
|
|
|
327
328
|
describe('Category API', () => {
|
|
328
329
|
let db;
|
package/eslint.config.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
|
|
3
|
+
export default [
|
|
4
|
+
js.configs.recommended,
|
|
5
|
+
{
|
|
6
|
+
languageOptions: {
|
|
7
|
+
ecmaVersion: 2023,
|
|
8
|
+
sourceType: 'module',
|
|
9
|
+
globals: {
|
|
10
|
+
console: 'readonly',
|
|
11
|
+
process: 'readonly',
|
|
12
|
+
Buffer: 'readonly',
|
|
13
|
+
global: 'readonly',
|
|
14
|
+
setTimeout: 'readonly',
|
|
15
|
+
clearTimeout: 'readonly',
|
|
16
|
+
setInterval: 'readonly',
|
|
17
|
+
clearInterval: 'readonly',
|
|
18
|
+
URL: 'readonly',
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
rules: {
|
|
22
|
+
'no-var': 'error',
|
|
23
|
+
'prefer-const': 'error',
|
|
24
|
+
'no-unused-vars': ['error', {
|
|
25
|
+
vars: 'all',
|
|
26
|
+
args: 'after-used',
|
|
27
|
+
ignoreRestSiblings: true,
|
|
28
|
+
argsIgnorePattern: '^_',
|
|
29
|
+
varsIgnorePattern: '^_',
|
|
30
|
+
}],
|
|
31
|
+
'no-console': 'off',
|
|
32
|
+
eqeqeq: ['error', 'always'],
|
|
33
|
+
'no-eval': 'error',
|
|
34
|
+
'no-implied-eval': 'error',
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
ignores: ['node_modules/**', '_migrations/**', 'test/**'],
|
|
39
|
+
},
|
|
40
|
+
];
|
package/insertManager.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
1
|
// version 1.0.0 - FAANG-level refactor
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
import tools from './Tools.js';
|
|
3
|
+
import queryScript from './QueryLanguage/queryScript.js';
|
|
4
|
+
import FieldTransformer from './Entity/fieldTransformer.js';
|
|
6
5
|
|
|
7
6
|
// Constants
|
|
8
7
|
const TIMESTAMP_FIELDS = {
|
|
@@ -352,27 +351,36 @@ class InsertManager {
|
|
|
352
351
|
if (!isRelationship) {
|
|
353
352
|
const val = currentRealModel[entity];
|
|
354
353
|
if (val != null && typeof val === 'object') {
|
|
355
|
-
// Always reject Promises —
|
|
354
|
+
// Always reject Promises — no transform/set can meaningfully handle them
|
|
356
355
|
if (typeof val.then === 'function') {
|
|
357
356
|
const entityName = entityModel.__name || 'unknown';
|
|
358
357
|
this._errorModel.isValid = false;
|
|
359
358
|
this._errorModel.errors.push(
|
|
360
359
|
`Property '${entity}' on entity '${entityName}' contains a Promise. Did you forget to await an async call?`
|
|
361
360
|
);
|
|
362
|
-
} else
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
361
|
+
} else {
|
|
362
|
+
// Allow Array/Object if the field has any serializer that can
|
|
363
|
+
// turn it into a scalar before the SQL insert runs:
|
|
364
|
+
// - legacy set() transform (currentEntity.set)
|
|
365
|
+
// - field transformer (currentEntity.transform.toDatabase)
|
|
366
|
+
const hasLegacySet = typeof currentEntity.set === 'function';
|
|
367
|
+
const hasTransformer = FieldTransformer.hasTransformer(currentEntity)
|
|
368
|
+
&& typeof currentEntity.transform.toDatabase === 'function';
|
|
369
|
+
const canSerialize = hasLegacySet || hasTransformer;
|
|
370
|
+
|
|
371
|
+
if (!canSerialize && !(val instanceof Date)) {
|
|
372
|
+
const entityName = entityModel.__name || 'unknown';
|
|
373
|
+
if (Array.isArray(val)) {
|
|
374
|
+
this._errorModel.isValid = false;
|
|
375
|
+
this._errorModel.errors.push(
|
|
376
|
+
`Property '${entity}' on entity '${entityName}' contains an Array, expected a scalar value`
|
|
377
|
+
);
|
|
378
|
+
} else {
|
|
379
|
+
this._errorModel.isValid = false;
|
|
380
|
+
this._errorModel.errors.push(
|
|
381
|
+
`Property '${entity}' on entity '${entityName}' contains an Object, expected a scalar value`
|
|
382
|
+
);
|
|
383
|
+
}
|
|
376
384
|
}
|
|
377
385
|
}
|
|
378
386
|
}
|
|
@@ -441,4 +449,4 @@ class InsertManager {
|
|
|
441
449
|
}
|
|
442
450
|
}
|
|
443
451
|
|
|
444
|
-
|
|
452
|
+
export default InsertManager;
|
package/mySQLConnect.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Version 1.0.0 - MySQL async connection manager using mysql2/promise
|
|
2
|
-
|
|
2
|
+
import mysql from 'mysql2/promise';
|
|
3
3
|
|
|
4
4
|
class MySQLAsyncClient {
|
|
5
5
|
constructor(config) {
|
|
@@ -48,4 +48,4 @@ class MySQLAsyncClient {
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
export default MySQLAsyncClient;
|
package/mySQLEngine.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Version 1.0.0 - Complete MySQL implementation with mysql2/promise
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import tools from './Tools.js';
|
|
3
|
+
import FieldTransformer from './Entity/fieldTransformer.js';
|
|
4
4
|
|
|
5
5
|
class MySQLEngine {
|
|
6
6
|
|
|
@@ -627,9 +627,23 @@ class MySQLEngine {
|
|
|
627
627
|
params.push(model["_" + dirtyFields[column]]);
|
|
628
628
|
break;
|
|
629
629
|
|
|
630
|
-
default:
|
|
630
|
+
default: {
|
|
631
|
+
// Covers `text` and any other column type without a dedicated
|
|
632
|
+
// case above. Run the toDatabase transformer here too so that
|
|
633
|
+
// fields with a serializer (e.g. JSON text columns) get their
|
|
634
|
+
// object values turned into scalars before they reach the driver.
|
|
635
|
+
let rawValue = model["_" + dirtyFields[column]];
|
|
636
|
+
if (rawValue === undefined) {
|
|
637
|
+
rawValue = model[dirtyFields[column]];
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
rawValue = FieldTransformer.toDatabase(rawValue, model.__entity[dirtyFields[column]], model.__entity.__name, dirtyFields[column]);
|
|
641
|
+
} catch (transformError) {
|
|
642
|
+
throw new Error(`UPDATE failed: ${transformError.message}`);
|
|
643
|
+
}
|
|
631
644
|
sqlParts.push(`\`${dirtyFields[column]}\` = ?`);
|
|
632
|
-
params.push(
|
|
645
|
+
params.push(rawValue);
|
|
646
|
+
}
|
|
633
647
|
}
|
|
634
648
|
}
|
|
635
649
|
|
|
@@ -656,13 +670,19 @@ class MySQLEngine {
|
|
|
656
670
|
fieldColumn = fields[modelEntity[column].foreignKey];
|
|
657
671
|
}
|
|
658
672
|
|
|
659
|
-
if (
|
|
673
|
+
if (fieldColumn !== undefined && fieldColumn !== null) {
|
|
674
|
+
// 🔥 Apply toDatabase transformer FIRST — transformers may turn
|
|
675
|
+
// objects into scalars (e.g. JSON.stringify) so running them
|
|
676
|
+
// before the type check is essential for fields that use a
|
|
677
|
+
// custom serializer on top of a text/json column.
|
|
660
678
|
try {
|
|
661
679
|
fieldColumn = FieldTransformer.toDatabase(fieldColumn, modelEntity[column], modelEntity.__name, column);
|
|
662
680
|
} catch (transformError) {
|
|
663
681
|
throw new Error(`INSERT failed: ${transformError.message}`);
|
|
664
682
|
}
|
|
683
|
+
}
|
|
665
684
|
|
|
685
|
+
if ((fieldColumn !== undefined && fieldColumn !== null) && typeof(fieldColumn) !== "object") {
|
|
666
686
|
try {
|
|
667
687
|
fieldColumn = $that._validateAndCoerceFieldType(fieldColumn, modelEntity[column], modelEntity.__name, column);
|
|
668
688
|
} catch (typeError) {
|
|
@@ -854,4 +874,4 @@ class MySQLEngine {
|
|
|
854
874
|
}
|
|
855
875
|
}
|
|
856
876
|
|
|
857
|
-
|
|
877
|
+
export default MySQLEngine;
|
package/package.json
CHANGED
|
@@ -1,14 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.000",
|
|
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
|
+
"main": "./MasterRecord.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./MasterRecord.js",
|
|
9
|
+
"./context": "./context.js",
|
|
10
|
+
"./Tools": "./Tools.js",
|
|
11
|
+
"./SQLLiteEngine": "./SQLLiteEngine.js",
|
|
12
|
+
"./mySQLEngine": "./mySQLEngine.js",
|
|
13
|
+
"./postgresEngine": "./postgresEngine.js",
|
|
14
|
+
"./mySQLConnect": "./mySQLConnect.js",
|
|
15
|
+
"./postgresSyncConnect": "./postgresSyncConnect.js",
|
|
16
|
+
"./insertManager": "./insertManager.js",
|
|
17
|
+
"./deleteManager": "./deleteManager.js",
|
|
18
|
+
"./Cache/QueryCache": "./Cache/QueryCache.js",
|
|
19
|
+
"./Cache/RedisQueryCache": "./Cache/RedisQueryCache.js",
|
|
20
|
+
"./Entity/entityModel": "./Entity/entityModel.js",
|
|
21
|
+
"./Entity/entityModelBuilder": "./Entity/entityModelBuilder.js",
|
|
22
|
+
"./Entity/entityTrackerModel": "./Entity/entityTrackerModel.js",
|
|
23
|
+
"./Entity/fieldTransformer": "./Entity/fieldTransformer.js",
|
|
24
|
+
"./QueryLanguage/queryMethods": "./QueryLanguage/queryMethods.js",
|
|
25
|
+
"./QueryLanguage/queryParameters": "./QueryLanguage/queryParameters.js",
|
|
26
|
+
"./QueryLanguage/queryScript": "./QueryLanguage/queryScript.js",
|
|
27
|
+
"./Migrations/schema": "./Migrations/schema.js",
|
|
28
|
+
"./Migrations/migrations": "./Migrations/migrations.js",
|
|
29
|
+
"./Migrations/migrationTemplate": "./Migrations/migrationTemplate.js",
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
6
32
|
"bin": {
|
|
7
|
-
"masterrecord": "Migrations/cli.js"
|
|
33
|
+
"masterrecord": "./Migrations/cli.js"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20.0.0"
|
|
8
37
|
},
|
|
9
38
|
"scripts": {
|
|
10
|
-
"test": "
|
|
11
|
-
"preinstall": "node -e \"try { require.resolve('masterrecord'); } catch(e) { if (!process.env.npm_config_global) { console.log('\\n\\u001b[36m📦 MasterRecord Installation\\u001b[0m'); console.log('\\u001b[33mℹ For best experience, install globally first:\\u001b[0m'); console.log(' npm install -g masterrecord\\n'); } }\""
|
|
39
|
+
"test": "node --test test/ Migrations/pathUtils.test.js"
|
|
12
40
|
},
|
|
13
41
|
"author": "Alexandr Rich",
|
|
14
42
|
"license": "MIT",
|
|
@@ -24,6 +52,7 @@
|
|
|
24
52
|
"mysql",
|
|
25
53
|
"sqlite",
|
|
26
54
|
"postgres",
|
|
55
|
+
"esm",
|
|
27
56
|
"masterrecord"
|
|
28
57
|
],
|
|
29
58
|
"dependencies": {
|
package/postgresEngine.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Version 0.1.0 - Complete PostgreSQL implementation with pg 8.16.3
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import tools from './Tools.js';
|
|
3
|
+
import FieldTransformer from './Entity/fieldTransformer.js';
|
|
4
|
+
import pg from 'pg';
|
|
5
|
+
|
|
6
|
+
const { Pool } = pg;
|
|
5
7
|
|
|
6
8
|
class postgresEngine {
|
|
7
9
|
|
|
@@ -572,9 +574,23 @@ class postgresEngine {
|
|
|
572
574
|
params.push(model["_" + dirtyFields[column]]);
|
|
573
575
|
break;
|
|
574
576
|
|
|
575
|
-
default:
|
|
577
|
+
default: {
|
|
578
|
+
// Covers `text` and any other column type without a dedicated
|
|
579
|
+
// case above. Run the toDatabase transformer here too so that
|
|
580
|
+
// fields with a serializer (e.g. JSONB/text columns) get their
|
|
581
|
+
// object values turned into scalars before they reach pg.
|
|
582
|
+
let rawValue = model["_" + dirtyFields[column]];
|
|
583
|
+
if (rawValue === undefined) {
|
|
584
|
+
rawValue = model[dirtyFields[column]];
|
|
585
|
+
}
|
|
586
|
+
try {
|
|
587
|
+
rawValue = FieldTransformer.toDatabase(rawValue, model.__entity[dirtyFields[column]], model.__entity.__name, dirtyFields[column]);
|
|
588
|
+
} catch (transformError) {
|
|
589
|
+
throw new Error(`UPDATE failed: ${transformError.message}`);
|
|
590
|
+
}
|
|
576
591
|
sqlParts.push(`${dirtyFields[column]} = $${paramIndex++}`);
|
|
577
|
-
params.push(
|
|
592
|
+
params.push(rawValue);
|
|
593
|
+
}
|
|
578
594
|
}
|
|
579
595
|
}
|
|
580
596
|
|
|
@@ -603,14 +619,19 @@ class postgresEngine {
|
|
|
603
619
|
fieldColumn = fields[modelEntity[column].foreignKey];
|
|
604
620
|
}
|
|
605
621
|
|
|
606
|
-
if (
|
|
607
|
-
// Apply toDatabase transformer
|
|
622
|
+
if (fieldColumn !== undefined && fieldColumn !== null) {
|
|
623
|
+
// 🔥 Apply toDatabase transformer FIRST — transformers may turn
|
|
624
|
+
// objects into scalars (e.g. JSON.stringify) so running them
|
|
625
|
+
// before the type check is essential for fields that use a
|
|
626
|
+
// custom serializer on top of a text/json column.
|
|
608
627
|
try {
|
|
609
628
|
fieldColumn = FieldTransformer.toDatabase(fieldColumn, modelEntity[column], modelEntity.__name, column);
|
|
610
629
|
} catch (transformError) {
|
|
611
630
|
throw new Error(`INSERT failed: ${transformError.message}`);
|
|
612
631
|
}
|
|
632
|
+
}
|
|
613
633
|
|
|
634
|
+
if ((fieldColumn !== undefined && fieldColumn !== null) && typeof(fieldColumn) !== "object") {
|
|
614
635
|
// Validate and coerce type
|
|
615
636
|
try {
|
|
616
637
|
fieldColumn = $that._validateAndCoerceFieldType(fieldColumn, modelEntity[column], modelEntity.__name, column);
|
|
@@ -804,4 +825,4 @@ class postgresEngine {
|
|
|
804
825
|
}
|
|
805
826
|
}
|
|
806
827
|
|
|
807
|
-
|
|
828
|
+
export default postgresEngine;
|
package/postgresSyncConnect.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Version 1.0.0 - PostgreSQL connection helper for pg 8.16.3
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import pg from 'pg';
|
|
3
|
+
import postgresEngine from './postgresEngine.js';
|
|
4
|
+
|
|
5
|
+
const { Pool } = pg;
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* PostgreSQL connection manager for MasterRecord
|
|
@@ -206,4 +208,4 @@ class PostgresSyncConnect {
|
|
|
206
208
|
}
|
|
207
209
|
}
|
|
208
210
|
|
|
209
|
-
|
|
211
|
+
export default PostgresSyncConnect;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export default {
|
|
2
|
+
printWidth: 100,
|
|
3
|
+
tabWidth: 4,
|
|
4
|
+
useTabs: false,
|
|
5
|
+
semi: true,
|
|
6
|
+
singleQuote: true,
|
|
7
|
+
quoteProps: 'as-needed',
|
|
8
|
+
trailingComma: 'es5',
|
|
9
|
+
bracketSpacing: true,
|
|
10
|
+
bracketSameLine: false,
|
|
11
|
+
arrowParens: 'avoid',
|
|
12
|
+
endOfLine: 'lf',
|
|
13
|
+
proseWrap: 'preserve',
|
|
14
|
+
htmlWhitespaceSensitivity: 'css',
|
|
15
|
+
singleAttributePerLine: false,
|
|
16
|
+
overrides: [
|
|
17
|
+
{ files: '*.md', options: { printWidth: 80, proseWrap: 'always' } },
|
|
18
|
+
{ files: '*.json', options: { tabWidth: 2 } },
|
|
19
|
+
{ files: ['*.yml', '*.yaml'], options: { tabWidth: 2 } },
|
|
20
|
+
{ files: 'package.json', options: { tabWidth: 2 } },
|
|
21
|
+
],
|
|
22
|
+
};
|
package/readme.md
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
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 20+** and a host project with `"type": "module"` in `package.json`. There is no CommonJS build.
|
|
7
|
+
|
|
6
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.
|
|
7
9
|
|
|
8
10
|
## Key Features
|
|
@@ -231,9 +233,9 @@ await db.saveChanges(); // ✅ Batch save
|
|
|
231
233
|
|
|
232
234
|
```javascript
|
|
233
235
|
// app/models/context.js
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
236
|
+
import context from 'masterrecord/context';
|
|
237
|
+
import User from './User.js';
|
|
238
|
+
import Post from './Post.js';
|
|
237
239
|
|
|
238
240
|
class AppContext extends context {
|
|
239
241
|
constructor() {
|
|
@@ -255,7 +257,7 @@ class AppContext extends context {
|
|
|
255
257
|
}
|
|
256
258
|
}
|
|
257
259
|
|
|
258
|
-
|
|
260
|
+
export default AppContext;
|
|
259
261
|
```
|
|
260
262
|
|
|
261
263
|
### 2. Define Entities
|
|
@@ -272,7 +274,7 @@ class User {
|
|
|
272
274
|
}
|
|
273
275
|
}
|
|
274
276
|
|
|
275
|
-
|
|
277
|
+
export default User;
|
|
276
278
|
```
|
|
277
279
|
|
|
278
280
|
### 3. Run Migrations
|
|
@@ -291,7 +293,7 @@ masterrecord update-database AppContext
|
|
|
291
293
|
### 4. Query Your Data
|
|
292
294
|
|
|
293
295
|
```javascript
|
|
294
|
-
|
|
296
|
+
import AppContext from './app/models/context.js';
|
|
295
297
|
const db = new AppContext();
|
|
296
298
|
|
|
297
299
|
// Create (Active Record style)
|
|
@@ -731,7 +733,7 @@ masterrecord update-database-all # Apply all pending migrations
|
|
|
731
733
|
|
|
732
734
|
```javascript
|
|
733
735
|
// db/migrations/20250111_143052_CreateUser.js
|
|
734
|
-
|
|
736
|
+
import masterrecord from 'masterrecord';
|
|
735
737
|
|
|
736
738
|
class CreateUser extends masterrecord.schema {
|
|
737
739
|
constructor(context) {
|
|
@@ -740,9 +742,9 @@ class CreateUser extends masterrecord.schema {
|
|
|
740
742
|
|
|
741
743
|
// IMPORTANT: Migrations must be async
|
|
742
744
|
async up(table) {
|
|
743
|
-
this.init(table);
|
|
745
|
+
await this.init(table);
|
|
744
746
|
|
|
745
|
-
// Create table
|
|
747
|
+
// Create table
|
|
746
748
|
await this.createTable(table.User);
|
|
747
749
|
|
|
748
750
|
// Seed initial data
|
|
@@ -754,14 +756,14 @@ class CreateUser extends masterrecord.schema {
|
|
|
754
756
|
}
|
|
755
757
|
|
|
756
758
|
async down(table) {
|
|
757
|
-
this.init(table);
|
|
759
|
+
await this.init(table);
|
|
758
760
|
|
|
759
761
|
// Rollback
|
|
760
|
-
this.dropTable(table.User);
|
|
762
|
+
await this.dropTable(table.User);
|
|
761
763
|
}
|
|
762
764
|
}
|
|
763
765
|
|
|
764
|
-
|
|
766
|
+
export default CreateUser;
|
|
765
767
|
```
|
|
766
768
|
|
|
767
769
|
### Migration Operations
|
|
@@ -818,28 +820,34 @@ class MyMigration extends masterrecord.schema {
|
|
|
818
820
|
### Seed Data
|
|
819
821
|
|
|
820
822
|
```javascript
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
823
|
+
import masterrecord from 'masterrecord';
|
|
824
|
+
|
|
825
|
+
class SeedUsers extends masterrecord.schema {
|
|
826
|
+
async up(table) {
|
|
827
|
+
await this.init(table);
|
|
828
|
+
await this.createTable(table.User);
|
|
824
829
|
|
|
825
830
|
// Single record
|
|
826
|
-
|
|
831
|
+
this.seed('User', {
|
|
827
832
|
name: 'Admin',
|
|
828
833
|
email: 'admin@example.com'
|
|
829
834
|
});
|
|
830
835
|
|
|
831
836
|
// Multiple records (efficient bulk insert)
|
|
832
|
-
|
|
837
|
+
this.bulkSeed('User', [
|
|
833
838
|
{ name: 'Alice', email: 'alice@example.com', age: 25 },
|
|
834
839
|
{ name: 'Bob', email: 'bob@example.com', age: 30 },
|
|
835
840
|
{ name: 'Charlie', email: 'charlie@example.com', age: 35 }
|
|
836
841
|
]);
|
|
837
|
-
}
|
|
842
|
+
}
|
|
838
843
|
|
|
839
|
-
down
|
|
840
|
-
|
|
844
|
+
async down(table) {
|
|
845
|
+
await this.init(table);
|
|
846
|
+
await this.dropTable(table.User);
|
|
841
847
|
}
|
|
842
|
-
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
export default SeedUsers;
|
|
843
851
|
```
|
|
844
852
|
|
|
845
853
|
**Seed data is idempotent** - re-running migrations won't create duplicates:
|
|
@@ -913,7 +921,7 @@ class AppContext extends context {
|
|
|
913
921
|
### Transactions (PostgreSQL)
|
|
914
922
|
|
|
915
923
|
```javascript
|
|
916
|
-
|
|
924
|
+
import PostgresSyncConnect from 'masterrecord/postgresSyncConnect';
|
|
917
925
|
|
|
918
926
|
const connection = new PostgresSyncConnect();
|
|
919
927
|
await connection.connect(config);
|
|
@@ -1082,8 +1090,8 @@ db.setQueryCacheEnabled(true);
|
|
|
1082
1090
|
For multi-process or clustered deployments, use Redis:
|
|
1083
1091
|
|
|
1084
1092
|
```javascript
|
|
1085
|
-
|
|
1086
|
-
|
|
1093
|
+
import { createClient } from 'redis';
|
|
1094
|
+
import RedisQueryCache from 'masterrecord/Cache/RedisQueryCache';
|
|
1087
1095
|
|
|
1088
1096
|
class AppContext extends context {
|
|
1089
1097
|
constructor() {
|
|
@@ -1689,7 +1697,7 @@ Add lifecycle hooks to your entity definitions to execute logic before/after dat
|
|
|
1689
1697
|
**Example:**
|
|
1690
1698
|
|
|
1691
1699
|
```javascript
|
|
1692
|
-
|
|
1700
|
+
import bcrypt from 'bcrypt';
|
|
1693
1701
|
|
|
1694
1702
|
class User {
|
|
1695
1703
|
constructor() {
|
|
@@ -2512,7 +2520,7 @@ for (const record of factoryRecords) {
|
|
|
2512
2520
|
|
|
2513
2521
|
**Faker Integration (Optional):**
|
|
2514
2522
|
```javascript
|
|
2515
|
-
|
|
2523
|
+
import { faker } from '@faker-js/faker';
|
|
2516
2524
|
|
|
2517
2525
|
this.dbset(User).seedFactory(100, i => ({
|
|
2518
2526
|
name: faker.person.fullName(),
|
|
@@ -3027,7 +3035,7 @@ schema.bulkSeed(tableName, dataArray)
|
|
|
3027
3035
|
### Complete CRUD Example
|
|
3028
3036
|
|
|
3029
3037
|
```javascript
|
|
3030
|
-
|
|
3038
|
+
import AppContext from './app/models/context.js';
|
|
3031
3039
|
|
|
3032
3040
|
async function demo() {
|
|
3033
3041
|
const db = new AppContext();
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verifies the custom error classes exported from context.js
|
|
3
|
+
* behave correctly (inheritance, name, context metadata).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { test } from 'node:test';
|
|
7
|
+
import assert from 'node:assert/strict';
|
|
8
|
+
import {
|
|
9
|
+
ContextError,
|
|
10
|
+
ConfigurationError,
|
|
11
|
+
DatabaseConnectionError,
|
|
12
|
+
EntityValidationError,
|
|
13
|
+
} from '../context.js';
|
|
14
|
+
|
|
15
|
+
test('ContextError is a subclass of Error', () => {
|
|
16
|
+
const err = new ContextError('test', { foo: 'bar' });
|
|
17
|
+
assert.ok(err instanceof Error);
|
|
18
|
+
assert.ok(err instanceof ContextError);
|
|
19
|
+
assert.equal(err.name, 'ContextError');
|
|
20
|
+
assert.equal(err.message, 'test');
|
|
21
|
+
assert.deepEqual(err.context, { foo: 'bar' });
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('ConfigurationError inherits from ContextError', () => {
|
|
25
|
+
const err = new ConfigurationError('bad config');
|
|
26
|
+
assert.ok(err instanceof ContextError);
|
|
27
|
+
assert.ok(err instanceof ConfigurationError);
|
|
28
|
+
assert.equal(err.name, 'ConfigurationError');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('DatabaseConnectionError attaches dbType to context', () => {
|
|
32
|
+
const err = new DatabaseConnectionError('cannot connect', 'mysql', { host: 'localhost' });
|
|
33
|
+
assert.ok(err instanceof ContextError);
|
|
34
|
+
assert.equal(err.context.dbType, 'mysql');
|
|
35
|
+
assert.equal(err.context.host, 'localhost');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('EntityValidationError attaches entityName to context', () => {
|
|
39
|
+
const err = new EntityValidationError('invalid', 'User', { field: 'email' });
|
|
40
|
+
assert.ok(err instanceof ContextError);
|
|
41
|
+
assert.equal(err.context.entityName, 'User');
|
|
42
|
+
assert.equal(err.context.field, 'email');
|
|
43
|
+
});
|