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,313 +0,0 @@
1
- /**
2
- * Test: Seed Data Deduplication in #addSeedData()
3
- * Verifies Fix #2 - that calling seed() multiple times uses EF Core HasData semantics:
4
- * - If record with same primary key exists, update it
5
- * - If record doesn't exist, insert it
6
- */
7
-
8
- console.log("╔════════════════════════════════════════════════════════════════╗");
9
- console.log("║ Seed Data Deduplication Test - EF Core Semantics ║");
10
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
11
-
12
- let passed = 0;
13
- let failed = 0;
14
-
15
- // Simulate the context class with EF Core-style seed data deduplication
16
- class SimulatedContext {
17
- constructor() {
18
- this.__entities = [];
19
- this.__contextSeedData = {};
20
- }
21
-
22
- dbset(model, tableName = null) {
23
- const entityName = tableName || model.name;
24
-
25
- // Register entity if not already registered
26
- const existingEntity = this.__entities.find(e => e.__name === entityName);
27
- if (!existingEntity) {
28
- this.__entities.push({
29
- __name: entityName,
30
- ...model.schema
31
- });
32
- }
33
-
34
- // Return chainable object with seed() method
35
- return {
36
- seed: (data) => this.#addSeedData(entityName, data, model.schema)
37
- };
38
- }
39
-
40
- #addSeedData(tableName, data, schema) {
41
- if (!this.__contextSeedData[tableName]) {
42
- this.__contextSeedData[tableName] = [];
43
- }
44
-
45
- const records = Array.isArray(data) ? data : [data];
46
-
47
- // Find primary key field from schema
48
- let primaryKey = 'id'; // Default
49
- if (schema) {
50
- for (const key in schema) {
51
- if (schema[key].primary) {
52
- primaryKey = key;
53
- break;
54
- }
55
- }
56
- }
57
-
58
- // Check if we're adding duplicate seed data
59
- const existingData = this.__contextSeedData[tableName];
60
- if (existingData.length > 0) {
61
- console.warn(`Warning: seed() called multiple times for table '${tableName}' - using upsert semantics (update if primary key exists, insert otherwise)`);
62
- }
63
-
64
- // Upsert each record by primary key (EF Core HasData semantics)
65
- records.forEach(newRecord => {
66
- const pkValue = newRecord[primaryKey];
67
- if (pkValue !== undefined) {
68
- // Find existing record with same primary key
69
- const existingIndex = existingData.findIndex(r => r[primaryKey] === pkValue);
70
- if (existingIndex !== -1) {
71
- // Update existing record (merge properties)
72
- existingData[existingIndex] = { ...existingData[existingIndex], ...newRecord };
73
- } else {
74
- // Insert new record
75
- existingData.push(newRecord);
76
- }
77
- } else {
78
- // No primary key value - just append (insert semantics)
79
- existingData.push(newRecord);
80
- }
81
- });
82
-
83
- return {
84
- seed: (moreData) => this.#addSeedData(tableName, moreData, schema)
85
- };
86
- }
87
- }
88
-
89
- // Test entities
90
- class TestEntity {
91
- static name = 'TestEntity';
92
- static schema = {
93
- id: { type: 'int', primary: true },
94
- name: { type: 'string' },
95
- email: { type: 'string' }
96
- };
97
- }
98
-
99
- class CustomEntity {
100
- static name = 'CustomEntity';
101
- static schema = {
102
- uuid: { type: 'string', primary: true },
103
- name: { type: 'string' }
104
- };
105
- }
106
-
107
- function test(description, fn) {
108
- try {
109
- fn();
110
- console.log(`✓ ${description}`);
111
- passed++;
112
- } catch (error) {
113
- console.log(`✗ ${description}`);
114
- console.log(` Error: ${error.message}`);
115
- failed++;
116
- }
117
- }
118
-
119
- function assertEqual(actual, expected, message) {
120
- if (actual !== expected) {
121
- throw new Error(`${message}\n Expected: ${expected}\n Actual: ${actual}`);
122
- }
123
- }
124
-
125
- function assertOk(value, message) {
126
- if (!value) {
127
- throw new Error(message);
128
- }
129
- }
130
-
131
- // =============================================================================
132
- // Test Suite: Seed Data Deduplication
133
- // =============================================================================
134
- console.log("📋 Test Suite: EF Core HasData Semantics - Upsert by Primary Key\n");
135
-
136
- test('should upsert seed data when seed() is called twice with same primary key', () => {
137
- const ctx = new SimulatedContext();
138
- ctx.dbset(TestEntity)
139
- .seed([{ id: 1, name: 'Original', email: 'original@test.com' }]);
140
-
141
- // Second seed call with same ID but updated fields
142
- ctx.dbset(TestEntity)
143
- .seed([{ id: 1, name: 'Updated', email: 'updated@test.com' }]);
144
-
145
- // Should only have 1 record (upserted, not duplicated)
146
- assertEqual(ctx.__contextSeedData['TestEntity'].length, 1, 'Should only have 1 record after upsert');
147
-
148
- // Should have updated values from second seed call
149
- const record = ctx.__contextSeedData['TestEntity'][0];
150
- assertEqual(record.id, 1, 'Record should have ID 1');
151
- assertEqual(record.name, 'Updated', 'Record should have updated name');
152
- assertEqual(record.email, 'updated@test.com', 'Record should have updated email');
153
- });
154
-
155
- test('should insert new records when seed() is called with different primary keys', () => {
156
- const ctx = new SimulatedContext();
157
- ctx.dbset(TestEntity)
158
- .seed([{ id: 1, name: 'First', email: 'first@test.com' }]);
159
-
160
- // Second seed call with different ID
161
- ctx.dbset(TestEntity)
162
- .seed([{ id: 2, name: 'Second', email: 'second@test.com' }]);
163
-
164
- // Should have 2 records (both inserted)
165
- assertEqual(ctx.__contextSeedData['TestEntity'].length, 2, 'Should have 2 records');
166
- assertEqual(ctx.__contextSeedData['TestEntity'][0].id, 1, 'First record should have ID 1');
167
- assertEqual(ctx.__contextSeedData['TestEntity'][1].id, 2, 'Second record should have ID 2');
168
- });
169
-
170
- test('should handle mixed upsert and insert in same seed call', () => {
171
- const ctx = new SimulatedContext();
172
- ctx.dbset(TestEntity)
173
- .seed([
174
- { id: 1, name: 'First', email: 'first@test.com' },
175
- { id: 2, name: 'Second', email: 'second@test.com' }
176
- ]);
177
-
178
- // Second seed call: update ID 1, insert ID 3
179
- ctx.dbset(TestEntity)
180
- .seed([
181
- { id: 1, name: 'Updated', email: 'updated@test.com' },
182
- { id: 3, name: 'Third', email: 'third@test.com' }
183
- ]);
184
-
185
- // Should have 3 records (1 upserted, 2 kept, 3 inserted)
186
- assertEqual(ctx.__contextSeedData['TestEntity'].length, 3, 'Should have 3 records');
187
-
188
- // Verify ID 1 was updated
189
- const record1 = ctx.__contextSeedData['TestEntity'].find(r => r.id === 1);
190
- assertEqual(record1.name, 'Updated', 'Record 1 should be updated');
191
-
192
- // Verify ID 2 still exists
193
- const record2 = ctx.__contextSeedData['TestEntity'].find(r => r.id === 2);
194
- assertEqual(record2.name, 'Second', 'Record 2 should still exist');
195
-
196
- // Verify ID 3 was inserted
197
- const record3 = ctx.__contextSeedData['TestEntity'].find(r => r.id === 3);
198
- assertEqual(record3.name, 'Third', 'Record 3 should be inserted');
199
- });
200
-
201
- test('should handle the qaContext pattern (dbset then dbset.seed with same data)', () => {
202
- const templates = [
203
- { id: 1, name: 'Template 1', email: 'template1@test.com' },
204
- { id: 2, name: 'Template 2', email: 'template2@test.com' },
205
- { id: 3, name: 'Template 3', email: 'template3@test.com' }
206
- ];
207
-
208
- const ctx = new SimulatedContext();
209
- ctx.dbset(TestEntity); // Line 58 pattern
210
- ctx.dbset(TestEntity).seed(templates); // Line 207 pattern
211
-
212
- // Should only have 3 records (not 6 duplicates)
213
- assertEqual(ctx.__contextSeedData['TestEntity'].length, 3, 'Should only have 3 records, not duplicated');
214
-
215
- // Verify all 3 records exist
216
- assertEqual(ctx.__contextSeedData['TestEntity'][0].id, 1, 'Record 1 should exist');
217
- assertEqual(ctx.__contextSeedData['TestEntity'][1].id, 2, 'Record 2 should exist');
218
- assertEqual(ctx.__contextSeedData['TestEntity'][2].id, 3, 'Record 3 should exist');
219
- });
220
-
221
- test('should append records without primary key values', () => {
222
- const ctx = new SimulatedContext();
223
- ctx.dbset(TestEntity)
224
- .seed([{ name: 'No ID 1', email: 'noid1@test.com' }]);
225
-
226
- // Second seed call without ID
227
- ctx.dbset(TestEntity)
228
- .seed([{ name: 'No ID 2', email: 'noid2@test.com' }]);
229
-
230
- // Should append both records (no PK to deduplicate by)
231
- assertEqual(ctx.__contextSeedData['TestEntity'].length, 2, 'Should have 2 records when no PK provided');
232
- assertEqual(ctx.__contextSeedData['TestEntity'][0].name, 'No ID 1', 'First record should exist');
233
- assertEqual(ctx.__contextSeedData['TestEntity'][1].name, 'No ID 2', 'Second record should exist');
234
- });
235
-
236
- test('should emit warning when seed() is called multiple times', () => {
237
- let warningEmitted = false;
238
- const originalWarn = console.warn;
239
- console.warn = function(msg) {
240
- if (msg.includes('seed() called multiple times for table')) {
241
- warningEmitted = true;
242
- }
243
- };
244
-
245
- const ctx = new SimulatedContext();
246
- ctx.dbset(TestEntity).seed([{ id: 1, name: 'First' }]);
247
- ctx.dbset(TestEntity).seed([{ id: 2, name: 'Second' }]); // Should emit warning
248
-
249
- console.warn = originalWarn;
250
-
251
- assertEqual(warningEmitted, true, 'Should emit warning when seed() called multiple times');
252
- });
253
-
254
- test('should handle custom primary key field', () => {
255
- const ctx = new SimulatedContext();
256
- ctx.dbset(CustomEntity)
257
- .seed([{ uuid: 'abc-123', name: 'Original' }]);
258
-
259
- // Second seed with same uuid
260
- ctx.dbset(CustomEntity)
261
- .seed([{ uuid: 'abc-123', name: 'Updated' }]);
262
-
263
- // Should upsert by custom primary key
264
- assertEqual(ctx.__contextSeedData['CustomEntity'].length, 1, 'Should only have 1 record');
265
- assertEqual(ctx.__contextSeedData['CustomEntity'][0].name, 'Updated', 'Should have updated name');
266
- });
267
-
268
- test('should handle real-world qaContext scenario with 9 seeds', () => {
269
- class TaxonomyTemplate {
270
- static name = 'TaxonomyTemplate';
271
- static schema = {
272
- id: { type: 'int', primary: true },
273
- name: { type: 'string' },
274
- description: { type: 'text' }
275
- };
276
- }
277
-
278
- const templates = [
279
- { id: 1, name: 'General Knowledge', description: 'General knowledge questions' },
280
- { id: 2, name: 'Science', description: 'Science questions' },
281
- { id: 3, name: 'History', description: 'History questions' },
282
- { id: 4, name: 'Mathematics', description: 'Math questions' },
283
- { id: 5, name: 'Literature', description: 'Literature questions' },
284
- { id: 6, name: 'Geography', description: 'Geography questions' },
285
- { id: 7, name: 'Technology', description: 'Technology questions' },
286
- { id: 8, name: 'Arts', description: 'Arts questions' },
287
- { id: 9, name: 'Sports', description: 'Sports questions' }
288
- ];
289
-
290
- const ctx = new SimulatedContext();
291
- ctx.dbset(TaxonomyTemplate); // Line 58
292
- ctx.dbset(TaxonomyTemplate).seed(templates); // Line 207
293
-
294
- // Should only have 9 seed records (not 18)
295
- assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 9,
296
- 'Should only have 9 seed records, not 18 duplicates');
297
-
298
- // Verify all 9 templates exist
299
- for (let i = 1; i <= 9; i++) {
300
- const template = ctx.__contextSeedData['TaxonomyTemplate'].find(t => t.id === i);
301
- assertOk(template, `Template ${i} should exist`);
302
- }
303
- });
304
-
305
- // =============================================================================
306
- // Summary
307
- // =============================================================================
308
- console.log("\n" + "═".repeat(64));
309
- console.log(`\n✅ Passed: ${passed}`);
310
- console.log(`❌ Failed: ${failed}`);
311
- console.log(`\nTotal: ${passed + failed} tests\n`);
312
-
313
- process.exit(failed > 0 ? 1 : 0);