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,202 +0,0 @@
1
- /**
2
- * Validation Test: Auto-Increment ID Setting
3
- *
4
- * Confirms the critical bug fix: IDs are properly set back on entities after insert
5
- * Tests both single and batch insert paths
6
- */
7
-
8
- const masterrecord = require('../MasterRecord.js');
9
- const path = require('path');
10
- const fs = require('fs');
11
-
12
- console.log("╔════════════════════════════════════════════════════════════════╗");
13
- console.log("║ Auto-Increment ID Setting Validation Test ║");
14
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
15
-
16
- let passed = 0;
17
- let failed = 0;
18
-
19
- class User {
20
- id(db) {
21
- db.integer().primary().auto();
22
- }
23
- name(db) {
24
- db.string();
25
- }
26
- }
27
-
28
- class TestContext extends masterrecord.context {
29
- constructor() {
30
- super();
31
- }
32
- onConfig(db) {
33
- this.dbset(User);
34
- }
35
- }
36
-
37
- const dbPath = path.join(__dirname, '..', 'database', 'idValidation.db');
38
- if (fs.existsSync(dbPath)) {
39
- fs.unlinkSync(dbPath);
40
- }
41
-
42
- async function runTests() {
43
- const db = new TestContext();
44
-
45
- // Initialize SQLite database
46
- const SQLLiteEngine = require('../SQLLiteEngine');
47
- const sqlite3 = require('better-sqlite3');
48
- db.isSQLite = true;
49
- db.isMySQL = false;
50
- db.isPostgres = false;
51
- db._SQLEngine = new SQLLiteEngine();
52
- db.db = new sqlite3(dbPath);
53
- db._SQLEngine.setDB(db.db, 'better-sqlite3');
54
-
55
- db.onConfig();
56
-
57
- // Create table
58
- db.db.exec('CREATE TABLE IF NOT EXISTS User (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)');
59
-
60
- // Test 1: Single insert sets ID
61
- console.log("📝 Test 1: Single insert sets ID (insertManager path)");
62
- console.log("──────────────────────────────────────────────────");
63
- try {
64
- const user1 = db.User.new();
65
- user1.name = 'User 1';
66
- await user1.save();
67
-
68
- if (user1.id === 1) {
69
- console.log(" ✓ Single insert: ID = 1");
70
- passed++;
71
- } else {
72
- console.log(` ✗ Single insert: ID = ${user1.id} (expected 1)`);
73
- failed++;
74
- }
75
- } catch(err) {
76
- console.log(` ✗ Error: ${err.message}`);
77
- failed++;
78
- }
79
-
80
- // Test 2: Batch insert sets IDs (2 entities triggers bulkInsert path)
81
- console.log("\n📝 Test 2: Batch insert sets IDs (bulkInsert path)");
82
- console.log("──────────────────────────────────────────────────");
83
- try {
84
- const user2 = db.User.new();
85
- user2.name = 'User 2';
86
-
87
- const user3 = db.User.new();
88
- user3.name = 'User 3';
89
-
90
- await db.saveChanges(); // Batch insert
91
-
92
- if (user2.id === 2 && user3.id === 3) {
93
- console.log(" ✓ Batch insert: IDs = 2, 3");
94
- passed++;
95
- } else {
96
- console.log(` ✗ Batch insert: IDs = ${user2.id}, ${user3.id} (expected 2, 3)`);
97
- failed++;
98
- }
99
- } catch(err) {
100
- console.log(` ✗ Error: ${err.message}`);
101
- failed++;
102
- }
103
-
104
- // Test 3: Multiple batch inserts
105
- console.log("\n📝 Test 3: Multiple batch inserts maintain sequence");
106
- console.log("──────────────────────────────────────────────────");
107
- try {
108
- const users = [];
109
- for (let i = 0; i < 5; i++) {
110
- const user = db.User.new();
111
- user.name = `Batch User ${i}`;
112
- users.push(user);
113
- }
114
-
115
- await db.saveChanges();
116
-
117
- const ids = users.map(u => u.id);
118
- const expectedIds = [4, 5, 6, 7, 8];
119
- const allCorrect = ids.every((id, idx) => id === expectedIds[idx]);
120
-
121
- if (allCorrect) {
122
- console.log(" ✓ Batch insert: IDs = [4, 5, 6, 7, 8]");
123
- passed++;
124
- } else {
125
- console.log(` ✗ Batch insert: IDs = [${ids.join(', ')}] (expected [4, 5, 6, 7, 8])`);
126
- failed++;
127
- }
128
- } catch(err) {
129
- console.log(` ✗ Error: ${err.message}`);
130
- failed++;
131
- }
132
-
133
- // Test 4: ID available immediately after save()
134
- console.log("\n📝 Test 4: ID available immediately after save()");
135
- console.log("──────────────────────────────────────────────────");
136
- try {
137
- const user = db.User.new();
138
- user.name = 'Immediate ID Test';
139
-
140
- const idBefore = user.id;
141
- await user.save();
142
- const idAfter = user.id;
143
-
144
- if (idBefore === undefined && idAfter === 9) {
145
- console.log(" ✓ ID undefined before save, set to 9 after save");
146
- passed++;
147
- } else {
148
- console.log(` ✗ ID before: ${idBefore}, after: ${idAfter} (expected undefined, 9)`);
149
- failed++;
150
- }
151
- } catch(err) {
152
- console.log(` ✗ Error: ${err.message}`);
153
- failed++;
154
- }
155
-
156
- // Test 5: Can use ID immediately for relationships
157
- console.log("\n📝 Test 5: Can use ID immediately for relationships");
158
- console.log("──────────────────────────────────────────────────");
159
- try {
160
- const parent = db.User.new();
161
- parent.name = 'Parent';
162
- await parent.save();
163
-
164
- // Should be able to use parent.id immediately
165
- const parentId = parent.id;
166
-
167
- if (typeof parentId === 'number' && parentId === 10) {
168
- console.log(" ✓ ID available for immediate use: 10");
169
- passed++;
170
- } else {
171
- console.log(` ✗ ID not available: ${parentId}`);
172
- failed++;
173
- }
174
- } catch(err) {
175
- console.log(` ✗ Error: ${err.message}`);
176
- failed++;
177
- }
178
-
179
- // Summary
180
- console.log("\n" + "=".repeat(64));
181
- console.log(`Test Results: ${passed} passed, ${failed} failed`);
182
- console.log("=".repeat(64));
183
-
184
- if (failed === 0) {
185
- console.log("\n✅ ALL TESTS PASSED - ID setting bug is FIXED!");
186
- console.log("Auto-increment IDs are properly set for:");
187
- console.log(" • Single inserts (insertManager path)");
188
- console.log(" • Batch inserts (bulkInsert path)");
189
- console.log(" • Multiple sequential operations");
190
- } else {
191
- console.log("\n❌ SOME TESTS FAILED - Review output above");
192
- }
193
-
194
- if (failed > 0) {
195
- process.exit(1);
196
- }
197
- }
198
-
199
- runTests().catch(err => {
200
- console.error('Fatal error:', err);
201
- process.exit(1);
202
- });
@@ -1,183 +0,0 @@
1
- /**
2
- * Test: .includes() Feature
3
- *
4
- * This test demonstrates the new .includes() syntax that allows
5
- * natural JavaScript array operations in queries.
6
- *
7
- * Example: const ids = [1, 2, 3];
8
- * context.User.where(u => $$.includes(u.id), ids).toList()
9
- */
10
-
11
- // Create in-memory test models
12
- class User {
13
- constructor(){
14
- this.id = { type: "integer", primary: true, auto: true };
15
- this.name = { type: "string" };
16
- this.__name = "User";
17
- }
18
- }
19
-
20
- class TestContext {
21
- constructor(){
22
- this.isSQLite = true;
23
- this.isMySQL = false;
24
- this.isPostgres = false;
25
-
26
- // Mock database
27
- this.db = {
28
- prepare: (sql) => {
29
- console.log("\n🔍 Generated SQL:", sql);
30
- return {
31
- all: (...params) => {
32
- console.log("📦 Parameters:", params);
33
- // Return mock data
34
- return [
35
- { id: 1, name: "Alice" },
36
- { id: 2, name: "Bob" },
37
- { id: 5, name: "Charlie" }
38
- ];
39
- },
40
- get: (...params) => {
41
- console.log("📦 Parameters:", params);
42
- return { id: 1, name: "Alice" };
43
- }
44
- };
45
- }
46
- };
47
-
48
- // Track entities
49
- this.trackedEntities = [];
50
- this.__track = (entity) => {
51
- this.trackedEntities.push(entity);
52
- };
53
-
54
- // Mock SQL engine
55
- this._SQLEngine = {
56
- all: (script, entity, context) => {
57
- console.log("\n📊 Query Script:", JSON.stringify(script, null, 2));
58
- return [];
59
- },
60
- get: (script, entity, context) => {
61
- console.log("\n📊 Query Script:", JSON.stringify(script, null, 2));
62
- return null;
63
- }
64
- };
65
- }
66
-
67
- dbset(model, name){
68
- const queryMethods = require('../QueryLanguage/queryMethods');
69
- const entity = new model();
70
- return new queryMethods(entity, this);
71
- }
72
- }
73
-
74
- // Run tests
75
- console.log("╔════════════════════════════════════════════════════════════════╗");
76
- console.log("║ .includes() Feature Test Suite ║");
77
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
78
-
79
- try {
80
- const context = new TestContext();
81
- const userSet = context.dbset(User, "User");
82
-
83
- // Test 1: Basic .includes() with integer array
84
- console.log("📝 Test 1: Basic .includes() with integer array");
85
- console.log("──────────────────────────────────────────────");
86
- const userIds = [1, 2, 5];
87
- console.log("Input: const userIds = [1, 2, 5];");
88
- console.log("Query: context.User.where(u => $$.includes(u.id), userIds).toList()");
89
-
90
- try {
91
- const result1 = userSet.where(u => $$.includes(u.id), userIds).toList();
92
- console.log("✅ Test 1 PASSED - No errors thrown");
93
- } catch(err) {
94
- console.log("❌ Test 1 FAILED:", err.message);
95
- console.log(err.stack);
96
- }
97
-
98
- // Test 2: .includes() with string array
99
- console.log("\n\n📝 Test 2: .includes() with string array");
100
- console.log("──────────────────────────────────────────────");
101
- const names = ["Alice", "Bob", "Charlie"];
102
- console.log("Input: const names = ['Alice', 'Bob', 'Charlie'];");
103
- console.log("Query: context.User.where(u => $$.includes(u.name), names).toList()");
104
-
105
- try {
106
- const result2 = userSet.where(u => $$.includes(u.name), names).toList();
107
- console.log("✅ Test 2 PASSED - No errors thrown");
108
- } catch(err) {
109
- console.log("❌ Test 2 FAILED:", err.message);
110
- console.log(err.stack);
111
- }
112
-
113
- // Test 3: Combined .includes() with other conditions
114
- console.log("\n\n📝 Test 3: Combined .includes() with AND condition");
115
- console.log("──────────────────────────────────────────────");
116
- const ids = [1, 2, 3];
117
- console.log("Input: const ids = [1, 2, 3];");
118
- console.log("Query: context.User.where(u => $$.includes(u.id), ids)");
119
- console.log(" .and(u => u.name != $$, 'Admin')");
120
- console.log(" .toList()");
121
-
122
- try {
123
- const result3 = userSet
124
- .where(u => $$.includes(u.id), ids)
125
- .and(u => u.name != $$, 'Admin')
126
- .toList();
127
- console.log("✅ Test 3 PASSED - No errors thrown");
128
- } catch(err) {
129
- console.log("❌ Test 3 FAILED:", err.message);
130
- console.log(err.stack);
131
- }
132
-
133
- // Test 4: Empty array (should fail with proper error)
134
- console.log("\n\n📝 Test 4: Empty array (should throw error)");
135
- console.log("──────────────────────────────────────────────");
136
- const emptyArray = [];
137
- console.log("Input: const emptyArray = [];");
138
- console.log("Query: context.User.where(u => $$.includes(u.id), emptyArray).toList()");
139
-
140
- try {
141
- const result4 = userSet.where(u => $$.includes(u.id), emptyArray).toList();
142
- console.log("❌ Test 4 FAILED - Should have thrown error for empty array");
143
- } catch(err) {
144
- if(err.message.includes('empty array')){
145
- console.log("✅ Test 4 PASSED - Correctly rejected empty array");
146
- console.log(" Error message:", err.message);
147
- } else {
148
- console.log("⚠️ Test 4 PARTIAL - Threw error but wrong message:", err.message);
149
- }
150
- }
151
-
152
- // Test 5: Security test - array with special characters
153
- console.log("\n\n📝 Test 5: Security - Array with special SQL characters");
154
- console.log("──────────────────────────────────────────────");
155
- const maliciousNames = ["Alice'; DROP TABLE User;--", "Bob", "Charlie"];
156
- console.log("Input: const maliciousNames = [\"Alice'; DROP TABLE User;--\", \"Bob\", \"Charlie\"];");
157
- console.log("Query: context.User.where(u => $$.includes(u.name), maliciousNames).toList()");
158
-
159
- try {
160
- const result5 = userSet.where(u => $$.includes(u.name), maliciousNames).toList();
161
- console.log("✅ Test 5 PASSED - Parameters properly escaped (no SQL injection)");
162
- } catch(err) {
163
- console.log("❌ Test 5 FAILED:", err.message);
164
- console.log(err.stack);
165
- }
166
-
167
- // Summary
168
- console.log("\n\n╔════════════════════════════════════════════════════════════════╗");
169
- console.log("║ Test Summary ║");
170
- console.log("╚════════════════════════════════════════════════════════════════╝");
171
- console.log("\n✨ .includes() feature implementation complete!");
172
- console.log("\n📖 Usage Guide:");
173
- console.log(" Instead of: context.User.where(u => u.id.any($$), '1,2,3')");
174
- console.log(" You can now: context.User.where(u => $$.includes(u.id), [1, 2, 3])");
175
- console.log("\n🔒 Security: All array values are properly parameterized");
176
- console.log(" preventing SQL injection attacks.");
177
-
178
- } catch(err) {
179
- console.log("\n❌ CRITICAL ERROR:", err.message);
180
- console.log(err.stack);
181
- }
182
-
183
- console.log("\n");
@@ -1,110 +0,0 @@
1
- /**
2
- * Unit Test: .includes() Transformation Logic
3
- *
4
- * This test verifies the __transformIncludes method correctly transforms
5
- * JavaScript .includes() syntax to MasterRecord's .any() syntax.
6
- */
7
-
8
- // Simple mock of the transformation method
9
- function __transformIncludes(str, args){
10
- // Pattern: $$.includes(entity.field) or $$.includes(entity.field.nested)
11
- const includesPattern = /\$\$\.includes\s*\(\s*([\w\d$_]+)\.([.\w\d_]+)\s*\)/g;
12
-
13
- // Use replace with a function - when using a function, return value is used literally
14
- const transformedStr = str.replace(includesPattern, (match, entity, field) => {
15
- // Transform to .any() syntax: entity.field.any($$)
16
- return entity + '.' + field + '.any($$)';
17
- });
18
-
19
- return { query: transformedStr, args: args };
20
- }
21
-
22
- // Test cases
23
- const tests = [
24
- {
25
- name: "Basic .includes() with simple field",
26
- input: "u => $$.includes(u.id)",
27
- expected: "u => u.id.any($$)",
28
- args: [[1, 2, 3]]
29
- },
30
- {
31
- name: ".includes() with string field",
32
- input: "u => $$.includes(u.name)",
33
- expected: "u => u.name.any($$)",
34
- args: [["Alice", "Bob"]]
35
- },
36
- {
37
- name: ".includes() with spaces",
38
- input: "u => $$.includes( u.id )",
39
- expected: "u => u.id.any($$)",
40
- args: [[1, 2, 3]]
41
- },
42
- {
43
- name: ".includes() in complex query",
44
- input: "u => $$.includes(u.id) && u.active == true",
45
- expected: "u => u.id.any($$) && u.active == true",
46
- args: [[1, 2, 3]]
47
- },
48
- {
49
- name: "Multiple .includes() in same query",
50
- input: "u => $$.includes(u.id) && $$.includes(u.role_id)",
51
- expected: "u => u.id.any($$) && u.role_id.any($$)",
52
- args: [[1, 2, 3], [10, 20]]
53
- },
54
- {
55
- name: "No .includes() - should not change",
56
- input: "u => u.id == $$",
57
- expected: "u => u.id == $$",
58
- args: [5]
59
- },
60
- {
61
- name: ".includes() with nested field path",
62
- input: "u => $$.includes(u.profile_id)",
63
- expected: "u => u.profile_id.any($$)",
64
- args: [[100, 200, 300]]
65
- }
66
- ];
67
-
68
- // Run tests
69
- console.log("╔════════════════════════════════════════════════════════════════╗");
70
- console.log("║ .includes() Transformation Unit Tests ║");
71
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
72
-
73
- let passed = 0;
74
- let failed = 0;
75
-
76
- for(const test of tests){
77
- console.log(`📝 ${test.name}`);
78
- console.log(` Input: ${test.input}`);
79
- console.log(` Expected: ${test.expected}`);
80
-
81
- const result = __transformIncludes(test.input, test.args);
82
-
83
- if(result.query === test.expected){
84
- console.log(` ✅ PASS - Got: ${result.query}\n`);
85
- passed++;
86
- } else {
87
- console.log(` ❌ FAIL - Got: ${result.query}\n`);
88
- failed++;
89
- }
90
- }
91
-
92
- // Summary
93
- console.log("╔════════════════════════════════════════════════════════════════╗");
94
- console.log("║ Test Summary ║");
95
- console.log("╚════════════════════════════════════════════════════════════════╝");
96
- console.log(` Total: ${tests.length} tests`);
97
- console.log(` ✅ Passed: ${passed}`);
98
- console.log(` ❌ Failed: ${failed}`);
99
- console.log(` Success Rate: ${Math.round((passed/tests.length)*100)}%\n`);
100
-
101
- if(failed === 0){
102
- console.log("🎉 All transformation tests passed!");
103
- console.log("\n📖 The .includes() feature is ready to use:");
104
- console.log(" const ids = [1, 2, 3];");
105
- console.log(" context.User.where(u => $$.includes(u.id), ids).toList()");
106
- process.exit(0);
107
- } else {
108
- console.log("⚠️ Some tests failed. Review the transformation logic.");
109
- process.exit(1);
110
- }
@@ -1,188 +0,0 @@
1
- /**
2
- * Test: Index Bug Fix - createTable should not generate "undefined undefined NOT NULL"
3
- *
4
- * Verifies that .index() method doesn't cause malformed column definitions in CREATE TABLE statements
5
- */
6
-
7
- console.log("╔════════════════════════════════════════════════════════════════╗");
8
- console.log("║ Index Bug Fix Test - createTable() Method ║");
9
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
10
-
11
- const MigrationSQLiteQuery = require('../Migrations/migrationSQLiteQuery.js');
12
- const MigrationMySQLQuery = require('../Migrations/migrationMySQLQuery.js');
13
- const MigrationPostgresQuery = require('../Migrations/migrationPostgresQuery.js');
14
-
15
- let passed = 0;
16
- let failed = 0;
17
-
18
- function assert(condition, message) {
19
- if (!condition) {
20
- console.log(`❌ FAIL: ${message}`);
21
- failed++;
22
- return false;
23
- }
24
- return true;
25
- }
26
-
27
- function test(description, fn) {
28
- try {
29
- fn();
30
- console.log(`✓ ${description}`);
31
- passed++;
32
- } catch (error) {
33
- console.log(`✗ ${description}`);
34
- console.log(` Error: ${error.message}`);
35
- failed++;
36
- }
37
- }
38
-
39
- // Mock table object with indexes property (simulates what EntityModel creates)
40
- const mockTable = {
41
- __name: 'TestTable',
42
- id: {
43
- name: 'id',
44
- type: 'integer',
45
- nullable: false,
46
- primary: true,
47
- autoIncrement: true
48
- },
49
- organization_id: {
50
- name: 'organization_id',
51
- type: 'integer',
52
- nullable: false,
53
- indexes: ['idx_org'] // This property on the column caused the original bug
54
- },
55
- name: {
56
- name: 'name',
57
- type: 'string',
58
- nullable: false
59
- },
60
- // This is the problematic property that was being treated as a column
61
- indexes: ['idx_org']
62
- };
63
-
64
- console.log("Testing SQLite Query Builder...\n");
65
-
66
- test('SQLite createTable should skip indexes property', () => {
67
- const sqliteQuery = new MigrationSQLiteQuery();
68
- const sql = sqliteQuery.createTable(mockTable);
69
-
70
- assert(!sql.includes('undefined undefined'),
71
- `SQL should not contain "undefined undefined" but got: ${sql}`);
72
- assert(sql.includes('id'), 'Should include id column');
73
- assert(sql.includes('organization_id'), 'Should include organization_id column');
74
- assert(sql.includes('name'), 'Should include name column');
75
- assert(sql.startsWith('CREATE TABLE IF NOT EXISTS TestTable'),
76
- 'Should start with CREATE TABLE');
77
-
78
- console.log(` Generated SQL: ${sql}\n`);
79
- });
80
-
81
- console.log("Testing MySQL Query Builder...\n");
82
-
83
- test('MySQL createTable should skip indexes property', () => {
84
- const mysqlQuery = new MigrationMySQLQuery();
85
- const sql = mysqlQuery.createTable(mockTable);
86
-
87
- assert(!sql.includes('undefined undefined'),
88
- `SQL should not contain "undefined undefined" but got: ${sql}`);
89
- assert(sql.includes('id'), 'Should include id column');
90
- assert(sql.includes('organization_id'), 'Should include organization_id column');
91
- assert(sql.includes('name'), 'Should include name column');
92
- assert(sql.startsWith('CREATE TABLE IF NOT EXISTS `TestTable`'),
93
- 'Should start with CREATE TABLE');
94
-
95
- console.log(` Generated SQL: ${sql}\n`);
96
- });
97
-
98
- console.log("Testing PostgreSQL Query Builder...\n");
99
-
100
- test('PostgreSQL createTable should skip indexes property', () => {
101
- const postgresQuery = new MigrationPostgresQuery();
102
- const sql = postgresQuery.createTable(mockTable);
103
-
104
- assert(!sql.includes('undefined undefined'),
105
- `SQL should not contain "undefined undefined" but got: ${sql}`);
106
- assert(sql.includes('id'), 'Should include id column');
107
- assert(sql.includes('organization_id'), 'Should include organization_id column');
108
- assert(sql.includes('name'), 'Should include name column');
109
- assert(sql.startsWith('CREATE TABLE IF NOT EXISTS "TestTable"'),
110
- 'Should start with CREATE TABLE');
111
-
112
- console.log(` Generated SQL: ${sql}\n`);
113
- });
114
-
115
- console.log("Testing metadata properties filtering...\n");
116
-
117
- test('Should skip __compositeIndexes and other __ properties', () => {
118
- const tableWithMetadata = {
119
- ...mockTable,
120
- __compositeIndexes: [['col1', 'col2']],
121
- __someOtherMetadata: 'value'
122
- };
123
-
124
- const sqliteQuery = new MigrationSQLiteQuery();
125
- const sql = sqliteQuery.createTable(tableWithMetadata);
126
-
127
- assert(!sql.includes('undefined undefined'),
128
- `SQL should not contain "undefined undefined" but got: ${sql}`);
129
-
130
- const columnCount = (sql.match(/,/g) || []).length + 1;
131
- assert(columnCount === 3, `Should have exactly 3 columns (id, organization_id, name), got ${columnCount}`);
132
- });
133
-
134
- console.log("Testing relationships filtering...\n");
135
-
136
- test('Should handle table with relationships correctly', () => {
137
- const tableWithRelations = {
138
- __name: 'User',
139
- id: {
140
- name: 'id',
141
- type: 'integer',
142
- nullable: false,
143
- primary: true
144
- },
145
- name: {
146
- name: 'name',
147
- type: 'string',
148
- nullable: false
149
- },
150
- posts: {
151
- name: 'posts',
152
- type: 'hasMany',
153
- target: 'Post'
154
- },
155
- profile: {
156
- name: 'profile',
157
- type: 'hasOne',
158
- target: 'Profile'
159
- },
160
- indexes: ['idx_user_name']
161
- };
162
-
163
- const sqliteQuery = new MigrationSQLiteQuery();
164
- const sql = sqliteQuery.createTable(tableWithRelations);
165
-
166
- assert(!sql.includes('hasMany'), 'Should not include hasMany');
167
- assert(!sql.includes('hasOne'), 'Should not include hasOne');
168
- assert(!sql.includes('undefined undefined'),
169
- `SQL should not contain "undefined undefined" but got: ${sql}`);
170
- assert(sql.includes('id'), 'Should include id column');
171
- assert(sql.includes('name'), 'Should include name column');
172
- assert(!sql.includes('posts'), 'Should not include posts relationship');
173
- assert(!sql.includes('profile'), 'Should not include profile relationship');
174
-
175
- console.log(` Generated SQL: ${sql}\n`);
176
- });
177
-
178
- console.log("\n" + "=".repeat(64));
179
- console.log(`Test Results: ${passed} passed, ${failed} failed`);
180
- console.log("=".repeat(64));
181
-
182
- if (failed > 0) {
183
- console.log("\n❌ Some tests failed!");
184
- process.exit(1);
185
- } else {
186
- console.log("\n✅ All tests passed!");
187
- process.exit(0);
188
- }