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,394 @@
1
+ // Ported from Entity Framework Core (dotnet/efcore, MIT) —
2
+ // Storage/RelationalDatabaseCreator.cs and the provider implementations
3
+ // (SqliteDatabaseCreator, SqlServerDatabaseCreator, NpgsqlDatabaseCreator).
4
+ // See THIRD-PARTY-NOTICES.md.
5
+
6
+ import fs from 'node:fs';
7
+
8
+ // The schema layer imports context.js, so importing it here at module scope would
9
+ // close a cycle (context -> DatabaseFacade -> creator -> schema -> context) and
10
+ // leave context.js half-initialized. It is loaded on demand instead, which also
11
+ // keeps the migrations stack (pg, mysql2) out of the runtime graph until used.
12
+ /** Database names are interpolated into DDL that cannot be parameterized. */
13
+ function assertDatabaseName(name) {
14
+ if (!name || !/^[a-zA-Z0-9_-]+$/.test(name)) {
15
+ throw new Error(`masterrecord: refusing to operate on an invalid database name '${name}'.`);
16
+ }
17
+ return name;
18
+ }
19
+
20
+ let _schemaCtor = null;
21
+ let _queryBuilders = null;
22
+
23
+ async function loadSchema() {
24
+ if (!_schemaCtor) { _schemaCtor = (await import('./schema.js')).default; }
25
+ return _schemaCtor;
26
+ }
27
+
28
+ async function loadQueryBuilders() {
29
+ if (!_queryBuilders) {
30
+ const [sqlite, mysql, postgres] = await Promise.all([
31
+ import('./migrationSQLiteQuery.js'),
32
+ import('./migrationMySQLQuery.js'),
33
+ import('./migrationPostgresQuery.js'),
34
+ ]);
35
+ _queryBuilders = { sqlite: sqlite.default, mysql: mysql.default, postgres: postgres.default };
36
+ }
37
+ return _queryBuilders;
38
+ }
39
+
40
+ /**
41
+ * Creates and drops databases and their schema (EF `RelationalDatabaseCreator`).
42
+ *
43
+ * `ensureCreated()` is the cold-start primitive: it creates the database and,
44
+ * when the database has NO tables at all, every table in the model. It does not
45
+ * use migrations, and — exactly as in EF — a database created this way is not
46
+ * expected to be updated by migrations afterwards. It never alters an existing
47
+ * table: if the database already has any table, it does nothing.
48
+ */
49
+ class RelationalDatabaseCreator {
50
+ /**
51
+ * @param {{context: object}} dependencies
52
+ */
53
+ constructor(dependencies) {
54
+ this.dependencies = dependencies;
55
+ }
56
+
57
+ get context() { return this.dependencies.context; }
58
+
59
+ /** A schema layer bound to the EXISTING context (no second connection). */
60
+ async getSchema() {
61
+ if (!this._schema) {
62
+ const schema = await loadSchema();
63
+ const s = Object.create(schema.prototype);
64
+ s.context = this.context;
65
+ s._dbEnsured = false;
66
+ s._ready = true;
67
+ this._schema = s;
68
+ }
69
+ return this._schema;
70
+ }
71
+
72
+ /** The entity definitions that map to tables (TPH derived types share a table). */
73
+ get model() {
74
+ return (this.context.__entities || []).filter(e => e && e.__name);
75
+ }
76
+
77
+ /** Does the database exist? (EF: Exists) */
78
+ async exists() { throw new Error('masterrecord: RelationalDatabaseCreator.exists must be implemented by a provider.'); }
79
+
80
+ /** Create the database, without any tables (EF: Create). */
81
+ async create() { throw new Error('masterrecord: RelationalDatabaseCreator.create must be implemented by a provider.'); }
82
+
83
+ /** Drop the database (EF: Delete). */
84
+ async delete() { throw new Error('masterrecord: RelationalDatabaseCreator.delete must be implemented by a provider.'); }
85
+
86
+ /** Does the database contain ANY tables? (EF: HasTables) */
87
+ async hasTables() { throw new Error('masterrecord: RelationalDatabaseCreator.hasTables must be implemented by a provider.'); }
88
+
89
+ /**
90
+ * Create every table in the model (EF: CreateTables — the model diffed
91
+ * against an empty database).
92
+ */
93
+ async createTables() {
94
+ const schema = await this.getSchema();
95
+ const created = [];
96
+ for (const entity of this.model) {
97
+ await schema.createTable(entity);
98
+ created.push(entity.__name);
99
+ }
100
+ if (typeof schema.finalize === 'function') {
101
+ await schema.finalize();
102
+ }
103
+ return created;
104
+ }
105
+
106
+ /**
107
+ * Ensure the database exists and, when it has no tables, that the model's
108
+ * tables exist. Returns true when anything was created (EF: EnsureCreated).
109
+ */
110
+ async ensureCreated() {
111
+ let operationsPerformed = false;
112
+ if (!(await this.exists())) {
113
+ await this.create();
114
+ await this.createTables();
115
+ operationsPerformed = true;
116
+ } else if (!(await this.hasTables())) {
117
+ await this.createTables();
118
+ operationsPerformed = true;
119
+ }
120
+ return operationsPerformed;
121
+ }
122
+
123
+ /** Drop the database when it exists; true when it was dropped (EF: EnsureDeleted). */
124
+ async ensureDeleted() {
125
+ if (await this.exists()) {
126
+ await this.delete();
127
+ return true;
128
+ }
129
+ return false;
130
+ }
131
+
132
+ /** The DDL that ensureCreated would run, as a script (EF: GenerateCreateScript). */
133
+ async generateCreateScript() {
134
+ const builder = await this._queryBuilder();
135
+ const schema = await this.getSchema();
136
+ const statements = [];
137
+ for (const entity of this.model) {
138
+ if (typeof schema._foreignKeysFor === 'function') {
139
+ try {
140
+ Object.defineProperty(entity, '__foreignKeys', {
141
+ value: schema._foreignKeysFor(entity),
142
+ enumerable: false, writable: true, configurable: true,
143
+ });
144
+ } catch (_) { /* definition already carries them */ }
145
+ }
146
+ statements.push(builder.createTable(entity));
147
+ }
148
+ return statements.join('\n') + (statements.length ? '\n' : '');
149
+ }
150
+
151
+ /** True when the database is reachable (EF: CanConnect). */
152
+ async canConnect() {
153
+ try {
154
+ return await this.exists();
155
+ } catch (_) {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ async _queryBuilder() {
161
+ const b = await loadQueryBuilders();
162
+ if (this.context.isSQLite) return new b.sqlite();
163
+ if (this.context.isMySQL) return new b.mysql();
164
+ return new b.postgres();
165
+ }
166
+
167
+ async _executeRows(sql) {
168
+ const ctx = this.context;
169
+ const engine = ctx._SQLEngine;
170
+ if (ctx.isSQLite) return engine.db.prepare(sql).all();
171
+ if (ctx.isMySQL) return await engine._runWithParams(sql, []);
172
+ const r = await engine._runWithParams(sql, []);
173
+ return r && r.rows ? r.rows : [];
174
+ }
175
+
176
+ async _executeScalar(sql) {
177
+ const rows = await this._executeRows(sql);
178
+ if (!rows || !rows.length) return null;
179
+ const first = rows[0];
180
+ return (first && typeof first === 'object') ? Object.values(first)[0] : first;
181
+ }
182
+ }
183
+
184
+ /** EF: SqliteDatabaseCreator. */
185
+ class SqliteDatabaseCreator extends RelationalDatabaseCreator {
186
+ /**
187
+ * The database file, or null for an in-memory database. Resolved once and
188
+ * remembered: delete() closes the connection, after which the engine can no
189
+ * longer report its path, and exists() must still answer about the same file.
190
+ */
191
+ get dataSource() {
192
+ if (this._dataSource !== undefined) return this._dataSource;
193
+ const engine = this.context._SQLEngine;
194
+ const name = engine && engine.db && engine.db.name ? engine.db.name : null;
195
+ const conn = this.context._dbConfig && this.context._dbConfig.connection;
196
+ this._dataSource = name || (typeof conn === 'string' ? conn : null);
197
+ return this._dataSource;
198
+ }
199
+
200
+ /** Only an explicit in-memory database — an unknown path is NOT "in memory". */
201
+ get isMemory() {
202
+ const src = this.dataSource;
203
+ return src === ':memory:' || (typeof src === 'string' && src.includes('mode=memory'));
204
+ }
205
+
206
+ async exists() {
207
+ if (this.isMemory) return true;
208
+ const src = this.dataSource;
209
+ return src ? fs.existsSync(src) : false;
210
+ }
211
+
212
+ async create() {
213
+ // Opening the connection creates the file; masterrecord opens it when the
214
+ // context is constructed, so there is nothing further to do.
215
+ return undefined;
216
+ }
217
+
218
+ async hasTables() {
219
+ const count = await this._executeScalar(
220
+ `SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL`);
221
+ return Number(count) !== 0;
222
+ }
223
+
224
+ async delete() {
225
+ const path = this.dataSource;
226
+ if (this.isMemory || !path) return;
227
+ try { await this.context.close(); } catch (_) { /* already closed */ }
228
+ if (fs.existsSync(path)) fs.rmSync(path);
229
+ for (const suffix of ['-wal', '-shm']) {
230
+ if (fs.existsSync(path + suffix)) fs.rmSync(path + suffix);
231
+ }
232
+ }
233
+ }
234
+
235
+ /** EF: SqlServerDatabaseCreator, adapted to MySQL. */
236
+ class MySqlDatabaseCreator extends RelationalDatabaseCreator {
237
+ get databaseName() {
238
+ return this.context._dbConfig && this.context._dbConfig.database;
239
+ }
240
+
241
+ async exists() {
242
+ const rows = await this._adminQuery(
243
+ `SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${assertDatabaseName(this.databaseName)}'`);
244
+ return !!(rows && rows.length);
245
+ }
246
+
247
+ async create() {
248
+ const schema = await this.getSchema();
249
+ await schema._createDatabaseFromConfig();
250
+ await this._reconnect();
251
+ }
252
+
253
+ /**
254
+ * Re-open the context's pool now that the database exists, and mark the context
255
+ * ready — its original _initPromise rejected (the database was missing) and
256
+ * _ensureReady() would otherwise keep re-awaiting that stale rejection.
257
+ */
258
+ async _reconnect() {
259
+ const schema = await this.getSchema();
260
+ if (typeof schema._retryMySQLInit === 'function') {
261
+ await schema._retryMySQLInit();
262
+ this.context._ready = true;
263
+ }
264
+ }
265
+
266
+ async hasTables() {
267
+ const count = await this._executeScalar(
268
+ `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()`);
269
+ return Number(count) !== 0;
270
+ }
271
+
272
+ /**
273
+ * Drop through an ADMIN connection with no database selected, after closing the
274
+ * context's own pool — dropping the schema a live pool is pointed at leaves every
275
+ * pooled connection referring to a database that no longer exists.
276
+ */
277
+ async delete() {
278
+ const dbName = assertDatabaseName(this.databaseName);
279
+ try { await this.context.close(); } catch (_) { /* already closed */ }
280
+ await this._adminQuery(`DROP DATABASE IF EXISTS \`${dbName}\``);
281
+ }
282
+
283
+ /** Run a statement on a connection that has no database selected; returns rows. */
284
+ async _adminQuery(sql) {
285
+ const config = this.context._dbConfig || {};
286
+ const { default: MySQLAsyncClient } = await import('../mySQLConnect.js');
287
+ const adminConfig = { ...config };
288
+ delete adminConfig.database;
289
+ delete adminConfig.type;
290
+ const admin = new MySQLAsyncClient(adminConfig);
291
+ await admin.connect();
292
+ try {
293
+ const pool = admin.getPool();
294
+ if (!pool) return [];
295
+ const [rows] = await pool.query(sql);
296
+ return Array.isArray(rows) ? rows : [];
297
+ } finally {
298
+ await admin.close();
299
+ }
300
+ }
301
+ }
302
+
303
+ /** EF: NpgsqlDatabaseCreator. */
304
+ class PostgresDatabaseCreator extends RelationalDatabaseCreator {
305
+ get databaseName() {
306
+ return this.context._dbConfig && this.context._dbConfig.database;
307
+ }
308
+
309
+ async exists() {
310
+ const rows = await this._adminQuery(
311
+ `SELECT 1 FROM pg_database WHERE datname = '${assertDatabaseName(this.databaseName)}'`);
312
+ return !!(rows && rows.length);
313
+ }
314
+
315
+ async create() {
316
+ const schema = await this.getSchema();
317
+ if (typeof schema._createPostgresDatabaseFromConfig === 'function') {
318
+ await schema._createPostgresDatabaseFromConfig();
319
+ }
320
+ await this._reconnect();
321
+ }
322
+
323
+ /**
324
+ * Re-open the context's pool now that the database exists, and mark the context
325
+ * ready — its original _initPromise rejected (the database was missing) and
326
+ * _ensureReady() would otherwise keep re-awaiting that stale rejection.
327
+ */
328
+ async _reconnect() {
329
+ const schema = await this.getSchema();
330
+ if (typeof schema._retryPostgresInit === 'function') {
331
+ await schema._retryPostgresInit();
332
+ this.context._ready = true;
333
+ }
334
+ }
335
+
336
+ async hasTables() {
337
+ const count = await this._executeScalar(
338
+ `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = current_schema()`);
339
+ return Number(count) !== 0;
340
+ }
341
+
342
+ /**
343
+ * Postgres refuses to drop the database the session is connected to
344
+ * ("cannot drop the currently open database"), so this closes the context's
345
+ * pool and drops from the `postgres` maintenance database, terminating any
346
+ * other backend still attached — the same shape as EF's Npgsql provider and
347
+ * as masterrecord's own _createPostgresDatabaseFromConfig().
348
+ */
349
+ async delete() {
350
+ const dbName = assertDatabaseName(this.databaseName);
351
+ try { await this.context.close(); } catch (_) { /* already closed */ }
352
+ await this._adminQuery(
353
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${dbName}' AND pid <> pg_backend_pid()`);
354
+ await this._adminQuery(`DROP DATABASE IF EXISTS "${dbName}"`);
355
+ }
356
+
357
+ /** Run a statement on the `postgres` maintenance database. */
358
+ async _adminQuery(sql) {
359
+ const config = this.context._dbConfig || {};
360
+ const { default: pg } = await import('pg');
361
+ const adminPool = new pg.Pool({
362
+ host: config.host || 'localhost',
363
+ port: config.port || 5432,
364
+ user: config.user,
365
+ password: config.password,
366
+ database: 'postgres',
367
+ ssl: config.ssl || false,
368
+ });
369
+ try {
370
+ const r = await adminPool.query(sql);
371
+ return (r && r.rows) ? r.rows : [];
372
+ } finally {
373
+ await adminPool.end();
374
+ }
375
+ }
376
+ }
377
+
378
+ /** Resolve the database creator for a context's provider. */
379
+ function createDatabaseCreator(context, options = {}) {
380
+ const dependencies = { context, ...options };
381
+ if (context.isSQLite) return new SqliteDatabaseCreator(dependencies);
382
+ if (context.isMySQL) return new MySqlDatabaseCreator(dependencies);
383
+ if (context.isPostgres) return new PostgresDatabaseCreator(dependencies);
384
+ throw new Error('masterrecord: no database creator for this provider (expected sqlite, mysql or postgres).');
385
+ }
386
+
387
+ export default RelationalDatabaseCreator;
388
+ export {
389
+ RelationalDatabaseCreator,
390
+ SqliteDatabaseCreator,
391
+ MySqlDatabaseCreator,
392
+ PostgresDatabaseCreator,
393
+ createDatabaseCreator,
394
+ };