masterrecord 1.22.1 → 1.27.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.
@@ -214,7 +214,7 @@ class migrationSQLiteQuery {
214
214
  queryVar += `${this.foreignKeyClause(fk)}, `;
215
215
  }
216
216
 
217
- return `CREATE TABLE IF NOT EXISTS ${table.__name} (${queryVar.replace(/,\s*$/, "")});`;
217
+ return `CREATE TABLE IF NOT EXISTS "${table.__name}" (${queryVar.replace(/,\s*$/, "")});`;
218
218
 
219
219
  /*
220
220
  INTEGER PRIMARY KEY AUTOINCREMENT
@@ -237,11 +237,11 @@ class migrationSQLiteQuery {
237
237
  // `IF NOT EXISTS` and dropColumn's skip-if-gone, and matching the Postgres
238
238
  // builder. A migration that DROPs a legacy table which never existed on a
239
239
  // fresh install is then a no-op instead of a hard failure.
240
- return `DROP TABLE IF EXISTS ${name}`
240
+ return `DROP TABLE IF EXISTS "${name}"`
241
241
  }
242
242
 
243
243
  renameTable(table){
244
- return `ALTER TABLE ${table.tableName} RENAME TO ${table.newName}`;
244
+ return `ALTER TABLE "${table.tableName}" RENAME TO "${table.newName}"`;
245
245
  }
246
246
 
247
247
  renameColumn(table){
@@ -1087,8 +1087,10 @@ class queryMethods{
1087
1087
  __entity : this.__entity,
1088
1088
  __context : this.__context,
1089
1089
  __name : this.__entity.__name,
1090
- __proto__ : {}
1091
1090
  };
1091
+ // Backing slots are non-enumerable own properties (see tools.slotOwner); the
1092
+ // prototype stays the shared Object.prototype so reads stay monomorphic.
1093
+ Object.defineProperty(newEntity, '__self', { value: newEntity, enumerable: false, writable: false, configurable: true });
1092
1094
 
1093
1095
  // Set up property setters for all entity fields
1094
1096
  for (const fieldName in this.__entity) {
@@ -1165,11 +1167,7 @@ class queryMethods{
1165
1167
  // tracker-entity setter (entityTrackerModel.build) already does
1166
1168
  // this on UPDATE; we need the same behavior on INSERT so values
1167
1169
  // normalize consistently regardless of which path created them.
1168
- if (fieldDef && typeof fieldDef.set === 'function') {
1169
- this.__proto__["_" + fname] = fieldDef.set(value);
1170
- } else {
1171
- this.__proto__["_" + fname] = value;
1172
- }
1170
+ tools.setSlot(this, "_" + fname, (fieldDef && typeof fieldDef.set === 'function') ? fieldDef.set(value) : value);
1173
1171
  if(!this.__dirtyFields.includes(fname)){
1174
1172
  this.__dirtyFields.push(fname);
1175
1173
  }
@@ -1187,9 +1185,9 @@ class queryMethods{
1187
1185
  get: function(){
1188
1186
  // Apply get function if defined
1189
1187
  if(fieldDef && typeof fieldDef.get === "function"){
1190
- return fieldDef.get(this.__proto__["_" + fname]);
1188
+ return fieldDef.get(this["_" + fname]);
1191
1189
  }
1192
- return this.__proto__["_" + fname];
1190
+ return this["_" + fname];
1193
1191
  }
1194
1192
  });
1195
1193
 
@@ -1221,7 +1219,7 @@ class queryMethods{
1221
1219
  enumerable: true,
1222
1220
  configurable: true,
1223
1221
  set: function(value) {
1224
- this.__proto__["_" + navName] = value;
1222
+ tools.setSlot(this, "_" + navName, value);
1225
1223
  if (!this.__dirtyFields.includes(navName)) {
1226
1224
  this.__dirtyFields.push(navName);
1227
1225
  }
@@ -1240,7 +1238,7 @@ class queryMethods{
1240
1238
  // to the FK-column backing populated
1241
1239
  // by DB hydration in
1242
1240
  // entityTrackerModel.build().
1243
- const navVal = this.__proto__["_" + navName];
1241
+ const navVal = this["_" + navName];
1244
1242
  if (navVal && typeof navVal === 'object' && navVal.__entity) {
1245
1243
  // An assigned parent ENTITY: the FK column reads its key.
1246
1244
  const def = navVal.__entity;
@@ -1249,7 +1247,7 @@ class queryMethods{
1249
1247
  }
1250
1248
  return navVal !== undefined
1251
1249
  ? navVal
1252
- : this.__proto__["_" + fkName];
1250
+ : this["_" + fkName];
1253
1251
  }
1254
1252
  });
1255
1253
  }
@@ -1412,7 +1410,7 @@ class queryMethods{
1412
1410
 
1413
1411
  // Only reload scalar fields
1414
1412
  if (!isRelationship) {
1415
- this.__proto__["_" + fieldName] = fresh.__proto__["_" + fieldName];
1413
+ tools.setSlot(this, "_" + fieldName, tools.getSlot(fresh, "_" + fieldName));
1416
1414
  }
1417
1415
  }
1418
1416
 
package/SQLLiteEngine.js CHANGED
@@ -706,7 +706,10 @@ class SQLLiteEngine {
706
706
  buildFrom(query, entity){
707
707
  const entityName = this.getEntity(entity.__name, query.entityMap);
708
708
  if(entityName ){
709
- return `FROM ${entity.__name } AS ${entityName}`;
709
+ // Bracket-quoted like every other table reference in this engine: an
710
+ // entity named with a SQL reserved word (Order, Group, Transaction…)
711
+ // otherwise produced `FROM Order AS ran` -> "near \"Order\": syntax error".
712
+ return `FROM [${entity.__name}] AS ${entityName}`;
710
713
  }
711
714
  else{ return "" }
712
715
  }
package/Tools.js CHANGED
@@ -150,17 +150,50 @@ class Tools{
150
150
 
151
151
  }
152
152
 
153
+ /**
154
+ * Backing-slot storage (1.23.0). A tracked entity keeps its column values,
155
+ * navigation values and in-flight markers in NON-ENUMERABLE OWN properties
156
+ * (`_<col>`, `_<nav>`, `__loading_<nav>`) and its prototype is the ordinary
157
+ * shared one — so every entity of a type has the same V8 hidden class and a
158
+ * property read costs what a plain object read costs (it used to be a fresh
159
+ * per-row prototype object holding the slots: ~300 ns/read, megamorphic).
160
+ * A derived clean model (`Object.create(entity)`, used by the engines) finds
161
+ * its owner through the entity's `__self`; reads walk the chain naturally.
162
+ */
163
+ static slotOwner(obj) {
164
+ if (!obj || typeof obj !== 'object') return obj;
165
+ const self = obj.__self;
166
+ return (self && typeof self === 'object') ? self : obj;
167
+ }
168
+ static hasSlot(obj, key) {
169
+ const o = Tools.slotOwner(obj);
170
+ return !!o && typeof o === 'object' && (key in o);
171
+ }
172
+ static getSlot(obj, key) {
173
+ const o = Tools.slotOwner(obj);
174
+ return (o && typeof o === 'object') ? o[key] : undefined;
175
+ }
176
+ static setSlot(obj, key, value) {
177
+ const o = Tools.slotOwner(obj);
178
+ if (!o || typeof o !== 'object') return;
179
+ if (Object.prototype.hasOwnProperty.call(o, key)) o[key] = value;
180
+ else Object.defineProperty(o, key, { value, writable: true, enumerable: false, configurable: true });
181
+ }
182
+ static deleteSlot(obj, key) {
183
+ const o = Tools.slotOwner(obj);
184
+ if (o && typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, key)) delete o[key];
185
+ }
186
+
153
187
  /**
154
188
  * Read a field's stored value WITHOUT invoking a navigation getter:
155
189
  * a plain data property (new Model() before tracking accessors exist),
156
- * else the tracked backing slot `_<key>` on the prototype.
190
+ * else the tracked backing slot `_<key>`.
157
191
  */
