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.
- package/.claude/settings.local.json +3 -1
- package/CHANGES.md +31 -2
- package/Cache/QueryCache.js +10 -4
- package/Cache/RedisQueryCache.js +3 -2
- package/Entity/entityModel.js +1 -1
- package/Entity/entityModelBuilder.js +2 -2
- package/Entity/entityTrackerModel.js +3 -3
- package/Entity/fieldTransformer.js +1 -1
- package/FOREIGN_KEY_STRING_FIX.md +2 -2
- package/MasterRecord.js +6 -43
- package/Migrations/cli.js +70 -83
- package/Migrations/dependencyGraph.js +1 -1
- package/Migrations/migrationMySQLQuery.js +1 -1
- package/Migrations/migrationPostgresQuery.js +1 -1
- package/Migrations/migrationSQLiteQuery.js +1 -1
- package/Migrations/migrationTemplate.js +10 -10
- package/Migrations/migrations.js +14 -12
- package/Migrations/pathUtils.js +2 -5
- package/Migrations/pathUtils.test.js +33 -49
- package/Migrations/schema.js +52 -89
- package/QueryLanguage/queryMethods.js +4 -4
- package/QueryLanguage/queryParameters.js +1 -1
- package/QueryLanguage/queryScript.js +4 -3
- package/SQLLiteEngine.js +26 -7
- package/Tools.js +10 -8
- package/context.js +43 -42
- package/deleteManager.js +2 -2
- package/docs/MIGRATIONS_GUIDE.md +237 -532
- package/docs/POSTGRESQL_SETUP.md +4 -4
- package/docs/QUERY_CACHING_GUIDE.md +8 -7
- package/eslint.config.js +40 -0
- package/insertManager.js +28 -20
- package/mySQLConnect.js +2 -2
- package/mySQLEngine.js +26 -6
- package/package.json +34 -5
- package/postgresEngine.js +29 -8
- package/postgresSyncConnect.js +5 -3
- package/prettier.config.js +22 -0
- package/readme.md +35 -27
- package/test/context-errors.test.js +43 -0
- package/test/esm-imports.test.js +110 -0
- package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +1 -0
- package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
- package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +1 -0
- package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
- package/test/migration-template.test.js +47 -0
- package/test/new-setter-large-string.test.js +191 -0
- package/test/pool-key.test.js +43 -0
- package/test/sqlite-lifecycle.test.js +76 -0
- package/.eslintrc.js +0 -290
- package/.prettierrc.js +0 -109
- package/test/anyCommaStringTest.js +0 -237
- package/test/anyMethodTest.js +0 -176
- package/test/attachDetached.test.js +0 -303
- package/test/bulk-operations-test.js +0 -235
- package/test/cache-toObject-test.js +0 -105
- package/test/cacheIntegration.test.js +0 -319
- package/test/config-glob-pattern-test.js +0 -232
- package/test/double-where-bug-test.js +0 -71
- package/test/ensure-ready-test.js +0 -251
- package/test/entity-deduplication-test.js +0 -174
- package/test/entity-methods-test.js +0 -269
- package/test/findByIdTest.js +0 -227
- package/test/foreign-key-string-value-test.js +0 -406
- package/test/global-model-registry-test.js +0 -538
- package/test/id-setting-validation.js +0 -202
- package/test/includesFeatureTest.js +0 -183
- package/test/includesTransformTest.js +0 -110
- package/test/index-bug-fix-test.js +0 -188
- package/test/insert-return-test.js +0 -39
- package/test/lifecycle-hooks-test.js +0 -258
- package/test/multiContextCache.test.js +0 -230
- package/test/new-entity-migration-test.js +0 -162
- package/test/newMethodTest.js +0 -330
- package/test/newMethodUnitTest.js +0 -320
- package/test/optInCache.test.js +0 -221
- package/test/parameterizedPlaceholderTest.js +0 -159
- package/test/pool-registry-test.js +0 -303
- package/test/post-insert-tracking-test.js +0 -258
- package/test/postgresEngineTest.js +0 -463
- package/test/postgresIntegrationTest.js +0 -381
- package/test/promise-detection-test.js +0 -290
- package/test/qa-context-pattern-test.js +0 -319
- package/test/query-helpers-test.js +0 -258
- package/test/query-isolation-test.js +0 -59
- package/test/queryCache.test.js +0 -148
- package/test/securityTest.js +0 -268
- package/test/seed-data-test.js +0 -212
- package/test/seed-deduplication-test.js +0 -313
- package/test/seed-features-integration-test.js +0 -418
- package/test/seed-migration-template-test.js +0 -220
- package/test/singleDollarPlaceholderTest.js +0 -238
- package/test/tablePrefixTest.js +0 -100
- package/test/transformerTest.js +0 -287
- package/test/v0.3.34-bug-fixes-test.js +0 -428
- package/test/validation-test.js +0 -302
- package/test/whereChainingTest.js +0 -88
|
@@ -1,319 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Test: qaContext Pattern Integration
|
|
3
|
-
* Simulates the exact pattern from user's qaContext that caused duplicate bug:
|
|
4
|
-
* - Line 58: this.dbset(TaxonomyTemplate)
|
|
5
|
-
* - Line 207: this.dbset(TaxonomyTemplate).seed(templates)
|
|
6
|
-
*
|
|
7
|
-
* Verifies end-to-end that this pattern doesn't create:
|
|
8
|
-
* - Duplicate entities in __entities
|
|
9
|
-
* - Duplicate seed data in __contextSeedData
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
console.log("╔════════════════════════════════════════════════════════════════╗");
|
|
13
|
-
console.log("║ qaContext Pattern Integration Test (Real Scenario) ║");
|
|
14
|
-
console.log("╚════════════════════════════════════════════════════════════════╝\n");
|
|
15
|
-
|
|
16
|
-
let passed = 0;
|
|
17
|
-
let failed = 0;
|
|
18
|
-
|
|
19
|
-
// Simulate the ACTUAL context.js implementation with both fixes
|
|
20
|
-
class SimulatedContext {
|
|
21
|
-
constructor() {
|
|
22
|
-
this.__entities = [];
|
|
23
|
-
this.__builderEntities = [];
|
|
24
|
-
this.__contextSeedData = {};
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
dbset(model, tableName = null) {
|
|
28
|
-
const entityName = tableName || model.name;
|
|
29
|
-
|
|
30
|
-
// Create model object
|
|
31
|
-
const validModel = {
|
|
32
|
-
__name: entityName,
|
|
33
|
-
...model.schema
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
// FIX #1: Entity Deduplication
|
|
37
|
-
const existingIndex = this.__entities.findIndex(e => e.__name === entityName);
|
|
38
|
-
if (existingIndex !== -1) {
|
|
39
|
-
console.warn(`Warning: dbset() called multiple times for table '${entityName}' - updating existing registration`);
|
|
40
|
-
this.__entities[existingIndex] = validModel;
|
|
41
|
-
this.__builderEntities[existingIndex] = { type: 'builder', model: validModel };
|
|
42
|
-
} else {
|
|
43
|
-
this.__entities.push(validModel);
|
|
44
|
-
this.__builderEntities.push({ type: 'builder', model: validModel });
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Return chainable object with seed() method
|
|
48
|
-
return {
|
|
49
|
-
seed: (data) => this.#addSeedData(entityName, data, model.schema)
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
#addSeedData(tableName, data, schema) {
|
|
54
|
-
if (!this.__contextSeedData[tableName]) {
|
|
55
|
-
this.__contextSeedData[tableName] = [];
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const records = Array.isArray(data) ? data : [data];
|
|
59
|
-
|
|
60
|
-
// Find primary key
|
|
61
|
-
let primaryKey = 'id';
|
|
62
|
-
if (schema) {
|
|
63
|
-
for (const key in schema) {
|
|
64
|
-
if (schema[key].primary) {
|
|
65
|
-
primaryKey = key;
|
|
66
|
-
break;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// FIX #2: Seed Data Deduplication (EF Core HasData semantics)
|
|
72
|
-
const existingData = this.__contextSeedData[tableName];
|
|
73
|
-
if (existingData.length > 0) {
|
|
74
|
-
console.warn(`Warning: seed() called multiple times for table '${tableName}' - using upsert semantics (update if primary key exists, insert otherwise)`);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
records.forEach(newRecord => {
|
|
78
|
-
const pkValue = newRecord[primaryKey];
|
|
79
|
-
if (pkValue !== undefined) {
|
|
80
|
-
const existingIndex = existingData.findIndex(r => r[primaryKey] === pkValue);
|
|
81
|
-
if (existingIndex !== -1) {
|
|
82
|
-
existingData[existingIndex] = { ...existingData[existingIndex], ...newRecord };
|
|
83
|
-
} else {
|
|
84
|
-
existingData.push(newRecord);
|
|
85
|
-
}
|
|
86
|
-
} else {
|
|
87
|
-
existingData.push(newRecord);
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
return {
|
|
92
|
-
seed: (moreData) => this.#addSeedData(tableName, moreData, schema)
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// Simulate real entities from qaContext
|
|
98
|
-
class TaxonomyTemplate {
|
|
99
|
-
static name = 'TaxonomyTemplate';
|
|
100
|
-
static schema = {
|
|
101
|
-
id: { type: 'int', primary: true },
|
|
102
|
-
name: { type: 'string' },
|
|
103
|
-
description: { type: 'text' }
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
class TaxonomyTemplateVersion {
|
|
108
|
-
static name = 'TaxonomyTemplateVersion';
|
|
109
|
-
static schema = {
|
|
110
|
-
id: { type: 'int', primary: true },
|
|
111
|
-
templateId: { type: 'int' },
|
|
112
|
-
version: { type: 'int' }
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function test(description, fn) {
|
|
117
|
-
try {
|
|
118
|
-
fn();
|
|
119
|
-
console.log(`✓ ${description}`);
|
|
120
|
-
passed++;
|
|
121
|
-
} catch (error) {
|
|
122
|
-
console.log(`✗ ${description}`);
|
|
123
|
-
console.log(` Error: ${error.message}`);
|
|
124
|
-
failed++;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function assertEqual(actual, expected, message) {
|
|
129
|
-
if (actual !== expected) {
|
|
130
|
-
throw new Error(`${message}\n Expected: ${expected}\n Actual: ${actual}`);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function assertOk(value, message) {
|
|
135
|
-
if (!value) {
|
|
136
|
-
throw new Error(message);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// =============================================================================
|
|
141
|
-
// Test Suite: qaContext Real-World Pattern
|
|
142
|
-
// =============================================================================
|
|
143
|
-
console.log("📋 Test Suite: Real qaContext Usage Pattern\n");
|
|
144
|
-
|
|
145
|
-
test('should not duplicate entities with qaContext pattern', () => {
|
|
146
|
-
const templates = [
|
|
147
|
-
{ id: 1, name: 'Template 1', description: 'First template' },
|
|
148
|
-
{ id: 2, name: 'Template 2', description: 'Second template' },
|
|
149
|
-
{ id: 3, name: 'Template 3', description: 'Third template' }
|
|
150
|
-
];
|
|
151
|
-
|
|
152
|
-
const ctx = new SimulatedContext();
|
|
153
|
-
ctx.dbset(TaxonomyTemplate); // Line 58 pattern
|
|
154
|
-
ctx.dbset(TaxonomyTemplate).seed(templates); // Line 207 pattern
|
|
155
|
-
|
|
156
|
-
// Should only have 1 entity registered
|
|
157
|
-
assertEqual(ctx.__entities.length, 1, 'Should only have 1 entity in __entities');
|
|
158
|
-
assertEqual(ctx.__entities[0].__name, 'TaxonomyTemplate', 'Entity should be TaxonomyTemplate');
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
test('should not duplicate seed data with qaContext pattern', () => {
|
|
162
|
-
const templates = [
|
|
163
|
-
{ id: 1, name: 'Template 1', description: 'First template' },
|
|
164
|
-
{ id: 2, name: 'Template 2', description: 'Second template' },
|
|
165
|
-
{ id: 3, name: 'Template 3', description: 'Third template' }
|
|
166
|
-
];
|
|
167
|
-
|
|
168
|
-
const ctx = new SimulatedContext();
|
|
169
|
-
ctx.dbset(TaxonomyTemplate);
|
|
170
|
-
ctx.dbset(TaxonomyTemplate).seed(templates);
|
|
171
|
-
|
|
172
|
-
// Should only have 3 seed records (not 6)
|
|
173
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 3,
|
|
174
|
-
'Should only have 3 seed records, not duplicated');
|
|
175
|
-
|
|
176
|
-
// Verify all 3 templates exist
|
|
177
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'][0].id, 1, 'Template 1 should exist');
|
|
178
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'][1].id, 2, 'Template 2 should exist');
|
|
179
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'][2].id, 3, 'Template 3 should exist');
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
test('should not duplicate with multiple entities using qaContext pattern', () => {
|
|
183
|
-
const templates = [
|
|
184
|
-
{ id: 1, name: 'Template 1', description: 'First' }
|
|
185
|
-
];
|
|
186
|
-
|
|
187
|
-
const versions = [
|
|
188
|
-
{ id: 1, templateId: 1, version: 1 },
|
|
189
|
-
{ id: 2, templateId: 1, version: 2 }
|
|
190
|
-
];
|
|
191
|
-
|
|
192
|
-
const ctx = new SimulatedContext();
|
|
193
|
-
// Register both entities first (line 58 pattern)
|
|
194
|
-
ctx.dbset(TaxonomyTemplate);
|
|
195
|
-
ctx.dbset(TaxonomyTemplateVersion);
|
|
196
|
-
|
|
197
|
-
// Later seed both entities (line 207 pattern)
|
|
198
|
-
ctx.dbset(TaxonomyTemplate).seed(templates);
|
|
199
|
-
ctx.dbset(TaxonomyTemplateVersion).seed(versions);
|
|
200
|
-
|
|
201
|
-
// Should have 2 distinct entities
|
|
202
|
-
assertEqual(ctx.__entities.length, 2, 'Should have 2 entities');
|
|
203
|
-
|
|
204
|
-
// Should have correct seed data for each
|
|
205
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 1,
|
|
206
|
-
'TaxonomyTemplate should have 1 seed record');
|
|
207
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplateVersion'].length, 2,
|
|
208
|
-
'TaxonomyTemplateVersion should have 2 seed records');
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
test('should handle real-world qaContext scenario with 9 seeds', () => {
|
|
212
|
-
// Real data from user's qaContext
|
|
213
|
-
const templates = [
|
|
214
|
-
{ id: 1, name: 'General Knowledge', description: 'General knowledge questions' },
|
|
215
|
-
{ id: 2, name: 'Science', description: 'Science questions' },
|
|
216
|
-
{ id: 3, name: 'History', description: 'History questions' },
|
|
217
|
-
{ id: 4, name: 'Mathematics', description: 'Math questions' },
|
|
218
|
-
{ id: 5, name: 'Literature', description: 'Literature questions' },
|
|
219
|
-
{ id: 6, name: 'Geography', description: 'Geography questions' },
|
|
220
|
-
{ id: 7, name: 'Technology', description: 'Technology questions' },
|
|
221
|
-
{ id: 8, name: 'Arts', description: 'Arts questions' },
|
|
222
|
-
{ id: 9, name: 'Sports', description: 'Sports questions' }
|
|
223
|
-
];
|
|
224
|
-
|
|
225
|
-
const ctx = new SimulatedContext();
|
|
226
|
-
ctx.dbset(TaxonomyTemplate); // Line 58
|
|
227
|
-
ctx.dbset(TaxonomyTemplate).seed(templates); // Line 207
|
|
228
|
-
|
|
229
|
-
// Should only have 9 seed records (not 18)
|
|
230
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 9,
|
|
231
|
-
'Should only have 9 seed records, not 18 duplicates');
|
|
232
|
-
|
|
233
|
-
// Verify all 9 templates exist
|
|
234
|
-
for (let i = 1; i <= 9; i++) {
|
|
235
|
-
const template = ctx.__contextSeedData['TaxonomyTemplate'].find(t => t.id === i);
|
|
236
|
-
assertOk(template, `Template ${i} should exist`);
|
|
237
|
-
}
|
|
238
|
-
});
|
|
239
|
-
|
|
240
|
-
test('should preserve correct behavior when dbset.seed is called only once', () => {
|
|
241
|
-
const templates = [
|
|
242
|
-
{ id: 1, name: 'Template 1', description: 'First template' }
|
|
243
|
-
];
|
|
244
|
-
|
|
245
|
-
const ctx = new SimulatedContext();
|
|
246
|
-
// Only call dbset.seed once (normal pattern)
|
|
247
|
-
ctx.dbset(TaxonomyTemplate).seed(templates);
|
|
248
|
-
|
|
249
|
-
// Should work normally
|
|
250
|
-
assertEqual(ctx.__entities.length, 1, 'Should have 1 entity');
|
|
251
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 1, 'Should have 1 seed record');
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
test('should handle incremental seed additions correctly', () => {
|
|
255
|
-
const ctx = new SimulatedContext();
|
|
256
|
-
// First batch of seeds
|
|
257
|
-
ctx.dbset(TaxonomyTemplate).seed([
|
|
258
|
-
{ id: 1, name: 'Template 1', description: 'First' }
|
|
259
|
-
]);
|
|
260
|
-
|
|
261
|
-
// Second batch with new ID
|
|
262
|
-
ctx.dbset(TaxonomyTemplate).seed([
|
|
263
|
-
{ id: 2, name: 'Template 2', description: 'Second' }
|
|
264
|
-
]);
|
|
265
|
-
|
|
266
|
-
// Third batch updates ID 1
|
|
267
|
-
ctx.dbset(TaxonomyTemplate).seed([
|
|
268
|
-
{ id: 1, name: 'Updated Template 1', description: 'Updated' }
|
|
269
|
-
]);
|
|
270
|
-
|
|
271
|
-
// Should have 2 records (ID 1 upserted, ID 2 inserted)
|
|
272
|
-
assertEqual(ctx.__contextSeedData['TaxonomyTemplate'].length, 2,
|
|
273
|
-
'Should have 2 records after upserts and inserts');
|
|
274
|
-
|
|
275
|
-
// Verify ID 1 was updated
|
|
276
|
-
const template1 = ctx.__contextSeedData['TaxonomyTemplate'].find(t => t.id === 1);
|
|
277
|
-
assertEqual(template1.name, 'Updated Template 1', 'Template 1 should be updated');
|
|
278
|
-
|
|
279
|
-
// Verify ID 2 exists
|
|
280
|
-
const template2 = ctx.__contextSeedData['TaxonomyTemplate'].find(t => t.id === 2);
|
|
281
|
-
assertEqual(template2.name, 'Template 2', 'Template 2 should exist');
|
|
282
|
-
});
|
|
283
|
-
|
|
284
|
-
test('should handle the problematic ragContext Settings pattern', () => {
|
|
285
|
-
class Settings {
|
|
286
|
-
static name = 'Settings';
|
|
287
|
-
static schema = {
|
|
288
|
-
id: { type: 'int', primary: true },
|
|
289
|
-
key: { type: 'string' },
|
|
290
|
-
value: { type: 'string' }
|
|
291
|
-
};
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
const settings = [
|
|
295
|
-
{ id: 1, key: 'app_name', value: 'MyApp' },
|
|
296
|
-
{ id: 2, key: 'version', value: '1.0.0' }
|
|
297
|
-
];
|
|
298
|
-
|
|
299
|
-
const ctx = new SimulatedContext();
|
|
300
|
-
ctx.dbset(Settings); // First registration
|
|
301
|
-
ctx.dbset(Settings).seed(settings); // Second registration with seed
|
|
302
|
-
|
|
303
|
-
// Should only have 1 entity (not 2 as in the bug report)
|
|
304
|
-
assertEqual(ctx.__entities.length, 1, 'Should only have 1 Settings entity');
|
|
305
|
-
|
|
306
|
-
// Should only have 2 seed records (not 4 as in the bug report)
|
|
307
|
-
assertEqual(ctx.__contextSeedData['Settings'].length, 2,
|
|
308
|
-
'Should only have 2 Settings seed records, not duplicated');
|
|
309
|
-
});
|
|
310
|
-
|
|
311
|
-
// =============================================================================
|
|
312
|
-
// Summary
|
|
313
|
-
// =============================================================================
|
|
314
|
-
console.log("\n" + "═".repeat(64));
|
|
315
|
-
console.log(`\n✅ Passed: ${passed}`);
|
|
316
|
-
console.log(`❌ Failed: ${failed}`);
|
|
317
|
-
console.log(`\nTotal: ${passed + failed} tests\n`);
|
|
318
|
-
|
|
319
|
-
process.exit(failed > 0 ? 1 : 0);
|
|
@@ -1,258 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Test: Query Helper Methods
|
|
3
|
-
* Tests: .first(), .last(), .exists(), .pluck()
|
|
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("║ Query Helper Methods Test ║");
|
|
12
|
-
console.log("╚════════════════════════════════════════════════════════════════╝\n");
|
|
13
|
-
|
|
14
|
-
let passed = 0;
|
|
15
|
-
let failed = 0;
|
|
16
|
-
|
|
17
|
-
// Define test entities
|
|
18
|
-
class User {
|
|
19
|
-
id(db) {
|
|
20
|
-
db.integer().primary().auto();
|
|
21
|
-
}
|
|
22
|
-
name(db) {
|
|
23
|
-
db.string();
|
|
24
|
-
}
|
|
25
|
-
email(db) {
|
|
26
|
-
db.string();
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Create test context
|
|
31
|
-
class TestContext extends masterrecord.context {
|
|
32
|
-
constructor() {
|
|
33
|
-
super();
|
|
34
|
-
}
|
|
35
|
-
onConfig(db) {
|
|
36
|
-
this.dbset(User);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Clean test database
|
|
41
|
-
const dbPath = path.join(__dirname, '..', 'database', 'testQueryHelpers.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)');
|
|
63
|
-
|
|
64
|
-
// Create test data
|
|
65
|
-
const users = [
|
|
66
|
-
{ name: 'Alice', email: 'alice@example.com' },
|
|
67
|
-
{ name: 'Bob', email: 'bob@example.com' },
|
|
68
|
-
{ name: 'Charlie', email: 'charlie@example.com' },
|
|
69
|
-
{ name: 'Dave', email: 'dave@example.com' },
|
|
70
|
-
{ name: 'Eve', email: 'eve@example.com' }
|
|
71
|
-
];
|
|
72
|
-
|
|
73
|
-
for (const userData of users) {
|
|
74
|
-
const user = db.User.new();
|
|
75
|
-
user.name = userData.name;
|
|
76
|
-
user.email = userData.email;
|
|
77
|
-
await user.save();
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// Test 1: .first() returns first record
|
|
81
|
-
console.log("📝 Test 1: .first() returns first record");
|
|
82
|
-
console.log("──────────────────────────────────────────────────");
|
|
83
|
-
try {
|
|
84
|
-
const first = await db.User.first();
|
|
85
|
-
|
|
86
|
-
if (first && first.name === 'Alice') {
|
|
87
|
-
console.log(" ✓ .first() returns first record ordered by primary key");
|
|
88
|
-
passed++;
|
|
89
|
-
} else {
|
|
90
|
-
console.log(` ✗ .first() failed - got: ${first?.name}`);
|
|
91
|
-
failed++;
|
|
92
|
-
}
|
|
93
|
-
} catch(err) {
|
|
94
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
95
|
-
failed++;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Test 2: .last() returns last record
|
|
99
|
-
console.log("\n📝 Test 2: .last() returns last record");
|
|
100
|
-
console.log("──────────────────────────────────────────────────");
|
|
101
|
-
try {
|
|
102
|
-
const last = await db.User.last();
|
|
103
|
-
|
|
104
|
-
if (last && last.name === 'Eve') {
|
|
105
|
-
console.log(" ✓ .last() returns last record ordered by primary key descending");
|
|
106
|
-
passed++;
|
|
107
|
-
} else {
|
|
108
|
-
console.log(` ✗ .last() failed - got: ${last?.name}`);
|
|
109
|
-
failed++;
|
|
110
|
-
}
|
|
111
|
-
} catch(err) {
|
|
112
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
113
|
-
failed++;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// Test 3: .exists() returns true for existing records
|
|
117
|
-
console.log("\n📝 Test 3: .exists() checks record existence");
|
|
118
|
-
console.log("──────────────────────────────────────────────────");
|
|
119
|
-
try {
|
|
120
|
-
const exists = await db.User
|
|
121
|
-
.where(u => u.email == $$, 'alice@example.com')
|
|
122
|
-
.exists();
|
|
123
|
-
|
|
124
|
-
const notExists = await db.User
|
|
125
|
-
.where(u => u.email == $$, 'nonexistent@example.com')
|
|
126
|
-
.exists();
|
|
127
|
-
|
|
128
|
-
if (exists === true && notExists === false) {
|
|
129
|
-
console.log(" ✓ .exists() returns true for existing records");
|
|
130
|
-
console.log(" ✓ .exists() returns false for non-existing records");
|
|
131
|
-
passed++;
|
|
132
|
-
} else {
|
|
133
|
-
console.log(` ✗ .exists() failed - exists: ${exists}, notExists: ${notExists}`);
|
|
134
|
-
failed++;
|
|
135
|
-
}
|
|
136
|
-
} catch(err) {
|
|
137
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
138
|
-
failed++;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Test 4: .pluck() extracts column values
|
|
142
|
-
console.log("\n📝 Test 4: .pluck() extracts column values");
|
|
143
|
-
console.log("──────────────────────────────────────────────────");
|
|
144
|
-
try {
|
|
145
|
-
const emails = await db.User.pluck('email');
|
|
146
|
-
|
|
147
|
-
if (Array.isArray(emails) &&
|
|
148
|
-
emails.length === 5 &&
|
|
149
|
-
emails.includes('alice@example.com') &&
|
|
150
|
-
emails.includes('eve@example.com')) {
|
|
151
|
-
console.log(" ✓ .pluck() extracts column as array");
|
|
152
|
-
console.log(" ✓ All values included");
|
|
153
|
-
passed++;
|
|
154
|
-
} else {
|
|
155
|
-
console.log(` ✗ .pluck() failed - got: ${emails?.length} items`);
|
|
156
|
-
failed++;
|
|
157
|
-
}
|
|
158
|
-
} catch(err) {
|
|
159
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
160
|
-
failed++;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// Test 5: .pluck() with where clause
|
|
164
|
-
console.log("\n📝 Test 5: .pluck() respects where clause");
|
|
165
|
-
console.log("──────────────────────────────────────────────────");
|
|
166
|
-
try {
|
|
167
|
-
const emails = await db.User
|
|
168
|
-
.where(u => u.name == $$, 'Alice')
|
|
169
|
-
.pluck('email');
|
|
170
|
-
|
|
171
|
-
if (Array.isArray(emails) &&
|
|
172
|
-
emails.length === 1 &&
|
|
173
|
-
emails[0] === 'alice@example.com') {
|
|
174
|
-
console.log(" ✓ .pluck() respects where clause");
|
|
175
|
-
passed++;
|
|
176
|
-
} else {
|
|
177
|
-
console.log(` ✗ .pluck() with where failed`);
|
|
178
|
-
failed++;
|
|
179
|
-
}
|
|
180
|
-
} catch(err) {
|
|
181
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
182
|
-
failed++;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// Test 6: .first() with where clause
|
|
186
|
-
console.log("\n📝 Test 6: .first() respects where clause");
|
|
187
|
-
console.log("──────────────────────────────────────────────────");
|
|
188
|
-
try {
|
|
189
|
-
const first = await db.User
|
|
190
|
-
.where(u => u.name == $$, 'Charlie')
|
|
191
|
-
.first();
|
|
192
|
-
|
|
193
|
-
if (first && first.name === 'Charlie') {
|
|
194
|
-
console.log(" ✓ .first() respects where clause");
|
|
195
|
-
passed++;
|
|
196
|
-
} else {
|
|
197
|
-
console.log(` ✗ .first() with where failed`);
|
|
198
|
-
failed++;
|
|
199
|
-
}
|
|
200
|
-
} catch(err) {
|
|
201
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
202
|
-
failed++;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// Test 7: .first() returns null if no records
|
|
206
|
-
console.log("\n📝 Test 7: .first() returns null if no records");
|
|
207
|
-
console.log("──────────────────────────────────────────────────");
|
|
208
|
-
try {
|
|
209
|
-
const first = await db.User
|
|
210
|
-
.where(u => u.name == $$, 'NonExistent')
|
|
211
|
-
.first();
|
|
212
|
-
|
|
213
|
-
if (first === null) {
|
|
214
|
-
console.log(" ✓ .first() returns null if no records");
|
|
215
|
-
passed++;
|
|
216
|
-
} else {
|
|
217
|
-
console.log(` ✗ .first() should return null`);
|
|
218
|
-
failed++;
|
|
219
|
-
}
|
|
220
|
-
} catch(err) {
|
|
221
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
222
|
-
failed++;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Test 8: .pluck() with ordering
|
|
226
|
-
console.log("\n📝 Test 8: .pluck() respects ordering");
|
|
227
|
-
console.log("──────────────────────────────────────────────────");
|
|
228
|
-
try {
|
|
229
|
-
const names = await db.User
|
|
230
|
-
.orderBy(u => u.name)
|
|
231
|
-
.pluck('name');
|
|
232
|
-
|
|
233
|
-
if (names[0] === 'Alice' && names[4] === 'Eve') {
|
|
234
|
-
console.log(" ✓ .pluck() respects orderBy");
|
|
235
|
-
passed++;
|
|
236
|
-
} else {
|
|
237
|
-
console.log(` ✗ .pluck() ordering failed`);
|
|
238
|
-
failed++;
|
|
239
|
-
}
|
|
240
|
-
} catch(err) {
|
|
241
|
-
console.log(` ✗ Error: ${err.message}`);
|
|
242
|
-
failed++;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Summary
|
|
246
|
-
console.log("\n" + "=".repeat(64));
|
|
247
|
-
console.log(`Test Results: ${passed} passed, ${failed} failed`);
|
|
248
|
-
console.log("=".repeat(64));
|
|
249
|
-
|
|
250
|
-
if (failed > 0) {
|
|
251
|
-
process.exit(1);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
runTests().catch(err => {
|
|
256
|
-
console.error('Fatal error:', err);
|
|
257
|
-
process.exit(1);
|
|
258
|
-
});
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Test for query instance isolation
|
|
3
|
-
* Verifies that accessing an entity multiple times returns fresh queryMethods instances
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
const queryMethods = require('../QueryLanguage/queryMethods');
|
|
7
|
-
const queryScript = require('../QueryLanguage/queryScript');
|
|
8
|
-
|
|
9
|
-
console.log('=== Testing Query Instance Isolation ===\n');
|
|
10
|
-
|
|
11
|
-
// Mock entity
|
|
12
|
-
const mockEntity = {
|
|
13
|
-
__name: 'TestEntity',
|
|
14
|
-
id: { type: 'number' },
|
|
15
|
-
name: { type: 'string' }
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
// Mock context
|
|
19
|
-
const mockContext = {
|
|
20
|
-
__track: () => {},
|
|
21
|
-
__entities: []
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
console.log('Test 1: Creating separate query instances');
|
|
25
|
-
const query1 = new queryMethods(mockEntity, mockContext);
|
|
26
|
-
const query2 = new queryMethods(mockEntity, mockContext);
|
|
27
|
-
|
|
28
|
-
console.log(` Query 1 instance ID: ${query1.__queryObject !== undefined ? 'exists' : 'undefined'}`);
|
|
29
|
-
console.log(` Query 2 instance ID: ${query2.__queryObject !== undefined ? 'exists' : 'undefined'}`);
|
|
30
|
-
console.log(` ✓ Instances are separate: ${query1 !== query2}`);
|
|
31
|
-
console.log(` ✓ QueryObjects are separate: ${query1.__queryObject !== query2.__queryObject}\n`);
|
|
32
|
-
|
|
33
|
-
console.log('Test 2: Building queries with same parameters in different instances');
|
|
34
|
-
query1.where(e => e.id == $$, 1);
|
|
35
|
-
query2.where(e => e.id == $$, 2);
|
|
36
|
-
|
|
37
|
-
const params1 = query1.__queryObject.parameters.get();
|
|
38
|
-
const params2 = query2.__queryObject.parameters.get();
|
|
39
|
-
|
|
40
|
-
console.log(` Query 1 parameters: [${params1}]`);
|
|
41
|
-
console.log(` Query 2 parameters: [${params2}]`);
|
|
42
|
-
|
|
43
|
-
if (params1.length === 1 && params1[0] === 1) {
|
|
44
|
-
console.log(' ✓ Query 1 has correct parameters');
|
|
45
|
-
} else {
|
|
46
|
-
console.error(' ✗ FAIL: Query 1 parameters are wrong!');
|
|
47
|
-
process.exit(1);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
if (params2.length === 1 && params2[0] === 2) {
|
|
51
|
-
console.log(' ✓ Query 2 has correct parameters\n');
|
|
52
|
-
} else {
|
|
53
|
-
console.error(' ✗ FAIL: Query 2 parameters are wrong!');
|
|
54
|
-
process.exit(1);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
console.log('✅ All tests passed! Query instances are properly isolated.\n');
|
|
58
|
-
console.log('Note: This confirms the fix will work. The getter in context.js');
|
|
59
|
-
console.log('now creates a new queryMethods instance each time an entity is accessed.');
|