masterrecord 1.2.10 → 1.3.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 +35 -0
- package/Entity/entityModel.js +52 -0
- package/context.js +79 -64
- package/docs/MIGRATIONS_GUIDE.md +3 -1
- package/package.json +1 -1
- package/readme.md +85 -128
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.3.0 — full builder type set + inline `env()` config
|
|
4
|
+
|
|
5
|
+
**Added — builder convenience type methods.** Every column type the engines'
|
|
6
|
+
DDL mappers already supported but the entity builder didn't expose now has a
|
|
7
|
+
method: `date()`, `datetime()`, `timestamp()`, `float()`, `decimal()`, `bigint()`,
|
|
8
|
+
`json()`, `uuid()`, `binary()`. Previously only `string/text/integer/time/boolean`
|
|
9
|
+
had methods and everything else required the generic `.type('…')`. Each resolves to
|
|
10
|
+
a valid SQL column type on SQLite, MySQL, and Postgres (verified end-to-end).
|
|
11
|
+
|
|
12
|
+
**Fixed — `context.env()` inline configuration object.** `env()` is documented (its
|
|
13
|
+
JSDoc `@example` and the README) to accept an inline config object —
|
|
14
|
+
`this.env({ type: 'sqlite', connection: './db/' })` — but it always treated its
|
|
15
|
+
argument as a folder path and threw `The "path" argument must be of type string` for
|
|
16
|
+
objects. `env()` now branches: an object is used directly as the config; a string
|
|
17
|
+
still resolves to `env.<NODE_ENV>.json` (keyed by context class name). No change to
|
|
18
|
+
the file-path behavior.
|
|
19
|
+
|
|
20
|
+
**Docs.** README + MIGRATIONS_GUIDE corrected: entity fields are builder **methods**
|
|
21
|
+
(`id(db){ db.integer().primary().auto(); }`), not constructor object-literals (the
|
|
22
|
+
schema builder reads prototype methods and ignores `this.x = {…}` properties); env
|
|
23
|
+
JSON files are keyed by the context class name; the context file is named after the
|
|
24
|
+
context class so the migration CLI (`enable-migrations AppContext`) can resolve it.
|
|
25
|
+
|
|
26
|
+
Tests: `test/builder-type-methods.test.js`, `test/env-inline-config.test.js`.
|
|
27
|
+
|
|
28
|
+
## Tooling — cross-engine integration tests + CI (no package change)
|
|
29
|
+
|
|
30
|
+
Closes the long-standing verification caveat ("executed on SQLite; MySQL/Postgres verified by code-reading"). Each engine's `bulkInsert` is structurally different (SQLite loops single inserts; MySQL builds one multi-row `VALUES` + `insertId`; Postgres multi-row `VALUES … RETURNING`), so "green on SQLite" does not prove "green on MySQL/Postgres".
|
|
31
|
+
|
|
32
|
+
- **`test/integration/cross-engine.test.js`** — runs the real write/DDL paths against a live server: batch/single `.set()` parity (1.2.10), multi-row `bulkInsert` + auto-PK retrieval, and an executed `alterColumn` type change (1.2.9). Gated on `MR_TEST_MYSQL_URL` / `MR_TEST_PG_URL`; unset → skipped, so the default `npm test` stays SQLite-only and offline.
|
|
33
|
+
- **`.github/workflows/test.yml`** — CI matrix (Node 20/22) with `mysql:8` + `postgres:16` service containers wired to those env vars, so every push executes all three engines. Runs lint + the full suite.
|
|
34
|
+
- **`docker-compose.test.yml`** — spin the same databases up locally to run the integration suite on your machine.
|
|
35
|
+
|
|
36
|
+
None of this ships in the npm tarball (`test/`, `.github/`, compose file are outside the `files` allowlist) — it's repo tooling only, so no version bump.
|
|
37
|
+
|
|
3
38
|
## v1.2.10 — batch/single insert parity (.set() setters, defaults, timestamps, relationships)
|
|
4
39
|
|
|
5
40
|
**Bug:** masterrecord had two INSERT write paths that didn't agree. A **single** insert (1 entity) routed through `insertManager`, which applies `.set()` setters, default values, auto timestamps, `belongsTo` FK resolution and validation. A **batch** insert (≥2 entities) called `engine.bulkInsert(entities)` **directly**, bypassing `insertManager` entirely. So saving ≥2 entities at once handed the raw, un-transformed model values straight to the engine — e.g. a field whose `.set()` maps a label to an int (`"operator"→2`) reached an INTEGER column as the string `"operator"`, the engine's type validator threw, and the whole batch **fell back to slow per-row inserts**. Correct data landed (via the fallback), but it was noisy and defeated the batch optimization. The batch path also **silently dropped child-relationship rows** (`hasMany`/`hasOne`/`hasManyThrough`), which only the per-entity path inserts.
|
package/Entity/entityModel.js
CHANGED
|
@@ -93,11 +93,63 @@ class EntityModel {
|
|
|
93
93
|
return this;
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
// Date/time columns. All resolve to TEXT on SQLite, native types on
|
|
97
|
+
// MySQL/Postgres. Store ISO-8601 strings (or epoch numbers) in them.
|
|
98
|
+
date(){
|
|
99
|
+
this.obj.type = "date";
|
|
100
|
+
return this;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
datetime(){
|
|
104
|
+
this.obj.type = "datetime";
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
timestamp(){
|
|
109
|
+
this.obj.type = "timestamp";
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
|
|
96
113
|
boolean(){
|
|
97
114
|
this.obj.type = "boolean";
|
|
98
115
|
return this;
|
|
99
116
|
}
|
|
100
117
|
|
|
118
|
+
// Numeric columns beyond integer: REAL on SQLite, native on MySQL/Postgres.
|
|
119
|
+
float(){
|
|
120
|
+
this.obj.type = "float";
|
|
121
|
+
return this;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
decimal(){
|
|
125
|
+
this.obj.type = "decimal";
|
|
126
|
+
return this;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
bigint(){
|
|
130
|
+
this.obj.type = "bigint";
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Stored as TEXT/JSON depending on engine. Pair with .get()/.set() (or a
|
|
135
|
+
// transformer) to (de)serialize objects automatically.
|
|
136
|
+
json(){
|
|
137
|
+
this.obj.type = "json";
|
|
138
|
+
return this;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Universally-unique identifier column (TEXT on SQLite).
|
|
142
|
+
uuid(){
|
|
143
|
+
this.obj.type = "uuid";
|
|
144
|
+
return this;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Raw binary column (BLOB).
|
|
148
|
+
binary(){
|
|
149
|
+
this.obj.type = "binary";
|
|
150
|
+
return this;
|
|
151
|
+
}
|
|
152
|
+
|
|
101
153
|
// maxLength(amount){
|
|
102
154
|
// this.obj.maxLength = amount;
|
|
103
155
|
// return this;
|
package/context.js
CHANGED
|
@@ -759,76 +759,91 @@ class context {
|
|
|
759
759
|
}
|
|
760
760
|
const contextName = this.__name;
|
|
761
761
|
|
|
762
|
-
//
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
if (picked) {
|
|
788
|
-
// Smart root folder detection for plugin paths
|
|
789
|
-
// If the env file is in a bb-plugins/<plugin-name>/config/environments/ structure,
|
|
790
|
-
// we should set rootFolder to the project root, not the plugin's config folder
|
|
791
|
-
let detectedRoot = path.dirname(path.dirname(picked));
|
|
792
|
-
|
|
793
|
-
// Check if we're in a bb-plugins structure
|
|
794
|
-
const pickedParts = picked.split(path.sep);
|
|
795
|
-
const pluginsIndex = pickedParts.findIndex(part => part === 'bb-plugins');
|
|
796
|
-
|
|
797
|
-
if (pluginsIndex !== -1 && pluginsIndex + 3 < pickedParts.length) {
|
|
798
|
-
// We're in bb-plugins/<plugin-name>/config/environments/...
|
|
799
|
-
// Set rootFolder to the project root (parent of bb-plugins)
|
|
800
|
-
const projectRootParts = pickedParts.slice(0, pluginsIndex);
|
|
801
|
-
detectedRoot = projectRootParts.join(path.sep) || path.sep;
|
|
762
|
+
// The config can be supplied two ways:
|
|
763
|
+
// 1. An inline config object: this.env({ type: 'sqlite', connection: './db/' })
|
|
764
|
+
// 2. A folder path to load env.<NODE_ENV>.json (keyed by context name):
|
|
765
|
+
// this.env('config/environments')
|
|
766
|
+
let options;
|
|
767
|
+
let rootFolder;
|
|
768
|
+
|
|
769
|
+
if (rootFolderLocationOrConfig && typeof rootFolderLocationOrConfig === 'object') {
|
|
770
|
+
// (1) Inline configuration — use it directly, no file lookup.
|
|
771
|
+
options = rootFolderLocationOrConfig;
|
|
772
|
+
rootFolder = process.cwd();
|
|
773
|
+
} else {
|
|
774
|
+
// (2) Folder path — locate and read env.<NODE_ENV>.json.
|
|
775
|
+
// Try multiple base roots for robustness
|
|
776
|
+
const candidateRoots = [process.cwd(), appRoot.path, __dirname];
|
|
777
|
+
let file = null;
|
|
778
|
+
const searchErrors = [];
|
|
779
|
+
|
|
780
|
+
// Performance: Use for...of instead of index-based loop (more readable, same speed)
|
|
781
|
+
for (const candidateRoot of candidateRoots) {
|
|
782
|
+
try {
|
|
783
|
+
file = this.__findSettings(candidateRoot, rootFolderLocationOrConfig, envType);
|
|
784
|
+
if (file) break;
|
|
785
|
+
} catch (error) {
|
|
786
|
+
searchErrors.push(`${candidateRoot}: ${error.message}`);
|
|
802
787
|
}
|
|
788
|
+
}
|
|
803
789
|
|
|
804
|
-
|
|
790
|
+
if (!file && searchErrors.length > 0) {
|
|
791
|
+
console.log('[Context] Config search errors:', searchErrors.join('; '));
|
|
805
792
|
}
|
|
806
|
-
|
|
793
|
+
// If still not found and an absolute path was provided, try directly
|
|
794
|
+
if (!file && path.isAbsolute(rootFolderLocationOrConfig)) {
|
|
795
|
+
const directFolder = rootFolderLocationOrConfig;
|
|
796
|
+
const envFileA = path.join(directFolder, `env.${envType}.json`);
|
|
797
|
+
const envFileB = path.join(directFolder, `${envType}.json`);
|
|
798
|
+
const picked = fs.existsSync(envFileA) ? envFileA : (fs.existsSync(envFileB) ? envFileB : null);
|
|
799
|
+
|
|
800
|
+
if (picked) {
|
|
801
|
+
// Smart root folder detection for plugin paths
|
|
802
|
+
// If the env file is in a bb-plugins/<plugin-name>/config/environments/ structure,
|
|
803
|
+
// we should set rootFolder to the project root, not the plugin's config folder
|
|
804
|
+
let detectedRoot = path.dirname(path.dirname(picked));
|
|
805
|
+
|
|
806
|
+
// Check if we're in a bb-plugins structure
|
|
807
|
+
const pickedParts = picked.split(path.sep);
|
|
808
|
+
const pluginsIndex = pickedParts.findIndex(part => part === 'bb-plugins');
|
|
809
|
+
|
|
810
|
+
if (pluginsIndex !== -1 && pluginsIndex + 3 < pickedParts.length) {
|
|
811
|
+
// We're in bb-plugins/<plugin-name>/config/environments/...
|
|
812
|
+
// Set rootFolder to the project root (parent of bb-plugins)
|
|
813
|
+
const projectRootParts = pickedParts.slice(0, pluginsIndex);
|
|
814
|
+
detectedRoot = projectRootParts.join(path.sep) || path.sep;
|
|
815
|
+
}
|
|
807
816
|
|
|
808
|
-
|
|
809
|
-
throw new ConfigurationError(
|
|
810
|
-
`Environment configuration not found for '${envType}'`,
|
|
811
|
-
{
|
|
812
|
-
searchPath: rootFolderLocationOrConfig,
|
|
813
|
-
environment: envType,
|
|
814
|
-
attemptedRoots: candidateRoots
|
|
817
|
+
file = { file: picked, rootFolder: detectedRoot };
|
|
815
818
|
}
|
|
816
|
-
|
|
817
|
-
}
|
|
819
|
+
}
|
|
818
820
|
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
821
|
+
if (!file) {
|
|
822
|
+
throw new ConfigurationError(
|
|
823
|
+
`Environment configuration not found for '${envType}'`,
|
|
824
|
+
{
|
|
825
|
+
searchPath: rootFolderLocationOrConfig,
|
|
826
|
+
environment: envType,
|
|
827
|
+
attemptedRoots: candidateRoots
|
|
828
|
+
}
|
|
829
|
+
);
|
|
830
|
+
}
|
|
823
831
|
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
+
// Always use absolute file path to avoid module root ambiguity on global installs/Windows
|
|
833
|
+
const settingsPath = path.isAbsolute(file.file) ? file.file : path.resolve(file.rootFolder, file.file);
|
|
834
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
|
835
|
+
options = settings[contextName];
|
|
836
|
+
rootFolder = file.rootFolder;
|
|
837
|
+
|
|
838
|
+
if (!options || typeof options !== 'object') {
|
|
839
|
+
throw new ConfigurationError(
|
|
840
|
+
`Configuration missing settings for context '${contextName}'`,
|
|
841
|
+
{
|
|
842
|
+
configFile: settingsPath,
|
|
843
|
+
availableContexts: Object.keys(settings)
|
|
844
|
+
}
|
|
845
|
+
);
|
|
846
|
+
}
|
|
832
847
|
}
|
|
833
848
|
|
|
834
849
|
const type = String(options.type || '').toLowerCase();
|
|
@@ -849,7 +864,7 @@ class context {
|
|
|
849
864
|
this.isPostgres = false;
|
|
850
865
|
|
|
851
866
|
// Resolve database path using extracted method
|
|
852
|
-
const dbPath = this._resolveDatabasePath(options.connection,
|
|
867
|
+
const dbPath = this._resolveDatabasePath(options.connection, rootFolder, contextName);
|
|
853
868
|
|
|
854
869
|
// Ensure database directory exists
|
|
855
870
|
const dbDir = path.dirname(dbPath);
|
package/docs/MIGRATIONS_GUIDE.md
CHANGED
|
@@ -30,7 +30,9 @@ MasterRecord migrations let you:
|
|
|
30
30
|
### 1. Set up your context
|
|
31
31
|
|
|
32
32
|
```javascript
|
|
33
|
-
// app/models/
|
|
33
|
+
// app/models/AppContext.js
|
|
34
|
+
// Name the file after the context class so `masterrecord enable-migrations AppContext`
|
|
35
|
+
// can find it (the CLI resolves the context by file name: *AppContext.js).
|
|
34
36
|
import context from 'masterrecord/context';
|
|
35
37
|
import User from './User.js';
|
|
36
38
|
import Post from './Post.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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/readme.md
CHANGED
|
@@ -234,7 +234,9 @@ await db.saveChanges(); // ✅ Batch save
|
|
|
234
234
|
### 1. Create a Context
|
|
235
235
|
|
|
236
236
|
```javascript
|
|
237
|
-
// app/models/
|
|
237
|
+
// app/models/AppContext.js
|
|
238
|
+
// Name the file after the context class so the `masterrecord` migration CLI can
|
|
239
|
+
// resolve it: `masterrecord enable-migrations AppContext` looks for *AppContext.js.
|
|
238
240
|
import context from 'masterrecord/context';
|
|
239
241
|
import User from './User.js';
|
|
240
242
|
import Post from './Post.js';
|
|
@@ -266,14 +268,13 @@ export default AppContext;
|
|
|
266
268
|
|
|
267
269
|
```javascript
|
|
268
270
|
// app/models/User.js
|
|
271
|
+
// Each field is a METHOD that receives the schema builder (db).
|
|
269
272
|
class User {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
this.created_at = { type: 'timestamp', default: 'CURRENT_TIMESTAMP' };
|
|
276
|
-
}
|
|
273
|
+
id(db) { db.integer().primary().auto(); }
|
|
274
|
+
name(db) { db.string().notNullable(); }
|
|
275
|
+
email(db) { db.string().notNullable().unique(); }
|
|
276
|
+
age(db) { db.integer(); } // nullable by default
|
|
277
|
+
created_at(db) { db.datetime(); }
|
|
277
278
|
}
|
|
278
279
|
|
|
279
280
|
export default User;
|
|
@@ -295,7 +296,7 @@ masterrecord update-database AppContext
|
|
|
295
296
|
### 4. Query Your Data
|
|
296
297
|
|
|
297
298
|
```javascript
|
|
298
|
-
import AppContext from './app/models/
|
|
299
|
+
import AppContext from './app/models/AppContext.js';
|
|
299
300
|
const db = new AppContext();
|
|
300
301
|
|
|
301
302
|
// Create (Active Record style)
|
|
@@ -398,17 +399,20 @@ await db.saveChanges(); // SQLite now has async API wrapper
|
|
|
398
399
|
|
|
399
400
|
### Environment Files
|
|
400
401
|
|
|
401
|
-
Store configurations in JSON files
|
|
402
|
+
Store configurations in JSON files **keyed by the context class name** (so one file
|
|
403
|
+
can hold settings for multiple contexts):
|
|
402
404
|
|
|
403
405
|
```json
|
|
404
406
|
// config/environments/env.development.json
|
|
405
407
|
{
|
|
406
|
-
"
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
408
|
+
"AppContext": {
|
|
409
|
+
"type": "postgres",
|
|
410
|
+
"host": "localhost",
|
|
411
|
+
"port": 5432,
|
|
412
|
+
"database": "myapp_dev",
|
|
413
|
+
"user": "postgres",
|
|
414
|
+
"password": "dev_password"
|
|
415
|
+
}
|
|
412
416
|
}
|
|
413
417
|
```
|
|
414
418
|
|
|
@@ -433,44 +437,32 @@ node app.js
|
|
|
433
437
|
|
|
434
438
|
### Basic Entity
|
|
435
439
|
|
|
440
|
+
Each field is a method on the class that receives the schema builder (`db`) and
|
|
441
|
+
chains type + modifiers:
|
|
442
|
+
|
|
436
443
|
```javascript
|
|
437
444
|
class User {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
this.id = {
|
|
441
|
-
type: 'integer',
|
|
442
|
-
primary: true,
|
|
443
|
-
auto: true
|
|
444
|
-
};
|
|
445
|
+
// Primary key with auto-increment
|
|
446
|
+
id(db) { db.integer().primary().auto(); }
|
|
445
447
|
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
type: 'string',
|
|
449
|
-
nullable: false
|
|
450
|
-
};
|
|
448
|
+
// Required string field
|
|
449
|
+
name(db) { db.string().notNullable(); }
|
|
451
450
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
type: 'string',
|
|
455
|
-
nullable: true,
|
|
456
|
-
default: 'active'
|
|
457
|
-
};
|
|
451
|
+
// Optional field with a default value
|
|
452
|
+
status(db) { db.string().default('active'); }
|
|
458
453
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
type: 'string',
|
|
462
|
-
unique: true
|
|
463
|
-
};
|
|
454
|
+
// Unique constraint
|
|
455
|
+
email(db) { db.string().unique(); }
|
|
464
456
|
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
type: 'timestamp',
|
|
468
|
-
default: 'CURRENT_TIMESTAMP'
|
|
469
|
-
};
|
|
470
|
-
}
|
|
457
|
+
// Timestamp (stored as TEXT on SQLite; set it in app code or a beforeSave hook)
|
|
458
|
+
created_at(db) { db.datetime(); }
|
|
471
459
|
}
|
|
472
460
|
```
|
|
473
461
|
|
|
462
|
+
> **Note:** fields are *methods*, not assigned object literals. MasterRecord reads
|
|
463
|
+
> the class's prototype methods to build the schema; plain `this.x = {...}`
|
|
464
|
+
> properties in the constructor are ignored.
|
|
465
|
+
|
|
474
466
|
### Field Types
|
|
475
467
|
|
|
476
468
|
| MasterRecord Type | PostgreSQL | MySQL | SQLite |
|
|
@@ -493,34 +485,24 @@ class User {
|
|
|
493
485
|
|
|
494
486
|
### Relationships
|
|
495
487
|
|
|
488
|
+
Relationships are declared with the `hasMany` / `hasOne` / `belongsTo` builder
|
|
489
|
+
methods. `belongsTo('User')` automatically creates the `user_id` foreign-key column.
|
|
490
|
+
|
|
496
491
|
```javascript
|
|
497
492
|
class User {
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
this.Posts = {
|
|
504
|
-
type: 'hasMany',
|
|
505
|
-
model: 'Post',
|
|
506
|
-
foreignKey: 'user_id'
|
|
507
|
-
};
|
|
508
|
-
}
|
|
493
|
+
id(db) { db.integer().primary().auto(); }
|
|
494
|
+
name(db) { db.string(); }
|
|
495
|
+
|
|
496
|
+
// One-to-many: User has many Posts (foreign key inferred as user_id on Post)
|
|
497
|
+
Posts(db) { db.hasMany('Post'); }
|
|
509
498
|
}
|
|
510
499
|
|
|
511
500
|
class Post {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
// Many-to-one: Post belongs to User
|
|
518
|
-
this.User = {
|
|
519
|
-
type: 'belongsTo',
|
|
520
|
-
model: 'User',
|
|
521
|
-
foreignKey: 'user_id'
|
|
522
|
-
};
|
|
523
|
-
}
|
|
501
|
+
id(db) { db.integer().primary().auto(); }
|
|
502
|
+
title(db) { db.string(); }
|
|
503
|
+
|
|
504
|
+
// Many-to-one: Post belongs to a User (creates the user_id column)
|
|
505
|
+
User(db) { db.belongsTo('User'); }
|
|
524
506
|
}
|
|
525
507
|
```
|
|
526
508
|
|
|
@@ -528,23 +510,18 @@ class Post {
|
|
|
528
510
|
|
|
529
511
|
Store complex JavaScript types in simple database columns:
|
|
530
512
|
|
|
513
|
+
Use `.set(fn)` to transform a value on its way **into** the database and `.get(fn)`
|
|
514
|
+
to transform it on the way **out**:
|
|
515
|
+
|
|
531
516
|
```javascript
|
|
532
517
|
class User {
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
toDatabase: (value) => {
|
|
541
|
-
return Array.isArray(value) ? JSON.stringify(value) : value;
|
|
542
|
-
},
|
|
543
|
-
fromDatabase: (value) => {
|
|
544
|
-
return value ? JSON.parse(value) : [];
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
};
|
|
518
|
+
id(db) { db.integer().primary().auto(); }
|
|
519
|
+
|
|
520
|
+
// Store arrays as JSON strings transparently
|
|
521
|
+
tags(db) {
|
|
522
|
+
db.string()
|
|
523
|
+
.set((value) => (Array.isArray(value) ? JSON.stringify(value) : value))
|
|
524
|
+
.get((value) => (value ? JSON.parse(value) : []));
|
|
548
525
|
}
|
|
549
526
|
}
|
|
550
527
|
|
|
@@ -922,26 +899,20 @@ await db.saveChanges();
|
|
|
922
899
|
|
|
923
900
|
```javascript
|
|
924
901
|
class Post {
|
|
925
|
-
|
|
926
|
-
this.id = { type: 'integer', primary: true, auto: true };
|
|
927
|
-
|
|
928
|
-
// Store array as JSON
|
|
929
|
-
this.tags = {
|
|
930
|
-
type: 'string',
|
|
931
|
-
transform: {
|
|
932
|
-
toDatabase: (v) => Array.isArray(v) ? JSON.stringify(v) : v,
|
|
933
|
-
fromDatabase: (v) => v ? JSON.parse(v) : []
|
|
934
|
-
}
|
|
935
|
-
};
|
|
902
|
+
id(db) { db.integer().primary().auto(); }
|
|
936
903
|
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
904
|
+
// Store array as JSON in a TEXT column
|
|
905
|
+
tags(db) {
|
|
906
|
+
db.string()
|
|
907
|
+
.set((v) => (Array.isArray(v) ? JSON.stringify(v) : v))
|
|
908
|
+
.get((v) => (v ? JSON.parse(v) : []));
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Native JSON column (JSON/JSONB on Postgres & MySQL, TEXT on SQLite)
|
|
912
|
+
metadata(db) {
|
|
913
|
+
db.json()
|
|
914
|
+
.set((v) => JSON.stringify(v || {}))
|
|
915
|
+
.get((v) => (typeof v === 'string' ? JSON.parse(v) : v));
|
|
945
916
|
}
|
|
946
917
|
}
|
|
947
918
|
```
|
|
@@ -1575,17 +1546,10 @@ If your entity has cascade delete rules, they will be applied automatically:
|
|
|
1575
1546
|
|
|
1576
1547
|
```javascript
|
|
1577
1548
|
class User {
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
this.Posts = {
|
|
1583
|
-
type: 'hasMany',
|
|
1584
|
-
model: 'Post',
|
|
1585
|
-
foreignKey: 'user_id',
|
|
1586
|
-
cascade: true // Enable cascade delete
|
|
1587
|
-
};
|
|
1588
|
-
}
|
|
1549
|
+
id(db) { db.integer().primary().auto(); }
|
|
1550
|
+
|
|
1551
|
+
// hasMany cascades by default — call .stopCascadeOnDelete() to opt out
|
|
1552
|
+
Posts(db) { db.hasMany('Post'); }
|
|
1589
1553
|
}
|
|
1590
1554
|
|
|
1591
1555
|
const user = await db.User.findById(1);
|
|
@@ -1749,25 +1713,18 @@ Add lifecycle hooks to your entity definitions to execute logic before/after dat
|
|
|
1749
1713
|
import bcrypt from 'bcrypt';
|
|
1750
1714
|
|
|
1751
1715
|
class User {
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
this.role = { type: 'string' };
|
|
1759
|
-
}
|
|
1716
|
+
id(db) { db.integer().primary().auto(); }
|
|
1717
|
+
email(db) { db.string(); }
|
|
1718
|
+
password(db) { db.string(); }
|
|
1719
|
+
created_at(db) { db.datetime(); }
|
|
1720
|
+
updated_at(db) { db.datetime(); }
|
|
1721
|
+
role(db) { db.string(); }
|
|
1760
1722
|
|
|
1761
|
-
// Hash password before saving
|
|
1723
|
+
// Hash the password (when changed) and stamp timestamps before saving.
|
|
1762
1724
|
beforeSave() {
|
|
1763
|
-
// Only hash if password was changed
|
|
1764
1725
|
if (this.__dirtyFields.includes('password')) {
|
|
1765
1726
|
this.password = bcrypt.hashSync(this.password, 10);
|
|
1766
1727
|
}
|
|
1767
|
-
}
|
|
1768
|
-
|
|
1769
|
-
// Set timestamps automatically
|
|
1770
|
-
beforeSave() {
|
|
1771
1728
|
if (this.__state === 'insert') {
|
|
1772
1729
|
this.created_at = new Date();
|
|
1773
1730
|
}
|
|
@@ -3110,7 +3067,7 @@ schema.bulkSeed(tableName, dataArray)
|
|
|
3110
3067
|
### Complete CRUD Example
|
|
3111
3068
|
|
|
3112
3069
|
```javascript
|
|
3113
|
-
import AppContext from './app/models/
|
|
3070
|
+
import AppContext from './app/models/AppContext.js';
|
|
3114
3071
|
|
|
3115
3072
|
async function demo() {
|
|
3116
3073
|
const db = new AppContext();
|