masterrecord 1.5.17 → 1.22.1
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 +216 -0
- package/Cache/QueryCache.js +5 -14
- package/Entity/entityModel.js +171 -0
- package/Entity/entityTrackerModel.js +93 -125
- package/Entity/fieldTransformer.js +26 -2
- package/MasterRecord.js +11 -0
- package/Migrations/cli.js +252 -6
- package/Migrations/ddlClauses.js +86 -0
- package/Migrations/migrationMySQLQuery.js +26 -7
- package/Migrations/migrationPostgresQuery.js +32 -8
- package/Migrations/migrationSQLiteQuery.js +42 -8
- package/Migrations/migrationTemplate.js +24 -0
- package/Migrations/migrations.js +72 -1
- package/Migrations/schema.js +183 -4
- package/QueryLanguage/queryMethods.js +488 -38
- package/QueryLanguage/rawSql.js +41 -0
- package/SQLLiteEngine.js +188 -61
- package/Tools.js +73 -0
- package/context.js +1320 -95
- package/deleteManager.js +26 -3
- package/docs/CHANGE_TRACKING_AND_CONTEXT_LIFETIME.md +143 -0
- package/docs/EF_CORE_GAP_ANALYSIS.md +132 -0
- package/docs/METHODS_REFERENCE.md +40 -0
- package/docs/MIGRATIONS_GUIDE.md +18 -0
- package/errors.js +28 -0
- package/insertManager.js +109 -0
- package/logging.js +109 -0
- package/mySQLEngine.js +0 -0
- package/package.json +6 -2
- package/postgresEngine.js +142 -27
- package/resilience.js +68 -0
|
@@ -43,6 +43,21 @@ class EntityTrackerModel {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
// Snapshot ORIGINAL values as loaded from the database (EF's
|
|
47
|
+
// EntityEntry.OriginalValues). Used for optimistic concurrency — the
|
|
48
|
+
// original value of a concurrency token goes into the UPDATE/DELETE
|
|
49
|
+
// WHERE clause — and for conflict resolution / entry() introspection.
|
|
50
|
+
// Non-enumerable so it never leaks into spreads/JSON.
|
|
51
|
+
const originals = {};
|
|
52
|
+
for (const [modelField, modelFieldValue] of modelFields) {
|
|
53
|
+
if (!$that._isRelationship(currentEntity[modelField])) {
|
|
54
|
+
originals[modelField] = modelFieldValue;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
Object.defineProperty(modelClass, '__originalValues', {
|
|
58
|
+
value: originals, enumerable: false, writable: true, configurable: true,
|
|
59
|
+
});
|
|
60
|
+
|
|
46
61
|
// Add Active Record-style .save() method
|
|
47
62
|
modelClass.save = async function() {
|
|
48
63
|
if (!this.__context) {
|
|
@@ -169,20 +184,20 @@ class EntityTrackerModel {
|
|
|
169
184
|
throw new Error('Cannot reload: entity is not attached to a context');
|
|
170
185
|
}
|
|
171
186
|
|
|
172
|
-
// Get primary key
|
|
173
|
-
const
|
|
174
|
-
const
|
|
187
|
+
// Get primary key (all columns of a composite key — EF HasKey(a, b))
|
|
188
|
+
const keys = tools.primaryKeys(this.__entity);
|
|
189
|
+
const keyValues = keys.map(k => this[k]);
|
|
175
190
|
|
|
176
|
-
if (!
|
|
191
|
+
if (!keys.length || keyValues.some(v => v === undefined || v === null || v === '')) {
|
|
177
192
|
throw new Error('Cannot reload: entity has no primary key value');
|
|
178
193
|
}
|
|
179
194
|
|
|
180
195
|
// Fetch fresh from database
|
|
181
196
|
const EntityClass = this.__context[this.__name];
|
|
182
|
-
const fresh = await EntityClass.findById(
|
|
197
|
+
const fresh = await EntityClass.findById(...keyValues);
|
|
183
198
|
if (!fresh) {
|
|
184
199
|
throw new Error(
|
|
185
|
-
`Cannot reload: ${this.__name} with ${
|
|
200
|
+
`Cannot reload: ${this.__name} with ${keys.map((k, i) => `${k}=${keyValues[i]}`).join(', ')} not found`
|
|
186
201
|
);
|
|
187
202
|
}
|
|
188
203
|
|
|
@@ -204,6 +219,17 @@ class EntityTrackerModel {
|
|
|
204
219
|
// Reset dirty fields and state
|
|
205
220
|
this.__dirtyFields = [];
|
|
206
221
|
this.__state = 'track';
|
|
222
|
+
// Reload resets ORIGINAL values to the database state (EF's
|
|
223
|
+
// Reload()), so a later concurrency check compares against what
|
|
224
|
+
// is now in the row — this is what makes "reload and retry" work.
|
|
225
|
+
if (typeof this.__context._refreshOriginalValues === 'function') {
|
|
226
|
+
this.__context._refreshOriginalValues(this);
|
|
227
|
+
}
|
|
228
|
+
// findById tracked a second instance of this row; drop it so the
|
|
229
|
+
// identity map holds only this entity (EF never tracks two copies).
|
|
230
|
+
if (typeof this.__context.__untrack === 'function') {
|
|
231
|
+
this.__context.__untrack([fresh]);
|
|
232
|
+
}
|
|
207
233
|
|
|
208
234
|
return this;
|
|
209
235
|
};
|
|
@@ -407,7 +433,15 @@ class EntityTrackerModel {
|
|
|
407
433
|
}
|
|
408
434
|
this["__proto__"]["_" + modelField] = storedValue;
|
|
409
435
|
if (navNameForFk) {
|
|
410
|
-
|
|
436
|
+
// FK -> navigation fix-up (EF): changing the FK column invalidates
|
|
437
|
+
// a previously loaded/assigned navigation so the next read
|
|
438
|
+
// re-resolves it (lazy) instead of returning a stale parent.
|
|
439
|
+
// The engines persist the FK via tools.foreignKeyValue(), which
|
|
440
|
+
// falls back to this column when the navigation slot is unset.
|
|
441
|
+
const proto = this["__proto__"];
|
|
442
|
+
const nav = proto["_" + navNameForFk];
|
|
443
|
+
if (nav !== undefined && nav !== storedValue) delete proto["_" + navNameForFk];
|
|
444
|
+
delete proto["__loading_" + navNameForFk];
|
|
411
445
|
}
|
|
412
446
|
},
|
|
413
447
|
get: function() {
|
|
@@ -486,6 +520,12 @@ class EntityTrackerModel {
|
|
|
486
520
|
// the user set and that the INSERT persisted — not a raw DB row.
|
|
487
521
|
this._defineTrackedColumn(target, modelField, captured[modelField], currentEntity, fkToNavName, false);
|
|
488
522
|
}
|
|
523
|
+
// Original values for a just-inserted (or attached) entity are its
|
|
524
|
+
// current values — exactly what was written. (EF: originals equal
|
|
525
|
+
// current for attached entities.)
|
|
526
|
+
Object.defineProperty(target, '__originalValues', {
|
|
527
|
+
value: { ...captured }, enumerable: false, writable: true, configurable: true,
|
|
528
|
+
});
|
|
489
529
|
return target;
|
|
490
530
|
}
|
|
491
531
|
|
|
@@ -530,7 +570,7 @@ class EntityTrackerModel {
|
|
|
530
570
|
|
|
531
571
|
Object.defineProperty(modelClass, entityField, {
|
|
532
572
|
set: function(value) {
|
|
533
|
-
if(typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" ){
|
|
573
|
+
if(typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value === null){
|
|
534
574
|
modelClass.__state = "modified";
|
|
535
575
|
modelClass.__version = (modelClass.__version || 0) + 1;
|
|
536
576
|
modelClass.__dirtyFields.push(entityField);
|
|
@@ -540,125 +580,53 @@ class EntityTrackerModel {
|
|
|
540
580
|
modelClass.__context.__track(modelClass);
|
|
541
581
|
}
|
|
542
582
|
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
else{
|
|
556
|
-
return `Error - Entity ${parentEntity} not found. Please check your context for proper name.`
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
if(currentEntity[entityField].relationshipType === "belongsTo"){
|
|
562
|
-
if(currentEntity[entityField].lazyLoading){
|
|
563
|
-
// TODO: UPDATE THIS CODE TO USE SOMETHING ELSE - THIS WILL NOT WORK WHEN USING DIFFERENT DATABASES BECAUSE THIS IS USING SQLITE CODE.
|
|
564
|
-
|
|
565
|
-
const name = currentEntity[entityField].foreignKey;
|
|
566
|
-
var priKey = tools.getPrimaryKeyObject(ent.__entity);
|
|
567
|
-
|
|
568
|
-
//var idValue = currentEntity[entityField].foreignKey;
|
|
569
|
-
const currentValue = this.__proto__[`_${name}`];
|
|
570
|
-
const val = this["__proto__"]["_"+entityField];
|
|
571
|
-
var modelValue = null;
|
|
572
|
-
if(!val){
|
|
573
|
-
modelValue = ent.where(`r => r.${priKey} == ${ currentValue }`).single();
|
|
574
|
-
|
|
575
|
-
}
|
|
576
|
-
else{
|
|
577
|
-
modelValue = val;
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
this[entityField] = modelValue;
|
|
581
|
-
}
|
|
582
|
-
else{
|
|
583
|
-
return this["__proto__"]["_" + entityField];
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
else{
|
|
587
|
-
// user.tags = gets all tags related to user
|
|
588
|
-
// tag.users = get all users related to tags
|
|
589
|
-
if(currentEntity[entityField].lazyLoading){
|
|
590
|
-
var priKey = tools.getPrimaryKeyObject(this.__entity);
|
|
591
|
-
var entityName = currentEntity[entityField].foreignTable === undefined ? entityField : currentEntity[entityField].foreignTable;
|
|
592
|
-
let tableName = "";
|
|
593
|
-
if(entityName){
|
|
594
|
-
switch(currentEntity[entityField].type){
|
|
595
|
-
// TODO: move the SQL generation part to the SQL builder so that we can later on use many diffrent types of SQL databases.
|
|
596
|
-
case "hasManyThrough" :
|
|
597
|
-
try{
|
|
598
|
-
const joiningEntity = this.__context[tools.capitalize(entityName)];
|
|
599
|
-
const entityFieldJoinName = currentEntity[entityField].foreignTable === undefined? entityField : currentEntity[entityField].foreignTable;
|
|
600
|
-
const _thirdEntity = this.__context[tools.capitalize(entityFieldJoinName)];
|
|
601
|
-
const firstJoiningID = joiningEntity.__entity[this.__entity.__name].foreignTable;
|
|
602
|
-
const secondJoiningID = Object.values(joiningEntity.__entity).find(e => e.foreignTable === ent.__name);
|
|
603
|
-
if(firstJoiningID && secondJoiningID )
|
|
604
|
-
{
|
|
605
|
-
var modelValue = ent.include(`p => p.${entityFieldJoinName}.select(j => j.${joiningEntity.__entity[this.__entity.__name].foreignKey})`).include(`p =>p.${this.__entity.__name}`).where(`r =>r.${this.__entity.__name}.${priKey} = ${this[priKey]}`).toList();
|
|
606
|
-
// var modelQuery = `select ${selectParameter} from ${this.__entity.__name} INNER JOIN ${entityName} ON ${this.__entity.__name}.${priKey} = ${entityName}.${firstJoiningID} INNER JOIN ${entityField} ON ${entityField}.${joinTablePriKey} = ${entityName}.${secondJoiningID} WHERE ${this.__entity.__name}.${priKey} = ${ this[priKey]}`;
|
|
607
|
-
// var modelValue = ent.raw(modelQuery).toList();
|
|
608
|
-
this[entityField] = modelValue;
|
|
609
|
-
}
|
|
610
|
-
else{
|
|
611
|
-
return "Joining table must declaire joining table names"
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
catch(error){
|
|
615
|
-
return error;
|
|
616
|
-
}
|
|
617
|
-
/*
|
|
618
|
-
select * from User
|
|
619
|
-
INNER JOIN Tagging ON User.id = Tagging.user_id
|
|
620
|
-
INNER JOIN Tag ON Tag.id = Tagging.tag_id
|
|
621
|
-
WHERE Tagging.user_id = 13
|
|
622
|
-
*/
|
|
623
|
-
break;
|
|
624
|
-
case "hasOne" :
|
|
625
|
-
var entityName = tools.findForeignTable(this.__entity.__name, ent.__entity);
|
|
626
|
-
if(entityName){
|
|
627
|
-
tableName = entityName.foreignKey;
|
|
628
|
-
}
|
|
629
|
-
else{
|
|
630
|
-
return `Error - Entity ${ent.__entity.__name} has no property named ${this.__entity.__name}`;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
//var jj = ent.raw(`select * from ${entityName} where ${tableName} = ${ this[priKey] }`).single();
|
|
634
|
-
var modelValue = ent.where(`r => r.${tableName} == ${this[priKey]}`).single();
|
|
635
|
-
this[entityField] = modelValue;
|
|
636
|
-
break;
|
|
637
|
-
case "hasMany" :
|
|
638
|
-
var entityName = tools.findForeignTable(this.__entity.__name, ent.__entity);
|
|
639
|
-
if(entityName){
|
|
640
|
-
tableName = entityName.foreignKey;
|
|
641
|
-
}
|
|
642
|
-
else{
|
|
643
|
-
return `Error - Entity ${ent.__entity.__name} has no property named ${this.__entity.__name}`;
|
|
644
|
-
}
|
|
645
|
-
//var modelValue = ent.raw(`select * from ${entityName} where ${tableName} = ${ this[priKey] }`).toList();
|
|
646
|
-
var modelValue = ent.where(`r => r.${tableName} == ${this[priKey]}`).toList();
|
|
647
|
-
this[entityField] = modelValue;
|
|
648
|
-
break;
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
else{
|
|
652
|
-
return "Entity name must be defined"
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
else{
|
|
656
|
-
return this["__proto__"]["_" + entityField];
|
|
583
|
+
// Relationship fix-up (EF): assigning a parent ENTITY to a
|
|
584
|
+
// belongsTo navigation also sets the foreign-key column, so
|
|
585
|
+
// `post.author = someAuthor` persists author_id on save.
|
|
586
|
+
const def = currentEntity[entityField];
|
|
587
|
+
const proto = Object.getPrototypeOf(modelClass); // accessor owner's slot, never `this`
|
|
588
|
+
if (value && typeof value === 'object' && value.__entity && def && def.relationshipType === 'belongsTo' && def.foreignKey) {
|
|
589
|
+
const parentPk = tools.getPrimaryKeyObject(value.__entity);
|
|
590
|
+
const fkVal = parentPk ? value[parentPk] : undefined;
|
|
591
|
+
if (fkVal !== undefined && fkVal !== null && typeof fkVal !== 'function' && tools.dataValue(modelClass, def.foreignKey) !== fkVal) {
|
|
592
|
+
// Tracked entity: the FK column's accessor marks the entity dirty
|
|
593
|
+
// (and invalidates the old navigation); plain object: data property.
|
|
594
|
+
modelClass[def.foreignKey] = fkVal;
|
|
657
595
|
}
|
|
596
|
+
} else if ((value === null || typeof value !== 'object') && def && def.relationshipType === 'belongsTo' && def.foreignKey && ('_' + def.foreignKey) in proto) {
|
|
597
|
+
proto['_' + def.foreignKey] = value; // legacy idiom `post.author = authorId`
|
|
658
598
|
}
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
599
|
+
delete proto['__loading_' + entityField];
|
|
600
|
+
proto["_" + entityField] = value;
|
|
601
|
+
},
|
|
602
|
+
get : function(){
|
|
603
|
+
// Navigation getter (EF semantics, adapted to async JS drivers):
|
|
604
|
+
// - already loaded (via include() or a previous load) -> the value, synchronously;
|
|
605
|
+
// - lazyLoadingOff() and not loaded -> null (EF: null when not loaded);
|
|
606
|
+
// - otherwise -> a Promise that loads it ONCE via the engine-agnostic,
|
|
607
|
+
// parameterized context.loadNavigation() and caches the result, so
|
|
608
|
+
// `await post.author` works on every engine. (The old getter issued
|
|
609
|
+
// SQLite-shaped SQL with the key VALUE interpolated into the lambda.)
|
|
610
|
+
// Resolve the backing slot from the accessor OWNER, never from
|
|
611
|
+
// `this`: a derived object (Object.create(entity), used by the
|
|
612
|
+
// engines) must not end up with its own shadowing `_<nav>`.
|
|
613
|
+
const proto = Object.getPrototypeOf(modelClass);
|
|
614
|
+
const loaded = proto['_' + entityField];
|
|
615
|
+
// undefined = not loaded; null = loaded, no related row (EF); a thenable = in flight
|
|
616
|
+
if (loaded !== undefined && !(loaded && typeof loaded.then === 'function')) return loaded;
|
|
617
|
+
const def = currentEntity[entityField];
|
|
618
|
+
if (!def || def.lazyLoading === false) return (loaded === undefined) ? null : loaded;
|
|
619
|
+
const ctx = modelClass.__context;
|
|
620
|
+
if (!ctx || typeof ctx.loadNavigation !== 'function') return (loaded === undefined) ? null : loaded;
|
|
621
|
+
const inflightKey = '__loading_' + entityField;
|
|
622
|
+
if (proto[inflightKey] && typeof proto[inflightKey].then === 'function') return proto[inflightKey];
|
|
623
|
+
const p = ctx.loadNavigation(modelClass, entityField).then(
|
|
624
|
+
(v) => { proto['_' + entityField] = v; delete proto[inflightKey]; return v; },
|
|
625
|
+
(err) => { delete proto[inflightKey]; throw err; }
|
|
626
|
+
);
|
|
627
|
+
proto[inflightKey] = p;
|
|
628
|
+
p.catch(() => {}); // awaiters still see the rejection; avoids an unhandled-rejection crash when un-awaited
|
|
629
|
+
return p;
|
|
662
630
|
}
|
|
663
631
|
});
|
|
664
632
|
|
|
@@ -134,6 +134,30 @@ class FieldTransformer {
|
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Built-in materialization of a raw column value into its declared JS type
|
|
139
|
+
* (EF Core value conversion on read). SQLite stores booleans as INTEGER 0/1
|
|
140
|
+
* and MySQL as TINYINT(1), so `db.boolean()` columns come back as numbers
|
|
141
|
+
* unless converted here; Postgres already returns true/false. Other types
|
|
142
|
+
* pass through unchanged; null/undefined are preserved.
|
|
143
|
+
*
|
|
144
|
+
* @param {*} value - Raw value from the database row
|
|
145
|
+
* @param {Object} fieldDef - Field definition ({ type, ... })
|
|
146
|
+
* @returns {*} Value in its application type
|
|
147
|
+
*/
|
|
148
|
+
static materialize(value, fieldDef) {
|
|
149
|
+
if (value === null || value === undefined || !fieldDef) return value;
|
|
150
|
+
const type = fieldDef.type;
|
|
151
|
+
if (type === 'boolean' || type === 'bool') {
|
|
152
|
+
if (typeof value === 'boolean') return value;
|
|
153
|
+
if (value === 1 || value === '1' || value === 'true' || value === 'TRUE') return true;
|
|
154
|
+
if (value === 0 || value === '0' || value === 'false' || value === 'FALSE') return false;
|
|
155
|
+
if (typeof value === 'bigint') return value !== 0n;
|
|
156
|
+
if (Buffer.isBuffer(value) && value.length === 1) return value[0] !== 0; // MySQL BIT(1)
|
|
157
|
+
}
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
160
|
+
|
|
137
161
|
/**
|
|
138
162
|
* Transform a value from database storage to application format
|
|
139
163
|
* Executes the fromDatabase transformer if defined
|
|
@@ -146,9 +170,9 @@ class FieldTransformer {
|
|
|
146
170
|
* @throws {Error} If transformation fails
|
|
147
171
|
*/
|
|
148
172
|
static fromDatabase(value, fieldDef, entityName, fieldName) {
|
|
149
|
-
// No transformer -
|
|
173
|
+
// No transformer - apply the built-in type materialization only
|
|
150
174
|
if (!this.hasTransformer(fieldDef)) {
|
|
151
|
-
return value;
|
|
175
|
+
return this.materialize(value, fieldDef);
|
|
152
176
|
}
|
|
153
177
|
|
|
154
178
|
const transformer = fieldDef.transform;
|
package/MasterRecord.js
CHANGED
|
@@ -2,12 +2,23 @@
|
|
|
2
2
|
import context from './context.js';
|
|
3
3
|
import schema from './Migrations/schema.js';
|
|
4
4
|
import ContextPool from './ContextPool.js';
|
|
5
|
+
import { sql, RawSql } from './QueryLanguage/rawSql.js';
|
|
6
|
+
import { ConcurrencyError } from './errors.js';
|
|
7
|
+
import { configureLogging, getLoggingConfig } from './logging.js';
|
|
8
|
+
import { isTransientError } from './resilience.js';
|
|
5
9
|
|
|
6
10
|
class masterrecord {
|
|
7
11
|
constructor() {
|
|
8
12
|
this.context = context;
|
|
9
13
|
this.schema = schema;
|
|
10
14
|
this.ContextPool = ContextPool; // EF AddDbContextPool equivalent
|
|
15
|
+
this.sql = sql; // raw SET fragment for executeUpdate (EF SetProperty(b => b.X + 1))
|
|
16
|
+
this.RawSql = RawSql;
|
|
17
|
+
this.ConcurrencyError = ConcurrencyError;
|
|
18
|
+
this.configureLogging = configureLogging; // EF LogTo / EnableSensitiveDataLogging
|
|
19
|
+
this.getLoggingConfig = getLoggingConfig;
|
|
20
|
+
this.configureRetry = (opts) => context.configureRetry(opts); // EF EnableRetryOnFailure (global default)
|
|
21
|
+
this.isTransientError = isTransientError;
|
|
11
22
|
}
|
|
12
23
|
}
|
|
13
24
|
|