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,221 +0,0 @@
1
- /**
2
- * Test: Opt-In Caching Behavior
3
- *
4
- * Verifies that caching is disabled by default and only enabled with .cache()
5
- */
6
-
7
- const QueryCache = require('../Cache/QueryCache');
8
-
9
- console.log("╔════════════════════════════════════════════════════════════════╗");
10
- console.log("║ Opt-In Caching Test ║");
11
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
12
-
13
- let passed = 0;
14
- let failed = 0;
15
-
16
- // Simulate queryMethods with opt-in caching
17
- class SimulatedQuery {
18
- constructor(context) {
19
- this._context = context;
20
- this.__useCache = false; // Default: caching disabled
21
- this._queryString = 'SELECT * FROM test';
22
- this._tableName = 'Test';
23
- }
24
-
25
- // Enable caching for this query
26
- cache() {
27
- this.__useCache = true;
28
- return this;
29
- }
30
-
31
- // Execute query
32
- toList() {
33
- const cacheKey = this._context.cache.generateKey(this._queryString, [], this._tableName);
34
-
35
- // Check cache if enabled
36
- if (this.__useCache) {
37
- const cached = this._context.cache.get(cacheKey);
38
- if (cached) {
39
- return cached;
40
- }
41
- }
42
-
43
- // Simulate DB query
44
- const result = [{ id: 1, name: 'Test' }];
45
-
46
- // Store in cache if enabled
47
- if (this.__useCache) {
48
- this._context.cache.set(cacheKey, result, this._tableName);
49
- }
50
-
51
- return result;
52
- }
53
- }
54
-
55
- class SimulatedContext {
56
- constructor() {
57
- this.cache = new QueryCache({ ttl: 60000, maxSize: 100 });
58
- }
59
-
60
- createQuery() {
61
- return new SimulatedQuery(this);
62
- }
63
- }
64
-
65
- // Test 1: Default behavior - no caching
66
- console.log("📝 Test 1: Queries without .cache() are NOT cached");
67
- console.log("──────────────────────────────────────────────────");
68
-
69
- try {
70
- const ctx = new SimulatedContext();
71
- ctx.cache.clear();
72
-
73
- // Execute same query twice WITHOUT .cache()
74
- const result1 = ctx.createQuery().toList();
75
- const result2 = ctx.createQuery().toList();
76
-
77
- const stats = ctx.cache.getStats();
78
-
79
- if(stats.size === 0 && stats.hits === 0) {
80
- console.log(" ✓ Queries without .cache() do not store results");
81
- console.log(" ✓ No cache hits recorded");
82
- console.log(" ✓ Cache size remains 0");
83
- passed++;
84
- } else {
85
- console.log(` ✗ Queries were cached without .cache() call`);
86
- console.log(` ✗ Cache size: ${stats.size}, hits: ${stats.hits}`);
87
- failed++;
88
- }
89
- } catch(err) {
90
- console.log(` ✗ Error: ${err.message}`);
91
- failed++;
92
- }
93
-
94
- // Test 2: Opt-in with .cache() enables caching
95
- console.log("\n📝 Test 2: Queries with .cache() ARE cached");
96
- console.log("──────────────────────────────────────────────────");
97
-
98
- try {
99
- const ctx = new SimulatedContext();
100
- ctx.cache.clear();
101
-
102
- // Execute same query twice WITH .cache()
103
- const result1 = ctx.createQuery().cache().toList();
104
- const result2 = ctx.createQuery().cache().toList();
105
-
106
- const stats = ctx.cache.getStats();
107
-
108
- if(stats.size === 1 && stats.hits === 1 && stats.misses === 1) {
109
- console.log(" ✓ First query with .cache() stored result (miss)");
110
- console.log(" ✓ Second query with .cache() hit cache (hit)");
111
- console.log(` ✓ Cache stats: ${stats.hits} hit, ${stats.misses} miss`);
112
- passed++;
113
- } else {
114
- console.log(` ✗ Caching with .cache() didn't work properly`);
115
- console.log(` ✗ Expected: 1 hit, 1 miss. Got: ${stats.hits} hits, ${stats.misses} misses`);
116
- failed++;
117
- }
118
- } catch(err) {
119
- console.log(` ✗ Error: ${err.message}`);
120
- failed++;
121
- }
122
-
123
- // Test 3: Mixed queries - cached and non-cached
124
- console.log("\n📝 Test 3: Mixed cached and non-cached queries");
125
- console.log("──────────────────────────────────────────────────");
126
-
127
- try {
128
- const ctx = new SimulatedContext();
129
- ctx.cache.clear();
130
-
131
- // Non-cached query (no .cache())
132
- ctx.createQuery().toList();
133
- ctx.createQuery().toList();
134
-
135
- // Cached query (with .cache())
136
- ctx.createQuery().cache().toList();
137
- ctx.createQuery().cache().toList();
138
-
139
- const stats = ctx.cache.getStats();
140
-
141
- if(stats.size === 1 && stats.hits === 1 && stats.misses === 1) {
142
- console.log(" ✓ Non-cached queries didn't affect cache");
143
- console.log(" ✓ Cached queries stored and retrieved correctly");
144
- console.log(` ✓ Cache contains only .cache() queries: ${stats.size} entry`);
145
- passed++;
146
- } else {
147
- console.log(` ✗ Mixed query handling incorrect`);
148
- console.log(` ✗ Cache size: ${stats.size}, expected: 1`);
149
- failed++;
150
- }
151
- } catch(err) {
152
- console.log(` ✗ Error: ${err.message}`);
153
- failed++;
154
- }
155
-
156
- // Test 4: Default __useCache flag is false
157
- console.log("\n📝 Test 4: Default __useCache flag is false");
158
- console.log("──────────────────────────────────────────────────");
159
-
160
- try {
161
- const ctx = new SimulatedContext();
162
- const query = ctx.createQuery();
163
-
164
- if(query.__useCache === false) {
165
- console.log(" ✓ Default __useCache is false");
166
- console.log(" ✓ Caching is opt-in by default");
167
- passed++;
168
- } else {
169
- console.log(` ✗ Default __useCache is ${query.__useCache}, expected false`);
170
- failed++;
171
- }
172
- } catch(err) {
173
- console.log(` ✗ Error: ${err.message}`);
174
- failed++;
175
- }
176
-
177
- // Test 5: .cache() sets __useCache to true
178
- console.log("\n📝 Test 5: .cache() enables caching flag");
179
- console.log("──────────────────────────────────────────────────");
180
-
181
- try {
182
- const ctx = new SimulatedContext();
183
- const query = ctx.createQuery();
184
-
185
- const beforeCache = query.__useCache;
186
- query.cache();
187
- const afterCache = query.__useCache;
188
-
189
- if(beforeCache === false && afterCache === true) {
190
- console.log(" ✓ __useCache starts as false");
191
- console.log(" ✓ .cache() sets __useCache to true");
192
- console.log(" ✓ Caching is explicitly enabled");
193
- passed++;
194
- } else {
195
- console.log(` ✗ Flag transition incorrect`);
196
- console.log(` ✗ Before: ${beforeCache}, After: ${afterCache}`);
197
- failed++;
198
- }
199
- } catch(err) {
200
- console.log(` ✗ Error: ${err.message}`);
201
- failed++;
202
- }
203
-
204
- // Summary
205
- console.log("\n╔════════════════════════════════════════════════════════════════╗");
206
- console.log("║ Test Summary ║");
207
- console.log("╚════════════════════════════════════════════════════════════════╝");
208
- console.log(`\n ✓ Passed: ${passed}`);
209
- console.log(` ✗ Failed: ${failed}`);
210
- console.log(` 📊 Total: ${passed + failed}\n`);
211
-
212
- if(failed === 0) {
213
- console.log(" 🎉 All tests passed!\n");
214
- console.log(" ✅ Opt-in caching behavior verified");
215
- console.log(" ✅ Default is safe (no caching)");
216
- console.log(" ✅ .cache() explicitly enables caching\n");
217
- process.exit(0);
218
- } else {
219
- console.log(" ❌ Some tests failed\n");
220
- process.exit(1);
221
- }
@@ -1,159 +0,0 @@
1
- /**
2
- * Test: Parameterized Query Placeholder Bug Fix
3
- *
4
- * Verifies that $ placeholders are correctly converted to ? (not '?')
5
- * and that the SQL WHERE clause uses bare ? for parameter binding.
6
- *
7
- * Bug: MasterRecord was quoting the ? placeholder as '?' (literal string)
8
- * Fix: Detect placeholders and skip quoting them
9
- */
10
-
11
- const queryScript = require('../QueryLanguage/queryScript');
12
- const QueryParameters = require('../QueryLanguage/queryParameters');
13
-
14
- console.log("╔════════════════════════════════════════════════════════════════╗");
15
- console.log("║ Parameterized Placeholder Test - Bug Fix Verification ║");
16
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
17
-
18
- let passed = 0;
19
- let failed = 0;
20
-
21
- // Test 1: Verify QueryParameters returns unquoted placeholder
22
- console.log("📝 Test 1: QueryParameters.addParam returns unquoted ?");
23
- console.log("──────────────────────────────────────────────────");
24
-
25
- try {
26
- const params = new QueryParameters();
27
- const placeholder = params.addParam("test_value", "mysql");
28
-
29
- if(placeholder === '?'){
30
- console.log(" ✓ Returns bare '?' (not quoted)");
31
- passed++;
32
- } else {
33
- console.log(` ✗ Expected '?', got '${placeholder}'`);
34
- failed++;
35
- }
36
- } catch(err) {
37
- console.log(` ✗ Error: ${err.message}`);
38
- failed++;
39
- }
40
-
41
- // Test 2: Verify Postgres placeholder format
42
- console.log("\n📝 Test 2: QueryParameters.addParam returns unquoted $1 for Postgres");
43
- console.log("──────────────────────────────────────────────────");
44
-
45
- try {
46
- const params = new QueryParameters();
47
- const placeholder1 = params.addParam("value1", "postgres");
48
- const placeholder2 = params.addParam("value2", "postgres");
49
-
50
- if(placeholder1 === '$1' && placeholder2 === '$2'){
51
- console.log(" ✓ Returns bare '$1', '$2' (not quoted)");
52
- passed++;
53
- } else {
54
- console.log(` ✗ Expected '$1', '$2', got '${placeholder1}', '${placeholder2}'`);
55
- failed++;
56
- }
57
- } catch(err) {
58
- console.log(` ✗ Error: ${err.message}`);
59
- failed++;
60
- }
61
-
62
- // Test 3: Simulate buildWhere with placeholder detection
63
- console.log("\n📝 Test 3: Placeholder detection logic");
64
- console.log("──────────────────────────────────────────────────");
65
-
66
- try {
67
- // Simulate the placeholder check from the fix
68
- function testPlaceholderDetection(arg) {
69
- var isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
70
- return isPlaceholder;
71
- }
72
-
73
- const test1 = testPlaceholderDetection('?'); // MySQL/SQLite placeholder
74
- const test2 = testPlaceholderDetection('$1'); // Postgres placeholder
75
- const test3 = testPlaceholderDetection('$123'); // Postgres placeholder
76
- const test4 = testPlaceholderDetection('test'); // Regular value
77
- const test5 = testPlaceholderDetection('$abc'); // Not a placeholder
78
-
79
- if(test1 && test2 && test3 && !test4 && !test5){
80
- console.log(" ✓ Correctly identifies: '?' → placeholder");
81
- console.log(" ✓ Correctly identifies: '$1' → placeholder");
82
- console.log(" ✓ Correctly identifies: '$123' → placeholder");
83
- console.log(" ✓ Correctly identifies: 'test' → NOT placeholder");
84
- console.log(" ✓ Correctly identifies: '$abc' → NOT placeholder");
85
- passed++;
86
- } else {
87
- console.log(` ✗ Detection failed: ?=${test1}, $1=${test2}, $123=${test3}, test=${test4}, $abc=${test5}`);
88
- failed++;
89
- }
90
- } catch(err) {
91
- console.log(` ✗ Error: ${err.message}`);
92
- failed++;
93
- }
94
-
95
- // Test 4: Verify queryScript parsing preserves placeholder markers
96
- console.log("\n📝 Test 4: QueryScript parsing with $");
97
- console.log("──────────────────────────────────────────────────");
98
-
99
- try {
100
- const script = new queryScript();
101
- const lambdaExpr = "r => r.temp_access_token == $";
102
- const result = script.where(lambdaExpr, "User");
103
-
104
- // The result structure varies, so let's just verify it parsed without error
105
- if(result && result.where !== false){
106
- console.log(" ✓ Lambda expression parsed without error");
107
- console.log(" ✓ Query script created successfully");
108
- console.log(" ℹ $ marker will be replaced with ? by __validateAndCollectParameters");
109
- passed++;
110
- } else {
111
- console.log(` ✗ Parsing failed: result=${JSON.stringify(result)}`);
112
- failed++;
113
- }
114
- } catch(err) {
115
- console.log(` ✗ Error: ${err.message}`);
116
- failed++;
117
- }
118
-
119
- // Test 5: Integration flow simulation
120
- console.log("\n📝 Test 5: Full Flow Simulation");
121
- console.log("──────────────────────────────────────────────────");
122
- console.log(" Flow: Lambda → Parse → Replace $ → buildWhere");
123
- console.log(" 1. User writes: .where(r => r.field == $, 'value')");
124
- console.log(" 2. queryScript parses: arg = '$'");
125
- console.log(" 3. __validateAndCollectParameters replaces: arg = '?'");
126
- console.log(" 4. buildWhere detects placeholder: isPlaceholder = true");
127
- console.log(" 5. buildWhere skips quoting: returns 'field = ?' (not 'field = '?'')");
128
- console.log(" ✓ Expected SQL: WHERE r.field = ?");
129
- console.log(" ✓ Expected Params: ['value']");
130
- console.log(" ✗ Bug (before fix): WHERE r.field = '?' (literal string)");
131
- passed++;
132
-
133
- // Summary
134
- console.log("\n\n╔════════════════════════════════════════════════════════════════╗");
135
- console.log("║ Test Summary ║");
136
- console.log("╚════════════════════════════════════════════════════════════════╝");
137
-
138
- const total = passed + failed;
139
- const successRate = Math.round((passed/total)*100);
140
-
141
- console.log(`\n Total Tests: ${total}`);
142
- console.log(` ✅ Passed: ${passed}`);
143
- console.log(` ❌ Failed: ${failed}`);
144
- console.log(` Success Rate: ${successRate}%\n`);
145
-
146
- if(failed === 0){
147
- console.log("🎉 All placeholder tests passed!");
148
- console.log("\n✨ Bug Fix Verified!");
149
- console.log("\n📖 What was fixed:");
150
- console.log(" - realMySQLEngine.js: Added placeholder detection in buildWhere");
151
- console.log(" - SQLLiteEngine.js: Added placeholder detection in buildWhere");
152
- console.log(" - postgresEngine.js: Added placeholder detection in buildWhere");
153
- console.log("\n Placeholders (?, $1, $2, etc.) are no longer quoted as literal strings.");
154
- console.log(" Parameterized queries now work correctly! 🚀\n");
155
- process.exit(0);
156
- } else {
157
- console.log("⚠️ Some tests failed. Review and fix issues.");
158
- process.exit(1);
159
- }
@@ -1,303 +0,0 @@
1
- /**
2
- * Test: Global Pool Registry — One Pool Per Database
3
- *
4
- * Verifies that multiple context instances share the same connection pool
5
- * instead of creating a new pool per instance (the bug this fixes).
6
- */
7
-
8
- const context = require('../context');
9
-
10
- console.log("╔════════════════════════════════════════════════════════════════╗");
11
- console.log("║ Pool Registry Test — One Pool Per Database ║");
12
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
13
-
14
- let passed = 0;
15
- let failed = 0;
16
-
17
- function assert(condition, passMsg, failMsg) {
18
- if (condition) {
19
- console.log(` ✓ ${passMsg}`);
20
- passed++;
21
- } else {
22
- console.log(` ✗ ${failMsg}`);
23
- failed++;
24
- }
25
- }
26
-
27
- // ---------------------------------------------------------------------------
28
- // Test 1: _pools global registry exists
29
- // ---------------------------------------------------------------------------
30
- console.log("📝 Test 1: Global pool registry exists");
31
- console.log("──────────────────────────────────────────────────");
32
-
33
- try {
34
- const pools = global.__MR_POOLS__;
35
- assert(
36
- pools instanceof Map,
37
- "global.__MR_POOLS__ is a Map",
38
- `global.__MR_POOLS__ is not a Map (got: ${typeof pools})`
39
- );
40
- } catch (err) {
41
- console.log(` ✗ Error: ${err.message}`);
42
- failed++;
43
- }
44
-
45
- // ---------------------------------------------------------------------------
46
- // Test 2: closeAll() is a static method
47
- // ---------------------------------------------------------------------------
48
- console.log("\n📝 Test 2: context.closeAll() is a static method");
49
- console.log("──────────────────────────────────────────────────");
50
-
51
- try {
52
- assert(
53
- typeof context.closeAll === 'function',
54
- "context.closeAll exists and is a function",
55
- `context.closeAll is not a function (got: ${typeof context.closeAll})`
56
- );
57
- } catch (err) {
58
- console.log(` ✗ Error: ${err.message}`);
59
- failed++;
60
- }
61
-
62
- // ---------------------------------------------------------------------------
63
- // Test 3: getPoolStats() is a static method
64
- // ---------------------------------------------------------------------------
65
- console.log("\n📝 Test 3: context.getPoolStats() is a static method");
66
- console.log("──────────────────────────────────────────────────");
67
-
68
- try {
69
- assert(
70
- typeof context.getPoolStats === 'function',
71
- "context.getPoolStats exists and is a function",
72
- `context.getPoolStats is not a function (got: ${typeof context.getPoolStats})`
73
- );
74
- } catch (err) {
75
- console.log(` ✗ Error: ${err.message}`);
76
- failed++;
77
- }
78
-
79
- // ---------------------------------------------------------------------------
80
- // Test 4: getPoolStats() returns an array
81
- // ---------------------------------------------------------------------------
82
- console.log("\n📝 Test 4: getPoolStats() returns an array");
83
- console.log("──────────────────────────────────────────────────");
84
-
85
- try {
86
- const stats = context.getPoolStats();
87
- assert(
88
- Array.isArray(stats),
89
- `getPoolStats() returned array with ${stats.length} entries`,
90
- `Expected array, got: ${typeof stats}`
91
- );
92
- } catch (err) {
93
- console.log(` ✗ Error: ${err.message}`);
94
- failed++;
95
- }
96
-
97
- // Async tests wrapped in IIFE
98
- (async function runAsyncTests() {
99
-
100
- // ---------------------------------------------------------------------------
101
- // Test 5: closeAll() clears the registry
102
- // ---------------------------------------------------------------------------
103
- console.log("\n📝 Test 5: closeAll() clears the registry");
104
- console.log("──────────────────────────────────────────────────");
105
-
106
- try {
107
- const pools = global.__MR_POOLS__;
108
- pools.set('test:fake@localhost:5432/testdb', {
109
- engine: { close: function() {} },
110
- refCount: 1,
111
- dbType: 'test'
112
- });
113
-
114
- const beforeSize = pools.size;
115
- await context.closeAll();
116
- const afterSize = pools.size;
117
-
118
- assert(
119
- beforeSize > 0 && afterSize === 0,
120
- `Registry had ${beforeSize} entry, now has ${afterSize} after closeAll()`,
121
- `Expected registry to be cleared (before: ${beforeSize}, after: ${afterSize})`
122
- );
123
- } catch (err) {
124
- console.log(` ✗ Error: ${err.message}`);
125
- failed++;
126
- }
127
-
128
- // ---------------------------------------------------------------------------
129
- // Test 6: close() on instance decrements refCount
130
- // ---------------------------------------------------------------------------
131
- console.log("\n📝 Test 6: close() decrements refCount");
132
- console.log("──────────────────────────────────────────────────");
133
-
134
- try {
135
- const pools = global.__MR_POOLS__;
136
- const fakeEngine = { close: function() { return Promise.resolve(); } };
137
-
138
- pools.set('test:ref-count-test', {
139
- engine: fakeEngine,
140
- refCount: 2,
141
- dbType: 'test'
142
- });
143
-
144
- class TestCtx extends context {
145
- constructor() { super(); }
146
- }
147
-
148
- const db = new TestCtx();
149
- db._SQLEngine = fakeEngine;
150
-
151
- await db.close();
152
-
153
- const entry = pools.get('test:ref-count-test');
154
-
155
- assert(
156
- entry && entry.refCount === 1,
157
- "refCount decremented from 2 to 1 — pool NOT closed (still has references)",
158
- entry ? `Expected refCount 1, got ${entry.refCount}` : "Entry was deleted (should still exist with refCount 1)"
159
- );
160
-
161
- pools.delete('test:ref-count-test');
162
- } catch (err) {
163
- console.log(` ✗ Error: ${err.message}`);
164
- failed++;
165
- }
166
-
167
- // ---------------------------------------------------------------------------
168
- // Test 7: close() removes pool when refCount reaches 0
169
- // ---------------------------------------------------------------------------
170
- console.log("\n📝 Test 7: close() removes pool when refCount reaches 0");
171
- console.log("──────────────────────────────────────────────────");
172
-
173
- try {
174
- const pools = global.__MR_POOLS__;
175
- let closeCalled = false;
176
- const fakeEngine = { close: function() { closeCalled = true; return Promise.resolve(); } };
177
-
178
- pools.set('test:last-ref-test', {
179
- engine: fakeEngine,
180
- refCount: 1,
181
- dbType: 'test'
182
- });
183
-
184
- class TestCtx2 extends context {
185
- constructor() { super(); }
186
- }
187
-
188
- const db = new TestCtx2();
189
- db._SQLEngine = fakeEngine;
190
-
191
- await db.close();
192
-
193
- const entry = pools.get('test:last-ref-test');
194
-
195
- assert(
196
- !entry && closeCalled,
197
- "Pool removed from registry when refCount reached 0, engine.close() called",
198
- entry ? `Entry still exists with refCount ${entry.refCount}` : "Entry removed but engine.close() was not called"
199
- );
200
- } catch (err) {
201
- console.log(` ✗ Error: ${err.message}`);
202
- failed++;
203
- }
204
-
205
- // ---------------------------------------------------------------------------
206
- // Test 8: getPoolStats() returns correct shape
207
- // ---------------------------------------------------------------------------
208
- console.log("\n📝 Test 8: Pool registry entries have correct shape");
209
- console.log("──────────────────────────────────────────────────");
210
-
211
- try {
212
- const pools = global.__MR_POOLS__;
213
- const fakeEngine = { close: function() {} };
214
-
215
- pools.set('mysql:testuser@localhost:3306/testdb', {
216
- client: {},
217
- engine: fakeEngine,
218
- refCount: 3,
219
- dbType: 'mysql'
220
- });
221
-
222
- const stats = context.getPoolStats();
223
- const mysqlStat = stats.find(function(s) { return s.key === 'mysql:testuser@localhost:3306/testdb'; });
224
-
225
- assert(
226
- mysqlStat && mysqlStat.dbType === 'mysql' && mysqlStat.refCount === 3,
227
- `getPoolStats() correct: ${mysqlStat.key} (type: ${mysqlStat.dbType}, refs: ${mysqlStat.refCount})`,
228
- `Expected mysql entry with refCount 3, got: ${JSON.stringify(mysqlStat)}`
229
- );
230
-
231
- pools.delete('mysql:testuser@localhost:3306/testdb');
232
- } catch (err) {
233
- console.log(` ✗ Error: ${err.message}`);
234
- failed++;
235
- }
236
-
237
- // ---------------------------------------------------------------------------
238
- // Test 9: Two context instances with same fake engine share one pool entry
239
- // ---------------------------------------------------------------------------
240
- console.log("\n📝 Test 9: Two instances sharing a pool both decrement correctly");
241
- console.log("──────────────────────────────────────────────────");
242
-
243
- try {
244
- const pools = global.__MR_POOLS__;
245
- let closeCalled = false;
246
- const sharedEngine = { close: function() { closeCalled = true; return Promise.resolve(); } };
247
-
248
- pools.set('test:shared-engine', {
249
- engine: sharedEngine,
250
- refCount: 2,
251
- dbType: 'test'
252
- });
253
-
254
- class TestCtx3 extends context {
255
- constructor() { super(); }
256
- }
257
-
258
- const db1 = new TestCtx3();
259
- db1._SQLEngine = sharedEngine;
260
-
261
- const db2 = new TestCtx3();
262
- db2._SQLEngine = sharedEngine;
263
-
264
- // First close: refCount 2 -> 1
265
- await db1.close();
266
- let entry = pools.get('test:shared-engine');
267
- const afterFirst = entry ? entry.refCount : -1;
268
-
269
- // Second close: refCount 1 -> 0, pool removed
270
- await db2.close();
271
- entry = pools.get('test:shared-engine');
272
-
273
- assert(
274
- afterFirst === 1 && !entry && closeCalled,
275
- "First close: refs 2->1. Second close: refs 1->0, pool destroyed, engine.close() called",
276
- `afterFirst=${afterFirst}, entryGone=${!entry}, closeCalled=${closeCalled}`
277
- );
278
- } catch (err) {
279
- console.log(` ✗ Error: ${err.message}`);
280
- failed++;
281
- }
282
-
283
- // ---------------------------------------------------------------------------
284
- // Summary
285
- // ---------------------------------------------------------------------------
286
- console.log("\n╔════════════════════════════════════════════════════════════════╗");
287
- console.log("║ Test Summary ║");
288
- console.log("╚════════════════════════════════════════════════════════════════╝");
289
- console.log(`\n ✓ Passed: ${passed}`);
290
- console.log(` ✗ Failed: ${failed}`);
291
- console.log(` 📊 Total: ${passed + failed}\n`);
292
-
293
- if (failed === 0) {
294
- console.log(" 🎉 All tests passed!\n");
295
- console.log(" ✅ Global pool registry is working correctly");
296
- console.log(" ✅ One pool per database — no more connection exhaustion\n");
297
- process.exit(0);
298
- } else {
299
- console.log(" ❌ Some tests failed\n");
300
- process.exit(1);
301
- }
302
-
303
- })();