masterrecord 0.3.68 → 1.0.1

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.
Files changed (103) hide show
  1. package/.claude/settings.local.json +3 -1
  2. package/CHANGES.md +31 -2
  3. package/Cache/QueryCache.js +10 -4
  4. package/Cache/RedisQueryCache.js +3 -2
  5. package/Entity/entityModel.js +1 -1
  6. package/Entity/entityModelBuilder.js +2 -2
  7. package/Entity/entityTrackerModel.js +3 -3
  8. package/Entity/fieldTransformer.js +1 -1
  9. package/FOREIGN_KEY_STRING_FIX.md +2 -2
  10. package/MasterRecord.js +6 -43
  11. package/Migrations/cli.js +44 -113
  12. package/Migrations/dependencyGraph.js +1 -1
  13. package/Migrations/migrationMySQLQuery.js +1 -1
  14. package/Migrations/migrationPostgresQuery.js +1 -1
  15. package/Migrations/migrationSQLiteQuery.js +1 -1
  16. package/Migrations/migrationTemplate.js +8 -39
  17. package/Migrations/migrations.js +16 -14
  18. package/Migrations/pathUtils.js +2 -5
  19. package/Migrations/pathUtils.test.js +33 -49
  20. package/Migrations/schema.js +52 -89
  21. package/QueryLanguage/queryMethods.js +4 -4
  22. package/QueryLanguage/queryParameters.js +1 -1
  23. package/QueryLanguage/queryScript.js +4 -3
  24. package/SQLLiteEngine.js +30 -8
  25. package/Tools.js +10 -8
  26. package/context.js +43 -42
  27. package/deleteManager.js +2 -2
  28. package/docs/MIGRATIONS_GUIDE.md +237 -532
  29. package/docs/POSTGRESQL_SETUP.md +4 -4
  30. package/docs/QUERY_CACHING_GUIDE.md +8 -7
  31. package/eslint.config.js +40 -0
  32. package/insertManager.js +28 -20
  33. package/mySQLConnect.js +2 -2
  34. package/mySQLEngine.js +161 -16
  35. package/package.json +34 -5
  36. package/postgresEngine.js +74 -26
  37. package/postgresSyncConnect.js +5 -3
  38. package/prettier.config.js +22 -0
  39. package/readme.md +35 -27
  40. package/test/context-errors.test.js +43 -0
  41. package/test/count-chained-where.test.js +136 -0
  42. package/test/esm-imports.test.js +110 -0
  43. package/test/fixtures/count-chained-where/config/environments/env.countchained.json +1 -0
  44. package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
  45. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +1 -0
  46. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  47. package/test/fixtures/query-builder-parity/config/environments/env.parity.json +1 -0
  48. package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
  49. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +1 -0
  50. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  51. package/test/migration-template.test.js +47 -0
  52. package/test/new-setter-large-string.test.js +191 -0
  53. package/test/pool-key.test.js +43 -0
  54. package/test/query-builder-parity.test.js +260 -0
  55. package/test/sqlite-lifecycle.test.js +76 -0
  56. package/.eslintrc.js +0 -290
  57. package/.prettierrc.js +0 -109
  58. package/test/anyCommaStringTest.js +0 -237
  59. package/test/anyMethodTest.js +0 -176
  60. package/test/attachDetached.test.js +0 -303
  61. package/test/bulk-operations-test.js +0 -235
  62. package/test/cache-toObject-test.js +0 -105
  63. package/test/cacheIntegration.test.js +0 -319
  64. package/test/config-glob-pattern-test.js +0 -232
  65. package/test/double-where-bug-test.js +0 -71
  66. package/test/ensure-ready-test.js +0 -251
  67. package/test/entity-deduplication-test.js +0 -174
  68. package/test/entity-methods-test.js +0 -269
  69. package/test/findByIdTest.js +0 -227
  70. package/test/foreign-key-string-value-test.js +0 -406
  71. package/test/global-model-registry-test.js +0 -538
  72. package/test/id-setting-validation.js +0 -202
  73. package/test/includesFeatureTest.js +0 -183
  74. package/test/includesTransformTest.js +0 -110
  75. package/test/index-bug-fix-test.js +0 -188
  76. package/test/insert-return-test.js +0 -39
  77. package/test/lifecycle-hooks-test.js +0 -258
  78. package/test/multiContextCache.test.js +0 -230
  79. package/test/new-entity-migration-test.js +0 -162
  80. package/test/newMethodTest.js +0 -330
  81. package/test/newMethodUnitTest.js +0 -320
  82. package/test/optInCache.test.js +0 -221
  83. package/test/parameterizedPlaceholderTest.js +0 -159
  84. package/test/pool-registry-test.js +0 -303
  85. package/test/post-insert-tracking-test.js +0 -258
  86. package/test/postgresEngineTest.js +0 -463
  87. package/test/postgresIntegrationTest.js +0 -381
  88. package/test/promise-detection-test.js +0 -290
  89. package/test/qa-context-pattern-test.js +0 -319
  90. package/test/query-helpers-test.js +0 -258
  91. package/test/query-isolation-test.js +0 -59
  92. package/test/queryCache.test.js +0 -148
  93. package/test/securityTest.js +0 -268
  94. package/test/seed-data-test.js +0 -212
  95. package/test/seed-deduplication-test.js +0 -313
  96. package/test/seed-features-integration-test.js +0 -418
  97. package/test/seed-migration-template-test.js +0 -220
  98. package/test/singleDollarPlaceholderTest.js +0 -238
  99. package/test/tablePrefixTest.js +0 -100
  100. package/test/transformerTest.js +0 -287
  101. package/test/v0.3.34-bug-fixes-test.js +0 -428
  102. package/test/validation-test.js +0 -302
  103. package/test/whereChainingTest.js +0 -88
