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.
package/CHANGES.md CHANGED
@@ -1,5 +1,179 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.27.0 — `Migrator.GenerateScript` and `HasPendingModelChanges`: EF's `IMigrator` is now complete
4
+
5
+ 1.26.0 moved applying into `Migrator`; this finishes the interface. EF's `IMigrator` is
6
+ `Migrate` / `GenerateScript` / `HasPendingModelChanges`, and every masterrecord CLI command
7
+ is now a shell over it — there is no second implementation of anything left.
8
+
9
+ - **`Migrator.generateScript(from, to, { idempotent, appliedMigrations })`** (EF:
10
+ `GenerateScript`). `from` omitted or `'0'` scripts from an empty database and emits the
11
+ history-table bootstrap first, exactly as EF does; `appliedMigrations` scripts against
12
+ what a live database has actually applied, which is what `masterrecord script` passes.
13
+ `--idempotent` wraps each migration in a "only if not already applied" guard (Postgres
14
+ `DO $MR$ … IF NOT EXISTS …`); SQLite and MySQL refuse it, as EF's SQLite provider does.
15
+ - **`Migrator.hasPendingModelChanges()`** and `context.database.hasPendingModelChanges()`
16
+ (EF: `HasPendingModelChanges`) — true when entities have changed since the last migration.
17
+ - **`context.database.generateMigrationScript()`** for the same thing from an app.
18
+ - **`masterrecord script` delegates to it** and gained `--idempotent`.
19
+ - **Fix:** the generated script recorded each migration with a *parameterized* insert
20
+ (`VALUES (?, ?)` plus a `-- params:` comment), which is not runnable SQL — the point of
21
+ the command is to hand a DBA something they can execute. It now emits literal values via
22
+ `HistoryRepository.getInsertScript`.
23
+ - **`migrations-status` and `remove-migration`** read history through `HistoryRepository`
24
+ instead of their own SQL. The last of the duplicated migration helpers
25
+ (`__getAppliedMigrations`, `__recordMigrationApplied`, `__getAppliedMigrationRows`,
26
+ and the `_masterrecord_migrations` string constant) are deleted — **139 lines of
27
+ duplication removed across 1.26.0 and 1.27.0**.
28
+
29
+ New tests: `generateScript` (runnable output, applies nothing, pending-only, SQLite refusing
30
+ idempotent) and `hasPendingModelChanges` in `test/ef-migrator-apply.test.js`.
31
+
32
+ ## v1.26.0 — one migration code path: `Migrator.Migrate` (EF), and the CLI is a thin shell over it
33
+
34
+ EF's `IMigrator` is `Migrate` / `GenerateScript` / `HasPendingModelChanges` — applying
35
+ migrations *is* the Migrator, and `dotnet ef database update` is a thin shell over it.
36
+ masterrecord had the apply logic living inside the `update-database` CLI command instead,
37
+ with `update-database-all`, `update-database-down` and `remove-migration` each carrying
38
+ their own copy. That is now one path.
39
+
40
+ - **`Migrator.migrate(target)`** applies and reverts: no target applies everything pending,
41
+ a migration id migrates up or down to it, and `'0'` (EF's `Migration.InitialDatabase`)
42
+ reverts everything, newest first. Each migration is applied **atomically with its history
43
+ row** and recorded as it goes, so an interrupted run resumes where it stopped.
44
+ - **`context.database.migrate()`** — EF's `context.Database.Migrate()`, callable from an app
45
+ at startup, not just from the CLI. It discovers the snapshot and migration files, or takes
46
+ them explicitly.
47
+ - **`update-database`, `update-database-all`, `update-database-down` and `remove-migration`
48
+ now all delegate to `Migrator`**, and 71 lines of duplicated apply logic were deleted
49
+ (`__applyMigrationStep`, `__ensureMigrationsTable`, `__removeMigrationApplied`).
50
+ - **Fix:** `update-database-down` ran `down()` **outside any transaction** — a failed
51
+ rollback could leave a half-reverted schema with the history row still present. Rolling
52
+ back now uses the same per-migration transaction as applying.
53
+ - **Fix:** every migration opens its own context (its schema constructor builds one); it is
54
+ now released after the migration runs. Only `update-database-all` did this before, so
55
+ single-context runs leaked a connection per migration.
56
+
57
+ New tests: `test/ef-migrator-apply.test.js` (apply-all and idempotency, targeted up/down,
58
+ revert-to-`'0'`, and `context.database.migrate()`).
59
+
60
+ ## v1.25.0 — EF's Migrator planning: getMigrations / getPendingMigrations
61
+
62
+ Completes the read half of EF's `DbContext.Database` surface. Ported from Entity
63
+ Framework Core (see `THIRD-PARTY-NOTICES.md`).
64
+
65
+ - **`Migrator`** (`Migrations/Migrator.js`) — EF's `PopulateMigrations` planning, faithfully:
66
+ no target applies every unapplied migration; the `'0'` target (EF's
67
+ `Migration.InitialDatabase`) reverts every applied one, newest first; a target id applies
68
+ unapplied migrations up to and including it and reverts applied ones after it. Applied-id
69
+ matching is case-insensitive, as in EF. `plan(target)` reads the live history table.
70
+ - **`MigrationsAssembly`** (`Migrations/MigrationsAssembly.js`) — EF's `IMigrationsAssembly`
71
+ over `<timestamp>_<Name>_migration.js` files, with `getMigrationId()` resolving a full id,
72
+ a file name or the bare migration name (and reporting ambiguity).
73
+ - **`context.database.getMigrations()` / `.getPendingMigrations()`** (EF: `GetMigrations` /
74
+ `GetPendingMigrations`). A non-empty pending list means the schema is behind the code —
75
+ a useful startup or health check.
76
+ - **Fix (ordering):** `getAppliedMigrations()` returned rows in the history table's
77
+ lexicographic `ORDER BY`, so `1000_Beta` sorted before `900_Alpha`. Migration ids are
78
+ epoch milliseconds and only the same width by coincidence, so ids are now ordered
79
+ chronologically by a comparator (`Migrations/migrationId.js`) shared with
80
+ `MigrationsAssembly` — the files on disk and the rows in the table can no longer disagree
81
+ about what the next migration is.
82
+
83
+ Applying migrations remains the `masterrecord update-database` CLI's job; this release is
84
+ the planner it and your app can both ask. New tests: `test/ef-migrator-planning.test.js`.
85
+
86
+ ## v1.24.2 — reserved-word entity names work end to end on SQLite
87
+
88
+ - **Fix (SQLite):** `buildFrom` emitted `FROM Order AS ran` unquoted, so every query
89
+ against an entity named with a SQL reserved word (`Order`, `Group`, `Transaction`,
90
+ `Index`…) failed with `near "Order": syntax error`. It is now bracket-quoted like every
91
+ other table reference in that engine. Together with the DDL quoting in 1.24.0, a
92
+ reserved-word entity now creates, inserts, queries, filters, counts, updates and deletes
93
+ normally. MySQL (backticks) and Postgres (`_q()`) already quoted correctly — this was
94
+ SQLite-only. New test: `test/reserved-word-entity.test.js`.
95
+ - **Fix (tooling):** `mySQLEngine.js` contained a literal NUL byte — a deliberate delimiter
96
+ in a composite cache key, but written as a raw byte rather than the `\u0000` escape. That
97
+ made the file count as binary, so `grep` skipped it **silently**: no search of the
98
+ repository ever matched anything in the MySQL engine. Same runtime value, now written as
99
+ an escape; the file is UTF-8 text again and searchable.
100
+
101
+ ## v1.24.1 — MySQL/Postgres coverage for the EF port, and a Postgres `ensureDeleted` fix
102
+
103
+ 1.24.0's MySQL and Postgres providers shipped without ever being executed — masterrecord
104
+ has no live cross-engine suite (`docker-compose.test.yml` advertises `MR_TEST_MYSQL_URL` /
105
+ `MR_TEST_PG_URL`, but nothing read them). Reviewing and testing those paths found a real bug:
106
+
107
+ - **Fix (Postgres):** `ensureDeleted()` issued `DROP DATABASE` on the context's own
108
+ connection, which Postgres always rejects — *"cannot drop the currently open database"*.
109
+ It now closes the context's pool, connects to the `postgres` maintenance database,
110
+ terminates any other backend attached to the target, and drops from there — the shape
111
+ EF's Npgsql provider uses and the one masterrecord's own
112
+ `_createPostgresDatabaseFromConfig()` already used for CREATE.
113
+ - **Fix (MySQL):** `ensureDeleted()` likewise drops through an admin connection with no
114
+ database selected, after closing the context pool. Dropping the schema a live pool points
115
+ at left every pooled connection referring to a database that no longer existed.
116
+ - **Hardening:** a database name that is not a plain identifier is now refused rather than
117
+ interpolated into `DROP DATABASE` (the same rule the schema layer already applied to CREATE).
118
+ - **Tests:** `test/ef-provider-sql.test.js` drives the HistoryRepository and
119
+ RelationalDatabaseCreator SQL for **all three engines** with a context that captures
120
+ statements instead of running them — no database required, so MySQL/Postgres SQL
121
+ generation is covered on every `npm test`. `test/ef-cross-engine.integration.test.js`
122
+ adds real end-to-end coverage (EnsureCreated → query → history → baseline → EnsureDeleted
123
+ against a scratch database), skipped unless `MR_TEST_MYSQL_URL` / `MR_TEST_PG_URL` are set.
124
+
125
+ ## v1.24.0 — EF Core's database-creation and migrations-history object model
126
+
127
+ Ported from Entity Framework Core (dotnet/efcore, MIT — see `THIRD-PARTY-NOTICES.md`),
128
+ preserving EF's class structure, method names and algorithms.
129
+
130
+ - **`context.database`** — EF's `DbContext.Database` facade: `ensureCreated()`,
131
+ `ensureDeleted()`, `canConnect()`, `hasTables()`, `generateCreateScript()`,
132
+ `getAppliedMigrations()`, `getAppliedMigrationRows()`, `baseline()`.
133
+ - **`RelationalDatabaseCreator`** (`Migrations/RelationalDatabaseCreator.js`) with SQLite,
134
+ MySQL and Postgres implementations: `exists`, `create`, `delete`, `hasTables`,
135
+ `createTables`, `ensureCreated`, `ensureDeleted`, `generateCreateScript`, `canConnect`.
136
+ **`ensureCreated()` is all-or-nothing, exactly as in EF**: it creates the database and the
137
+ model's tables only when the database has *no tables at all*, and never alters an existing
138
+ table. It does not use migrations — use it for tests, prototypes and cold starts, and
139
+ migrations for a schema that has to evolve.
140
+ - **`HistoryRepository`** (`Migrations/HistoryRepository.js`) — the migrations history table
141
+ as a first-class, overridable abstraction (EF's `__EFMigrationsHistory`): `exists`,
142
+ `create`, `createIfNotExists`, `getAppliedMigrations`, `getInsertScript`,
143
+ `getDeleteScript`, `recordApplied`, `recordReverted`, and EF's
144
+ `getBeginIfNotExistsScript`/`getEndIfScript` idempotency hooks (implemented for Postgres;
145
+ SQLite refuses them, as EF's SQLite provider does). masterrecord's existing
146
+ `_masterrecord_migrations` table and its column names remain the defaults, so nothing
147
+ changes for existing databases; EF's `ProductVersion` is added as a nullable
148
+ `product_version` column the first time history is written.
149
+ - **`HistoryRow`** (`Migrations/HistoryRow.js`) — EF's history row, plus `appliedAt`.
150
+ - **Baselining** — `ctx.database.baseline(migrationId)` and `masterrecord baseline <context>
151
+ [migration] [--all]` record a migration as applied **without running it**: EF's documented
152
+ way to bring a database that already has the schema under migration control.
153
+ - **CLI**: `masterrecord ensure-created <context>` (EF `EnsureCreated`),
154
+ `masterrecord ensure-deleted <context> --force` (EF `EnsureDeleted`; refuses without
155
+ `--force`), `masterrecord baseline`. `ensure-created` works on a project with no
156
+ migrations yet, so a cold start no longer needs a hand-written bootstrap script.
157
+ - **Subpath exports opened** for `Migrations/HistoryRow`, `Migrations/HistoryRepository`,
158
+ `Migrations/RelationalDatabaseCreator`, `Migrations/DatabaseFacade` and
159
+ `Migrations/contextInit` — the last of which previously forced callers to bypass the
160
+ package's `exports` map to reach `instantiateReadyContext`.
161
+ - **Fix (SQLite DDL):** `createTable`/`dropTable`/`renameTable` now quote the table name,
162
+ as the MySQL and Postgres builders already did. An entity named with a reserved word
163
+ (`Order`, `Group`, `Transaction`…) previously failed to create with
164
+ `near "Order": syntax error`. Note that **queries** against such a table still fail —
165
+ the query builder does not yet quote table names.
166
+
167
+ New tests: `test/ef-database-creator.test.js`.
168
+
169
+ ## v1.23.0 — entity property reads ~16x faster (shared prototype per entity type)
170
+
171
+ - **Perf:** every entity of a type now shares **one prototype** and keeps its backing slots (`_<col>`, `_<nav>`, `__loading_<nav>`) as **non-enumerable own properties**. Before, each row got a fresh `{}` prototype holding its slots, so every entity had its own V8 hidden class and `entity.col` was a megamorphic accessor read: **~326 ns/read** (both tracked and `asNoTracking()`), i.e. an O(n²) loop over two 2 000-row tables took seconds and over larger tables minutes. Now **~20 ns/read**; the 2 000×2 000 nested loop went from 2.07 s to 0.19 s. EF Core entities are POCOs — a property read should cost about what a plain object read costs.
172
+ - Public shape is unchanged: `Object.keys(entity)` / `JSON.stringify` / `{ ...entity }` still expose only columns; navigation getters, `asNoTracking()`, change tracking, `Object.create(entity)` clean models (engine idiom: reads walk the chain, writes reach the owner through the entity's `__self`) all behave as before. Internal slot access is centralized in `tools.slotOwner/getSlot/setSlot/hasSlot/deleteSlot` (code that poked `Object.getPrototypeOf(entity)['_col']` must use these).
173
+ - Guidance still holds for hot loops: prefer `asNoTracking()` for read-only queries (no tracking bookkeeping per row) and build one-pass `Map`s instead of nested loops.
174
+
175
+ New test: `test/entity-layout-read-performance.test.js`.
176
+
3
177
  ## v1.22.1 — boolean columns materialize as booleans on read (fix)
4
178
 
5
179
  - **Fix:** `db.boolean()` columns are now materialized as real `true`/`false` when rows are read (`toList()/find()/single()/first()`, tracked or `asNoTracking()`), matching EF Core value conversion. SQLite stores booleans as INTEGER `0/1` and MySQL as `TINYINT(1)`/`BIT(1)`, so an entity read back exposed `1`/`0` (an API echoed `{ published: true }` after the insert but `{ published: 1 }` after a later read/update). `null` is preserved; other types are untouched; a custom `transform()` still wins. Implemented as `FieldTransformer.materialize(value, fieldDef)`, applied on the single row→entity path.
@@ -5,14 +5,14 @@ import FieldTransformer from './fieldTransformer.js';
5
5
 
6
6
  class EntityTrackerModel {
7
7
 
8
-
9
- // entity states https://docs.microsoft.com/en-us/dotnet/api/system.data.entitystate?view=netframework-4.7.2
10
-
11
8
  // start tracking model
12
9
  build(dataModel, currentEntity, context){
13
10
  const $that = this;
14
11
  const modelClass = this.buildObject(); // build entity with models
15
- modelClass.__proto__ = {};
12
+ // The entity's prototype stays the ordinary shared Object.prototype and its
13
+ // backing slots are non-enumerable OWN properties (see tools.slotOwner):
14
+ // every row of a type shares one hidden class, so reads stay monomorphic.
15
+ Object.defineProperty(modelClass, '__self', { value: modelClass, enumerable: false, writable: false, configurable: true });
16
16
  const modelFields = Object.entries(dataModel); /// return array of objects
17
17
 
18
18
  modelClass.__entity = currentEntity;
@@ -212,7 +212,7 @@ class EntityTrackerModel {
212
212
 
213
213
  // Only reload scalar fields
214
214
  if (!isRelationship) {
215
- this.__proto__["_" + fieldName] = fresh.__proto__["_" + fieldName];
215
+ tools.setSlot(this, "_" + fieldName, tools.getSlot(fresh, "_" + fieldName));
216
216
  }
217
217
  }
218
218
 
@@ -328,7 +328,10 @@ class EntityTrackerModel {
328
328
  }
329
329
  }
330
330
 
331
- target["__proto__"]["_" + modelField] = transformedValue;
331
+ const slot = "_" + modelField; // backing slot (non-enumerable own property)
332
+ const fieldDef = currentEntity[modelField] || null; // static column definition
333
+ const customGet = (fieldDef && typeof fieldDef.get === "function") ? fieldDef.get : null;
334
+ tools.setSlot(target, slot, transformedValue);
332
335
 
333
336
  Object.defineProperty(target, modelField, {
334
337
  enumerable: true,
@@ -431,33 +434,26 @@ class EntityTrackerModel {
431
434
  } else {
432
435
  storedValue = value;
433
436
  }
434
- this["__proto__"]["_" + modelField] = storedValue;
437
+ tools.setSlot(this, slot, storedValue);
435
438
  if (navNameForFk) {
436
439
  // FK -> navigation fix-up (EF): changing the FK column invalidates
437
440
  // a previously loaded/assigned navigation so the next read
438
441
  // re-resolves it (lazy) instead of returning a stale parent.
439
442
  // The engines persist the FK via tools.foreignKeyValue(), which
440
443
  // 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];
444
+ const nav = tools.getSlot(this, "_" + navNameForFk);
445
+ if (nav !== undefined && nav !== storedValue) tools.deleteSlot(this, "_" + navNameForFk);
446
+ tools.deleteSlot(this, "__loading_" + navNameForFk);
445
447
  }
446
448
  },
449
+ // Hot path: a property read on an entity must cost about what a plain
450
+ // object read costs (EF Core entities are POCOs). The slot key, field
451
+ // definition and custom getter are resolved ONCE per accessor (closure),
452
+ // not per read — previously every read re-concatenated "_" + field and
453
+ // re-walked the definition (~300 ns/read, ~200x a plain property).
447
454
  get: function() {
448
- if (currentEntity[modelField]) {
449
- if (!currentEntity[modelField].skipGetFunction) {
450
- if (typeof currentEntity[modelField].get === "function") {
451
- return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
452
- } else {
453
- return this["__proto__"]["_" + modelField];
454
- }
455
- } else {
456
- return this["__proto__"]["_" + modelField];
457
- }
458
- } else {
459
- return this["__proto__"]["_" + modelField];
460
- }
455
+ const value = this[slot]; // own slot on the entity; a derived clean model reads it through the chain
456
+ return (customGet !== null && !fieldDef.skipGetFunction) ? customGet(value) : value;
461
457
  }
462
458
  });
463
459
  }
@@ -471,10 +467,9 @@ class EntityTrackerModel {
471
467
  * After this, the inserted entity behaves like a queried one: edits mark it
472
468
  * modified and produce an UPDATE.
473
469
  *
474
- * A per-entity backing layer is spliced into the prototype chain
475
- * (`Object.create(originalProto)`) so `_<field>` backings stay per-instance
476
- * while the class prototype — and any lifecycle-hook methods on it — remain
477
- * reachable.
470
+ * Backing slots (`_<field>`) are non-enumerable own properties of the object
471
+ * itself (see tools.slotOwner), so the class prototype — and any lifecycle-hook
472
+ * methods on it — is never touched.
478
473
  */
479
474
  attachTrackingTo(target) {
480
475
  const currentEntity = target && target.__entity;
@@ -508,12 +503,14 @@ class EntityTrackerModel {
508
503
  scalarFields.push(modelField);
509
504
  }
510
505
 
511
- // Splice a fresh backing layer in front of the original prototype so the
512
- // class prototype (and its lifecycle hooks) stays reachable.
513
- Object.setPrototypeOf(target, Object.create(Object.getPrototypeOf(target)));
506
+ // Backing slots become non-enumerable OWN properties of the user's object;
507
+ // its class prototype (and any lifecycle-hook methods on it) is untouched.
514
508
  Object.defineProperty(target, '__trackingAttached', {
515
509
  value: true, enumerable: false, writable: true, configurable: true,
516
510
  });
511
+ if (!Object.prototype.hasOwnProperty.call(target, '__self')) {
512
+ Object.defineProperty(target, '__self', { value: target, enumerable: false, writable: false, configurable: true });
513
+ }
517
514
 
518
515
  for (const modelField of scalarFields) {
519
516
  // applyFromDb=false: the captured value is already the domain value
@@ -584,7 +581,7 @@ class EntityTrackerModel {
584
581
  // belongsTo navigation also sets the foreign-key column, so
585
582
  // `post.author = someAuthor` persists author_id on save.
586
583
  const def = currentEntity[entityField];
587
- const proto = Object.getPrototypeOf(modelClass); // accessor owner's slot, never `this`
584
+ const proto = modelClass; // slots live on the accessor OWNER (own non-enumerable props), never on `this`
588
585
  if (value && typeof value === 'object' && value.__entity && def && def.relationshipType === 'belongsTo' && def.foreignKey) {
589
586
  const parentPk = tools.getPrimaryKeyObject(value.__entity);
590
587
  const fkVal = parentPk ? value[parentPk] : undefined;
@@ -594,10 +591,10 @@ class EntityTrackerModel {
594
591
  modelClass[def.foreignKey] = fkVal;
595
592
  }
596
593
  } 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`
594
+ tools.setSlot(proto, '_' + def.foreignKey, value); // legacy idiom `post.author = authorId`
598
595
  }
599
- delete proto['__loading_' + entityField];
600
- proto["_" + entityField] = value;
596
+ tools.deleteSlot(proto, '__loading_' + entityField);
597
+ tools.setSlot(proto, "_" + entityField, value);
601
598
  },
602
599
  get : function(){
603
600
  // Navigation getter (EF semantics, adapted to async JS drivers):
@@ -610,7 +607,7 @@ class EntityTrackerModel {
610
607
  // Resolve the backing slot from the accessor OWNER, never from
611
608
  // `this`: a derived object (Object.create(entity), used by the
612
609
  // engines) must not end up with its own shadowing `_<nav>`.
613
- const proto = Object.getPrototypeOf(modelClass);
610
+ const proto = modelClass;
614
611
  const loaded = proto['_' + entityField];
615
612
  // undefined = not loaded; null = loaded, no related row (EF); a thenable = in flight
616
613
  if (loaded !== undefined && !(loaded && typeof loaded.then === 'function')) return loaded;
@@ -621,10 +618,10 @@ class EntityTrackerModel {
621
618
  const inflightKey = '__loading_' + entityField;
622
619
  if (proto[inflightKey] && typeof proto[inflightKey].then === 'function') return proto[inflightKey];
623
620
  const p = ctx.loadNavigation(modelClass, entityField).then(
624
- (v) => { proto['_' + entityField] = v; delete proto[inflightKey]; return v; },
625
- (err) => { delete proto[inflightKey]; throw err; }
621
+ (v) => { tools.setSlot(proto, '_' + entityField, v); tools.deleteSlot(proto, inflightKey); return v; },
622
+ (err) => { tools.deleteSlot(proto, inflightKey); throw err; }
626
623
  );
627
- proto[inflightKey] = p;
624
+ tools.setSlot(proto, inflightKey, p);
628
625
  p.catch(() => {}); // awaiters still see the rejection; avoids an unhandled-rejection crash when un-awaited
629
626
  return p;
630
627
  }
@@ -0,0 +1,230 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) —
2
+ // Extensions/RelationalDatabaseFacadeExtensions.cs and Infrastructure/DatabaseFacade.cs.
3
+ // See THIRD-PARTY-NOTICES.md.
4
+
5
+ import { createRequire } from 'node:module';
6
+ import { createDatabaseCreator } from './RelationalDatabaseCreator.js';
7
+ import { createHistoryRepository } from './HistoryRepository.js';
8
+ import Migrator from './Migrator.js';
9
+ import HistoryRow from './HistoryRow.js';
10
+
11
+ const require = createRequire(import.meta.url);
12
+ let PRODUCT_VERSION = null;
13
+ try { PRODUCT_VERSION = require('../package.json').version; } catch (_) { PRODUCT_VERSION = null; }
14
+
15
+ /**
16
+ * Database-level operations for a context — EF's `context.Database`.
17
+ *
18
+ * await ctx.database.ensureCreated(); // EF EnsureCreated()
19
+ * await ctx.database.ensureDeleted(); // EF EnsureDeleted()
20
+ * await ctx.database.canConnect(); // EF CanConnect()
21
+ * await ctx.database.getAppliedMigrations(); // EF GetAppliedMigrations()
22
+ * ctx.database.generateCreateScript(); // EF GenerateCreateScript()
23
+ */
24
+ class DatabaseFacade {
25
+ constructor(context) {
26
+ this.context = context;
27
+ }
28
+
29
+ /** EF: IRelationalDatabaseCreator. */
30
+ get databaseCreator() {
31
+ if (!this._databaseCreator) {
32
+ this._databaseCreator = createDatabaseCreator(this.context);
33
+ }
34
+ return this._databaseCreator;
35
+ }
36
+
37
+ /** EF: IHistoryRepository. */
38
+ get historyRepository() {
39
+ if (!this._historyRepository) {
40
+ this._historyRepository = createHistoryRepository(this.context, {
41
+ databaseCreator: this.databaseCreator,
42
+ productVersion: PRODUCT_VERSION,
43
+ });
44
+ }
45
+ return this._historyRepository;
46
+ }
47
+
48
+ /**
49
+ * Ensure the database exists and, when it holds no tables, create every table
50
+ * in the model. Returns true when anything was created (EF: EnsureCreated).
51
+ *
52
+ * This does NOT use migrations and never alters an existing table. Use it for
53
+ * tests, prototypes and throwaway databases; use migrations for a database
54
+ * whose schema has to evolve.
55
+ */
56
+ async ensureCreated() {
57
+ await this._ready();
58
+ return this.databaseCreator.ensureCreated();
59
+ }
60
+
61
+ /** Drop the database when it exists; true when it was dropped (EF: EnsureDeleted). */
62
+ async ensureDeleted() {
63
+ await this._ready();
64
+ return this.databaseCreator.ensureDeleted();
65
+ }
66
+
67
+ /** Does the database contain any tables? (EF: IRelationalDatabaseCreator.HasTables) */
68
+ async hasTables() {
69
+ await this._ready();
70
+ return this.databaseCreator.hasTables();
71
+ }
72
+
73
+ /** Is the database reachable? (EF: CanConnect) */
74
+ async canConnect() {
75
+ await this._ready();
76
+ return this.databaseCreator.canConnect();
77
+ }
78
+
79
+ /** The DDL that ensureCreated() would run (EF: GenerateCreateScript). */
80
+ async generateCreateScript() {
81
+ await this._ready();
82
+ return this.databaseCreator.generateCreateScript();
83
+ }
84
+
85
+ /**
86
+ * EF's Migrator — the planner behind getMigrations/getPendingMigrations.
87
+ * `migrationsPath` defaults to the working directory; pass one when the app
88
+ * runs from somewhere other than the project root.
89
+ */
90
+ migrator(options = {}) {
91
+ return new Migrator({ historyRepository: this.historyRepository, ...options });
92
+ }
93
+
94
+ /** Every migration on disk, oldest first (EF: GetMigrations). */
95
+ getMigrations(options = {}) {
96
+ return this.migrator(options).getMigrations();
97
+ }
98
+
99
+ /**
100
+ * Migrations on disk that the database has NOT recorded as applied
101
+ * (EF: GetPendingMigrations). A useful startup/health check: a non-empty
102
+ * result means the schema is behind the code.
103
+ */
104
+ async getPendingMigrations(options = {}) {
105
+ await this._ready();
106
+ return this.migrator(options).getPendingMigrations();
107
+ }
108
+
109
+ /**
110
+ * Apply pending migrations to the database (EF: `context.Database.Migrate()`).
111
+ *
112
+ * await ctx.database.migrate(); // apply everything pending
113
+ * await ctx.database.migrate('0'); // revert everything
114
+ *
115
+ * The snapshot and migration files are discovered from the working directory;
116
+ * pass `{ snapshot, files }` when the app runs from somewhere else. This is the
117
+ * same Migrator the `masterrecord update-database` CLI runs.
118
+ */
119
+ async migrate(targetMigration = null, options = {}) {
120
+ const migrator = await this._buildMigrator(options);
121
+ return migrator.migrate(targetMigration);
122
+ }
123
+
124
+ /**
125
+ * The SQL for pending migrations, without applying it
126
+ * (EF: Migrator.GenerateScript). `idempotent` guards each migration so the
127
+ * script is safe to run against any database.
128
+ */
129
+ async generateMigrationScript(options = {}) {
130
+ const migrator = await this._buildMigrator(options);
131
+ const applied = await this.getAppliedMigrations();
132
+ return migrator.generateScript(options.from ?? null, options.to ?? null, {
133
+ idempotent: !!options.idempotent,
134
+ appliedMigrations: options.from === undefined ? applied : null,
135
+ });
136
+ }
137
+
138
+ /**
139
+ * Does the model have changes no migration captures yet?
140
+ * (EF: Database.HasPendingModelChanges)
141
+ */
142
+ async hasPendingModelChanges(options = {}) {
143
+ const migrator = await this._buildMigrator(options);
144
+ return migrator.hasPendingModelChanges();
145
+ }
146
+
147
+ /** Build a Migrator, discovering the snapshot and migration files when not given. */
148
+ async _buildMigrator(options = {}) {
149
+ await this._ready();
150
+ const { default: MigrationsAssembly } = await import('./MigrationsAssembly.js');
151
+ const resolved = { ...options };
152
+
153
+ if (!resolved.snapshot) {
154
+ const fs = await import('node:fs');
155
+ const path = await import('node:path');
156
+ const { globSync } = await import('glob');
157
+ const cwd = options.migrationsPath || process.cwd();
158
+ const name = String(this.context.constructor?.name || '').toLowerCase();
159
+ const hits = globSync(`**/*${name}_contextSnapShot.json`, {
160
+ cwd, dot: true, windowsPathsNoEscape: true, nocase: true, ignore: ['**/node_modules/**'],
161
+ });
162
+ if (!hits.length) {
163
+ throw new Error(
164
+ `masterrecord: could not find '${name}_contextSnapShot.json' under '${cwd}'. `
165
+ + `Run 'masterrecord enable-migrations ${name}' first, or pass { snapshot, files } to migrate().`);
166
+ }
167
+ const snapshotFile = path.resolve(cwd, hits[0]);
168
+ resolved.snapshot = JSON.parse(fs.readFileSync(snapshotFile, 'utf8'));
169
+ if (!resolved.files) {
170
+ const dir = path.dirname(snapshotFile);
171
+ resolved.files = globSync('**/*_migration.js', { cwd: dir, dot: true, windowsPathsNoEscape: true })
172
+ .map(f => path.resolve(dir, f));
173
+ }
174
+ }
175
+
176
+ return new Migrator({
177
+ context: this.context,
178
+ contextCtor: this.context.constructor,
179
+ snapshot: resolved.snapshot,
180
+ migrationsAssembly: resolved.migrationsAssembly || new MigrationsAssembly({ files: resolved.files, migrationsPath: resolved.migrationsPath }),
181
+ historyRepository: this.historyRepository,
182
+ databaseCreator: this.databaseCreator,
183
+ logger: resolved.logger,
184
+ });
185
+ }
186
+
187
+ /** Migration ids recorded as applied, oldest first (EF: GetAppliedMigrations). */
188
+ async getAppliedMigrations() {
189
+ await this._ready();
190
+ const rows = await this.historyRepository.getAppliedMigrations();
191
+ return rows.map(r => r.migrationId);
192
+ }
193
+
194
+ /** The full history rows — id, product version and applied timestamp. */
195
+ async getAppliedMigrationRows() {
196
+ await this._ready();
197
+ return this.historyRepository.getAppliedMigrations();
198
+ }
199
+
200
+ /**
201
+ * Record a migration as applied WITHOUT running it — EF's documented way to
202
+ * bring an existing database under migration control (baselining): the
203
+ * schema is already there, so only the history row is missing.
204
+ */
205
+ async baseline(migrationId) {
206
+ await this._ready();
207
+ if (!migrationId) throw new Error('masterrecord: baseline(migrationId) requires a migration id.');
208
+ const applied = new Set(await this.getAppliedMigrations());
209
+ if (applied.has(migrationId)) return false;
210
+ await this.historyRepository.recordApplied(migrationId, PRODUCT_VERSION);
211
+ return true;
212
+ }
213
+
214
+ /** The SQL that would record `migrationId` as applied (EF: GetInsertScript). */
215
+ getBaselineScript(migrationId) {
216
+ return this.historyRepository.getInsertScript(new HistoryRow(migrationId, PRODUCT_VERSION, new Date().toISOString()));
217
+ }
218
+
219
+ async _ready() {
220
+ if (this.context && this.context._initPromise) {
221
+ try { await this.context._initPromise; } catch (_) { /* provider reports it on first use */ }
222
+ }
223
+ if (this.context && typeof this.context._ensureReady === 'function') {
224
+ await this.context._ensureReady();
225
+ }
226
+ }
227
+ }
228
+
229
+ export default DatabaseFacade;
230
+ export { DatabaseFacade, PRODUCT_VERSION };