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.
@@ -0,0 +1,278 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) —
2
+ // Migrations/HistoryRepository.cs and the provider implementations
3
+ // (SqliteHistoryRepository, SqlServerHistoryRepository, NpgsqlHistoryRepository).
4
+ // See THIRD-PARTY-NOTICES.md.
5
+
6
+ import HistoryRow from './HistoryRow.js';
7
+ import { compareMigrationIds } from './migrationId.js';
8
+
9
+ /** Quote a string as a SQL literal (EF: ITypeMappingSource.GenerateSqlLiteral for string). */
10
+ function generateSqlLiteral(value) {
11
+ return `'${String(value).replace(/'/g, "''")}'`;
12
+ }
13
+
14
+ /**
15
+ * The Migrations history table — the record of which migrations have been
16
+ * applied to a database (EF `HistoryRepository`, whose table is
17
+ * `__EFMigrationsHistory`).
18
+ *
19
+ * masterrecord's table is `_masterrecord_migrations` and has carried
20
+ * (migration_name, applied_at) since migrations tracking was introduced, so
21
+ * those are the defaults here; `product_version` (EF's ProductVersion) is added
22
+ * to the table when missing. Every name is an overridable property, exactly as
23
+ * in EF, so a provider or an app can rename them.
24
+ */
25
+ class HistoryRepository {
26
+ static DefaultTableName = '_masterrecord_migrations';
27
+
28
+ /**
29
+ * @param {{context: object, databaseCreator?: object, tableName?: string, productVersion?: string}} dependencies
30
+ */
31
+ constructor(dependencies) {
32
+ this.dependencies = dependencies;
33
+ this.tableName = dependencies.tableName || HistoryRepository.DefaultTableName;
34
+ this._productVersionColumnChecked = false;
35
+ }
36
+
37
+ get context() { return this.dependencies.context; }
38
+ get databaseCreator() { return this.dependencies.databaseCreator; }
39
+ get productVersion() { return this.dependencies.productVersion || null; }
40
+
41
+ get migrationIdColumnName() { return 'migration_name'; }
42
+ get productVersionColumnName() { return 'product_version'; }
43
+ get appliedAtColumnName() { return 'applied_at'; }
44
+
45
+ /** Quote an identifier for this provider (EF: ISqlGenerationHelper.DelimitIdentifier). */
46
+ delimitIdentifier(_name) { throw new Error('masterrecord: HistoryRepository.delimitIdentifier must be implemented by a provider.'); }
47
+
48
+ /** SQL that reports whether the history table exists (EF: ExistsSql). */
49
+ get existsSql() { throw new Error('masterrecord: HistoryRepository.existsSql must be implemented by a provider.'); }
50
+
51
+ /** Interpret the scalar returned by existsSql (EF: InterpretExistsResult). */
52
+ interpretExistsResult(value) {
53
+ if (value === null || value === undefined) return false;
54
+ const n = typeof value === 'object' ? Object.values(value)[0] : value;
55
+ return Number(n) !== 0;
56
+ }
57
+
58
+ /** DDL that creates the history table (EF: GetCreateScript). */
59
+ getCreateScript() { throw new Error('masterrecord: HistoryRepository.getCreateScript must be implemented by a provider.'); }
60
+
61
+ /** DDL that creates the history table only when it is absent (EF: GetCreateIfNotExistsScript). */
62
+ getCreateIfNotExistsScript() {
63
+ const script = this.getCreateScript();
64
+ return script.replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS');
65
+ }
66
+
67
+ /** Does the history table exist? (EF: Exists) */
68
+ async exists() {
69
+ if (this.databaseCreator && !(await this.databaseCreator.exists())) return false;
70
+ try {
71
+ return this.interpretExistsResult(await this._executeScalar(this.existsSql));
72
+ } catch (_) {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /** Create the history table (EF: Create). */
78
+ async create() {
79
+ await this.context._execute(this.getCreateScript());
80
+ await this._ensureProductVersionColumn();
81
+ }
82
+
83
+ /** Create the history table when it is absent; true when it was created (EF: CreateIfNotExists). */
84
+ async createIfNotExists() {
85
+ const existed = await this.exists();
86
+ await this.context._execute(this.getCreateIfNotExistsScript());
87
+ await this._ensureProductVersionColumn();
88
+ return !existed;
89
+ }
90
+
91
+ /**
92
+ * The migrations recorded as applied, ordered by id (EF: GetAppliedMigrations).
93
+ * Reads every column so a table written by an earlier masterrecord (which had
94
+ * no product_version) still materializes.
95
+ */
96
+ async getAppliedMigrations() {
97
+ const rows = [];
98
+ if (!(await this.exists())) return rows;
99
+ const result = await this._executeRows(this.getAppliedMigrationsSql);
100
+ for (const r of (result || [])) {
101
+ if (!r) continue;
102
+ const id = r[this.migrationIdColumnName];
103
+ if (id === undefined || id === null) continue;
104
+ rows.push(new HistoryRow(id, r[this.productVersionColumnName] ?? null, r[this.appliedAtColumnName] ?? null));
105
+ }
106
+ // The SQL ORDER BY is lexicographic; migration ids are epoch milliseconds,
107
+ // so '900_A' must still come before '1000_B'. Order them the same way
108
+ // MigrationsAssembly orders the files on disk.
109
+ rows.sort((x, y) => compareMigrationIds(x.migrationId, y.migrationId));
110
+ return rows;
111
+ }
112
+
113
+ /** SQL that reads the applied migrations (EF: GetAppliedMigrationsSql). */
114
+ get getAppliedMigrationsSql() {
115
+ return `SELECT * FROM ${this.delimitIdentifier(this.tableName)} ORDER BY ${this.delimitIdentifier(this.migrationIdColumnName)}`;
116
+ }
117
+
118
+ /** SQL that records a migration as applied (EF: GetInsertScript). */
119
+ getInsertScript(row) {
120
+ const appliedAt = row.appliedAt || new Date().toISOString();
121
+ return `INSERT INTO ${this.delimitIdentifier(this.tableName)} `
122
+ + `(${this.delimitIdentifier(this.migrationIdColumnName)}, `
123
+ + `${this.delimitIdentifier(this.productVersionColumnName)}, `
124
+ + `${this.delimitIdentifier(this.appliedAtColumnName)}) VALUES (`
125
+ + `${generateSqlLiteral(row.migrationId)}, `
126
+ + `${row.productVersion === null || row.productVersion === undefined ? 'NULL' : generateSqlLiteral(row.productVersion)}, `
127
+ + `${generateSqlLiteral(appliedAt)})`;
128
+ }
129
+
130
+ /** SQL that removes a migration's history row (EF: GetDeleteScript). */
131
+ getDeleteScript(migrationId) {
132
+ return `DELETE FROM ${this.delimitIdentifier(this.tableName)} `
133
+ + `WHERE ${this.delimitIdentifier(this.migrationIdColumnName)} = ${generateSqlLiteral(migrationId)}`;
134
+ }
135
+
136
+ /** Record a migration as applied. */
137
+ async recordApplied(migrationId, productVersion = this.productVersion) {
138
+ await this.createIfNotExists();
139
+ await this.context._execute(this.getInsertScript(new HistoryRow(migrationId, productVersion, new Date().toISOString())));
140
+ }
141
+
142
+ /** Remove a migration's history row. */
143
+ async recordReverted(migrationId) {
144
+ await this.context._execute(this.getDeleteScript(migrationId));
145
+ }
146
+
147
+ // EF's conditional-DDL hooks for idempotent scripts. Providers that cannot
148
+ // express "run this only if the migration is absent" throw, exactly as EF's
149
+ // SQLite provider does.
150
+ getBeginIfNotExistsScript(_migrationId) { throw new Error('masterrecord: idempotent migration scripts are not supported by this provider.'); }
151
+ getBeginIfExistsScript(_migrationId) { throw new Error('masterrecord: idempotent migration scripts are not supported by this provider.'); }
152
+ getEndIfScript() { throw new Error('masterrecord: idempotent migration scripts are not supported by this provider.'); }
153
+
154
+ /**
155
+ * Add `product_version` to a history table created by an older masterrecord.
156
+ * A nullable ADD COLUMN is safe on every supported engine and runs once.
157
+ */
158
+ async _ensureProductVersionColumn() {
159
+ if (this._productVersionColumnChecked) return;
160
+ this._productVersionColumnChecked = true;
161
+ const col = this.delimitIdentifier(this.productVersionColumnName);
162
+ const table = this.delimitIdentifier(this.tableName);
163
+ try {
164
+ await this._executeRows(`SELECT ${col} FROM ${table} LIMIT 1`);
165
+ } catch (_) {
166
+ try {
167
+ await this.context._execute(`ALTER TABLE ${table} ADD COLUMN ${col} ${this.productVersionColumnType}`);
168
+ } catch (_e) { /* raced with another process, or unsupported — history still works without it */ }
169
+ }
170
+ }
171
+
172
+ get productVersionColumnType() { return 'VARCHAR(32)'; }
173
+
174
+ // ---- execution helpers (masterrecord engines) --------------------------
175
+
176
+ async _executeRows(sql) {
177
+ const ctx = this.context;
178
+ const engine = ctx._SQLEngine;
179
+ if (ctx.isSQLite) return engine.db.prepare(sql).all();
180
+ if (ctx.isMySQL) return await engine._runWithParams(sql, []);
181
+ const r = await engine._runWithParams(sql, []);
182
+ return r && r.rows ? r.rows : [];
183
+ }
184
+
185
+ async _executeScalar(sql) {
186
+ const rows = await this._executeRows(sql);
187
+ if (!rows || !rows.length) return null;
188
+ const first = rows[0];
189
+ return (first && typeof first === 'object') ? Object.values(first)[0] : first;
190
+ }
191
+ }
192
+
193
+ /** EF: SqliteHistoryRepository. */
194
+ class SqliteHistoryRepository extends HistoryRepository {
195
+ delimitIdentifier(name) { return `"${String(name).replace(/"/g, '""')}"`; }
196
+
197
+ get existsSql() {
198
+ return `SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = ${generateSqlLiteral(this.tableName)} AND "type" = 'table'`;
199
+ }
200
+
201
+ get productVersionColumnType() { return 'TEXT'; }
202
+
203
+ getCreateScript() {
204
+ return `CREATE TABLE ${this.delimitIdentifier(this.tableName)} (`
205
+ + `${this.delimitIdentifier(this.migrationIdColumnName)} TEXT NOT NULL PRIMARY KEY, `
206
+ + `${this.delimitIdentifier(this.productVersionColumnName)} TEXT NULL, `
207
+ + `${this.delimitIdentifier(this.appliedAtColumnName)} TEXT NOT NULL)`;
208
+ }
209
+
210
+ // EF's SQLite provider throws for these: SQLite has no conditional DDL.
211
+ getBeginIfNotExistsScript(_migrationId) {
212
+ throw new Error('masterrecord: SQLite does not support idempotent migration scripts (no conditional DDL). Generate a plain script instead.');
213
+ }
214
+ getBeginIfExistsScript(_migrationId) { return this.getBeginIfNotExistsScript(_migrationId); }
215
+ getEndIfScript() { return this.getBeginIfNotExistsScript(''); }
216
+ }
217
+
218
+ /** EF: SqlServerHistoryRepository, adapted to MySQL. */
219
+ class MySqlHistoryRepository extends HistoryRepository {
220
+ delimitIdentifier(name) { return `\`${String(name).replace(/`/g, '``')}\``; }
221
+
222
+ get existsSql() {
223
+ return `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${generateSqlLiteral(this.tableName)}`;
224
+ }
225
+
226
+ getCreateScript() {
227
+ return `CREATE TABLE ${this.delimitIdentifier(this.tableName)} (`
228
+ + `${this.delimitIdentifier(this.migrationIdColumnName)} VARCHAR(150) NOT NULL PRIMARY KEY, `
229
+ + `${this.delimitIdentifier(this.productVersionColumnName)} VARCHAR(32) NULL, `
230
+ + `${this.delimitIdentifier(this.appliedAtColumnName)} VARCHAR(64) NOT NULL)`;
231
+ }
232
+ }
233
+
234
+ /** EF: NpgsqlHistoryRepository. */
235
+ class PostgresHistoryRepository extends HistoryRepository {
236
+ delimitIdentifier(name) { return `"${String(name).replace(/"/g, '""')}"`; }
237
+
238
+ get existsSql() {
239
+ return `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ${generateSqlLiteral(this.tableName)}`;
240
+ }
241
+
242
+ getCreateScript() {
243
+ return `CREATE TABLE ${this.delimitIdentifier(this.tableName)} (`
244
+ + `${this.delimitIdentifier(this.migrationIdColumnName)} VARCHAR(150) NOT NULL PRIMARY KEY, `
245
+ + `${this.delimitIdentifier(this.productVersionColumnName)} VARCHAR(32) NULL, `
246
+ + `${this.delimitIdentifier(this.appliedAtColumnName)} VARCHAR(64) NOT NULL)`;
247
+ }
248
+
249
+ // Postgres can express conditional DDL with an anonymous DO block.
250
+ getBeginIfNotExistsScript(migrationId) {
251
+ return `DO $MR$\nBEGIN\n IF NOT EXISTS(SELECT 1 FROM ${this.delimitIdentifier(this.tableName)} `
252
+ + `WHERE ${this.delimitIdentifier(this.migrationIdColumnName)} = ${generateSqlLiteral(migrationId)}) THEN`;
253
+ }
254
+ getBeginIfExistsScript(migrationId) {
255
+ return `DO $MR$\nBEGIN\n IF EXISTS(SELECT 1 FROM ${this.delimitIdentifier(this.tableName)} `
256
+ + `WHERE ${this.delimitIdentifier(this.migrationIdColumnName)} = ${generateSqlLiteral(migrationId)}) THEN`;
257
+ }
258
+ getEndIfScript() { return ` END IF;\nEND $MR$;\n`; }
259
+ }
260
+
261
+ /** Resolve the history repository for a context's provider. */
262
+ function createHistoryRepository(context, options = {}) {
263
+ const dependencies = { context, ...options };
264
+ if (context.isSQLite) return new SqliteHistoryRepository(dependencies);
265
+ if (context.isMySQL) return new MySqlHistoryRepository(dependencies);
266
+ if (context.isPostgres) return new PostgresHistoryRepository(dependencies);
267
+ throw new Error('masterrecord: no history repository for this provider (expected sqlite, mysql or postgres).');
268
+ }
269
+
270
+ export default HistoryRepository;
271
+ export {
272
+ HistoryRepository,
273
+ SqliteHistoryRepository,
274
+ MySqlHistoryRepository,
275
+ PostgresHistoryRepository,
276
+ createHistoryRepository,
277
+ generateSqlLiteral,
278
+ };
@@ -0,0 +1,26 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) — Migrations/HistoryRow.cs.
2
+ // See THIRD-PARTY-NOTICES.md.
3
+
4
+ /**
5
+ * An entity type that represents a row in the Migrations history table.
6
+ *
7
+ * EF stores (MigrationId, ProductVersion). masterrecord's history table has
8
+ * carried (migration_name, applied_at) since the tracking table was introduced,
9
+ * so a row also exposes `appliedAt`; `productVersion` is null for rows written
10
+ * by versions that predate it.
11
+ */
12
+ class HistoryRow {
13
+ /**
14
+ * @param {string} migrationId - The migration identifier.
15
+ * @param {string|null} [productVersion] - The masterrecord version that applied it.
16
+ * @param {string|null} [appliedAt] - ISO timestamp the migration was applied.
17
+ */
18
+ constructor(migrationId, productVersion = null, appliedAt = null) {
19
+ this.migrationId = migrationId;
20
+ this.productVersion = productVersion;
21
+ this.appliedAt = appliedAt;
22
+ }
23
+ }
24
+
25
+ export default HistoryRow;
26
+ export { HistoryRow };
@@ -0,0 +1,83 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) —
2
+ // Migrations/IMigrationsAssembly.cs and MigrationsAssemblyExtensions.cs.
3
+ // See THIRD-PARTY-NOTICES.md.
4
+
5
+ import path from 'node:path';
6
+ import { globSync } from 'glob';
7
+ import { INITIAL_DATABASE, timestampOf, compareMigrationIds } from './migrationId.js';
8
+
9
+ /**
10
+ * The set of migrations available to a context (EF `IMigrationsAssembly`).
11
+ *
12
+ * EF discovers migration classes in a compiled assembly and keys them by
13
+ * MigrationId; masterrecord's migrations are `<timestamp>_<Name>_migration.js`
14
+ * files on disk, and the history table records the FILE NAME, so that is the id.
15
+ */
16
+ class MigrationsAssembly {
17
+ /**
18
+ * @param {{migrationsPath?: string, files?: string[]}} [options]
19
+ * `files` lets a caller supply the list directly (used by tests and by the
20
+ * CLI, which has already resolved the migrations directory from the snapshot).
21
+ */
22
+ constructor(options = {}) {
23
+ this.options = options;
24
+ this._migrations = null;
25
+ }
26
+
27
+ static timestampOf(id) { return timestampOf(id); }
28
+ static compareIds(a, b) { return compareMigrationIds(a, b); }
29
+
30
+ /** Every migration id, oldest first (EF: IMigrationsAssembly.Migrations.Keys). */
31
+ get migrations() {
32
+ if (this._migrations) return this._migrations;
33
+ let files = this.options.files;
34
+ if (!files) {
35
+ const cwd = this.options.migrationsPath || process.cwd();
36
+ files = globSync('**/*_migration.js', {
37
+ cwd, dot: true, windowsPathsNoEscape: true, ignore: ['**/node_modules/**'],
38
+ }).map(f => path.resolve(cwd, f));
39
+ }
40
+ const byId = new Map();
41
+ for (const file of files) {
42
+ byId.set(path.basename(file), file);
43
+ }
44
+ this._migrations = new Map(
45
+ [...byId.entries()].sort((a, b) => MigrationsAssembly.compareIds(a[0], b[0])));
46
+ return this._migrations;
47
+ }
48
+
49
+ /** Ids only, oldest first. */
50
+ get migrationIds() { return [...this.migrations.keys()]; }
51
+
52
+ /**
53
+ * Resolve a full migration id from a full id, a file name, or the bare
54
+ * migration name (EF: MigrationsAssemblyExtensions.GetMigrationId).
55
+ */
56
+ getMigrationId(nameOrId) {
57
+ if (!nameOrId) throw new Error('masterrecord: a migration name is required.');
58
+ const wanted = String(nameOrId);
59
+ if (wanted === INITIAL_DATABASE) return wanted;
60
+
61
+ const ids = this.migrationIds;
62
+ const exact = ids.find(id => id.toLowerCase() === wanted.toLowerCase());
63
+ if (exact) return exact;
64
+
65
+ // `1700000000000_AddPosts_migration.js` also answers to `AddPosts`.
66
+ const nameOf = (id) => {
67
+ const m = /^\d+_(.+?)_migration\.js$/.exec(id);
68
+ return m ? m[1] : id.replace(/\.js$/, '');
69
+ };
70
+ const byName = ids.filter(id => nameOf(id).toLowerCase() === wanted.toLowerCase());
71
+ if (byName.length === 1) return byName[0];
72
+ if (byName.length > 1) {
73
+ throw new Error(`masterrecord: '${wanted}' matches more than one migration (${byName.join(', ')}). Use the full migration id.`);
74
+ }
75
+ throw new Error(`masterrecord: no migration named '${wanted}' was found. Known migrations: ${ids.length ? ids.join(', ') : '(none)'}`);
76
+ }
77
+
78
+ /** The file backing a migration id. */
79
+ getMigrationFile(id) { return this.migrations.get(id) || null; }
80
+ }
81
+
82
+ export default MigrationsAssembly;
83
+ export { MigrationsAssembly };