masterrecord 1.0.2 → 1.0.4
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/Migrations/cli.js +155 -23
- package/QueryLanguage/queryMethods.js +8 -0
- package/SQLLiteEngine.js +6 -1
- package/package.json +1 -1
- package/postgresEngine.js +15 -0
- package/test/broad-audit.test.js +256 -0
- package/test/count-no-from-audit.test.js +124 -0
- package/test/edge-cases-audit.test.js +180 -0
- package/test/fixtures/broad-audit/config/environments/env.audit.json +1 -0
- package/test/fixtures/broad-audit/db/auditctx.sqlite +0 -0
- package/test/fixtures/count-no-from/config/environments/env.countfrom.json +1 -0
- package/test/fixtures/count-no-from/db/countfromctx.sqlite +0 -0
- package/test/fixtures/edge-cases-audit/config/environments/env.edgeaudit.json +1 -0
- package/test/fixtures/edge-cases-audit/db/edgectx.sqlite +0 -0
- package/test/fixtures/multi-migration-3Rsgm3/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
- package/test/fixtures/multi-migration-3Rsgm3/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
- package/test/fixtures/multi-migration-3Rsgm3/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
- package/test/fixtures/multi-migration-3Rsgm3/app/models/db/migrations/multimigctx_contextSnapShot.json +104 -0
- package/test/fixtures/multi-migration-3Rsgm3/app/models/multimigctx.js +26 -0
- package/test/fixtures/multi-migration-3Rsgm3/config/environments/env.multimig.json +1 -0
- package/test/fixtures/multi-migration-3Rsgm3/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-3Rsgm3/package.json +1 -0
- package/test/fixtures/multi-migration-GAf8bq/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
- package/test/fixtures/multi-migration-GAf8bq/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
- package/test/fixtures/multi-migration-GAf8bq/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
- package/test/fixtures/multi-migration-GAf8bq/app/models/db/migrations/multimigctx_contextSnapShot.json +96 -0
- package/test/fixtures/multi-migration-GAf8bq/app/models/multimigctx.js +26 -0
- package/test/fixtures/multi-migration-GAf8bq/config/environments/env.multimig.json +1 -0
- package/test/fixtures/multi-migration-GAf8bq/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-GAf8bq/package.json +1 -0
- package/test/fixtures/multi-migration-QZg3WH/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +14 -0
- package/test/fixtures/multi-migration-QZg3WH/app/models/db/migrations/1700000002000_CreateBook_migration.js +14 -0
- package/test/fixtures/multi-migration-QZg3WH/app/models/db/migrations/1700000003000_CreateReview_migration.js +14 -0
- package/test/fixtures/multi-migration-QZg3WH/app/models/db/migrations/multimigctx_contextSnapShot.json +96 -0
- package/test/fixtures/multi-migration-QZg3WH/app/models/multimigctx.js +26 -0
- package/test/fixtures/multi-migration-QZg3WH/config/environments/env.multimig.json +1 -0
- package/test/fixtures/multi-migration-QZg3WH/db/multimigctx.sqlite +0 -0
- package/test/fixtures/multi-migration-QZg3WH/package.json +1 -0
- package/test/update-database-multi.test.js +239 -0
package/Migrations/cli.js
CHANGED
|
@@ -42,6 +42,77 @@ function __getMigrationTimestamp(file){
|
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
// ============================================================================
|
|
46
|
+
// Migration tracking — one row per applied migration filename.
|
|
47
|
+
// Without this, update-database cannot tell which files are pending, so it
|
|
48
|
+
// used to run only the last one and silently skip the rest.
|
|
49
|
+
// ============================================================================
|
|
50
|
+
|
|
51
|
+
const __MIGRATIONS_TABLE__ = '_masterrecord_migrations';
|
|
52
|
+
|
|
53
|
+
async function __ensureMigrationsTable(ctx){
|
|
54
|
+
const engine = ctx._SQLEngine;
|
|
55
|
+
if (ctx.isSQLite) {
|
|
56
|
+
await ctx._execute(`CREATE TABLE IF NOT EXISTS [${__MIGRATIONS_TABLE__}] (
|
|
57
|
+
migration_name TEXT PRIMARY KEY,
|
|
58
|
+
applied_at TEXT NOT NULL
|
|
59
|
+
)`);
|
|
60
|
+
} else if (ctx.isMySQL) {
|
|
61
|
+
await ctx._execute(`CREATE TABLE IF NOT EXISTS \`${__MIGRATIONS_TABLE__}\` (
|
|
62
|
+
migration_name VARCHAR(255) PRIMARY KEY,
|
|
63
|
+
applied_at VARCHAR(64) NOT NULL
|
|
64
|
+
)`);
|
|
65
|
+
} else if (ctx.isPostgres) {
|
|
66
|
+
await ctx._execute(`CREATE TABLE IF NOT EXISTS "${__MIGRATIONS_TABLE__}" (
|
|
67
|
+
migration_name VARCHAR(255) PRIMARY KEY,
|
|
68
|
+
applied_at VARCHAR(64) NOT NULL
|
|
69
|
+
)`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function __getAppliedMigrations(ctx){
|
|
74
|
+
const applied = new Set();
|
|
75
|
+
const engine = ctx._SQLEngine;
|
|
76
|
+
let rows;
|
|
77
|
+
try {
|
|
78
|
+
if (ctx.isSQLite) {
|
|
79
|
+
rows = engine.db.prepare(`SELECT migration_name FROM [${__MIGRATIONS_TABLE__}]`).all();
|
|
80
|
+
} else if (ctx.isMySQL) {
|
|
81
|
+
rows = await engine._runWithParams(`SELECT migration_name FROM \`${__MIGRATIONS_TABLE__}\``, []);
|
|
82
|
+
} else if (ctx.isPostgres) {
|
|
83
|
+
const r = await engine._runWithParams(`SELECT migration_name FROM "${__MIGRATIONS_TABLE__}"`, []);
|
|
84
|
+
rows = r && r.rows ? r.rows : [];
|
|
85
|
+
}
|
|
86
|
+
} catch (_) {
|
|
87
|
+
rows = [];
|
|
88
|
+
}
|
|
89
|
+
for (const r of (rows || [])) {
|
|
90
|
+
if (r && r.migration_name) applied.add(r.migration_name);
|
|
91
|
+
}
|
|
92
|
+
return applied;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function __recordMigrationApplied(ctx, migrationName){
|
|
96
|
+
const appliedAt = new Date().toISOString();
|
|
97
|
+
if (ctx.isSQLite) {
|
|
98
|
+
await ctx._execute(`INSERT INTO [${__MIGRATIONS_TABLE__}] (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
|
|
99
|
+
} else if (ctx.isMySQL) {
|
|
100
|
+
await ctx._execute(`INSERT INTO \`${__MIGRATIONS_TABLE__}\` (migration_name, applied_at) VALUES (?, ?)`, [migrationName, appliedAt]);
|
|
101
|
+
} else if (ctx.isPostgres) {
|
|
102
|
+
await ctx._execute(`INSERT INTO "${__MIGRATIONS_TABLE__}" (migration_name, applied_at) VALUES ($1, $2)`, [migrationName, appliedAt]);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function __removeMigrationApplied(ctx, migrationName){
|
|
107
|
+
if (ctx.isSQLite) {
|
|
108
|
+
await ctx._execute(`DELETE FROM [${__MIGRATIONS_TABLE__}] WHERE migration_name = ?`, [migrationName]);
|
|
109
|
+
} else if (ctx.isMySQL) {
|
|
110
|
+
await ctx._execute(`DELETE FROM \`${__MIGRATIONS_TABLE__}\` WHERE migration_name = ?`, [migrationName]);
|
|
111
|
+
} else if (ctx.isPostgres) {
|
|
112
|
+
await ctx._execute(`DELETE FROM "${__MIGRATIONS_TABLE__}" WHERE migration_name = $1`, [migrationName]);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
45
116
|
// Helper to cleanup context and exit
|
|
46
117
|
async function __cleanupAndExit(contextInstance, exitCode = 0) {
|
|
47
118
|
try {
|
|
@@ -360,23 +431,22 @@ program.option('-V', 'output the version');
|
|
|
360
431
|
await __cleanupAndExit(contextInstance, 1);
|
|
361
432
|
}
|
|
362
433
|
|
|
363
|
-
//
|
|
434
|
+
// Sort by timestamp prefix (filename convention) or file mtime as fallback.
|
|
435
|
+
// Then run EVERY pending migration in order, not just the last one —
|
|
436
|
+
// the old behavior silently skipped earlier pending migrations when a
|
|
437
|
+
// user had stacked multiple add-migration calls before deploying.
|
|
364
438
|
var mFiles = migrationFiles.slice().sort(function(a, b){
|
|
365
439
|
return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
|
|
366
440
|
});
|
|
367
|
-
|
|
368
|
-
console.log(`✓ Found ${mFiles.length} migration file(s), using latest: ${path.basename(mFile)}`);
|
|
441
|
+
console.log(`✓ Found ${mFiles.length} migration file(s)`);
|
|
369
442
|
|
|
370
443
|
console.log(`\n🔍 Loading Context file from: ${contextAbs}`);
|
|
371
|
-
var migrationProjectFile;
|
|
372
444
|
var ContextCtor;
|
|
373
445
|
try{
|
|
374
|
-
migrationProjectFile = await __loadUserModule(mFile);
|
|
375
446
|
ContextCtor = await __loadUserModule(contextAbs);
|
|
376
447
|
}catch(err){
|
|
377
|
-
console.error(`\n❌ Error - Cannot load Context
|
|
448
|
+
console.error(`\n❌ Error - Cannot load Context file`);
|
|
378
449
|
console.error(`\nContext file: ${contextAbs}`);
|
|
379
|
-
console.error(`Migration file: ${mFile}`);
|
|
380
450
|
console.error(`\nDetails: ${err.message}`);
|
|
381
451
|
if(err.stack){
|
|
382
452
|
console.error(`\nStack trace:`);
|
|
@@ -390,6 +460,11 @@ program.option('-V', 'output the version');
|
|
|
390
460
|
|
|
391
461
|
try{
|
|
392
462
|
contextInstance = new ContextCtor();
|
|
463
|
+
// MySQL/Postgres initialize asynchronously — wait for the pool
|
|
464
|
+
// before we can run any migration queries against it.
|
|
465
|
+
if (contextInstance && contextInstance._initPromise) {
|
|
466
|
+
await contextInstance._initPromise;
|
|
467
|
+
}
|
|
393
468
|
}catch(err){
|
|
394
469
|
console.error(`\n❌ Error - Failed to instantiate Context`);
|
|
395
470
|
console.error(`\nContext file: ${contextAbs}`);
|
|
@@ -425,6 +500,8 @@ program.option('-V', 'output the version');
|
|
|
425
500
|
}
|
|
426
501
|
}else if(contextInstance.isMySQL){
|
|
427
502
|
console.log(`\n📊 Database Type: MySQL`);
|
|
503
|
+
}else if(contextInstance.isPostgres){
|
|
504
|
+
console.log(`\n📊 Database Type: PostgreSQL`);
|
|
428
505
|
}
|
|
429
506
|
|
|
430
507
|
console.log(`\n🔍 Loading entities from context...`);
|
|
@@ -439,22 +516,54 @@ program.option('-V', 'output the version');
|
|
|
439
516
|
console.error(` this.dbset(Post, 'Post');`);
|
|
440
517
|
}
|
|
441
518
|
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
519
|
+
// Build tableObj once from the current entity state. All pending
|
|
520
|
+
// migrations share this object — the old design assumed a single
|
|
521
|
+
// migration, so there's no historical per-migration tableObj.
|
|
522
|
+
// Idempotent helpers (createTable checks tableExists; addColumn
|
|
523
|
+
// no-ops on undefined `table.col`) make this safe in practice.
|
|
524
|
+
var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
|
|
525
|
+
|
|
526
|
+
// Bootstrap the migrations tracking table, then filter out any
|
|
527
|
+
// migrations already applied so re-running update-database is a
|
|
528
|
+
// no-op. Must run before any migration's `up()`.
|
|
529
|
+
try {
|
|
530
|
+
await __ensureMigrationsTable(contextInstance);
|
|
531
|
+
} catch (err) {
|
|
532
|
+
console.error(`\n❌ Error - Could not create migration tracking table`);
|
|
450
533
|
console.error(`\nDetails: ${err.message}`);
|
|
451
|
-
if(err.stack){
|
|
452
|
-
console.error(`\nStack trace:`);
|
|
453
|
-
console.error(err.stack);
|
|
454
|
-
}
|
|
455
534
|
await __cleanupAndExit(contextInstance, 1);
|
|
456
535
|
}
|
|
457
536
|
|
|
537
|
+
const appliedMigrations = await __getAppliedMigrations(contextInstance);
|
|
538
|
+
const pending = mFiles.filter(f => !appliedMigrations.has(path.basename(f)));
|
|
539
|
+
|
|
540
|
+
if (pending.length === 0) {
|
|
541
|
+
console.log(`\n✓ All migrations already applied (${appliedMigrations.size} on record). Database is up to date.`);
|
|
542
|
+
} else {
|
|
543
|
+
console.log(`\n🚀 Running ${pending.length} pending migration(s)...`);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
for (const mFile of pending) {
|
|
547
|
+
const migrationName = path.basename(mFile);
|
|
548
|
+
console.log(`\n → ${migrationName}`);
|
|
549
|
+
try {
|
|
550
|
+
const MigrationCtor = await __loadUserModule(mFile);
|
|
551
|
+
const instance = new MigrationCtor(ContextCtor);
|
|
552
|
+
await instance.up(tableObj);
|
|
553
|
+
await __recordMigrationApplied(contextInstance, migrationName);
|
|
554
|
+
console.log(` ✓ applied`);
|
|
555
|
+
} catch (err) {
|
|
556
|
+
console.error(`\n❌ Error - Migration '${migrationName}' failed during execution`);
|
|
557
|
+
console.error(`\nDetails: ${err.message}`);
|
|
558
|
+
if (err.stack) {
|
|
559
|
+
console.error(`\nStack trace:`);
|
|
560
|
+
console.error(err.stack);
|
|
561
|
+
}
|
|
562
|
+
console.error(`\n💡 Earlier migrations (if any) were already applied and recorded. Fix the failing migration and re-run update-database to resume from this point.`);
|
|
563
|
+
await __cleanupAndExit(contextInstance, 1);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
458
567
|
console.log(`\n💾 Updating snapshot...`);
|
|
459
568
|
var snap = {
|
|
460
569
|
file : contextAbs,
|
|
@@ -525,11 +634,11 @@ program.option('-V', 'output the version');
|
|
|
525
634
|
console.log("Error - Cannot read or find migration file");
|
|
526
635
|
return;
|
|
527
636
|
}
|
|
528
|
-
// Sort
|
|
637
|
+
// Sort so we can find the latest APPLIED migration (not just the
|
|
638
|
+
// latest on disk) using the tracking table.
|
|
529
639
|
var mFiles = migrationFiles.slice().sort(function(a, b){
|
|
530
640
|
return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
|
|
531
641
|
});
|
|
532
|
-
var latestFile = mFiles[mFiles.length - 1];
|
|
533
642
|
|
|
534
643
|
// Prepare context and table object
|
|
535
644
|
let ContextCtor;
|
|
@@ -548,6 +657,9 @@ program.option('-V', 'output the version');
|
|
|
548
657
|
var contextInstance;
|
|
549
658
|
try{
|
|
550
659
|
contextInstance = new ContextCtor();
|
|
660
|
+
if (contextInstance && contextInstance._initPromise) {
|
|
661
|
+
await contextInstance._initPromise;
|
|
662
|
+
}
|
|
551
663
|
}catch(err){
|
|
552
664
|
console.error(`\n❌ Error - Failed to construct Context from '${contextAbs}'`);
|
|
553
665
|
console.error(`\nThis usually happens when:`);
|
|
@@ -565,12 +677,32 @@ program.option('-V', 'output the version');
|
|
|
565
677
|
var cleanEntities = migration.cleanEntities(contextInstance.__entities);
|
|
566
678
|
var tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
|
|
567
679
|
|
|
568
|
-
|
|
680
|
+
// Roll back the most recently APPLIED migration. Falls back to the
|
|
681
|
+
// latest migration file on disk if the tracking table is missing or
|
|
682
|
+
// empty (preserves legacy behavior for users who haven't run
|
|
683
|
+
// update-database under the tracked system yet).
|
|
684
|
+
await __ensureMigrationsTable(contextInstance);
|
|
685
|
+
const applied = await __getAppliedMigrations(contextInstance);
|
|
686
|
+
let rollbackFile;
|
|
687
|
+
let rollbackName;
|
|
688
|
+
if (applied.size > 0) {
|
|
689
|
+
// Pick the applied file with the latest timestamp prefix.
|
|
690
|
+
const appliedFiles = mFiles.filter(f => applied.has(path.basename(f)));
|
|
691
|
+
rollbackFile = appliedFiles[appliedFiles.length - 1];
|
|
692
|
+
rollbackName = path.basename(rollbackFile || mFiles[mFiles.length - 1]);
|
|
693
|
+
} else {
|
|
694
|
+
rollbackFile = mFiles[mFiles.length - 1];
|
|
695
|
+
rollbackName = path.basename(rollbackFile);
|
|
696
|
+
console.log(`⚠️ No applied-migration record found; falling back to latest file on disk: ${rollbackName}`);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
var MigCtor = await __loadUserModule(rollbackFile);
|
|
569
700
|
var migInstance = new MigCtor(ContextCtor);
|
|
570
701
|
if(typeof migInstance.down === 'function'){
|
|
571
702
|
await migInstance.down(tableObj);
|
|
703
|
+
await __removeMigrationApplied(contextInstance, rollbackName);
|
|
572
704
|
}else{
|
|
573
|
-
console.log(`Warning - Migration '${
|
|
705
|
+
console.log(`Warning - Migration '${rollbackName}' has no down method; skipping.`);
|
|
574
706
|
}
|
|
575
707
|
|
|
576
708
|
// Update snapshot
|
|
@@ -171,6 +171,14 @@ class queryMethods{
|
|
|
171
171
|
this.__queryObject.count(str, this.__entity.__name);
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
+
// Bootstrap the entityMap if no prior clause was chained. Without
|
|
175
|
+
// this, a plain `.count()` produced empty FROM/alias on SQLite and
|
|
176
|
+
// silently returned 1 (the row count of a no-FROM SELECT). `.single()`
|
|
177
|
+
// and `.toList()` already do this bootstrap — count() was the gap.
|
|
178
|
+
if(this.__queryObject.script.entityMap.length === 0){
|
|
179
|
+
this.__queryObject.skipClause(this.__entity.__name);
|
|
180
|
+
}
|
|
181
|
+
|
|
174
182
|
await this.__context._ensureReady();
|
|
175
183
|
|
|
176
184
|
if(this.__context.isSQLite){
|
package/SQLLiteEngine.js
CHANGED
|
@@ -577,7 +577,12 @@ class SQLLiteEngine {
|
|
|
577
577
|
return map.entity
|
|
578
578
|
}
|
|
579
579
|
}
|
|
580
|
-
return
|
|
580
|
+
// Fallthrough: return the input name so buildFrom/buildSelect still
|
|
581
|
+
// produce valid SQL when entityMap has not been populated (e.g. a
|
|
582
|
+
// `.count()` with no prior `.where()`). Returning "" used to produce
|
|
583
|
+
// `SELECT COUNT(*)` with no FROM clause, which silently returned 1.
|
|
584
|
+
// MySQL/Postgres getEntity already have this fallthrough.
|
|
585
|
+
return name || "";
|
|
581
586
|
}
|
|
582
587
|
|
|
583
588
|
// return a list of entity names and skip foreign keys and underscore.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.004",
|
|
4
4
|
"description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./MasterRecord.js",
|
package/postgresEngine.js
CHANGED
|
@@ -255,6 +255,21 @@ class postgresEngine {
|
|
|
255
255
|
return await this._runWithParams(query, params);
|
|
256
256
|
}
|
|
257
257
|
|
|
258
|
+
/**
|
|
259
|
+
* Introspection: Check if a table exists in the current Postgres schema.
|
|
260
|
+
* Mirrors the SQLite/MySQL engines so migration code and the CLI's
|
|
261
|
+
* migration tracker can call it uniformly across all three drivers.
|
|
262
|
+
*/
|
|
263
|
+
async tableExists(tableName) {
|
|
264
|
+
try {
|
|
265
|
+
const sql = `SELECT 1 FROM information_schema.tables WHERE table_schema = ANY(current_schemas(false)) AND table_name = $1 LIMIT 1`;
|
|
266
|
+
const result = await this._runWithParams(sql, [tableName]);
|
|
267
|
+
return !!(result && result.rows && result.rows.length > 0);
|
|
268
|
+
} catch (_) {
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
258
273
|
/**
|
|
259
274
|
* Build complete SELECT query with parameters
|
|
260
275
|
*/
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Broad integration audit against SQLite. Each test exercises a common
|
|
3
|
+
* consumer pattern; any failure points at a real bug. Uses raw SQL for
|
|
4
|
+
* schema setup so we don't depend on the migration CLI.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { test } from 'node:test';
|
|
8
|
+
import assert from 'node:assert/strict';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
process.env.master = 'audit';
|
|
14
|
+
|
|
15
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
const fixturesDir = path.join(__dirname, 'fixtures', 'broad-audit');
|
|
17
|
+
const envDir = path.join(fixturesDir, 'config', 'environments');
|
|
18
|
+
const dbDir = path.join(fixturesDir, 'db');
|
|
19
|
+
const dbFile = path.join(dbDir, 'auditctx.sqlite');
|
|
20
|
+
|
|
21
|
+
fs.mkdirSync(envDir, { recursive: true });
|
|
22
|
+
fs.mkdirSync(dbDir, { recursive: true });
|
|
23
|
+
if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
|
|
24
|
+
|
|
25
|
+
fs.writeFileSync(
|
|
26
|
+
path.join(envDir, 'env.audit.json'),
|
|
27
|
+
JSON.stringify({
|
|
28
|
+
AuditCtx: {
|
|
29
|
+
type: 'better-sqlite3',
|
|
30
|
+
connection: dbDir + path.sep,
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const { default: context } = await import('../context.js');
|
|
36
|
+
|
|
37
|
+
class Author {
|
|
38
|
+
id(db) { db.integer().primary().auto(); }
|
|
39
|
+
name(db) { db.string(); }
|
|
40
|
+
// camelCase field — bites any engine that capitalizes inconsistently
|
|
41
|
+
createdAt(db) { db.integer(); }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
class Post {
|
|
45
|
+
id(db) { db.integer().primary().auto(); }
|
|
46
|
+
title(db) { db.string(); }
|
|
47
|
+
views(db) { db.integer(); }
|
|
48
|
+
author_id(db) { db.integer(); }
|
|
49
|
+
Author(db) { db.belongsTo('Author'); }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
class AuditCtx extends context {
|
|
53
|
+
constructor() {
|
|
54
|
+
super();
|
|
55
|
+
this.env(envDir);
|
|
56
|
+
this.dbset(Author);
|
|
57
|
+
this.dbset(Post);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
{
|
|
62
|
+
const ctx = new AuditCtx();
|
|
63
|
+
ctx._SQLEngine.db.exec(`
|
|
64
|
+
CREATE TABLE IF NOT EXISTS Author (
|
|
65
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
66
|
+
name TEXT,
|
|
67
|
+
createdAt INTEGER
|
|
68
|
+
);
|
|
69
|
+
CREATE TABLE IF NOT EXISTS Post (
|
|
70
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
71
|
+
title TEXT,
|
|
72
|
+
views INTEGER,
|
|
73
|
+
author_id INTEGER
|
|
74
|
+
);
|
|
75
|
+
`);
|
|
76
|
+
const insertAuthor = ctx._SQLEngine.db.prepare('INSERT INTO Author (name, createdAt) VALUES (?, ?)');
|
|
77
|
+
insertAuthor.run('Alice', 1000);
|
|
78
|
+
insertAuthor.run('Bob', 2000);
|
|
79
|
+
insertAuthor.run('Carol', 3000);
|
|
80
|
+
|
|
81
|
+
const insertPost = ctx._SQLEngine.db.prepare('INSERT INTO Post (title, views, author_id) VALUES (?, ?, ?)');
|
|
82
|
+
insertPost.run('Alice Post 1', 100, 1);
|
|
83
|
+
insertPost.run('Alice Post 2', 50, 1);
|
|
84
|
+
insertPost.run('Bob Post', 200, 2);
|
|
85
|
+
await ctx.close();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
test('camelCase field name round-trips through .where()', async () => {
|
|
89
|
+
const db = new AuditCtx();
|
|
90
|
+
const author = await db.Author.where('a => a.createdAt == $$', 2000).single();
|
|
91
|
+
assert.ok(author, 'row should be found');
|
|
92
|
+
assert.equal(author.name, 'Bob');
|
|
93
|
+
assert.equal(author.createdAt, 2000);
|
|
94
|
+
await db.close();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('toList returns all rows with correct fields', async () => {
|
|
98
|
+
const db = new AuditCtx();
|
|
99
|
+
const rows = await db.Author.orderBy('a => a.id').toList();
|
|
100
|
+
assert.equal(rows.length, 3);
|
|
101
|
+
assert.deepEqual(rows.map(r => r.name), ['Alice', 'Bob', 'Carol']);
|
|
102
|
+
await db.close();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('single with no match returns null (not undefined or error)', async () => {
|
|
106
|
+
const db = new AuditCtx();
|
|
107
|
+
const result = await db.Author.where('a => a.name == $$', '__nonexistent__').single();
|
|
108
|
+
assert.equal(result, null);
|
|
109
|
+
await db.close();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('count returns a number', async () => {
|
|
113
|
+
const db = new AuditCtx();
|
|
114
|
+
const n = await db.Author.count();
|
|
115
|
+
assert.equal(n, 3);
|
|
116
|
+
await db.close();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('count with chained where filters correctly', async () => {
|
|
120
|
+
const db = new AuditCtx();
|
|
121
|
+
const n = await db.Author.where('a => a.createdAt > $$', 1500).count();
|
|
122
|
+
assert.equal(n, 2, 'Bob (2000) and Carol (3000)');
|
|
123
|
+
await db.close();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('update persists via tracked entity modification', async () => {
|
|
127
|
+
const db = new AuditCtx();
|
|
128
|
+
const alice = await db.Author.where('a => a.name == $$', 'Alice').single();
|
|
129
|
+
alice.name = 'Alice Updated';
|
|
130
|
+
await alice.save();
|
|
131
|
+
|
|
132
|
+
const reloaded = await db.Author.where('a => a.id == $$', alice.id).single();
|
|
133
|
+
assert.equal(reloaded.name, 'Alice Updated');
|
|
134
|
+
await db.close();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('update only writes dirty fields (unchanged fields stay intact)', async () => {
|
|
138
|
+
const db = new AuditCtx();
|
|
139
|
+
const bob = await db.Author.where('a => a.name == $$', 'Bob').single();
|
|
140
|
+
const originalCreatedAt = bob.createdAt;
|
|
141
|
+
bob.name = 'Robert';
|
|
142
|
+
await bob.save();
|
|
143
|
+
|
|
144
|
+
const reloaded = await db.Author.where('a => a.id == $$', bob.id).single();
|
|
145
|
+
assert.equal(reloaded.name, 'Robert');
|
|
146
|
+
assert.equal(reloaded.createdAt, originalCreatedAt, 'untouched field must not be altered');
|
|
147
|
+
await db.close();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('delete via entity.delete() removes the row', async () => {
|
|
151
|
+
const db = new AuditCtx();
|
|
152
|
+
const carol = await db.Author.where('a => a.name == $$', 'Carol').single();
|
|
153
|
+
assert.ok(carol);
|
|
154
|
+
carol.__state = 'delete';
|
|
155
|
+
db.__track(carol);
|
|
156
|
+
await db.saveChanges();
|
|
157
|
+
|
|
158
|
+
const gone = await db.Author.where('a => a.name == $$', 'Carol').single();
|
|
159
|
+
assert.equal(gone, null);
|
|
160
|
+
await db.close();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('.new() + save produces a row visible to subsequent queries', async () => {
|
|
164
|
+
const db = new AuditCtx();
|
|
165
|
+
const row = db.Author.new();
|
|
166
|
+
row.name = 'Dave';
|
|
167
|
+
row.createdAt = 4000;
|
|
168
|
+
await row.save();
|
|
169
|
+
assert.ok(row.id, 'auto-increment id populated');
|
|
170
|
+
|
|
171
|
+
const reloaded = await db.Author.where('a => a.id == $$', row.id).single();
|
|
172
|
+
assert.equal(reloaded.name, 'Dave');
|
|
173
|
+
assert.equal(reloaded.createdAt, 4000);
|
|
174
|
+
await db.close();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test('raw-loaded belongsTo foreign key column is readable as a scalar', async () => {
|
|
178
|
+
const db = new AuditCtx();
|
|
179
|
+
const post = await db.Post.where('p => p.title == $$', 'Bob Post').single();
|
|
180
|
+
assert.ok(post);
|
|
181
|
+
assert.equal(post.author_id, 2);
|
|
182
|
+
assert.equal(post.views, 200);
|
|
183
|
+
await db.close();
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test('bulkCreate on context creates multiple rows', async () => {
|
|
187
|
+
const db = new AuditCtx();
|
|
188
|
+
await db.bulkCreate('Post', [
|
|
189
|
+
{ title: 'Bulk 1', views: 1, author_id: 1 },
|
|
190
|
+
{ title: 'Bulk 2', views: 2, author_id: 1 },
|
|
191
|
+
{ title: 'Bulk 3', views: 3, author_id: 2 },
|
|
192
|
+
]);
|
|
193
|
+
const rows = await db.Post.where('p => p.title == $$', 'Bulk 1').toList();
|
|
194
|
+
assert.equal(rows.length, 1);
|
|
195
|
+
const all = await db.Post.toList();
|
|
196
|
+
assert.ok(all.length >= 6, `expected at least 6 posts, got ${all.length}`);
|
|
197
|
+
await db.close();
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test('orderBy ASC then OrderBy DESC give opposite orderings', async () => {
|
|
201
|
+
const db = new AuditCtx();
|
|
202
|
+
const asc = await db.Post.orderBy('p => p.views').toList();
|
|
203
|
+
const desc = await db.Post.orderByDescending('p => p.views').toList();
|
|
204
|
+
|
|
205
|
+
const ascViews = asc.map(p => p.views);
|
|
206
|
+
const descViews = desc.map(p => p.views);
|
|
207
|
+
assert.deepEqual(descViews, [...ascViews].reverse());
|
|
208
|
+
await db.close();
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test('skip/take pagination works end-to-end', async () => {
|
|
212
|
+
const db = new AuditCtx();
|
|
213
|
+
const page = await db.Post.orderBy('p => p.id').skip(1).take(2).toList();
|
|
214
|
+
assert.equal(page.length, 2);
|
|
215
|
+
await db.close();
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test('cache invalidation: modifying a row invalidates subsequent .toList()', async () => {
|
|
219
|
+
const db = new AuditCtx();
|
|
220
|
+
// Warm the cache
|
|
221
|
+
const first = await db.Post.cache().orderBy('p => p.id').toList();
|
|
222
|
+
const firstCount = first.length;
|
|
223
|
+
|
|
224
|
+
// Create a new row
|
|
225
|
+
const p = db.Post.new();
|
|
226
|
+
p.title = 'Cache Invalidator';
|
|
227
|
+
p.views = 999;
|
|
228
|
+
p.author_id = 1;
|
|
229
|
+
await p.save();
|
|
230
|
+
|
|
231
|
+
// A fresh query should see the new row (cache must be invalidated)
|
|
232
|
+
const second = await db.Post.cache().orderBy('p => p.id').toList();
|
|
233
|
+
assert.equal(second.length, firstCount + 1, 'cache should be invalidated after insert');
|
|
234
|
+
await db.close();
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
test('saveChanges with no changes is safe and returns truthy', async () => {
|
|
238
|
+
const db = new AuditCtx();
|
|
239
|
+
const result = await db.saveChanges();
|
|
240
|
+
assert.ok(result !== false, 'saveChanges on empty tracker should not error');
|
|
241
|
+
await db.close();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('validation: required field with empty string throws on save', async () => {
|
|
245
|
+
// Reuse AuditCtx with an Author entity that has a required name.
|
|
246
|
+
// (We can't add a new context class without a matching env entry.)
|
|
247
|
+
const db = new AuditCtx();
|
|
248
|
+
const row = db.Author.new();
|
|
249
|
+
row.name = ''; // empty string on a nullable field — insertManager catches this for non-null required fields
|
|
250
|
+
row.createdAt = 9999;
|
|
251
|
+
// Author.name is nullable by default, so this will NOT throw. Instead,
|
|
252
|
+
// verify the persist succeeded — catching a different real behavior.
|
|
253
|
+
await row.save();
|
|
254
|
+
assert.ok(row.id, 'nullable empty string saves without error');
|
|
255
|
+
await db.close();
|
|
256
|
+
});
|