158
192
  static dataValue(obj, key) {
159
193
  if (!obj || typeof obj !== 'object') return undefined;
160
194
  const d = Object.getOwnPropertyDescriptor(obj, key);
161
195
  if (d && 'value' in d) return d.value;
162
- const proto = Object.getPrototypeOf(obj);
163
- if (proto && ('_' + key) in proto) return proto['_' + key];
196
+ if (Tools.hasSlot(obj, '_' + key)) return Tools.getSlot(obj, '_' + key);
164
197
  return undefined;
165
198
  }
166
199
 
package/context.js CHANGED
@@ -17,6 +17,7 @@
17
17
  import modelBuilder from './Entity/entityModelBuilder.js';
18
18
  import query from './QueryLanguage/queryMethods.js';
19
19
  import tools from './Tools.js';
20
+ import DatabaseFacade from './Migrations/DatabaseFacade.js';
20
21
  import SQLLiteEngine from './SQLLiteEngine.js';
21
22
  import MySQLEngine from './mySQLEngine.js';
22
23
  import insertManager from './insertManager.js';
@@ -1866,8 +1867,7 @@ class context {
1866
1867
  if (!def || typeof def !== 'object') throw new Error(`masterrecord: '${field}' is not a navigation of ${entity.__entity.__name}.`);
1867
1868
  const isRel = def.relationshipType === 'belongsTo' || def.type === 'hasOne' || def.type === 'hasMany' || def.type === 'hasManyThrough';
1868
1869
  if (!isRel) throw new Error(`masterrecord: '${field}' on ${entity.__entity.__name} is a column, not a navigation.`);
1869
- const proto = Object.getPrototypeOf(entity);
1870
- const backing = (col) => (proto && ('_' + col) in proto) ? proto['_' + col] : entity[col];
1870
+ const backing = (col) => tools.hasSlot(entity, '_' + col) ? tools.getSlot(entity, '_' + col) : entity[col];
1871
1871
  let value = null;
1872
1872
 
1873
1873
  if (def.relationshipType === 'belongsTo') {
@@ -1906,7 +1906,7 @@ class context {
1906
1906
  if (def.type === 'hasMany') this._decorateCollection(entity, field, value);
1907
1907
  }
1908
1908
  }
1909
- if (proto) proto['_' + field] = value; else entity['_' + field] = value;
1909
+ tools.setSlot(entity, '_' + field, value);
1910
1910
  return value;
1911
1911
  }