@@ -1,232 +0,0 @@
1
- /**
2
- * Test: Config File Glob Pattern Fix
3
- * Verifies that the glob pattern only matches environment config files,
4
- * not arbitrary files ending with .<envType>.json
5
- *
6
- * Bug: Old pattern matched too many files:
7
- * - env.development.json (correct)
8
- * - development.json (correct)
9
- * - free-audit-page.development.json (WRONG - should not match)
10
- *
11
- * Fix: Use separate patterns with priority:
12
- * - Pattern 1: env.development.json (preferred)
13
- * - Pattern 2: development.json (fallback)
14
- */
15
-
16
- console.log("╔════════════════════════════════════════════════════════════════╗");
17
- console.log("ā•‘ Config File Glob Pattern Test - Specific Matching ā•‘");
18
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
19
-
20
- const glob = require('glob');
21
- const path = require('path');
22
- const fs = require('fs');
23
- const os = require('os');
24
-
25
- let passed = 0;
26
- let failed = 0;
27
-
28
- function test(description, fn) {
29
- try {
30
- fn();
31
- console.log(`āœ“ ${description}`);
32
- passed++;
33
- } catch (error) {
34
- console.log(`āœ— ${description}`);
35
- console.log(` Error: ${error.message}`);
36
- failed++;
37
- }
38
- }
39
-
40
- function assertEqual(actual, expected, message) {
41
- if (actual !== expected) {
42
- throw new Error(`${message}\n Expected: ${expected}\n Actual: ${actual}`);
43
- }
44
- }
45
-
46
- function assertArrayContains(array, value, message) {
47
- if (!array.includes(value)) {
48
- throw new Error(`${message}\n Array: ${JSON.stringify(array)}\n Missing: ${value}`);
49
- }
50
- }
51
-
52
- function assertArrayNotContains(array, value, message) {
53
- if (array.includes(value)) {
54
- throw new Error(`${message}\n Array: ${JSON.stringify(array)}\n Should not contain: ${value}`);
55
- }
56
- }
57
-
58
- // =============================================================================
59
- // Test Suite: Config File Glob Pattern
60
- // =============================================================================
61
- console.log("šŸ“‹ Test Suite: Environment Config File Glob Pattern\n");
62
-
63
- test('should match env.development.json', () => {
64
- // Create temp directory structure
65
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
66
- const configDir = path.join(tmpDir, 'config', 'environments');
67
- fs.mkdirSync(configDir, { recursive: true });
68
-
69
- // Create test file
70
- fs.writeFileSync(path.join(configDir, 'env.development.json'), '{}');
71
-
72
- // Test new pattern
73
- const pattern1 = `${configDir}/**/env.development.json`;
74
- const files = glob.sync(pattern1, { cwd: tmpDir, nocase: true });
75
-
76
- assertArrayContains(files, path.join(configDir, 'env.development.json'),
77
- 'Should match env.development.json');
78
-
79
- // Cleanup
80
- fs.rmSync(tmpDir, { recursive: true, force: true });
81
- });
82
-
83
- test('should match development.json as fallback', () => {
84
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
85
- const configDir = path.join(tmpDir, 'config');
86
- fs.mkdirSync(configDir, { recursive: true });
87
-
88
- // Create test file
89
- fs.writeFileSync(path.join(configDir, 'development.json'), '{}');
90
-
91
- // Test fallback pattern
92
- const pattern2 = `${configDir}/**/development.json`;
93
- const files = glob.sync(pattern2, { cwd: tmpDir, nocase: true });
94
-
95
- assertArrayContains(files, path.join(configDir, 'development.json'),
96
- 'Should match development.json as fallback');
97
-
98
- // Cleanup
99
- fs.rmSync(tmpDir, { recursive: true, force: true });
100
- });
101
-
102
- test('should NOT match arbitrary files ending with .development.json', () => {
103
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
104
- const configDir = path.join(tmpDir, 'config', 'environments');
105
- fs.mkdirSync(configDir, { recursive: true });
106
-
107
- // Create files
108
- fs.writeFileSync(path.join(configDir, 'env.development.json'), '{}');
109
- fs.writeFileSync(path.join(configDir, 'free-audit-page.development.json'), '{}');
110
- fs.writeFileSync(path.join(configDir, 'my-config.development.json'), '{}');
111
-
112
- // Test new specific pattern
113
- const pattern1 = `${configDir}/**/env.development.json`;
114
- const files = glob.sync(pattern1, { cwd: tmpDir, nocase: true });
115
-
116
- // Should ONLY match env.development.json
117
- assertEqual(files.length, 1, 'Should match exactly 1 file');
118
- assertArrayContains(files, path.join(configDir, 'env.development.json'),
119
- 'Should match env.development.json');
120
- assertArrayNotContains(files, path.join(configDir, 'free-audit-page.development.json'),
121
- 'Should NOT match free-audit-page.development.json');
122
- assertArrayNotContains(files, path.join(configDir, 'my-config.development.json'),
123
- 'Should NOT match my-config.development.json');
124
-
125
- // Cleanup
126
- fs.rmSync(tmpDir, { recursive: true, force: true });
127
- });
128
-
129
- test('should prioritize env.development.json over development.json', () => {
130
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
131
- const configDir = path.join(tmpDir, 'config');
132
- fs.mkdirSync(configDir, { recursive: true });
133
-
134
- // Create both files
135
- fs.writeFileSync(path.join(configDir, 'env.development.json'), '{"priority": "high"}');
136
- fs.writeFileSync(path.join(configDir, 'development.json'), '{"priority": "low"}');
137
-
138
- // Test priority: try env.development.json first
139
- const pattern1 = `${configDir}/**/env.development.json`;
140
- const files1 = glob.sync(pattern1, { cwd: tmpDir, nocase: true });
141
-
142
- if (files1.length > 0) {
143
- assertEqual(files1[0], path.join(configDir, 'env.development.json'),
144
- 'Should find env.development.json first');
145
- }
146
-
147
- // Cleanup
148
- fs.rmSync(tmpDir, { recursive: true, force: true });
149
- });
150
-
151
- test('should work with nested directory structures', () => {
152
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
153
- const nestedDir = path.join(tmpDir, 'app', 'config', 'environments', 'production');
154
- fs.mkdirSync(nestedDir, { recursive: true });
155
-
156
- // Create test file in nested directory
157
- fs.writeFileSync(path.join(nestedDir, 'env.development.json'), '{}');
158
-
159
- // Test pattern from root
160
- const pattern = `${tmpDir}/**/env.development.json`;
161
- const files = glob.sync(pattern, { cwd: tmpDir, nocase: true });
162
-
163
- assertEqual(files.length, 1, 'Should find file in nested directory');
164
- assertArrayContains(files, path.join(nestedDir, 'env.development.json'),
165
- 'Should match nested env.development.json');
166
-
167
- // Cleanup
168
- fs.rmSync(tmpDir, { recursive: true, force: true });
169
- });
170
-
171
- test('should be case insensitive', () => {
172
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
173
- const configDir = path.join(tmpDir, 'config');
174
- fs.mkdirSync(configDir, { recursive: true });
175
-
176
- // Create test file with different casing (if filesystem allows)
177
- try {
178
- fs.writeFileSync(path.join(configDir, 'ENV.DEVELOPMENT.JSON'), '{}');
179
-
180
- const pattern = `${configDir}/**/env.development.json`;
181
- const files = glob.sync(pattern, { cwd: tmpDir, nocase: true });
182
-
183
- // On case-insensitive filesystems (macOS, Windows), this should match
184
- if (files.length > 0) {
185
- console.log(' (Case-insensitive filesystem detected - match confirmed)');
186
- }
187
- } catch (e) {
188
- console.log(' (Case-sensitive filesystem - test skipped)');
189
- }
190
-
191
- // Cleanup
192
- fs.rmSync(tmpDir, { recursive: true, force: true });
193
- });
194
-
195
- test('OLD pattern would have matched too many files (regression check)', () => {
196
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'masterrecord-test-'));
197
- const configDir = path.join(tmpDir, 'config', 'environments');
198
- fs.mkdirSync(configDir, { recursive: true });
199
-
200
- // Create files
201
- fs.writeFileSync(path.join(configDir, 'env.development.json'), '{}');
202
- fs.writeFileSync(path.join(configDir, 'free-audit-page.development.json'), '{}');
203
-
204
- // OLD pattern (the bug)
205
- const oldPattern = `${configDir}/**/*{env.development,development}.json`;
206
- const oldFiles = glob.sync(oldPattern, { cwd: tmpDir, nocase: true });
207
-
208
- // OLD pattern matches BOTH files (bad!)
209
- assertEqual(oldFiles.length, 2, 'OLD pattern matched 2 files (demonstrating the bug)');
210
-
211
- // NEW pattern (the fix)
212
- const newPattern = `${configDir}/**/env.development.json`;
213
- const newFiles = glob.sync(newPattern, { cwd: tmpDir, nocase: true });
214
-
215
- // NEW pattern matches only 1 file (good!)
216
- assertEqual(newFiles.length, 1, 'NEW pattern matches only 1 file (the fix)');
217
- assertArrayContains(newFiles, path.join(configDir, 'env.development.json'),
218
- 'NEW pattern matches correct file');
219
-
220
- // Cleanup
221
- fs.rmSync(tmpDir, { recursive: true, force: true });
222
- });
223
-
224
- // =============================================================================
225
- // Summary
226
- // =============================================================================
227
- console.log("\n" + "═".repeat(64));
228
- console.log(`\nāœ… Passed: ${passed}`);
229
- console.log(`āŒ Failed: ${failed}`);
230
- console.log(`\nTotal: ${passed + failed} tests\n`);
231
-
232
- process.exit(failed > 0 ? 1 : 0);
@@ -1,71 +0,0 @@
1
- /**
2
- * Test for double WHERE clause bug fix
3
- * Verifies that multiple queries don't accumulate parameters
4
- */
5
-
6
- // Note: This test doesn't actually run queries, just tests query building
7
- // No database needed
8
- const queryMethods = require('../QueryLanguage/queryMethods');
9
- const modelBuilder = require('../Entity/entityModelBuilder');
10
-
11
- // Mock entity
12
- const mockEntity = {
13
- __name: 'TestEntity',
14
- id: { type: 'number' },
15
- name: { type: 'string' }
16
- };
17
-
18
- // Create test context
19
- class TestContext extends context {
20
- constructor() {
21
- super();
22
- this.dbset(mockEntity);
23
- }
24
- }
25
-
26
- console.log('=== Testing double WHERE clause bug fix ===\n');
27
-
28
- try {
29
- const ctx = new TestContext();
30
-
31
- // Access the entity multiple times and build queries
32
- console.log('Test 1: Multiple separate queries should not share state');
33
- const query1 = ctx.TestEntity.where(e => e.id == $$, 1);
34
- const query2 = ctx.TestEntity.where(e => e.id == $$, 2);
35
-
36
- // Check that they have different queryObject instances
37
- const haveDifferentInstances = query1.__queryObject !== query2.__queryObject;
38
- console.log(` āœ“ Query instances are separate: ${haveDifferentInstances}`);
39
-
40
- // Check parameter accumulation
41
- const params1 = query1.__queryObject.parameters.get();
42
- const params2 = query2.__queryObject.parameters.get();
43
-
44
- console.log(` Query 1 parameters: [${params1}]`);
45
- console.log(` Query 2 parameters: [${params2}]`);
46
-
47
- if (params1.length === 1 && params1[0] === 1 && params2.length === 1 && params2[0] === 2) {
48
- console.log(' āœ“ Parameters are correctly isolated\n');
49
- } else {
50
- console.error(' āœ— FAIL: Parameters are not isolated!\n');
51
- process.exit(1);
52
- }
53
-
54
- console.log('Test 2: Accessing entity property multiple times returns fresh instances');
55
- const instance1 = ctx.TestEntity;
56
- const instance2 = ctx.TestEntity;
57
- const areDifferent = instance1 !== instance2;
58
- console.log(` āœ“ Each access returns a new instance: ${areDifferent}\n`);
59
-
60
- if (!areDifferent) {
61
- console.error(' āœ— FAIL: Instances are being reused!\n');
62
- process.exit(1);
63
- }
64
-
65
- console.log('āœ… All tests passed! Double WHERE bug is fixed.\n');
66
-
67
- } catch (error) {
68
- console.error('āŒ Test failed with error:', error.message);
69
- console.error(error.stack);
70
- process.exit(1);
71
- }
@@ -1,251 +0,0 @@
1
- /**
2
- * Test: _ensureReady(), validateDatabaseOptions rename, and async guards
3
- *
4
- * Verifies:
5
- * - Query before env() resolves → throws clear DatabaseConnectionError
6
- * - Query after await env() → works normally (no regression)
7
- * - SQLite works without _initPromise (fast path)
8
- * - validateDatabaseOptions works, validateSQLiteOptions alias works
9
- * - _execute() throws when engine is null
10
- * - saveChanges() throws when engine is null
11
- */
12
-
13
- const context = require('../context');
14
-
15
- console.log("╔════════════════════════════════════════════════════════════════╗");
16
- console.log("ā•‘ _ensureReady + Rename + Async Guards Test ā•‘");
17
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
18
-
19
- let passed = 0;
20
- let failed = 0;
21
-
22
- function assert(condition, passMsg, failMsg) {
23
- if (condition) {
24
- console.log(` āœ“ ${passMsg}`);
25
- passed++;
26
- } else {
27
- console.log(` āœ— ${failMsg}`);
28
- failed++;
29
- }
30
- }
31
-
32
- // ---------------------------------------------------------------------------
33
- // Test 1: _ensureReady() throws when engine is null and no init promise
34
- // ---------------------------------------------------------------------------
35
- console.log("šŸ“ Test 1: _ensureReady() throws DatabaseConnectionError when engine is null");
36
- console.log("──────────────────────────────────────────────────────────────────");
37
-
38
- (async () => {
39
- try {
40
- const ctx = new context();
41
- // No env() called — _SQLEngine is null, no _initPromise
42
- try {
43
- await ctx._ensureReady();
44
- assert(false, "", "_ensureReady() did not throw when engine is null");
45
- } catch (err) {
46
- assert(
47
- err.name === 'DatabaseConnectionError',
48
- `Throws DatabaseConnectionError (got: ${err.name})`,
49
- `Expected DatabaseConnectionError, got: ${err.name}`
50
- );
51
- assert(
52
- err.message.includes('Database engine not initialized'),
53
- `Error message is descriptive: "${err.message.substring(0, 60)}..."`,
54
- `Unexpected error message: ${err.message}`
55
- );
56
- }
57
- } catch (err) {
58
- console.log(` āœ— Unexpected error: ${err.message}`);
59
- failed++;
60
- }
61
-
62
- // ---------------------------------------------------------------------------
63
- // Test 2: _ensureReady() is a no-op after _ready is set
64
- // ---------------------------------------------------------------------------
65
- console.log("\nšŸ“ Test 2: _ensureReady() fast path — no-op when _ready is true");
66
- console.log("──────────────────────────────────────────────────────────────────");
67
-
68
- try {
69
- const ctx = new context();
70
- ctx._SQLEngine = {}; // Fake engine
71
- ctx.isSQLite = true;
72
- await ctx._ensureReady(); // Should set _ready = true
73
- assert(ctx._ready === true, "_ready is true after first call", "_ready was not set");
74
-
75
- // Second call should be instant (no-op)
76
- await ctx._ensureReady();
77
- assert(true, "Second call completes without error (fast path)", "");
78
- } catch (err) {
79
- console.log(` āœ— Unexpected error: ${err.message}`);
80
- failed++;
81
- }
82
-
83
- // ---------------------------------------------------------------------------
84
- // Test 3: _ensureReady() awaits _initPromise if present
85
- // ---------------------------------------------------------------------------
86
- console.log("\nšŸ“ Test 3: _ensureReady() awaits _initPromise");
87
- console.log("──────────────────────────────────────────────────────────────────");
88
-
89
- try {
90
- const ctx = new context();
91
- ctx.isMySQL = true;
92
- // Simulate async init that sets _SQLEngine after a tick
93
- ctx._initPromise = new Promise((resolve) => {
94
- setTimeout(() => {
95
- ctx._SQLEngine = {}; // Fake engine
96
- resolve();
97
- }, 10);
98
- });
99
- // Prevent unhandled rejection
100
- ctx._initPromise.catch(() => {});
101
-
102
- await ctx._ensureReady();
103
- assert(
104
- ctx._SQLEngine !== null,
105
- "_SQLEngine is set after _ensureReady() awaits _initPromise",
106
- "_SQLEngine is still null"
107
- );
108
- assert(ctx._ready === true, "_ready is true", "_ready was not set");
109
- } catch (err) {
110
- console.log(` āœ— Unexpected error: ${err.message}`);
111
- failed++;
112
- }
113
-
114
- // ---------------------------------------------------------------------------
115
- // Test 4: _ensureReady() propagates _initPromise rejection
116
- // ---------------------------------------------------------------------------
117
- console.log("\nšŸ“ Test 4: _ensureReady() propagates _initPromise rejection");
118
- console.log("──────────────────────────────────────────────────────────────────");
119
-
120
- try {
121
- const ctx = new context();
122
- ctx.isMySQL = true;
123
- ctx._initPromise = Promise.reject(new Error('Connection refused'));
124
- // Prevent unhandled rejection warning
125
- ctx._initPromise.catch(() => {});
126
-
127
- try {
128
- await ctx._ensureReady();
129
- assert(false, "", "_ensureReady() did not throw when _initPromise rejected");
130
- } catch (err) {
131
- assert(
132
- err.message === 'Connection refused',
133
- `Propagates original rejection: "${err.message}"`,
134
- `Unexpected error: ${err.message}`
135
- );
136
- }
137
- } catch (err) {
138
- console.log(` āœ— Unexpected error: ${err.message}`);
139
- failed++;
140
- }
141
-
142
- // ---------------------------------------------------------------------------
143
- // Test 5: validateDatabaseOptions exists and works
144
- // ---------------------------------------------------------------------------
145
- console.log("\nšŸ“ Test 5: validateDatabaseOptions() exists and works");
146
- console.log("──────────────────────────────────────────────────────────────────");
147
-
148
- try {
149
- const ctx = new context();
150
- assert(
151
- typeof ctx.validateDatabaseOptions === 'function',
152
- "validateDatabaseOptions is a function",
153
- `validateDatabaseOptions is ${typeof ctx.validateDatabaseOptions}`
154
- );
155
-
156
- // Test with a valid SQLite config
157
- const options = { type: 'sqlite', connection: './test.db' };
158
- ctx.validateDatabaseOptions(options);
159
- assert(true, "validateDatabaseOptions accepts valid SQLite config", "");
160
- } catch (err) {
161
- console.log(` āœ— Unexpected error: ${err.message}`);
162
- failed++;
163
- }
164
-
165
- // ---------------------------------------------------------------------------
166
- // Test 6: validateSQLiteOptions deprecated alias works
167
- // ---------------------------------------------------------------------------
168
- console.log("\nšŸ“ Test 6: validateSQLiteOptions() deprecated alias works");
169
- console.log("──────────────────────────────────────────────────────────────────");
170
-
171
- try {
172
- const ctx = new context();
173
- assert(
174
- typeof ctx.validateSQLiteOptions === 'function',
175
- "validateSQLiteOptions alias exists",
176
- `validateSQLiteOptions is ${typeof ctx.validateSQLiteOptions}`
177
- );
178
-
179
- // Should delegate to validateDatabaseOptions
180
- const options = { type: 'sqlite', connection: './test.db' };
181
- ctx.validateSQLiteOptions(options);
182
- assert(true, "validateSQLiteOptions alias delegates correctly", "");
183
- } catch (err) {
184
- console.log(` āœ— Unexpected error: ${err.message}`);
185
- failed++;
186
- }
187
-
188
- // ---------------------------------------------------------------------------
189
- // Test 7: _execute() throws when _SQLEngine is null
190
- // ---------------------------------------------------------------------------
191
- console.log("\nšŸ“ Test 7: _execute() throws when _SQLEngine is null");
192
- console.log("──────────────────────────────────────────────────────────────────");
193
-
194
- try {
195
- const ctx = new context();
196
- // _SQLEngine is null by default
197
- try {
198
- ctx._execute('SELECT 1');
199
- assert(false, "", "_execute() did not throw when engine is null");
200
- } catch (err) {
201
- assert(
202
- err.name === 'DatabaseConnectionError',
203
- `Throws DatabaseConnectionError (got: ${err.name})`,
204
- `Expected DatabaseConnectionError, got: ${err.name}`
205
- );
206
- assert(
207
- err.message.includes('database engine not initialized'),
208
- `Error message is descriptive`,
209
- `Unexpected error message: ${err.message}`
210
- );
211
- }
212
- } catch (err) {
213
- console.log(` āœ— Unexpected error: ${err.message}`);
214
- failed++;
215
- }
216
-
217
- // ---------------------------------------------------------------------------
218
- // Test 8: saveChanges() throws when engine is null (via _ensureReady)
219
- // ---------------------------------------------------------------------------
220
- console.log("\nšŸ“ Test 8: saveChanges() throws when engine is null");
221
- console.log("──────────────────────────────────────────────────────────────────");
222
-
223
- try {
224
- const ctx = new context();
225
- // No env() called — should throw via _ensureReady()
226
- try {
227
- await ctx.saveChanges();
228
- // saveChanges returns early if no tracked entities — that's OK
229
- // The _ensureReady check happens before the tracked-entities check
230
- assert(false, "", "saveChanges() did not throw when engine is null");
231
- } catch (err) {
232
- assert(
233
- err.name === 'DatabaseConnectionError',
234
- `Throws DatabaseConnectionError (got: ${err.name})`,
235
- `Expected DatabaseConnectionError, got: ${err.name}`
236
- );
237
- }
238
- } catch (err) {
239
- console.log(` āœ— Unexpected error: ${err.message}`);
240
- failed++;
241
- }
242
-
243
- // ---------------------------------------------------------------------------
244
- // Summary
245
- // ---------------------------------------------------------------------------
246
- console.log("\n══════════════════════════════════════════════════════════════════");
247
- console.log(`Results: ${passed} passed, ${failed} failed out of ${passed + failed} assertions`);
248
- console.log("══════════════════════════════════════════════════════════════════\n");
249
-
250
- process.exit(failed > 0 ? 1 : 0);
251
- })();