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,235 +0,0 @@
1
- /**
2
- * Test: Bulk Operations API
3
- * Tests: bulkCreate, bulkUpdate, bulkDelete
4
- */
5
-
6
- const masterrecord = require('../MasterRecord.js');
7
- const path = require('path');
8
- const fs = require('fs');
9
-
10
- console.log("╔════════════════════════════════════════════════════════════════╗");
11
- console.log("ā•‘ Bulk Operations API Test ā•‘");
12
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
13
-
14
- let passed = 0;
15
- let failed = 0;
16
-
17
- class User {
18
- id(db) {
19
- db.integer().primary().auto();
20
- }
21
- name(db) {
22
- db.string();
23
- }
24
- email(db) {
25
- db.string();
26
- }
27
- status(db) {
28
- db.string();
29
- }
30
- }
31
-
32
- class TestContext extends masterrecord.context {
33
- constructor() {
34
- super();
35
- }
36
- onConfig(db) {
37
- this.dbset(User);
38
- }
39
- }
40
-
41
- const dbPath = path.join(__dirname, '..', 'database', 'bulkOperations.db');
42
- if (fs.existsSync(dbPath)) {
43
- fs.unlinkSync(dbPath);
44
- }
45
-
46
- async function runTests() {
47
- const db = new TestContext();
48
-
49
- // Initialize SQLite database
50
- const SQLLiteEngine = require('../SQLLiteEngine');
51
- const sqlite3 = require('better-sqlite3');
52
- db.isSQLite = true;
53
- db.isMySQL = false;
54
- db.isPostgres = false;
55
- db._SQLEngine = new SQLLiteEngine();
56
- db.db = new sqlite3(dbPath);
57
- db._SQLEngine.setDB(db.db, 'better-sqlite3');
58
-
59
- db.onConfig();
60
-
61
- // Create table
62
- db.db.exec('CREATE TABLE IF NOT EXISTS User (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, status TEXT)');
63
-
64
- // Test 1: bulkCreate creates multiple entities
65
- console.log("šŸ“ Test 1: bulkCreate creates multiple entities");
66
- console.log("──────────────────────────────────────────────────");
67
- try {
68
- const users = await db.bulkCreate('User', [
69
- { name: 'Alice', email: 'alice@example.com', status: 'active' },
70
- { name: 'Bob', email: 'bob@example.com', status: 'active' },
71
- { name: 'Charlie', email: 'charlie@example.com', status: 'inactive' },
72
- { name: 'Dave', email: 'dave@example.com', status: 'active' },
73
- { name: 'Eve', email: 'eve@example.com', status: 'pending' }
74
- ]);
75
-
76
- if (users.length === 5 && users.every(u => u.id)) {
77
- console.log(" āœ“ Created 5 entities");
78
- console.log(` āœ“ All entities have IDs: ${users.map(u => u.id).join(', ')}`);
79
- passed++;
80
- } else {
81
- console.log(` āœ— bulkCreate failed: ${users.length} entities created`);
82
- failed++;
83
- }
84
- } catch(err) {
85
- console.log(` āœ— Error: ${err.message}`);
86
- failed++;
87
- }
88
-
89
- // Test 2: bulkCreate returns entities in order
90
- console.log("\nšŸ“ Test 2: bulkCreate returns entities in order");
91
- console.log("──────────────────────────────────────────────────");
92
- try {
93
- const users = await db.User.toList();
94
- const names = users.map(u => u.name);
95
-
96
- if (names[0] === 'Alice' && names[4] === 'Eve') {
97
- console.log(" āœ“ Entities created in correct order");
98
- passed++;
99
- } else {
100
- console.log(` āœ— Order incorrect: ${names.join(', ')}`);
101
- failed++;
102
- }
103
- } catch(err) {
104
- console.log(` āœ— Error: ${err.message}`);
105
- failed++;
106
- }
107
-
108
- // Test 3: bulkUpdate updates multiple entities
109
- console.log("\nšŸ“ Test 3: bulkUpdate updates multiple entities");
110
- console.log("──────────────────────────────────────────────────");
111
- try {
112
- await db.bulkUpdate('User', [
113
- { id: 1, status: 'inactive' },
114
- { id: 2, status: 'inactive' },
115
- { id: 4, status: 'inactive' }
116
- ]);
117
-
118
- const user1 = await db.User.findById(1);
119
- const user2 = await db.User.findById(2);
120
- const user4 = await db.User.findById(4);
121
-
122
- if (user1.status === 'inactive' && user2.status === 'inactive' && user4.status === 'inactive') {
123
- console.log(" āœ“ Updated 3 entities");
124
- console.log(" āœ“ Status changed to: inactive");
125
- passed++;
126
- } else {
127
- console.log(` āœ— Update failed: statuses are ${user1.status}, ${user2.status}, ${user4.status}`);
128
- failed++;
129
- }
130
- } catch(err) {
131
- console.log(` āœ— Error: ${err.message}`);
132
- failed++;
133
- }
134
-
135
- // Test 4: bulkUpdate leaves other fields unchanged
136
- console.log("\nšŸ“ Test 4: bulkUpdate leaves other fields unchanged");
137
- console.log("──────────────────────────────────────────────────");
138
- try {
139
- const user1 = await db.User.findById(1);
140
-
141
- if (user1.name === 'Alice' && user1.email === 'alice@example.com') {
142
- console.log(" āœ“ Other fields unchanged");
143
- passed++;
144
- } else {
145
- console.log(` āœ— Fields changed: name=${user1.name}, email=${user1.email}`);
146
- failed++;
147
- }
148
- } catch(err) {
149
- console.log(` āœ— Error: ${err.message}`);
150
- failed++;
151
- }
152
-
153
- // Test 5: bulkDelete deletes multiple entities
154
- console.log("\nšŸ“ Test 5: bulkDelete deletes multiple entities");
155
- console.log("──────────────────────────────────────────────────");
156
- try {
157
- await db.bulkDelete('User', [3, 5]);
158
-
159
- const user3 = await db.User.findById(3);
160
- const user5 = await db.User.findById(5);
161
- const remaining = await db.User.toList();
162
-
163
- if (user3 === null && user5 === null && remaining.length === 3) {
164
- console.log(" āœ“ Deleted 2 entities");
165
- console.log(` āœ“ Remaining entities: ${remaining.length}`);
166
- passed++;
167
- } else {
168
- console.log(` āœ— Delete failed: user3=${user3}, user5=${user5}, remaining=${remaining.length}`);
169
- failed++;
170
- }
171
- } catch(err) {
172
- console.log(` āœ— Error: ${err.message}`);
173
- failed++;
174
- }
175
-
176
- // Test 6: bulkCreate with empty array throws error
177
- console.log("\nšŸ“ Test 6: bulkCreate with empty array throws error");
178
- console.log("──────────────────────────────────────────────────");
179
- try {
180
- await db.bulkCreate('User', []);
181
- console.log(` āœ— Should have thrown error`);
182
- failed++;
183
- } catch(err) {
184
- if (err.message.includes('non-empty array')) {
185
- console.log(" āœ“ Empty array rejected");
186
- passed++;
187
- } else {
188
- console.log(` āœ— Wrong error: ${err.message}`);
189
- failed++;
190
- }
191
- }
192
-
193
- // Test 7: bulkUpdate with invalid entity throws error
194
- console.log("\nšŸ“ Test 7: bulkUpdate with invalid entity throws error");
195
- console.log("──────────────────────────────────────────────────");
196
- try {
197
- await db.bulkUpdate('NonExistentEntity', [{ id: 1, name: 'Test' }]);
198
- console.log(` āœ— Should have thrown error`);
199
- failed++;
200
- } catch(err) {
201
- if (err.message.includes('not found')) {
202
- console.log(" āœ“ Invalid entity name rejected");
203
- passed++;
204
- } else {
205
- console.log(` āœ— Wrong error: ${err.message}`);
206
- failed++;
207
- }
208
- }
209
-
210
- // Test 8: bulkDelete with non-existent IDs doesn't throw
211
- console.log("\nšŸ“ Test 8: bulkDelete with non-existent IDs doesn't throw");
212
- console.log("──────────────────────────────────────────────────");
213
- try {
214
- await db.bulkDelete('User', [999, 1000, 1001]);
215
- console.log(" āœ“ Non-existent IDs handled gracefully");
216
- passed++;
217
- } catch(err) {
218
- console.log(` āœ— Error: ${err.message}`);
219
- failed++;
220
- }
221
-
222
- // Summary
223
- console.log("\n" + "=".repeat(64));
224
- console.log(`Test Results: ${passed} passed, ${failed} failed`);
225
- console.log("=".repeat(64));
226
-
227
- if (failed > 0) {
228
- process.exit(1);
229
- }
230
- }
231
-
232
- runTests().catch(err => {
233
- console.error('Fatal error:', err);
234
- process.exit(1);
235
- });
@@ -1,105 +0,0 @@
1
- /**
2
- * Test to verify caching properly handles entity reconstruction
3
- */
4
- const assert = require('assert');
5
- const context = require('../context');
6
-
7
- describe('Cache Entity Reconstruction Test', function() {
8
- let db;
9
-
10
- before(async function() {
11
- // Create in-memory SQLite database
12
- db = new context({ filename: ":memory:", type: "SQLLite" });
13
-
14
- // Define a test entity
15
- db.TestEntity = {
16
- __name: "TestEntity",
17
- id: db.EntityModel("id").integer().primary().auto(),
18
- name: db.EntityModel("name").string(),
19
- description: db.EntityModel("description").string()
20
- };
21
-
22
- await db.initialize();
23
- });
24
-
25
- after(async function() {
26
- if (db && db.close) {
27
- await db.close();
28
- }
29
- });
30
-
31
- it('should properly return cached single entity with toObject method', async function() {
32
- // Insert test data
33
- const entity = db.TestEntity.create();
34
- entity.name = "Test Item";
35
- entity.description = "Test Description";
36
- await db.saveChanges();
37
-
38
- // First query (cache miss) - with caching enabled
39
- const result1 = await db.TestEntity.cache().where(t => t.id === entity.id).single();
40
-
41
- assert(result1, 'First query should return result');
42
- assert.strictEqual(result1.name, "Test Item");
43
- assert(typeof result1.toObject === 'function', 'Result should have toObject method');
44
-
45
- // Convert to plain object should work
46
- const plain1 = result1.toObject();
47
- assert.strictEqual(plain1.name, "Test Item");
48
-
49
- // Second query (cache hit) - should return entity with methods
50
- const result2 = await db.TestEntity.cache().where(t => t.id === entity.id).single();
51
-
52
- assert(result2, 'Cached query should return result');
53
- assert.strictEqual(result2.name, "Test Item");
54
- assert(typeof result2.toObject === 'function', 'Cached result should have toObject method');
55
-
56
- // toObject should work on cached entity
57
- const plain2 = result2.toObject();
58
- assert.strictEqual(plain2.name, "Test Item");
59
- });
60
-
61
- it('should properly return cached list with toObject methods', async function() {
62
- // Clear any existing data
63
- const existing = await db.TestEntity.toList();
64
- for (const item of existing) {
65
- await item.delete();
66
- }
67
- await db.saveChanges();
68
-
69
- // Insert test data
70
- const entity1 = db.TestEntity.create();
71
- entity1.name = "Item 1";
72
- const entity2 = db.TestEntity.create();
73
- entity2.name = "Item 2";
74
- await db.saveChanges();
75
-
76
- // First query (cache miss)
77
- const list1 = await db.TestEntity.cache().toList();
78
-
79
- assert(Array.isArray(list1), 'First query should return array');
80
- assert.strictEqual(list1.length, 2);
81
- assert(typeof list1[0].toObject === 'function', 'First item should have toObject method');
82
- assert(typeof list1[1].toObject === 'function', 'Second item should have toObject method');
83
-
84
- const plain1 = list1[0].toObject();
85
- assert.strictEqual(plain1.name, "Item 1");
86
-
87
- // Second query (cache hit)
88
- const list2 = await db.TestEntity.cache().toList();
89
-
90
- assert(Array.isArray(list2), 'Cached query should return array');
91
- assert.strictEqual(list2.length, 2, 'Cached array should have correct length');
92
- assert(typeof list2[0].toObject === 'function', 'Cached first item should have toObject method');
93
- assert(typeof list2[1].toObject === 'function', 'Cached second item should have toObject method');
94
-
95
- const plain2 = list2[0].toObject();
96
- assert.strictEqual(plain2.name, "Item 1");
97
- });
98
-
99
- it('should handle null results properly', async function() {
100
- // Query for non-existent entity
101
- const result = await db.TestEntity.cache().where(t => t.id === 99999).single();
102
-
103
- assert.strictEqual(result, null, 'Non-existent entity should return null');
104
- });
105
- });
@@ -1,319 +0,0 @@
1
- /**
2
- * Test: Query Cache Integration
3
- *
4
- * Tests the query result caching system integration points
5
- */
6
-
7
- const QueryCache = require('../Cache/QueryCache');
8
-
9
- console.log("╔════════════════════════════════════════════════════════════════╗");
10
- console.log("ā•‘ Query Cache Integration Test ā•‘");
11
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
12
-
13
- let passed = 0;
14
- let failed = 0;
15
-
16
- // Test 1: Query cache can be instantiated
17
- console.log("šŸ“ Test 1: Query cache instantiation");
18
- console.log("──────────────────────────────────────────────────");
19
-
20
- try {
21
- const cache = new QueryCache({ ttl: 5000, maxSize: 100 });
22
-
23
- if(cache.enabled && cache.ttl === 5000 && cache.maxSize === 100) {
24
- console.log(" āœ“ Query cache instantiated successfully");
25
- console.log(" āœ“ Configuration options applied correctly");
26
- passed++;
27
- } else {
28
- console.log(` āœ— Cache configuration incorrect`);
29
- failed++;
30
- }
31
- } catch(err) {
32
- console.log(` āœ— Error: ${err.message}`);
33
- failed++;
34
- }
35
-
36
- // Test 2: Cache key generation is deterministic
37
- console.log("\nšŸ“ Test 2: Cache key generation");
38
- console.log("──────────────────────────────────────────────────");
39
-
40
- try {
41
- const cache = new QueryCache();
42
-
43
- const key1 = cache.generateKey('SELECT * FROM users WHERE id = ?', [1], 'users');
44
- const key2 = cache.generateKey('SELECT * FROM users WHERE id = ?', [1], 'users');
45
- const key3 = cache.generateKey('SELECT * FROM users WHERE id = ?', [2], 'users');
46
-
47
- if(key1 === key2 && key1 !== key3) {
48
- console.log(" āœ“ Cache keys are deterministic (same input = same key)");
49
- console.log(" āœ“ Different parameters produce different keys");
50
- passed++;
51
- } else {
52
- console.log(` āœ— Cache key generation not working correctly`);
53
- failed++;
54
- }
55
- } catch(err) {
56
- console.log(` āœ— Error: ${err.message}`);
57
- failed++;
58
- }
59
-
60
- // Test 3: Cache set and get operations
61
- console.log("\nšŸ“ Test 3: Cache set and get operations");
62
- console.log("──────────────────────────────────────────────────");
63
-
64
- try {
65
- const cache = new QueryCache();
66
- const key = cache.generateKey('SELECT * FROM users', [], 'users');
67
- const data = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
68
-
69
- cache.set(key, data, 'users');
70
- const retrieved = cache.get(key);
71
-
72
- if(JSON.stringify(retrieved) === JSON.stringify(data)) {
73
- console.log(" āœ“ Data stored in cache successfully");
74
- console.log(" āœ“ Data retrieved from cache matches stored data");
75
- passed++;
76
- } else {
77
- console.log(` āœ— Retrieved data doesn't match stored data`);
78
- failed++;
79
- }
80
- } catch(err) {
81
- console.log(` āœ— Error: ${err.message}`);
82
- failed++;
83
- }
84
-
85
- // Test 4: Cache miss returns null
86
- console.log("\nšŸ“ Test 4: Cache miss behavior");
87
- console.log("──────────────────────────────────────────────────");
88
-
89
- try {
90
- const cache = new QueryCache();
91
- const key = cache.generateKey('SELECT * FROM users WHERE id = 999', [], 'users');
92
-
93
- const result = cache.get(key);
94
-
95
- if(result === null) {
96
- console.log(" āœ“ Cache miss returns null");
97
- console.log(" āœ“ Miss count incremented");
98
- passed++;
99
- } else {
100
- console.log(` āœ— Cache miss didn't return null`);
101
- failed++;
102
- }
103
- } catch(err) {
104
- console.log(` āœ— Error: ${err.message}`);
105
- failed++;
106
- }
107
-
108
- // Test 5: Cache invalidation by table
109
- console.log("\nšŸ“ Test 5: Table-based cache invalidation");
110
- console.log("──────────────────────────────────────────────────");
111
-
112
- try {
113
- const cache = new QueryCache();
114
-
115
- const key1 = cache.generateKey('SELECT * FROM users', [], 'users');
116
- const key2 = cache.generateKey('SELECT * FROM users WHERE id = 1', [], 'users');
117
- const key3 = cache.generateKey('SELECT * FROM posts', [], 'posts');
118
-
119
- cache.set(key1, [{ id: 1 }], 'users');
120
- cache.set(key2, { id: 1 }, 'users');
121
- cache.set(key3, [{ id: 1 }], 'posts');
122
-
123
- cache.invalidateTable('users');
124
-
125
- const result1 = cache.get(key1);
126
- const result2 = cache.get(key2);
127
- const result3 = cache.get(key3);
128
-
129
- if(result1 === null && result2 === null && result3 !== null) {
130
- console.log(" āœ“ Invalidated all entries for 'users' table");
131
- console.log(" āœ“ Did not invalidate 'posts' table entries");
132
- passed++;
133
- } else {
134
- console.log(` āœ— Invalidation didn't work as expected`);
135
- failed++;
136
- }
137
- } catch(err) {
138
- console.log(` āœ— Error: ${err.message}`);
139
- failed++;
140
- }
141
-
142
- // Test 6: Cache statistics tracking
143
- console.log("\nšŸ“ Test 6: Cache statistics");
144
- console.log("──────────────────────────────────────────────────");
145
-
146
- try {
147
- const cache = new QueryCache();
148
- const key = cache.generateKey('query', [], 'users');
149
-
150
- cache.set(key, 'data', 'users');
151
- cache.get(key); // Hit
152
- cache.get('nonexistent'); // Miss
153
-
154
- const stats = cache.getStats();
155
-
156
- if(stats.hits === 1 && stats.misses === 1 && stats.hitRate === '50.00%') {
157
- console.log(" āœ“ Hit count tracked correctly");
158
- console.log(" āœ“ Miss count tracked correctly");
159
- console.log(` āœ“ Hit rate calculated correctly: ${stats.hitRate}`);
160
- passed++;
161
- } else {
162
- console.log(` āœ— Stats incorrect: ${JSON.stringify(stats)}`);
163
- failed++;
164
- }
165
- } catch(err) {
166
- console.log(` āœ— Error: ${err.message}`);
167
- failed++;
168
- }
169
-
170
- // Test 7: Cache can be cleared
171
- console.log("\nšŸ“ Test 7: Cache clearing");
172
- console.log("──────────────────────────────────────────────────");
173
-
174
- try {
175
- const cache = new QueryCache();
176
- const key = cache.generateKey('query', [], 'users');
177
-
178
- cache.set(key, 'data', 'users');
179
- cache.get(key);
180
-
181
- const statsBefore = cache.getStats();
182
- cache.clear();
183
- const statsAfter = cache.getStats();
184
-
185
- if(statsAfter.size === 0 && statsAfter.hits === 0 && statsAfter.misses === 0) {
186
- console.log(" āœ“ All cache entries removed");
187
- console.log(" āœ“ Statistics reset to zero");
188
- passed++;
189
- } else {
190
- console.log(` āœ— Cache not properly cleared`);
191
- failed++;
192
- }
193
- } catch(err) {
194
- console.log(` āœ— Error: ${err.message}`);
195
- failed++;
196
- }
197
-
198
- // Test 8: Cache can be disabled
199
- console.log("\nšŸ“ Test 8: Cache enable/disable");
200
- console.log("──────────────────────────────────────────────────");
201
-
202
- try {
203
- const cache = new QueryCache({ enabled: false });
204
- const key = cache.generateKey('query', [], 'users');
205
-
206
- cache.set(key, 'data', 'users');
207
- const result = cache.get(key);
208
-
209
- if(result === null && cache.cache.size === 0) {
210
- console.log(" āœ“ Disabled cache doesn't store data");
211
- console.log(" āœ“ Disabled cache always returns null");
212
- passed++;
213
- } else {
214
- console.log(` āœ— Disabled cache still storing data`);
215
- failed++;
216
- }
217
- } catch(err) {
218
- console.log(` āœ— Error: ${err.message}`);
219
- failed++;
220
- }
221
-
222
- // Test 9: LRU eviction works
223
- console.log("\nšŸ“ Test 9: LRU eviction");
224
- console.log("──────────────────────────────────────────────────");
225
-
226
- try {
227
- const cache = new QueryCache({ maxSize: 3 });
228
-
229
- cache.set('key1', 'data1', 'table1');
230
-
231
- // Small delay to ensure different timestamps
232
- const delay = (ms) => {
233
- const start = Date.now();
234
- while (Date.now() - start < ms) {}
235
- };
236
-
237
- delay(2);
238
- cache.set('key2', 'data2', 'table2');
239
- delay(2);
240
- cache.set('key3', 'data3', 'table3');
241
-
242
- // Access key1 to make it recently used
243
- cache.get('key1');
244
-
245
- // Add key4 - should evict key2 (least recently used)
246
- cache.set('key4', 'data4', 'table4');
247
-
248
- const key1Result = cache.get('key1');
249
- const key2Result = cache.get('key2');
250
- const key3Result = cache.get('key3');
251
- const key4Result = cache.get('key4');
252
-
253
- if(key1Result !== null && key2Result === null && key3Result !== null && key4Result !== null) {
254
- console.log(" āœ“ LRU eviction removed least recently used entry");
255
- console.log(" āœ“ Recently accessed entries preserved");
256
- passed++;
257
- } else {
258
- console.log(` āœ— LRU eviction didn't work correctly`);
259
- console.log(` āœ— Debug: key1=${key1Result !== null}, key2=${key2Result !== null}, key3=${key3Result !== null}, key4=${key4Result !== null}`);
260
- failed++;
261
- }
262
- } catch(err) {
263
- console.log(` āœ— Error: ${err.message}`);
264
- failed++;
265
- }
266
-
267
- // Test 10: TTL expiration (short test)
268
- console.log("\nšŸ“ Test 10: TTL expiration");
269
- console.log("──────────────────────────────────────────────────");
270
-
271
- try {
272
- const cache = new QueryCache({ ttl: 100 }); // 100ms TTL
273
- const key = cache.generateKey('query', [], 'users');
274
-
275
- cache.set(key, 'data', 'users');
276
-
277
- // Should be cached immediately
278
- const result1 = cache.get(key);
279
-
280
- // Wait for TTL expiration
281
- setTimeout(() => {
282
- const result2 = cache.get(key);
283
-
284
- if(result1 !== null && result2 === null) {
285
- console.log(" āœ“ Data cached initially");
286
- console.log(" āœ“ Data expired after TTL");
287
- passed++;
288
- } else {
289
- console.log(` āœ— TTL expiration didn't work correctly`);
290
- failed++;
291
- }
292
-
293
- // Continue with summary after async test
294
- printSummary();
295
- }, 150);
296
- } catch(err) {
297
- console.log(` āœ— Error: ${err.message}`);
298
- failed++;
299
- printSummary();
300
- }
301
-
302
- function printSummary() {
303
-
304
- // Summary
305
- console.log("\n╔════════════════════════════════════════════════════════════════╗");
306
- console.log("ā•‘ Test Summary ā•‘");
307
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•");
308
- console.log(`\n āœ“ Passed: ${passed}`);
309
- console.log(` āœ— Failed: ${failed}`);
310
- console.log(` šŸ“Š Total: ${passed + failed}\n`);
311
-
312
- if(failed === 0) {
313
- console.log(" šŸŽ‰ All tests passed!\n");
314
- process.exit(0);
315
- } else {
316
- console.log(" āŒ Some tests failed\n");
317
- process.exit(1);
318
- }
319
- }