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,381 +0,0 @@
1
- /**
2
- * PostgreSQL Integration Test for MasterRecord
3
- *
4
- * Tests the complete PostgreSQL implementation with pg 8.16.3
5
- *
6
- * Requirements:
7
- * - PostgreSQL server running on localhost:5432
8
- * - Test database named 'masterrecord_test'
9
- * - User with credentials (set in config below)
10
- */
11
-
12
- const PostgresSyncConnect = require('../postgresSyncConnect');
13
- const postgresEngine = require('../postgresEngine');
14
-
15
- console.log("╔════════════════════════════════════════════════════════════════╗");
16
- console.log("║ PostgreSQL Integration Test for MasterRecord ║");
17
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
18
-
19
- let passed = 0;
20
- let failed = 0;
21
-
22
- // Test configuration - update these for your environment
23
- const TEST_CONFIG = {
24
- host: 'localhost',
25
- port: 5432,
26
- database: 'masterrecord_test',
27
- user: 'postgres',
28
- password: 'postgres',
29
- max: 10,
30
- idleTimeoutMillis: 30000,
31
- connectionTimeoutMillis: 2000
32
- };
33
-
34
- // Mock entity for testing
35
- const TEST_ENTITY = {
36
- __name: 'TestUser',
37
- id: { type: 'integer', primary: true, auto: true },
38
- name: { type: 'string', nullable: false },
39
- email: { type: 'string', nullable: false },
40
- age: { type: 'integer', nullable: true },
41
- created_at: { type: 'timestamp', nullable: true }
42
- };
43
-
44
- let connection = null;
45
- let engine = null;
46
-
47
- async function runTests() {
48
- try {
49
- // Test 1: Connection Initialization
50
- console.log("📝 Test 1: PostgreSQL Connection Initialization");
51
- console.log("──────────────────────────────────────────────────");
52
-
53
- try {
54
- connection = new PostgresSyncConnect();
55
- await connection.connect(TEST_CONFIG);
56
-
57
- if (connection.isConnected()) {
58
- console.log(" ✓ Connection established");
59
- console.log(` ✓ Connected to ${TEST_CONFIG.database}`);
60
- passed++;
61
- } else {
62
- console.log(" ✗ Connection failed");
63
- failed++;
64
- }
65
- } catch (err) {
66
- console.log(` ✗ Error: ${err.message}`);
67
- console.log(" ℹ Make sure PostgreSQL is running and test database exists");
68
- failed++;
69
- return; // Can't continue without connection
70
- }
71
-
72
- // Test 2: Get Engine Instance
73
- console.log("\n📝 Test 2: Get Engine Instance");
74
- console.log("──────────────────────────────────────────────────");
75
-
76
- try {
77
- engine = connection.getEngine();
78
-
79
- if (engine) {
80
- console.log(" ✓ Engine instance retrieved");
81
- console.log(` ✓ Engine type: ${engine.dbType}`);
82
- passed++;
83
- } else {
84
- console.log(" ✗ Failed to get engine");
85
- failed++;
86
- }
87
- } catch (err) {
88
- console.log(` ✗ Error: ${err.message}`);
89
- failed++;
90
- }
91
-
92
- // Test 3: Health Check
93
- console.log("\n📝 Test 3: Connection Health Check");
94
- console.log("──────────────────────────────────────────────────");
95
-
96
- try {
97
- const health = await connection.healthCheck();
98
-
99
- if (health.healthy) {
100
- console.log(" ✓ Health check passed");
101
- console.log(` ✓ Server time: ${health.serverTime}`);
102
- console.log(` ✓ Pool size: ${health.poolSize}`);
103
- console.log(` ✓ Idle connections: ${health.idleCount}`);
104
- passed++;
105
- } else {
106
- console.log(` ✗ Health check failed: ${health.error}`);
107
- failed++;
108
- }
109
- } catch (err) {
110
- console.log(` ✗ Error: ${err.message}`);
111
- failed++;
112
- }
113
-
114
- // Test 4: Create Test Table
115
- console.log("\n📝 Test 4: Create Test Table");
116
- console.log("──────────────────────────────────────────────────");
117
-
118
- try {
119
- // Drop table if exists
120
- await connection.query(`DROP TABLE IF EXISTS TestUser`);
121
-
122
- // Create table
123
- const createQuery = `
124
- CREATE TABLE TestUser (
125
- id SERIAL PRIMARY KEY,
126
- name VARCHAR(255) NOT NULL,
127
- email VARCHAR(255) NOT NULL,
128
- age INTEGER,
129
- created_at TIMESTAMP
130
- )
131
- `;
132
-
133
- await connection.query(createQuery);
134
- console.log(" ✓ Test table created");
135
- passed++;
136
- } catch (err) {
137
- console.log(` ✗ Error: ${err.message}`);
138
- failed++;
139
- }
140
-
141
- // Test 5: Parameterized INSERT with RETURNING
142
- console.log("\n📝 Test 5: INSERT with $1, $2 Placeholders and RETURNING");
143
- console.log("──────────────────────────────────────────────────");
144
-
145
- try {
146
- const insertQuery = `
147
- INSERT INTO TestUser (name, email, age, created_at)
148
- VALUES ($1, $2, $3, $4)
149
- RETURNING id
150
- `;
151
-
152
- const params = ['John Doe', 'john@example.com', 30, new Date()];
153
- const result = await connection.query(insertQuery, params);
154
-
155
- if (result.rows && result.rows.length > 0 && result.rows[0].id) {
156
- console.log(" ✓ INSERT with RETURNING successful");
157
- console.log(` ✓ Returned ID: ${result.rows[0].id}`);
158
- console.log(` ✓ Placeholder format: $1, $2, $3, $4`);
159
- passed++;
160
- } else {
161
- console.log(" ✗ INSERT did not return ID");
162
- failed++;
163
- }
164
- } catch (err) {
165
- console.log(` ✗ Error: ${err.message}`);
166
- failed++;
167
- }
168
-
169
- // Test 6: Parameterized SELECT
170
- console.log("\n📝 Test 6: SELECT with Parameterized Query");
171
- console.log("──────────────────────────────────────────────────");
172
-
173
- try {
174
- const selectQuery = `SELECT * FROM TestUser WHERE name = $1`;
175
- const result = await connection.query(selectQuery, ['John Doe']);
176
-
177
- if (result.rows && result.rows.length > 0) {
178
- console.log(" ✓ SELECT with $1 placeholder successful");
179
- console.log(` ✓ Found user: ${result.rows[0].name}`);
180
- console.log(` ✓ Email: ${result.rows[0].email}`);
181
- passed++;
182
- } else {
183
- console.log(" ✗ SELECT returned no results");
184
- failed++;
185
- }
186
- } catch (err) {
187
- console.log(` ✗ Error: ${err.message}`);
188
- failed++;
189
- }
190
-
191
- // Test 7: Parameterized UPDATE
192
- console.log("\n📝 Test 7: UPDATE with Parameterized Query");
193
- console.log("──────────────────────────────────────────────────");
194
-
195
- try {
196
- const updateQuery = `UPDATE TestUser SET age = $1 WHERE name = $2`;
197
- const result = await connection.query(updateQuery, [35, 'John Doe']);
198
-
199
- if (result.rowCount > 0) {
200
- console.log(" ✓ UPDATE with $1, $2 placeholders successful");
201
- console.log(` ✓ Rows affected: ${result.rowCount}`);
202
- passed++;
203
- } else {
204
- console.log(" ✗ UPDATE affected no rows");
205
- failed++;
206
- }
207
- } catch (err) {
208
- console.log(` ✗ Error: ${err.message}`);
209
- failed++;
210
- }
211
-
212
- // Test 8: Transaction Support
213
- console.log("\n📝 Test 8: Transaction (BEGIN/COMMIT/ROLLBACK)");
214
- console.log("──────────────────────────────────────────────────");
215
-
216
- try {
217
- const result = await connection.transaction(async (client) => {
218
- // Insert within transaction
219
- const insertResult = await client.query(
220
- `INSERT INTO TestUser (name, email, age) VALUES ($1, $2, $3) RETURNING id`,
221
- ['Jane Smith', 'jane@example.com', 28]
222
- );
223
-
224
- // Update within transaction
225
- await client.query(
226
- `UPDATE TestUser SET age = $1 WHERE id = $2`,
227
- [29, insertResult.rows[0].id]
228
- );
229
-
230
- return insertResult.rows[0].id;
231
- });
232
-
233
- if (result) {
234
- console.log(" ✓ Transaction completed successfully");
235
- console.log(` ✓ INSERT and UPDATE within transaction`);
236
- console.log(` ✓ Returned ID: ${result}`);
237
- passed++;
238
- } else {
239
- console.log(" ✗ Transaction failed");
240
- failed++;
241
- }
242
- } catch (err) {
243
- console.log(` ✗ Error: ${err.message}`);
244
- failed++;
245
- }
246
-
247
- // Test 9: IN Clause with Multiple Parameters
248
- console.log("\n📝 Test 9: IN Clause with Multiple Parameters");
249
- console.log("──────────────────────────────────────────────────");
250
-
251
- try {
252
- const inQuery = `SELECT * FROM TestUser WHERE name IN ($1, $2)`;
253
- const result = await connection.query(inQuery, ['John Doe', 'Jane Smith']);
254
-
255
- if (result.rows && result.rows.length >= 2) {
256
- console.log(" ✓ IN clause with $1, $2 successful");
257
- console.log(` ✓ Found ${result.rows.length} users`);
258
- passed++;
259
- } else {
260
- console.log(" ✗ IN clause returned insufficient results");
261
- failed++;
262
- }
263
- } catch (err) {
264
- console.log(` ✗ Error: ${err.message}`);
265
- failed++;
266
- }
267
-
268
- // Test 10: NULL Handling
269
- console.log("\n📝 Test 10: NULL Handling");
270
- console.log("──────────────────────────────────────────────────");
271
-
272
- try {
273
- const insertQuery = `INSERT INTO TestUser (name, email, age) VALUES ($1, $2, $3) RETURNING id`;
274
- const result = await connection.query(insertQuery, ['Bob Wilson', 'bob@example.com', null]);
275
-
276
- const selectQuery = `SELECT * FROM TestUser WHERE id = $1`;
277
- const selectResult = await connection.query(selectQuery, [result.rows[0].id]);
278
-
279
- if (selectResult.rows[0].age === null) {
280
- console.log(" ✓ NULL values handled correctly");
281
- console.log(" ✓ Inserted and retrieved NULL age");
282
- passed++;
283
- } else {
284
- console.log(" ✗ NULL handling failed");
285
- failed++;
286
- }
287
- } catch (err) {
288
- console.log(` ✗ Error: ${err.message}`);
289
- failed++;
290
- }
291
-
292
- // Test 11: Connection Pool Info
293
- console.log("\n📝 Test 11: Connection Pool Information");
294
- console.log("──────────────────────────────────────────────────");
295
-
296
- try {
297
- const info = connection.getConnectionInfo();
298
-
299
- if (info) {
300
- console.log(" ✓ Connection info retrieved");
301
- console.log(` ✓ Host: ${info.host}:${info.port}`);
302
- console.log(` ✓ Database: ${info.database}`);
303
- console.log(` ✓ User: ${info.user}`);
304
- console.log(` ✓ Max connections: ${info.maxConnections}`);
305
- passed++;
306
- } else {
307
- console.log(" ✗ Failed to get connection info");
308
- failed++;
309
- }
310
- } catch (err) {
311
- console.log(` ✗ Error: ${err.message}`);
312
- failed++;
313
- }
314
-
315
- // Cleanup: Drop test table
316
- console.log("\n📝 Cleanup: Dropping Test Table");
317
- console.log("──────────────────────────────────────────────────");
318
-
319
- try {
320
- await connection.query(`DROP TABLE IF EXISTS TestUser`);
321
- console.log(" ✓ Test table dropped");
322
- } catch (err) {
323
- console.log(` ⚠ Warning: ${err.message}`);
324
- }
325
-
326
- } catch (err) {
327
- console.log(`\n❌ Fatal error: ${err.message}`);
328
- console.log(err.stack);
329
- } finally {
330
- // Close connection
331
- if (connection) {
332
- try {
333
- await connection.close();
334
- console.log(" ✓ Connection closed");
335
- } catch (err) {
336
- console.log(` ⚠ Warning closing connection: ${err.message}`);
337
- }
338
- }
339
- }
340
-
341
- // Summary
342
- console.log("\n\n╔════════════════════════════════════════════════════════════════╗");
343
- console.log("║ Test Summary ║");
344
- console.log("╚════════════════════════════════════════════════════════════════╝");
345
-
346
- const total = passed + failed;
347
- const successRate = total > 0 ? Math.round((passed/total)*100) : 0;
348
-
349
- console.log(`\n Total Tests: ${total}`);
350
- console.log(` ✅ Passed: ${passed}`);
351
- console.log(` ❌ Failed: ${failed}`);
352
- console.log(` Success Rate: ${successRate}%\n`);
353
-
354
- if (failed === 0) {
355
- console.log("🎉 All PostgreSQL integration tests passed!");
356
- console.log("\n✨ PostgreSQL Implementation Complete!");
357
- console.log("\n📖 Features Verified:");
358
- console.log(" ✓ Connection pooling with pg 8.16.3");
359
- console.log(" ✓ Parameterized queries with $1, $2, $3... placeholders");
360
- console.log(" ✓ RETURNING clause for INSERT operations");
361
- console.log(" ✓ Async/await pattern throughout");
362
- console.log(" ✓ Transaction support (BEGIN/COMMIT/ROLLBACK)");
363
- console.log(" ✓ NULL value handling");
364
- console.log(" ✓ IN clauses with multiple parameters");
365
- console.log(" ✓ Connection pool management");
366
- console.log(" ✓ Health checks");
367
- console.log("\n✅ PostgreSQL engine is ready for production use!\n");
368
- process.exit(0);
369
- } else {
370
- console.log("⚠️ Some PostgreSQL tests failed.");
371
- console.log("\n📖 Common Issues:");
372
- console.log(" • PostgreSQL server not running");
373
- console.log(" • Test database 'masterrecord_test' doesn't exist");
374
- console.log(" • Incorrect credentials in TEST_CONFIG");
375
- console.log(" • Port 5432 not accessible\n");
376
- process.exit(1);
377
- }
378
- }
379
-
380
- // Run tests
381
- runTests();
@@ -1,290 +0,0 @@
1
- /**
2
- * Test: Promise / non-primitive detection in InsertManager.validateEntity()
3
- *
4
- * Verifies that assigning a Promise, Array, or plain Object to a scalar
5
- * entity column produces a clear validation error instead of being silently
6
- * dropped from the INSERT statement.
7
- */
8
-
9
- // Alias 'masterrecord' to local root so insertManager's require('masterrecord/...') resolves
10
- const path = require('path');
11
- const Module = require('module');
12
- const __MASTERRECORD_ROOT__ = path.join(__dirname, '..');
13
- const __ORIGINAL_REQUIRE__ = Module.prototype.require;
14
- Module.prototype.require = function(request) {
15
- if (request === 'masterrecord' || request.startsWith('masterrecord/')) {
16
- const resolved = request === 'masterrecord'
17
- ? __MASTERRECORD_ROOT__
18
- : path.join(__MASTERRECORD_ROOT__, request.slice('masterrecord/'.length));
19
- return __ORIGINAL_REQUIRE__.call(this, resolved);
20
- }
21
- return __ORIGINAL_REQUIRE__.call(this, request);
22
- };
23
-
24
- const InsertManager = require('../insertManager');
25
-
26
- console.log("╔════════════════════════════════════════════════════════════════╗");
27
- console.log("║ Promise / Non-Primitive Detection Test ║");
28
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
29
-
30
- let passed = 0;
31
- let failed = 0;
32
-
33
- function assert(condition, label) {
34
- if (condition) {
35
- console.log(` ✓ ${label}`);
36
- passed++;
37
- } else {
38
- console.log(` ✗ ${label}`);
39
- failed++;
40
- }
41
- }
42
-
43
- // Minimal stubs — we only need validateEntity(), no SQL engine
44
- function makeErrorModel() {
45
- return { isValid: true, errors: [] };
46
- }
47
-
48
- function makeManager() {
49
- const err = makeErrorModel();
50
- const mgr = new InsertManager(null, err, []);
51
- return { mgr, err };
52
- }
53
-
54
- // Entity definition for a simple "User" table
55
- const entityModel = {
56
- __name: 'User',
57
- id: { type: 'integer', primary: true, auto: true, nullable: true },
58
- user_name: { type: 'string', nullable: false },
59
- age: { type: 'integer', nullable: true },
60
- role: { type: 'string', nullable: true },
61
- };
62
-
63
- // -----------------------------------------------------------
64
- // Test 1: Promise assigned to a string column
65
- // -----------------------------------------------------------
66
- console.log("Test 1: Promise on string column");
67
- console.log("──────────────────────────────────────────────────");
68
- {
69
- const { mgr, err } = makeManager();
70
- const realModel = { user_name: Promise.resolve('alice'), age: 25, __entity: entityModel };
71
- const cleanModel = { user_name: Promise.resolve('alice'), age: 25, __entity: entityModel };
72
-
73
- mgr.validateEntity(cleanModel, realModel, entityModel);
74
-
75
- assert(!err.isValid, 'Validation fails');
76
- assert(err.errors.length === 1, 'Exactly one error');
77
- assert(err.errors[0].includes('Promise'), 'Error mentions Promise');
78
- assert(err.errors[0].includes('user_name'), 'Error mentions field name');
79
- assert(err.errors[0].includes('await'), 'Error suggests await');
80
- }
81
-
82
- // -----------------------------------------------------------
83
- // Test 2: Array assigned to a string column
84
- // -----------------------------------------------------------
85
- console.log("\nTest 2: Array on string column");
86
- console.log("──────────────────────────────────────────────────");
87
- {
88
- const { mgr, err } = makeManager();
89
- const realModel = { user_name: 'alice', role: ['admin', 'user'], __entity: entityModel };
90
- const cleanModel = { ...realModel };
91
-
92
- mgr.validateEntity(cleanModel, realModel, entityModel);
93
-
94
- assert(!err.isValid, 'Validation fails');
95
- assert(err.errors[0].includes('Array'), 'Error mentions Array');
96
- assert(err.errors[0].includes('role'), 'Error mentions field name');
97
- }
98
-
99
- // -----------------------------------------------------------
100
- // Test 3: Plain object assigned to an integer column
101
- // -----------------------------------------------------------
102
- console.log("\nTest 3: Plain object on integer column");
103
- console.log("──────────────────────────────────────────────────");
104
- {
105
- const { mgr, err } = makeManager();
106
- const realModel = { user_name: 'alice', age: { value: 25 }, __entity: entityModel };
107
- const cleanModel = { ...realModel };
108
-
109
- mgr.validateEntity(cleanModel, realModel, entityModel);
110
-
111
- assert(!err.isValid, 'Validation fails');
112
- assert(err.errors[0].includes('Object'), 'Error mentions Object');
113
- assert(err.errors[0].includes('age'), 'Error mentions field name');
114
- }
115
-
116
- // -----------------------------------------------------------
117
- // Test 4: Normal scalar values pass validation
118
- // -----------------------------------------------------------
119
- console.log("\nTest 4: Normal scalar values pass validation");
120
- console.log("──────────────────────────────────────────────────");
121
- {
122
- const { mgr, err } = makeManager();
123
- const realModel = { user_name: 'alice', age: 25, role: 'admin', __entity: entityModel };
124
- const cleanModel = { ...realModel };
125
-
126
- mgr.validateEntity(cleanModel, realModel, entityModel);
127
-
128
- assert(err.isValid, 'Validation passes');
129
- assert(err.errors.length === 0, 'No errors');
130
- }
131
-
132
- // -----------------------------------------------------------
133
- // Test 5: Date objects are allowed (not flagged)
134
- // -----------------------------------------------------------
135
- console.log("\nTest 5: Date objects are allowed");
136
- console.log("──────────────────────────────────────────────────");
137
- {
138
- const entityWithDate = {
139
- __name: 'Event',
140
- id: { type: 'integer', primary: true, auto: true, nullable: true },
141
- event_date: { type: 'string', nullable: true },
142
- };
143
- const { mgr, err } = makeManager();
144
- const realModel = { event_date: new Date(), __entity: entityWithDate };
145
- const cleanModel = { ...realModel };
146
-
147
- mgr.validateEntity(cleanModel, realModel, entityWithDate);
148
-
149
- assert(err.isValid, 'Date objects pass validation');
150
- assert(err.errors.length === 0, 'No errors for Date');
151
- }
152
-
153
- // -----------------------------------------------------------
154
- // Test 6: Relationship columns are NOT flagged for objects
155
- // -----------------------------------------------------------
156
- console.log("\nTest 6: Relationship columns allow objects");
157
- console.log("──────────────────────────────────────────────────");
158
- {
159
- const entityWithRel = {
160
- __name: 'Post',
161
- id: { type: 'integer', primary: true, auto: true, nullable: true },
162
- title: { type: 'string', nullable: false },
163
- author: { type: 'belongsTo', relationshipType: 'belongsTo', foreignKey: 'author_id', name: 'author' },
164
- tags: { type: 'hasMany', name: 'tags' },
165
- meta: { type: 'hasOne', name: 'meta' },
166
- cats: { type: 'hasManyThrough', name: 'cats' },
167
- };
168
- const { mgr, err } = makeManager();
169
- const realModel = {
170
- title: 'Hello',
171
- author: { id: 1, name: 'Alice' },
172
- tags: [{ id: 1 }],
173
- meta: { key: 'val' },
174
- cats: [{ id: 2 }],
175
- __entity: entityWithRel,
176
- };
177
- const cleanModel = { ...realModel };
178
-
179
- mgr.validateEntity(cleanModel, realModel, entityWithRel);
180
-
181
- assert(err.isValid, 'Relationship objects pass validation');
182
- assert(err.errors.length === 0, 'No errors for relationship objects');
183
- }
184
-
185
- // -----------------------------------------------------------
186
- // Test 7: null and undefined values are NOT flagged
187
- // -----------------------------------------------------------
188
- console.log("\nTest 7: null/undefined values are not flagged");
189
- console.log("──────────────────────────────────────────────────");
190
- {
191
- const { mgr, err } = makeManager();
192
- const realModel = { user_name: 'alice', age: null, role: undefined, __entity: entityModel };
193
- const cleanModel = { ...realModel };
194
-
195
- mgr.validateEntity(cleanModel, realModel, entityModel);
196
-
197
- assert(err.isValid, 'null/undefined pass validation');
198
- assert(err.errors.length === 0, 'No errors for null/undefined');
199
- }
200
-
201
- // -----------------------------------------------------------
202
- // Test 8: Multiple bad fields produce multiple errors
203
- // -----------------------------------------------------------
204
- console.log("\nTest 8: Multiple bad fields produce multiple errors");
205
- console.log("──────────────────────────────────────────────────");
206
- {
207
- const { mgr, err } = makeManager();
208
- const realModel = {
209
- user_name: Promise.resolve('alice'),
210
- age: [1, 2, 3],
211
- role: { x: 1 },
212
- __entity: entityModel,
213
- };
214
- const cleanModel = { ...realModel };
215
-
216
- mgr.validateEntity(cleanModel, realModel, entityModel);
217
-
218
- assert(!err.isValid, 'Validation fails');
219
- assert(err.errors.length === 3, 'Three errors (Promise + Array + Object)');
220
- }
221
-
222
- // -----------------------------------------------------------
223
- // Test 9: Array allowed when field has a custom set() transform
224
- // -----------------------------------------------------------
225
- console.log("\nTest 9: Array allowed with custom set() transform");
226
- console.log("──────────────────────────────────────────────────");
227
- {
228
- const entityWithSetter = {
229
- __name: 'BatchJob',
230
- id: { type: 'integer', primary: true, auto: true, nullable: true },
231
- name: { type: 'string', nullable: false },
232
- error_log: { type: 'string', nullable: true, set: function(value) {
233
- if (Array.isArray(value)) return JSON.stringify(value);
234
- return value;
235
- }},
236
- config_snapshot: { type: 'string', nullable: true, set: function(value) {
237
- if (typeof value === 'object' && value !== null) return JSON.stringify(value);
238
- return value;
239
- }},
240
- };
241
- const { mgr, err } = makeManager();
242
- const realModel = {
243
- name: 'job1',
244
- error_log: ['err1', 'err2'],
245
- config_snapshot: { retries: 3 },
246
- __entity: entityWithSetter,
247
- };
248
- const cleanModel = { ...realModel };
249
-
250
- mgr.validateEntity(cleanModel, realModel, entityWithSetter);
251
-
252
- assert(err.isValid, 'Array with set() passes validation');
253
- assert(err.errors.length === 0, 'No errors when set() is defined');
254
- }
255
-
256
- // -----------------------------------------------------------
257
- // Test 10: Promise still rejected even when field has set()
258
- // -----------------------------------------------------------
259
- console.log("\nTest 10: Promise rejected even with custom set()");
260
- console.log("──────────────────────────────────────────────────");
261
- {
262
- const entityWithSetter = {
263
- __name: 'BatchJob',
264
- id: { type: 'integer', primary: true, auto: true, nullable: true },
265
- error_log: { type: 'string', nullable: true, set: function(value) {
266
- if (Array.isArray(value)) return JSON.stringify(value);
267
- return value;
268
- }},
269
- };
270
- const { mgr, err } = makeManager();
271
- const realModel = {
272
- error_log: Promise.resolve(['err1']),
273
- __entity: entityWithSetter,
274
- };
275
- const cleanModel = { ...realModel };
276
-
277
- mgr.validateEntity(cleanModel, realModel, entityWithSetter);
278
-
279
- assert(!err.isValid, 'Promise still rejected with set()');
280
- assert(err.errors[0].includes('Promise'), 'Error mentions Promise');
281
- }
282
-
283
- // Summary
284
- console.log("\n" + "=".repeat(64));
285
- console.log(`Test Results: ${passed} passed, ${failed} failed`);
286
- console.log("=".repeat(64));
287
-
288
- if (failed > 0) {
289
- process.exit(1);
290
- }