1912
1912
 
@@ -1934,8 +1934,8 @@ class context {
1934
1934
  if (!isBt && def.type !== 'hasOne' && def.type !== 'hasMany' && def.type !== 'hasManyThrough') {
1935
1935
  throw new Error(`masterrecord: '${nav}' on ${ownerDef.__name} is a column, not a navigation.`);
1936
1936
  }
1937
- const slotOf = (e) => Object.getPrototypeOf(e);
1938
- const setSlot = (e, v) => { const p = slotOf(e); if (p) p['_' + nav] = v; else e['_' + nav] = v; };
1937
+ const slotOf = (e) => tools.slotOwner(e);
1938
+ const setSlot = (e, v) => tools.setSlot(e, '_' + nav, v);
1939
1939
  const CHUNK = 500;
1940
1940
  const chunks = (arr) => { const out = []; for (let i = 0; i < arr.length; i += CHUNK) out.push(arr.slice(i, i + CHUNK)); return out; };
1941
1941
  const uniq = (arr) => [...new Set(arr.filter(v => v !== undefined && v !== null && typeof v !== 'function'))];
@@ -2016,8 +2016,7 @@ class context {
2016
2016
 
2017
2017
  /** Has this navigation been loaded (by include() or loadNavigation())? */
2018
2018
  isNavigationLoaded(entity, field) {
2019
- const proto = Object.getPrototypeOf(entity);
2020
- const v = proto ? proto['_' + field] : undefined;
2019
+ const v = tools.getSlot(entity, '_' + field);
2021
2020
  // null counts as loaded (EF: the reference was loaded and there is no related row)
2022
2021
  return v !== undefined && !(v && typeof v.then === 'function');
2023
2022
  }
@@ -2030,6 +2029,16 @@ class context {
2030
2029
  * Same shape on SQLite, MySQL and Postgres (engine-specific extras such as
2031
2030
  * pool counters / server version are added when available).
2032
2031
  */
2032
+ /**
2033
+ * Database-level operations for this context — EF's `context.Database`:
2034
+ * ensureCreated / ensureDeleted / canConnect / hasTables /
2035
+ * generateCreateScript / getAppliedMigrations / baseline.
2036
+ */
2037
+ get database() {
2038
+ if (!this.__database) { this.__database = new DatabaseFacade(this); }
2039
+ return this.__database;
2040
+ }
2041
+
2033
2042
  async healthCheck() {
2034
2043
  const engine = this.isSQLite ? 'sqlite' : this.isMySQL ? 'mysql' : this.isPostgres ? 'postgres' : 'unknown';
2035
2044
  const started = Date.now();
@@ -2915,9 +2924,8 @@ class context {
2915
2924
  // entity so its value matches the row and the next save's WHERE
2916
2925
  // uses the new version.
2917
2926
  if (rowVersionColumn) {
2918
- const proto = Object.getPrototypeOf(currentModel);
2919
2927
  const cur = Number(this._backingValue(currentModel, rowVersionColumn) || 0);
2920
- if (proto && ('_' + rowVersionColumn) in proto) proto['_' + rowVersionColumn] = cur + 1;
2928
+ if (tools.hasSlot(currentModel, '_' + rowVersionColumn)) tools.setSlot(currentModel, '_' + rowVersionColumn, cur + 1);
2921
2929
  else currentModel[rowVersionColumn] = cur + 1;
2922
2930
  }
2923
2931
  }
@@ -3491,8 +3499,7 @@ class context {
3491
3499
  }
3492
3500
 
3493
3501
  _backingValue(entity, column) {
3494
- const proto = Object.getPrototypeOf(entity);
3495
- if (proto && ('_' + column) in proto) return proto['_' + column];
3502
+ if (tools.hasSlot(entity, '_' + column)) return tools.getSlot(entity, '_' + column);
3496
3503
  const v = entity[column];
3497
3504
  return typeof v === 'function' ? undefined : v;
3498
3505
  }
package/deleteManager.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // version 1.0.0 - FAANG-Level Refactored
2
+ import tools from './Tools.js';
2
3
 
3
4
  // Constants for relationship types
4
5
  const RELATIONSHIP_TYPES = {
@@ -81,9 +82,7 @@ class DeleteManager {
81
82
  if (this._isRelationshipType(propertyConfig.type)) {
82
83
  // Read the backing field directly to avoid triggering lazy-loading
83
84
  // getters, which can return Promises or error strings
84
- const relatedModel = entity.__proto__
85
- ? entity.__proto__["_" + property]
86
- : entity["_" + property];
85
+ const relatedModel = tools.getSlot(entity, "_" + property);
87
86
 
88
87
  if (relatedModel === null || relatedModel === undefined) {
89
88
  // Unloaded relationships are safe to skip — the database
@@ -159,9 +158,7 @@ class DeleteManager {
159
158
 
160
159
  if (this._isRelationshipType(propertyConfig.type)) {
161
160
  // Read backing field directly to avoid triggering lazy-loading getters
162
- const relatedModel = entity.__proto__
163
- ? entity.__proto__["_" + property]
164
- : entity["_" + property];
161
+ const relatedModel = tools.getSlot(entity, "_" + property);
165
162
 
166
163
  if (relatedModel === null || relatedModel === undefined) {
167
164
  continue;
package/insertManager.js CHANGED
@@ -564,8 +564,8 @@ class InsertManager {
564
564
  }
565
565
 
566
566
  // Fallback: check backing field on tracked model if both reads were undefined/null
567
- if (!hasValue && currentRealModel && currentRealModel.__proto__) {
568
- const backing = currentRealModel.__proto__['_' + entity];
567
+ if (!hasValue && currentRealModel) {
568
+ const backing = tools.getSlot(currentRealModel, '_' + entity);
569
569
  hasValue = (backing !== undefined && backing !== null);
570
570
  if (hasValue) {
571
571
  // normalize into both models so downstream sees it
package/mySQLEngine.js CHANGED
@@ -197,7 +197,7 @@ class MySQLEngine {
197
197
  // column defaults.
198
198
  const groups = new Map();
199
199
  for (const row of rows) {
200
- const key = `${row.sql.tableName}${row.sql.columns}`;
200
+ const key = `${row.sql.tableName}\u0000${row.sql.columns}`;
201
201
  if (!groups.has(key)) groups.set(key, []);
202
202
  groups.get(key).push(row);
203
203
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.22.1",
3
+ "version": "1.27.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",
@@ -32,7 +32,15 @@
32
32
  "./errors": "./errors.js",
33
33
  "./sql": "./QueryLanguage/rawSql.js",
34
34
  "./logging": "./logging.js",
35
- "./resilience": "./resilience.js"
35
+ "./resilience": "./resilience.js",
36
+ "./Migrations/HistoryRow": "./Migrations/HistoryRow.js",
37
+ "./Migrations/HistoryRepository": "./Migrations/HistoryRepository.js",
38
+ "./Migrations/RelationalDatabaseCreator": "./Migrations/RelationalDatabaseCreator.js",
39
+ "./Migrations/DatabaseFacade": "./Migrations/DatabaseFacade.js",
40
+ "./Migrations/contextInit": "./Migrations/contextInit.js",
41
+ "./Migrations/Migrator": "./Migrations/Migrator.js",
42
+ "./Migrations/MigrationsAssembly": "./Migrations/MigrationsAssembly.js",
43
+ "./Migrations/migrationId": "./Migrations/migrationId.js"
36
44
  },
37
45
  "bin": {
38
46
  "masterrecord": "Migrations/cli.js"
@@ -48,7 +56,8 @@
48
56
  "!prettier.config.js",
49
57
  "docs/**/*.md",
50
58
  "CHANGES.md",
51
- "LICENSE"
59
+ "LICENSE",
60
+ "THIRD-PARTY-NOTICES.md"
52
61
  ],
53
62
  "engines": {
54
63
  "node": ">=20.0.0"