masterrecord 1.23.0 → 1.28.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,194 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.28.0 — `ensureCreated()` actually works on MySQL/Postgres (found by live testing)
4
+
5
+ The first live run of the cross-engine suite, against a real PostgreSQL 16.15 server,
6
+ found that **`ensureCreated()` could never work on MySQL or Postgres when the database did
7
+ not exist** — which is the one case it exists for. The context cannot connect without an
8
+ existing database, so it threw during initialization long before `ensureCreated()` ran. It
9
+ only appeared to work on SQLite, where opening the file creates it.
10
+
11
+ - **Fix:** `exists()` and `create()` now run over an **admin connection** (the `postgres`
12
+ maintenance database; MySQL with no database selected) instead of the context's own
13
+ engine, so they work when the target database is absent — the approach EF's providers
14
+ take. After creating it the context's pool is reopened and the context marked ready, so
15
+ its stale rejected init promise is not re-awaited.
16
+ - **Fix:** `context.database` no longer fails outright when the database is missing; that
17
+ is the state `ensureCreated()` is for. Any other connection error still propagates.
18
+ - Verified end to end on live PostgreSQL 16.15: `CREATE DATABASE` -> `EnsureCreated`
19
+ (schema) -> insert/read -> history + `ProductVersion` -> `baseline()` -> `EnsureDeleted`
20
+ (`pg_terminate_backend` + drop from the maintenance database), with no scratch databases
21
+ or stray tables left behind.
22
+ - The cross-engine suite is safe against a shared server by default — it only creates and
23
+ drops its own `MrEfProbe*` tables. The create/drop-database lifecycle is opt-in with
24
+ `MR_TEST_ALLOW_CREATE_DB=1`.
25
+
26
+ ## v1.27.0 — `Migrator.GenerateScript` and `HasPendingModelChanges`: EF's `IMigrator` is now complete
27
+
28
+ 1.26.0 moved applying into `Migrator`; this finishes the interface. EF's `IMigrator` is
29
+ `Migrate` / `GenerateScript` / `HasPendingModelChanges`, and every masterrecord CLI command
30
+ is now a shell over it — there is no second implementation of anything left.
31
+
32
+ - **`Migrator.generateScript(from, to, { idempotent, appliedMigrations })`** (EF:
33
+ `GenerateScript`). `from` omitted or `'0'` scripts from an empty database and emits the
34
+ history-table bootstrap first, exactly as EF does; `appliedMigrations` scripts against
35
+ what a live database has actually applied, which is what `masterrecord script` passes.
36
+ `--idempotent` wraps each migration in a "only if not already applied" guard (Postgres
37
+ `DO $MR$ … IF NOT EXISTS …`); SQLite and MySQL refuse it, as EF's SQLite provider does.
38
+ - **`Migrator.hasPendingModelChanges()`** and `context.database.hasPendingModelChanges()`
39
+ (EF: `HasPendingModelChanges`) — true when entities have changed since the last migration.
40
+ - **`context.database.generateMigrationScript()`** for the same thing from an app.
41
+ - **`masterrecord script` delegates to it** and gained `--idempotent`.
42
+ - **Fix:** the generated script recorded each migration with a *parameterized* insert
43
+ (`VALUES (?, ?)` plus a `-- params:` comment), which is not runnable SQL — the point of
44
+ the command is to hand a DBA something they can execute. It now emits literal values via
45
+ `HistoryRepository.getInsertScript`.
46
+ - **`migrations-status` and `remove-migration`** read history through `HistoryRepository`
47
+ instead of their own SQL. The last of the duplicated migration helpers
48
+ (`__getAppliedMigrations`, `__recordMigrationApplied`, `__getAppliedMigrationRows`,
49
+ and the `_masterrecord_migrations` string constant) are deleted — **139 lines of
50
+ duplication removed across 1.26.0 and 1.27.0**.
51
+
52
+ New tests: `generateScript` (runnable output, applies nothing, pending-only, SQLite refusing
53
+ idempotent) and `hasPendingModelChanges` in `test/ef-migrator-apply.test.js`.
54
+
55
+ ## v1.26.0 — one migration code path: `Migrator.Migrate` (EF), and the CLI is a thin shell over it
56
+
57
+ EF's `IMigrator` is `Migrate` / `GenerateScript` / `HasPendingModelChanges` — applying
58
+ migrations *is* the Migrator, and `dotnet ef database update` is a thin shell over it.
59
+ masterrecord had the apply logic living inside the `update-database` CLI command instead,
60
+ with `update-database-all`, `update-database-down` and `remove-migration` each carrying
61
+ their own copy. That is now one path.
62
+
63
+ - **`Migrator.migrate(target)`** applies and reverts: no target applies everything pending,
64
+ a migration id migrates up or down to it, and `'0'` (EF's `Migration.InitialDatabase`)
65
+ reverts everything, newest first. Each migration is applied **atomically with its history
66
+ row** and recorded as it goes, so an interrupted run resumes where it stopped.
67
+ - **`context.database.migrate()`** — EF's `context.Database.Migrate()`, callable from an app
68
+ at startup, not just from the CLI. It discovers the snapshot and migration files, or takes
69
+ them explicitly.
70
+ - **`update-database`, `update-database-all`, `update-database-down` and `remove-migration`
71
+ now all delegate to `Migrator`**, and 71 lines of duplicated apply logic were deleted
72
+ (`__applyMigrationStep`, `__ensureMigrationsTable`, `__removeMigrationApplied`).
73
+ - **Fix:** `update-database-down` ran `down()` **outside any transaction** — a failed
74
+ rollback could leave a half-reverted schema with the history row still present. Rolling
75
+ back now uses the same per-migration transaction as applying.
76
+ - **Fix:** every migration opens its own context (its schema constructor builds one); it is
77
+ now released after the migration runs. Only `update-database-all` did this before, so
78
+ single-context runs leaked a connection per migration.
79
+
80
+ New tests: `test/ef-migrator-apply.test.js` (apply-all and idempotency, targeted up/down,
81
+ revert-to-`'0'`, and `context.database.migrate()`).
82
+
83
+ ## v1.25.0 — EF's Migrator planning: getMigrations / getPendingMigrations
84
+
85
+ Completes the read half of EF's `DbContext.Database` surface. Ported from Entity
86
+ Framework Core (see `THIRD-PARTY-NOTICES.md`).
87
+
88
+ - **`Migrator`** (`Migrations/Migrator.js`) — EF's `PopulateMigrations` planning, faithfully:
89
+ no target applies every unapplied migration; the `'0'` target (EF's
90
+ `Migration.InitialDatabase`) reverts every applied one, newest first; a target id applies
91
+ unapplied migrations up to and including it and reverts applied ones after it. Applied-id
92
+ matching is case-insensitive, as in EF. `plan(target)` reads the live history table.
93
+ - **`MigrationsAssembly`** (`Migrations/MigrationsAssembly.js`) — EF's `IMigrationsAssembly`
94
+ over `<timestamp>_<Name>_migration.js` files, with `getMigrationId()` resolving a full id,
95
+ a file name or the bare migration name (and reporting ambiguity).
96
+ - **`context.database.getMigrations()` / `.getPendingMigrations()`** (EF: `GetMigrations` /
97
+ `GetPendingMigrations`). A non-empty pending list means the schema is behind the code —
98
+ a useful startup or health check.
99
+ - **Fix (ordering):** `getAppliedMigrations()` returned rows in the history table's
100
+ lexicographic `ORDER BY`, so `1000_Beta` sorted before `900_Alpha`. Migration ids are
101
+ epoch milliseconds and only the same width by coincidence, so ids are now ordered
102
+ chronologically by a comparator (`Migrations/migrationId.js`) shared with
103
+ `MigrationsAssembly` — the files on disk and the rows in the table can no longer disagree
104
+ about what the next migration is.
105
+
106
+ Applying migrations remains the `masterrecord update-database` CLI's job; this release is
107
+ the planner it and your app can both ask. New tests: `test/ef-migrator-planning.test.js`.
108
+
109
+ ## v1.24.2 — reserved-word entity names work end to end on SQLite
110
+
111
+ - **Fix (SQLite):** `buildFrom` emitted `FROM Order AS ran` unquoted, so every query
112
+ against an entity named with a SQL reserved word (`Order`, `Group`, `Transaction`,
113
+ `Index`…) failed with `near "Order": syntax error`. It is now bracket-quoted like every
114
+ other table reference in that engine. Together with the DDL quoting in 1.24.0, a
115
+ reserved-word entity now creates, inserts, queries, filters, counts, updates and deletes
116
+ normally. MySQL (backticks) and Postgres (`_q()`) already quoted correctly — this was
117
+ SQLite-only. New test: `test/reserved-word-entity.test.js`.
118
+ - **Fix (tooling):** `mySQLEngine.js` contained a literal NUL byte — a deliberate delimiter
119
+ in a composite cache key, but written as a raw byte rather than the `\u0000` escape. That
120
+ made the file count as binary, so `grep` skipped it **silently**: no search of the
121
+ repository ever matched anything in the MySQL engine. Same runtime value, now written as
122
+ an escape; the file is UTF-8 text again and searchable.
123
+
124
+ ## v1.24.1 — MySQL/Postgres coverage for the EF port, and a Postgres `ensureDeleted` fix
125
+
126
+ 1.24.0's MySQL and Postgres providers shipped without ever being executed — masterrecord
127
+ has no live cross-engine suite (`docker-compose.test.yml` advertises `MR_TEST_MYSQL_URL` /
128
+ `MR_TEST_PG_URL`, but nothing read them). Reviewing and testing those paths found a real bug:
129
+
130
+ - **Fix (Postgres):** `ensureDeleted()` issued `DROP DATABASE` on the context's own
131
+ connection, which Postgres always rejects — *"cannot drop the currently open database"*.
132
+ It now closes the context's pool, connects to the `postgres` maintenance database,
133
+ terminates any other backend attached to the target, and drops from there — the shape
134
+ EF's Npgsql provider uses and the one masterrecord's own
135
+ `_createPostgresDatabaseFromConfig()` already used for CREATE.
136
+ - **Fix (MySQL):** `ensureDeleted()` likewise drops through an admin connection with no
137
+ database selected, after closing the context pool. Dropping the schema a live pool points
138
+ at left every pooled connection referring to a database that no longer existed.
139
+ - **Hardening:** a database name that is not a plain identifier is now refused rather than
140
+ interpolated into `DROP DATABASE` (the same rule the schema layer already applied to CREATE).
141
+ - **Tests:** `test/ef-provider-sql.test.js` drives the HistoryRepository and
142
+ RelationalDatabaseCreator SQL for **all three engines** with a context that captures
143
+ statements instead of running them — no database required, so MySQL/Postgres SQL
144
+ generation is covered on every `npm test`. `test/ef-cross-engine.integration.test.js`
145
+ adds real end-to-end coverage (EnsureCreated → query → history → baseline → EnsureDeleted
146
+ against a scratch database), skipped unless `MR_TEST_MYSQL_URL` / `MR_TEST_PG_URL` are set.
147
+
148
+ ## v1.24.0 — EF Core's database-creation and migrations-history object model
149
+
150
+ Ported from Entity Framework Core (dotnet/efcore, MIT — see `THIRD-PARTY-NOTICES.md`),
151
+ preserving EF's class structure, method names and algorithms.
152
+
153
+ - **`context.database`** — EF's `DbContext.Database` facade: `ensureCreated()`,
154
+ `ensureDeleted()`, `canConnect()`, `hasTables()`, `generateCreateScript()`,
155
+ `getAppliedMigrations()`, `getAppliedMigrationRows()`, `baseline()`.
156
+ - **`RelationalDatabaseCreator`** (`Migrations/RelationalDatabaseCreator.js`) with SQLite,
157
+ MySQL and Postgres implementations: `exists`, `create`, `delete`, `hasTables`,
158
+ `createTables`, `ensureCreated`, `ensureDeleted`, `generateCreateScript`, `canConnect`.
159
+ **`ensureCreated()` is all-or-nothing, exactly as in EF**: it creates the database and the
160
+ model's tables only when the database has *no tables at all*, and never alters an existing
161
+ table. It does not use migrations — use it for tests, prototypes and cold starts, and
162
+ migrations for a schema that has to evolve.
163
+ - **`HistoryRepository`** (`Migrations/HistoryRepository.js`) — the migrations history table
164
+ as a first-class, overridable abstraction (EF's `__EFMigrationsHistory`): `exists`,
165
+ `create`, `createIfNotExists`, `getAppliedMigrations`, `getInsertScript`,
166
+ `getDeleteScript`, `recordApplied`, `recordReverted`, and EF's
167
+ `getBeginIfNotExistsScript`/`getEndIfScript` idempotency hooks (implemented for Postgres;
168
+ SQLite refuses them, as EF's SQLite provider does). masterrecord's existing
169
+ `_masterrecord_migrations` table and its column names remain the defaults, so nothing
170
+ changes for existing databases; EF's `ProductVersion` is added as a nullable
171
+ `product_version` column the first time history is written.
172
+ - **`HistoryRow`** (`Migrations/HistoryRow.js`) — EF's history row, plus `appliedAt`.
173
+ - **Baselining** — `ctx.database.baseline(migrationId)` and `masterrecord baseline <context>
174
+ [migration] [--all]` record a migration as applied **without running it**: EF's documented
175
+ way to bring a database that already has the schema under migration control.
176
+ - **CLI**: `masterrecord ensure-created <context>` (EF `EnsureCreated`),
177
+ `masterrecord ensure-deleted <context> --force` (EF `EnsureDeleted`; refuses without
178
+ `--force`), `masterrecord baseline`. `ensure-created` works on a project with no
179
+ migrations yet, so a cold start no longer needs a hand-written bootstrap script.
180
+ - **Subpath exports opened** for `Migrations/HistoryRow`, `Migrations/HistoryRepository`,
181
+ `Migrations/RelationalDatabaseCreator`, `Migrations/DatabaseFacade` and
182
+ `Migrations/contextInit` — the last of which previously forced callers to bypass the
183
+ package's `exports` map to reach `instantiateReadyContext`.
184
+ - **Fix (SQLite DDL):** `createTable`/`dropTable`/`renameTable` now quote the table name,
185
+ as the MySQL and Postgres builders already did. An entity named with a reserved word
186
+ (`Order`, `Group`, `Transaction`…) previously failed to create with
187
+ `near "Order": syntax error`. Note that **queries** against such a table still fail —
188
+ the query builder does not yet quote table names.
189
+
190
+ New tests: `test/ef-database-creator.test.js`.
191
+
3
192
  ## v1.23.0 — entity property reads ~16x faster (shared prototype per entity type)
4
193
 
5
194
  - **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.
@@ -5,9 +5,6 @@ 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;
@@ -0,0 +1,242 @@
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
+ /**
220
+ * Wait for the context's connection, but do NOT fail when the database simply
221
+ * does not exist yet — that is precisely the state `ensureCreated()` exists to
222
+ * fix, and on MySQL/Postgres the context cannot connect until the database is
223
+ * there. Existence checks and creation run over an admin connection instead.
224
+ */
225
+ async _ready() {
226
+ if (this.context && this.context._initPromise) {
227
+ try { await this.context._initPromise; } catch (_) { /* reported by the first real query */ }
228
+ }
229
+ if (this.context && typeof this.context._ensureReady === 'function') {
230
+ try {
231
+ await this.context._ensureReady();
232
+ } catch (err) {
233
+ const msg = String((err && err.message) || '');
234
+ const missing = /does not exist|Unknown database/i.test(msg);
235
+ if (!missing) throw err;
236
+ }
237
+ }
238
+ }
239
+ }
240
+
241
+ export default DatabaseFacade;
242
+ export { DatabaseFacade, PRODUCT_VERSION };