masterrecord 1.23.0 → 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 +166 -0
- package/Entity/entityTrackerModel.js +0 -3
- package/Migrations/DatabaseFacade.js +230 -0
- package/Migrations/HistoryRepository.js +278 -0
- package/Migrations/HistoryRow.js +26 -0
- package/Migrations/MigrationsAssembly.js +83 -0
- package/Migrations/Migrator.js +361 -0
- package/Migrations/RelationalDatabaseCreator.js +363 -0
- package/Migrations/cli.js +245 -263
- package/Migrations/migrationId.js +32 -0
- package/Migrations/migrationSQLiteQuery.js +3 -3
- package/SQLLiteEngine.js +4 -1
- package/context.js +11 -0
- package/mySQLEngine.js +1 -1
- package/package.json +12 -3
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,171 @@
|
|
|
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
|
+
|
|
3
169
|
## v1.23.0 — entity property reads ~16x faster (shared prototype per entity type)
|
|
4
170
|
|
|
5
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.
|
|
@@ -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,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 };
|