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,174 +0,0 @@
1
- /**
2
- * Test: Entity Deduplication in dbset()
3
- * Verifies Fix #1 - that calling dbset() multiple times for the same entity
4
- * doesn't create duplicate entries in __entities array
5
- */
6
-
7
- console.log("╔════════════════════════════════════════════════════════════════╗");
8
- console.log("ā•‘ Entity Deduplication Test - dbset() Method ā•‘");
9
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
10
-
11
- let passed = 0;
12
- let failed = 0;
13
-
14
- // Simulate the context class with entity registration functionality
15
- class SimulatedContext {
16
- constructor() {
17
- this.__entities = [];
18
- this.__builderEntities = [];
19
- this.__contextSeedData = {};
20
- }
21
-
22
- dbset(model, tableName = null) {
23
- const entityName = tableName || model.name;
24
-
25
- // Create a simple model object to represent the entity
26
- const validModel = {
27
- __name: entityName,
28
- ...model.schema
29
- };
30
-
31
- // Check if this entity (by table name) is already registered
32
- const existingIndex = this.__entities.findIndex(e => e.__name === entityName);
33
- if (existingIndex !== -1) {
34
- // Entity already exists - update it instead of adding duplicate
35
- console.warn(`Warning: dbset() called multiple times for table '${entityName}' - updating existing registration`);
36
- this.__entities[existingIndex] = validModel;
37
- this.__builderEntities[existingIndex] = { type: 'builder', model: validModel };
38
- } else {
39
- // New entity - add to arrays
40
- this.__entities.push(validModel);
41
- this.__builderEntities.push({ type: 'builder', model: validModel });
42
- }
43
-
44
- // Return chainable object with seed() method
45
- return {
46
- seed: (data) => this.#addSeedData(entityName, data)
47
- };
48
- }
49
-
50
- #addSeedData(tableName, data) {
51
- if (!this.__contextSeedData[tableName]) {
52
- this.__contextSeedData[tableName] = [];
53
- }
54
- const records = Array.isArray(data) ? data : [data];
55
- this.__contextSeedData[tableName].push(...records);
56
-
57
- return {
58
- seed: (moreData) => this.#addSeedData(tableName, moreData)
59
- };
60
- }
61
- }
62
-
63
- // Test entities
64
- class TestEntity {
65
- static name = 'TestEntity';
66
- static schema = {
67
- id: { type: 'int', primary: true },
68
- name: { type: 'string' }
69
- };
70
- }
71
-
72
- class TestEntity2 {
73
- static name = 'TestEntity2';
74
- static schema = {
75
- id: { type: 'int', primary: true },
76
- title: { type: 'string' }
77
- };
78
- }
79
-
80
- function test(description, fn) {
81
- try {
82
- fn();
83
- console.log(`āœ“ ${description}`);
84
- passed++;
85
- } catch (error) {
86
- console.log(`āœ— ${description}`);
87
- console.log(` Error: ${error.message}`);
88
- failed++;
89
- }
90
- }
91
-
92
- function assertEqual(actual, expected, message) {
93
- if (actual !== expected) {
94
- throw new Error(`${message}\n Expected: ${expected}\n Actual: ${actual}`);
95
- }
96
- }
97
-
98
- // =============================================================================
99
- // Test Suite: Entity Deduplication
100
- // =============================================================================
101
- console.log("šŸ“‹ Test Suite: Entity Deduplication in context.__entities\n");
102
-
103
- test('should not duplicate entity when dbset() is called twice', () => {
104
- const ctx = new SimulatedContext();
105
- ctx.dbset(TestEntity);
106
- ctx.dbset(TestEntity); // Second call
107
-
108
- // Should only have 1 entity registered
109
- assertEqual(ctx.__entities.length, 1, 'Should only have 1 entity in __entities');
110
- assertEqual(ctx.__entities[0].__name, 'TestEntity', 'Entity name should be TestEntity');
111
-
112
- // Should only have 1 builder entity
113
- assertEqual(ctx.__builderEntities.length, 1, 'Should only have 1 builder entity');
114
- });
115
-
116
- test('should update existing entity when dbset() is called multiple times', () => {
117
- const ctx = new SimulatedContext();
118
- ctx.dbset(TestEntity);
119
- // Register again (would update)
120
- ctx.dbset(TestEntity);
121
-
122
- // Verify entity was updated, not duplicated
123
- assertEqual(ctx.__entities.length, 1, 'Should only have 1 entity after update');
124
- assertEqual(ctx.__entities[0].__name, 'TestEntity', 'Updated entity should have correct name');
125
- });
126
-
127
- test('should handle the qaContext pattern (dbset then dbset.seed)', () => {
128
- const ctx = new SimulatedContext();
129
- ctx.dbset(TestEntity); // Line 58 pattern
130
- ctx.dbset(TestEntity).seed([{ id: 1, name: 'Test' }]); // Line 207 pattern
131
-
132
- // Should only have 1 entity despite two dbset() calls
133
- assertEqual(ctx.__entities.length, 1, 'Should only have 1 entity with qaContext pattern');
134
- assertEqual(ctx.__entities[0].__name, 'TestEntity', 'Entity name should be TestEntity');
135
- });
136
-
137
- test('should allow different entities to be registered separately', () => {
138
- const ctx = new SimulatedContext();
139
- ctx.dbset(TestEntity);
140
- ctx.dbset(TestEntity2);
141
-
142
- // Should have 2 different entities
143
- assertEqual(ctx.__entities.length, 2, 'Should have 2 different entities');
144
- assertEqual(ctx.__entities[0].__name, 'TestEntity', 'First entity should be TestEntity');
145
- assertEqual(ctx.__entities[1].__name, 'TestEntity2', 'Second entity should be TestEntity2');
146
- });
147
-
148
- test('should emit warning when dbset() is called multiple times for same entity', () => {
149
- let warningEmitted = false;
150
- const originalWarn = console.warn;
151
- console.warn = function(msg) {
152
- if (msg.includes('dbset() called multiple times for table')) {
153
- warningEmitted = true;
154
- }
155
- };
156
-
157
- const ctx = new SimulatedContext();
158
- ctx.dbset(TestEntity);
159
- ctx.dbset(TestEntity); // Should emit warning
160
-
161
- console.warn = originalWarn;
162
-
163
- assertEqual(warningEmitted, true, 'Should emit warning when dbset() called multiple times');
164
- });
165
-
166
- // =============================================================================
167
- // Summary
168
- // =============================================================================
169
- console.log("\n" + "═".repeat(64));
170
- console.log(`\nāœ… Passed: ${passed}`);
171
- console.log(`āŒ Failed: ${failed}`);
172
- console.log(`\nTotal: ${passed + failed} tests\n`);
173
-
174
- process.exit(failed > 0 ? 1 : 0);
@@ -1,269 +0,0 @@
1
- /**
2
- * Test: Entity Instance Methods
3
- * Tests: .toObject(), .toJSON(), .delete(), .reload(), .clone()
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("ā•‘ Entity Instance 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
- Tags(db) {
29
- db.hasMany('Tag', 'user_id').nullable();
30
- }
31
- }
32
-
33
- class Tag {
34
- id(db) {
35
- db.integer().primary().auto();
36
- }
37
- name(db) {
38
- db.string();
39
- }
40
- user_id(db) {
41
- db.integer();
42
- }
43
- User(db) {
44
- db.belongsTo('User', 'user_id').nullable();
45
- }
46
- }
47
-
48
- // Create test context
49
- class TestContext extends masterrecord.context {
50
- constructor() {
51
- super();
52
- }
53
- onConfig(db) {
54
- this.dbset(User);
55
- this.dbset(Tag);
56
- }
57
- }
58
-
59
- // Clean test database
60
- const dbPath = path.join(__dirname, '..', 'database', 'testEntityMethods.db');
61
- if (fs.existsSync(dbPath)) {
62
- fs.unlinkSync(dbPath);
63
- }
64
-
65
- async function runTests() {
66
- const db = new TestContext();
67
-
68
- // Initialize SQLite database
69
- const SQLLiteEngine = require('../SQLLiteEngine');
70
- const sqlite3 = require('better-sqlite3');
71
- db.isSQLite = true;
72
- db.isMySQL = false;
73
- db.isPostgres = false;
74
- db._SQLEngine = new SQLLiteEngine();
75
- db.db = new sqlite3(dbPath);
76
- db._SQLEngine.setDB(db.db, 'better-sqlite3');
77
-
78
- db.onConfig();
79
-
80
- // Create tables
81
- db.db.exec('CREATE TABLE IF NOT EXISTS User (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)');
82
- db.db.exec('CREATE TABLE IF NOT EXISTS Tag (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, user_id INTEGER)');
83
-
84
- // Test 1: .toObject() converts entity to plain object
85
- console.log("šŸ“ Test 1: .toObject() converts entity to plain object");
86
- console.log("──────────────────────────────────────────────────");
87
- try {
88
- const user = db.User.new();
89
- user.name = 'Alice';
90
- user.email = 'alice@example.com';
91
- await user.save();
92
-
93
- const plain = user.toObject();
94
-
95
- if (plain.name === 'Alice' &&
96
- plain.email === 'alice@example.com' &&
97
- plain.__context === undefined &&
98
- plain.__entity === undefined) {
99
- console.log(" āœ“ .toObject() converts entity to plain object");
100
- console.log(" āœ“ Internal properties stripped");
101
- passed++;
102
- } else {
103
- console.log(` āœ— .toObject() failed - unexpected output`);
104
- failed++;
105
- }
106
- } catch(err) {
107
- console.log(` āœ— Error: ${err.message}`);
108
- failed++;
109
- }
110
-
111
- // Test 2: .toJSON() works with JSON.stringify
112
- console.log("\nšŸ“ Test 2: .toJSON() works with JSON.stringify");
113
- console.log("──────────────────────────────────────────────────");
114
- try {
115
- const user = db.User.new();
116
- user.name = 'Bob';
117
- user.email = 'bob@example.com';
118
- await user.save();
119
-
120
- const json = JSON.stringify(user);
121
- const parsed = JSON.parse(json);
122
-
123
- if (parsed.name === 'Bob' &&
124
- parsed.email === 'bob@example.com' &&
125
- parsed.__context === undefined) {
126
- console.log(" āœ“ JSON.stringify() works without errors");
127
- console.log(" āœ“ Circular references prevented");
128
- passed++;
129
- } else {
130
- console.log(` āœ— JSON.stringify() failed`);
131
- failed++;
132
- }
133
- } catch(err) {
134
- console.log(` āœ— Error: ${err.message}`);
135
- failed++;
136
- }
137
-
138
- // Test 3: .delete() removes entity
139
- console.log("\nšŸ“ Test 3: .delete() removes entity from database");
140
- console.log("──────────────────────────────────────────────────");
141
- try {
142
- const user = db.User.new();
143
- user.name = 'ToDelete';
144
- user.email = 'delete@example.com';
145
- await user.save();
146
-
147
- const id = user.id;
148
- if (!id) {
149
- console.log(` āœ— .delete() test skipped - user.id is undefined after save`);
150
- failed++;
151
- } else {
152
- await user.delete();
153
-
154
- const check = await db.User.findById(id);
155
-
156
- if (check === null) {
157
- console.log(" āœ“ .delete() removes entity from database");
158
- passed++;
159
- } else {
160
- console.log(` āœ— .delete() failed - entity still exists`);
161
- failed++;
162
- }
163
- }
164
- } catch(err) {
165
- console.log(` āœ— Error: ${err.message}`);
166
- failed++;
167
- }
168
-
169
- // Test 4: .reload() refreshes entity from database
170
- console.log("\nšŸ“ Test 4: .reload() refreshes entity from database");
171
- console.log("──────────────────────────────────────────────────");
172
- try {
173
- const user = db.User.new();
174
- user.name = 'Original';
175
- user.email = 'original@example.com';
176
- await user.save();
177
-
178
- // Modify in-memory
179
- user.name = 'Modified';
180
-
181
- // Reload
182
- await user.reload();
183
-
184
- if (user.name === 'Original' && user.__dirtyFields.length === 0) {
185
- console.log(" āœ“ .reload() refreshes entity from database");
186
- console.log(" āœ“ Dirty fields reset");
187
- passed++;
188
- } else {
189
- console.log(` āœ— .reload() failed - name: ${user.name}`);
190
- failed++;
191
- }
192
- } catch(err) {
193
- console.log(` āœ— Error: ${err.message}`);
194
- failed++;
195
- }
196
-
197
- // Test 5: .clone() creates copy without primary key
198
- console.log("\nšŸ“ Test 5: .clone() creates copy without primary key");
199
- console.log("──────────────────────────────────────────────────");
200
- try {
201
- const user = db.User.new();
202
- user.name = 'Original';
203
- user.email = 'original@example.com';
204
- await user.save();
205
-
206
- const originalId = user.id;
207
- const cloned = user.clone();
208
- cloned.name = 'Cloned';
209
- cloned.email = 'cloned@example.com';
210
- await cloned.save();
211
-
212
- if (cloned.id !== originalId && cloned.name === 'Cloned') {
213
- console.log(" āœ“ .clone() creates copy with new primary key");
214
- console.log(" āœ“ Original entity unchanged");
215
- passed++;
216
- } else {
217
- console.log(` āœ— .clone() failed`);
218
- failed++;
219
- }
220
- } catch(err) {
221
- console.log(` āœ— Error: ${err.message}`);
222
- failed++;
223
- }
224
-
225
- // Test 6: .toObject() with relationships
226
- console.log("\nšŸ“ Test 6: .toObject() with relationships");
227
- console.log("──────────────────────────────────────────────────");
228
- try {
229
- const user = db.User.new();
230
- user.name = 'Charlie';
231
- user.email = 'charlie@example.com';
232
- await user.save();
233
-
234
- const tag = db.Tag.new();
235
- tag.name = 'Important';
236
- tag.user_id = user.id;
237
- await tag.save();
238
-
239
- const freshUser = await db.User.findById(user.id);
240
- const tags = await freshUser.Tags;
241
-
242
- const plain = freshUser.toObject({ includeRelationships: true });
243
-
244
- if (Array.isArray(plain.Tags) && plain.Tags.length === 1 && plain.Tags[0].name === 'Important') {
245
- console.log(" āœ“ .toObject() includes relationships when requested");
246
- passed++;
247
- } else {
248
- console.log(` āœ— .toObject() failed to include relationships`);
249
- failed++;
250
- }
251
- } catch(err) {
252
- console.log(` āœ— Error: ${err.message}`);
253
- failed++;
254
- }
255
-
256
- // Summary
257
- console.log("\n" + "=".repeat(64));
258
- console.log(`Test Results: ${passed} passed, ${failed} failed`);
259
- console.log("=".repeat(64));
260
-
261
- if (failed > 0) {
262
- process.exit(1);
263
- }
264
- }
265
-
266
- runTests().catch(err => {
267
- console.error('Fatal error:', err);
268
- process.exit(1);
269
- });
@@ -1,227 +0,0 @@
1
- /**
2
- * Test: .findById() Convenience Method
3
- *
4
- * Adds a common helper method that other ORMs provide
5
- *
6
- * Usage:
7
- * const user = context.User.findById(123);
8
- *
9
- * Equivalent to:
10
- * const user = context.User.where(u => u.id == $$, 123).single();
11
- */
12
-
13
- const queryMethods = require('../QueryLanguage/queryMethods');
14
-
15
- console.log("╔════════════════════════════════════════════════════════════════╗");
16
- console.log("ā•‘ .findById() Method Test ā•‘");
17
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
18
-
19
- let passed = 0;
20
- let failed = 0;
21
-
22
- // Test 1: Verify .findById() method exists
23
- console.log("šŸ“ Test 1: Verify .findById() method exists");
24
- console.log("──────────────────────────────────────────────────");
25
-
26
- try {
27
- const hasFindById = typeof queryMethods.prototype.findById === 'function';
28
-
29
- if(hasFindById) {
30
- console.log(" āœ“ .findById() method exists");
31
- console.log(" āœ“ Method is a function");
32
- passed++;
33
- } else {
34
- console.log(` āœ— .findById() method not found`);
35
- failed++;
36
- }
37
- } catch(err) {
38
- console.log(` āœ— Error: ${err.message}`);
39
- failed++;
40
- }
41
-
42
- // Test 2: Test primary key detection
43
- console.log("\nšŸ“ Test 2: Primary key detection");
44
- console.log("──────────────────────────────────────────────────");
45
-
46
- try {
47
- // Mock entity with primary key
48
- const mockEntity = {
49
- __name: 'User',
50
- id: { type: 'integer', primary: true, auto: true },
51
- name: { type: 'string', nullable: false },
52
- email: { type: 'string', nullable: false }
53
- };
54
-
55
- // Find the primary key
56
- let primaryKeyField = null;
57
- for (const fieldName in mockEntity) {
58
- const field = mockEntity[fieldName];
59
- if (field && field.primary === true) {
60
- primaryKeyField = fieldName;
61
- break;
62
- }
63
- }
64
-
65
- if(primaryKeyField === 'id') {
66
- console.log(" āœ“ Primary key detected: 'id'");
67
- console.log(" āœ“ Correctly identified from entity definition");
68
- passed++;
69
- } else {
70
- console.log(` āœ— Expected 'id', got '${primaryKeyField}'`);
71
- failed++;
72
- }
73
- } catch(err) {
74
- console.log(` āœ— Error: ${err.message}`);
75
- failed++;
76
- }
77
-
78
- // Test 3: Test with entity without primary key
79
- console.log("\nšŸ“ Test 3: Entity without primary key (should error)");
80
- console.log("──────────────────────────────────────────────────");
81
-
82
- try {
83
- const mockEntity = {
84
- __name: 'NoPrimaryKey',
85
- name: { type: 'string' },
86
- email: { type: 'string' }
87
- };
88
-
89
- const mockContext = {
90
- __trackedEntities: [],
91
- __track: function(entity) { return entity; },
92
- isSQLite: true,
93
- _SQLEngine: { get: () => null }
94
- };
95
-
96
- const qm = new queryMethods(mockEntity, mockContext);
97
-
98
- try {
99
- qm.findById(123);
100
- console.log(" āœ— Should have thrown error for missing primary key");
101
- failed++;
102
- } catch(err) {
103
- if(err.message.includes('No primary key defined')) {
104
- console.log(" āœ“ Correctly throws error for missing primary key");
105
- console.log(` āœ“ Error message: ${err.message}`);
106
- passed++;
107
- } else {
108
- console.log(` āœ— Wrong error: ${err.message}`);
109
- failed++;
110
- }
111
- }
112
- } catch(err) {
113
- console.log(` āœ— Unexpected error: ${err.message}`);
114
- failed++;
115
- }
116
-
117
- // Test 4: Test where clause generation
118
- console.log("\nšŸ“ Test 4: WHERE clause generation");
119
- console.log("──────────────────────────────────────────────────");
120
-
121
- try {
122
- // Simulate the where clause that should be generated
123
- const entityParam = 'r';
124
- const primaryKeyField = 'id';
125
- const whereClause = `${entityParam} => ${entityParam}.${primaryKeyField} == $$`;
126
-
127
- const expectedClause = 'r => r.id == $$';
128
-
129
- if(whereClause === expectedClause) {
130
- console.log(" āœ“ WHERE clause generated correctly");
131
- console.log(` āœ“ Generated: "${whereClause}"`);
132
- console.log(" āœ“ Will be processed by .where() method");
133
- passed++;
134
- } else {
135
- console.log(` āœ— Expected '${expectedClause}', got '${whereClause}'`);
136
- failed++;
137
- }
138
- } catch(err) {
139
- console.log(` āœ— Error: ${err.message}`);
140
- failed++;
141
- }
142
-
143
- // Test 5: Different primary key names
144
- console.log("\nšŸ“ Test 5: Different primary key field names");
145
- console.log("──────────────────────────────────────────────────");
146
-
147
- try {
148
- const entities = [
149
- { name: 'User', pk: 'id' },
150
- { name: 'Post', pk: 'post_id' },
151
- { name: 'Comment', pk: 'comment_id' }
152
- ];
153
-
154
- let allCorrect = true;
155
-
156
- entities.forEach(({ name, pk }) => {
157
- const mockEntity = {
158
- __name: name,
159
- [pk]: { type: 'integer', primary: true }
160
- };
161
-
162
- let primaryKeyField = null;
163
- for (const fieldName in mockEntity) {
164
- const field = mockEntity[fieldName];
165
- if (field && field.primary === true) {
166
- primaryKeyField = fieldName;
167
- break;
168
- }
169
- }
170
-
171
- if(primaryKeyField === pk) {
172
- console.log(` āœ“ ${name}: Primary key '${pk}' detected`);
173
- } else {
174
- console.log(` āœ— ${name}: Expected '${pk}', got '${primaryKeyField}'`);
175
- allCorrect = false;
176
- }
177
- });
178
-
179
- if(allCorrect) {
180
- passed++;
181
- } else {
182
- failed++;
183
- }
184
- } catch(err) {
185
- console.log(` āœ— Error: ${err.message}`);
186
- failed++;
187
- }
188
-
189
- // Summary
190
- console.log("\n\n╔════════════════════════════════════════════════════════════════╗");
191
- console.log("ā•‘ Test Summary ā•‘");
192
- console.log("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•");
193
-
194
- const total = passed + failed;
195
- const successRate = total > 0 ? Math.round((passed/total)*100) : 0;
196
-
197
- console.log(`\n Total Tests: ${total}`);
198
- console.log(` āœ… Passed: ${passed}`);
199
- console.log(` āŒ Failed: ${failed}`);
200
- console.log(` Success Rate: ${successRate}%\n`);
201
-
202
- if(failed === 0){
203
- console.log("šŸŽ‰ All .findById() tests passed!");
204
- console.log("\n✨ Convenience Method Added!");
205
- console.log("\nšŸ“– Usage:");
206
- console.log(" // Simple and familiar syntax");
207
- console.log(" const user = context.User.findById(123);");
208
- console.log("\nšŸ“– Equivalent To:");
209
- console.log(" // Standard MasterRecord syntax");
210
- console.log(" const user = context.User.where(u => u.id == $$, 123).single();");
211
- console.log("\nšŸ“– Features:");
212
- console.log(" - Automatically detects primary key field");
213
- console.log(" - Works with any primary key name (id, user_id, etc.)");
214
- console.log(" - Returns single record or null");
215
- console.log(" - Validates entity has a primary key");
216
- console.log(" - Compatible with all database engines");
217
- console.log("\nšŸ“– Supported Primary Key Names:");
218
- console.log(" āœ… id");
219
- console.log(" āœ… user_id");
220
- console.log(" āœ… post_id");
221
- console.log(" āœ… Any field marked with primary: true");
222
- console.log("\nāœ… Now matches familiar ORM syntax from Mongoose, Sequelize, etc!\n");
223
- process.exit(0);
224
- } else {
225
- console.log("āš ļø Some tests failed. Review implementation.");
226
- process.exit(1);
227
- }