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,418 +0,0 @@
1
- /**
2
- * Integration tests for all 5 seed data features
3
- * Tests: Down Migrations, Conditional Seeding, Dependency Ordering, Factory Integration, Upsert Semantics
4
- */
5
-
6
- const assert = require('assert');
7
- const context = require('../context');
8
- const Migration = require('../Migrations/migrations');
9
- const MigrationTemplate = require('../Migrations/migrationTemplate');
10
- const DependencyGraph = require('../Migrations/dependencyGraph');
11
-
12
- // Mock entity definitions for testing
13
- class User {
14
- static __name = 'User';
15
- static id = { type: 'integer', primary: true };
16
- static name = { type: 'string' };
17
- static email = { type: 'string' };
18
- static org_id = {
19
- type: 'integer',
20
- relationshipType: 'belongsTo',
21
- foreignTable: 'Organization',
22
- foreignKey: 'org_id'
23
- };
24
- }
25
-
26
- class Organization {
27
- static __name = 'Organization';
28
- static id = { type: 'integer', primary: true };
29
- static name = { type: 'string' };
30
- static slug = { type: 'string' };
31
- }
32
-
33
- class Post {
34
- static __name = 'Post';
35
- static id = { type: 'integer', primary: true };
36
- static title = { type: 'string' };
37
- static user_id = {
38
- type: 'integer',
39
- relationshipType: 'belongsTo',
40
- foreignTable: 'User',
41
- foreignKey: 'user_id'
42
- };
43
- }
44
-
45
- // Test Context
46
- class TestContext extends context {
47
- constructor() {
48
- super();
49
- this.__entities = [User, Organization, Post];
50
- }
51
- }
52
-
53
- describe('Seed Data Features - Integration Tests', function() {
54
-
55
- describe('Feature 1: Down Migrations', function() {
56
- it('should generate down migration code when enabled', function() {
57
- const ctx = new TestContext();
58
- ctx.seedConfig({
59
- generateDownMigrations: true,
60
- downStrategy: 'delete',
61
- onRollbackError: 'warn'
62
- });
63
-
64
- ctx.dbset(User).seed({ id: 1, name: 'Test User', email: 'test@example.com' });
65
-
66
- const seedData = ctx.__contextSeedData;
67
- assert.ok(seedData.User, 'User seed data should exist');
68
- assert.strictEqual(seedData.User.length, 1);
69
- assert.ok(seedData.User[0].__rollback, 'Rollback metadata should be attached');
70
- assert.strictEqual(seedData.User[0].__rollback.key, 'id');
71
- assert.strictEqual(seedData.User[0].__rollback.value, 1);
72
- });
73
-
74
- it('should generate correct down migration template', function() {
75
- const MT = new MigrationTemplate('TestMigration');
76
- const records = [
77
- { id: 1, name: 'User 1', __rollback: { key: 'id', value: 1 } },
78
- { id: 2, name: 'User 2', __rollback: { key: 'id', value: 2 } }
79
- ];
80
- const config = { generateDownMigrations: true, onRollbackError: 'warn' };
81
-
82
- MT.seedDataDown('down', 'User', records, config);
83
- const result = MT.get();
84
-
85
- assert.ok(result.includes('async down(table)'), 'Should have down method');
86
- assert.ok(result.includes('table.User.findById'), 'Should query by ID');
87
- assert.ok(result.includes('await record.delete()'), 'Should delete record');
88
- assert.ok(result.includes('console.warn'), 'Should warn on error');
89
- });
90
-
91
- it('should not generate down migration when disabled', function() {
92
- const ctx = new TestContext();
93
- ctx.seedConfig({ generateDownMigrations: false });
94
-
95
- ctx.dbset(User).seed({ id: 1, name: 'Test' });
96
-
97
- assert.ok(!ctx.__contextSeedData.User[0].__rollback, 'Should not have rollback metadata');
98
- });
99
- });
100
-
101
- describe('Feature 2: Conditional Seeding', function() {
102
- it('should attach environment metadata with .when()', function() {
103
- const ctx = new TestContext();
104
- ctx.dbset(User)
105
- .seed({ name: 'Dev User' })
106
- .when('development', 'test');
107
-
108
- const seedData = ctx.__contextSeedData;
109
- assert.ok(seedData.User[0].__seedEnv, 'Environment metadata should exist');
110
- assert.deepStrictEqual(seedData.User[0].__seedEnv.conditions, ['development', 'test']);
111
- assert.strictEqual(seedData.User[0].__seedEnv.strategy, 'generation-time');
112
- });
113
-
114
- it('should filter records by environment at generation time', function() {
115
- const MT = new MigrationTemplate('TestMigration');
116
- const records = [
117
- { name: 'Prod User', __seedEnv: { conditions: ['production'], strategy: 'generation-time' } },
118
- { name: 'Dev User', __seedEnv: { conditions: ['development'], strategy: 'generation-time' } },
119
- { name: 'All User' }
120
- ];
121
-
122
- MT.seedData('up', 'User', records, 'development');
123
- const result = MT.get();
124
-
125
- assert.ok(!result.includes('Prod User'), 'Should not include production-only record');
126
- assert.ok(result.includes('Dev User'), 'Should include development record');
127
- assert.ok(result.includes('All User'), 'Should include unconditional record');
128
- });
129
-
130
- it('should support chaining with seed()', function() {
131
- const ctx = new TestContext();
132
- ctx.dbset(User)
133
- .seed({ name: 'User 1' })
134
- .when('development')
135
- .seed({ name: 'User 2' });
136
-
137
- assert.strictEqual(ctx.__contextSeedData.User.length, 2);
138
- assert.ok(ctx.__contextSeedData.User[0].__seedEnv, 'First record should have env condition');
139
- assert.ok(!ctx.__contextSeedData.User[1].__seedEnv, 'Second record should not have env condition');
140
- });
141
- });
142
-
143
- describe('Feature 3: Dependency Ordering', function() {
144
- it('should build dependency graph from entities', function() {
145
- const graph = new DependencyGraph([User, Organization, Post]);
146
- graph.buildFromEntities();
147
-
148
- assert.ok(graph.graph.has('User'), 'Should have User in graph');
149
- assert.ok(graph.graph.has('Organization'), 'Should have Organization in graph');
150
- assert.ok(graph.graph.has('Post'), 'Should have Post in graph');
151
- });
152
-
153
- it('should perform topological sort correctly', function() {
154
- const graph = new DependencyGraph([User, Organization, Post]);
155
- graph.buildFromEntities();
156
- const sorted = graph.topologicalSort();
157
-
158
- const orgIndex = sorted.indexOf('Organization');
159
- const userIndex = sorted.indexOf('User');
160
- const postIndex = sorted.indexOf('Post');
161
-
162
- assert.ok(orgIndex < userIndex, 'Organization should come before User');
163
- assert.ok(userIndex < postIndex, 'User should come before Post');
164
- });
165
-
166
- it('should filter to seeded tables only', function() {
167
- const graph = new DependencyGraph([User, Organization, Post]);
168
- graph.buildFromEntities();
169
- const seedData = { User: [], Post: [] }; // Only User and Post have seeds
170
- const filtered = graph.filterToSeededTables(seedData);
171
-
172
- assert.strictEqual(filtered.length, 2, 'Should only include seeded tables');
173
- assert.ok(filtered.includes('User'), 'Should include User');
174
- assert.ok(filtered.includes('Post'), 'Should include Post');
175
- assert.ok(!filtered.includes('Organization'), 'Should not include Organization');
176
- assert.ok(filtered.indexOf('User') < filtered.indexOf('Post'), 'User should come before Post');
177
- });
178
-
179
- it('should handle circular dependencies gracefully', function() {
180
- // Create entities with circular dependency
181
- class A {
182
- static __name = 'A';
183
- static b_id = { relationshipType: 'belongsTo', foreignTable: 'B' };
184
- }
185
- class B {
186
- static __name = 'B';
187
- static a_id = { relationshipType: 'belongsTo', foreignTable: 'A' };
188
- }
189
-
190
- const graph = new DependencyGraph([A, B]);
191
- graph.buildFromEntities();
192
-
193
- assert.throws(() => {
194
- graph.topologicalSort();
195
- }, /Circular dependency/, 'Should throw error on circular dependency');
196
- });
197
-
198
- it('should order seed data via getOrderedSeedData()', function() {
199
- const ctx = new TestContext();
200
- ctx.dbset(Post).seed({ title: 'Post 1', user_id: 1 });
201
- ctx.dbset(User).seed({ id: 1, name: 'User 1', org_id: 1 });
202
- ctx.dbset(Organization).seed({ id: 1, name: 'Org 1' });
203
-
204
- const ordered = ctx.getOrderedSeedData();
205
- const keys = Object.keys(ordered);
206
-
207
- assert.strictEqual(keys.length, 3);
208
- assert.strictEqual(keys[0], 'Organization', 'Organization should be first');
209
- assert.strictEqual(keys[1], 'User', 'User should be second');
210
- assert.strictEqual(keys[2], 'Post', 'Post should be third');
211
- });
212
- });
213
-
214
- describe('Feature 4: Factory Integration', function() {
215
- it('should generate records with seedFactory()', function() {
216
- const ctx = new TestContext();
217
- ctx.dbset(User).seedFactory(5, i => ({
218
- id: i + 1,
219
- name: `User ${i}`,
220
- email: `user${i}@example.com`
221
- }));
222
-
223
- const seedData = ctx.__contextSeedData;
224
- assert.strictEqual(seedData.User.length, 5, 'Should generate 5 records');
225
- assert.strictEqual(seedData.User[0].name, 'User 0');
226
- assert.strictEqual(seedData.User[4].name, 'User 4');
227
- assert.ok(seedData.User[0].__seedMeta?.generated, 'Should mark as factory-generated');
228
- });
229
-
230
- it('should throw error if generator is not a function', function() {
231
- const ctx = new TestContext();
232
- assert.throws(() => {
233
- ctx.dbset(User).seedFactory(5, 'not a function');
234
- }, /requires a generator function/);
235
- });
236
-
237
- it('should throw error if count is invalid', function() {
238
- const ctx = new TestContext();
239
- assert.throws(() => {
240
- ctx.dbset(User).seedFactory(-1, i => ({ name: `User ${i}` }));
241
- }, /requires a positive number/);
242
- });
243
-
244
- it('should generate loop syntax for 10+ factory records', function() {
245
- const MT = new MigrationTemplate('TestMigration');
246
- const records = Array.from({ length: 10 }, (_, i) => ({
247
- name: `User ${i}`,
248
- __seedMeta: { generated: true, index: i }
249
- }));
250
-
251
- MT.seedData('up', 'User', records, 'development');
252
- const result = MT.get();
253
-
254
- assert.ok(result.includes('const factoryRecords = ['), 'Should use array syntax');
255
- assert.ok(result.includes('for (const record of factoryRecords)'), 'Should use loop');
256
- });
257
-
258
- it('should use individual inserts for <10 factory records', function() {
259
- const MT = new MigrationTemplate('TestMigration');
260
- const records = Array.from({ length: 3 }, (_, i) => ({
261
- name: `User ${i}`,
262
- __seedMeta: { generated: true, index: i }
263
- }));
264
-
265
- MT.seedData('up', 'User', records, 'development');
266
- const result = MT.get();
267
-
268
- assert.ok(!result.includes('const factoryRecords'), 'Should not use array syntax');
269
- assert.ok(result.includes('await table.User.create'), 'Should use individual creates');
270
- });
271
- });
272
-
273
- describe('Feature 5: Upsert Semantics', function() {
274
- it('should attach upsert metadata with .upsert()', function() {
275
- const ctx = new TestContext();
276
- ctx.dbset(User)
277
- .seed({ id: 1, name: 'Admin' })
278
- .upsert();
279
-
280
- const seedData = ctx.__contextSeedData;
281
- assert.ok(seedData.User[0].__seedStrategy, 'Should have upsert strategy');
282
- assert.strictEqual(seedData.User[0].__seedStrategy.type, 'upsert');
283
- assert.strictEqual(seedData.User[0].__seedStrategy.conflictKey, 'primaryKey');
284
- });
285
-
286
- it('should support custom conflict key', function() {
287
- const ctx = new TestContext();
288
- ctx.dbset(User)
289
- .seed({ email: 'admin@example.com', name: 'Admin' })
290
- .upsert({ conflictKey: 'email' });
291
-
292
- const strategy = ctx.__contextSeedData.User[0].__seedStrategy;
293
- assert.strictEqual(strategy.conflictKey, 'email');
294
- });
295
-
296
- it('should support partial updates', function() {
297
- const ctx = new TestContext();
298
- ctx.dbset(User)
299
- .seed({ id: 1, name: 'Updated Name', email: 'old@example.com' })
300
- .upsert({ updateFields: ['name'] });
301
-
302
- const strategy = ctx.__contextSeedData.User[0].__seedStrategy;
303
- assert.deepStrictEqual(strategy.updateFields, ['name']);
304
- });
305
-
306
- it('should generate check-then-update code', function() {
307
- const MT = new MigrationTemplate('TestMigration');
308
- const records = [{
309
- id: 1,
310
- name: 'Admin',
311
- email: 'admin@example.com',
312
- __seedStrategy: { type: 'upsert', conflictKey: 'primaryKey', updateFields: null }
313
- }];
314
-
315
- MT.seedData('up', 'User', records, 'development');
316
- const result = MT.get();
317
-
318
- assert.ok(result.includes('const existing = await table.User.where'), 'Should check for existing');
319
- assert.ok(result.includes('if (existing)'), 'Should have conditional');
320
- assert.ok(result.includes('await existing.save()'), 'Should save on update');
321
- assert.ok(result.includes('await table.User.create'), 'Should create if not exists');
322
- });
323
-
324
- it('should apply default upsert strategy when configured', function() {
325
- const ctx = new TestContext();
326
- ctx.seedConfig({ defaultStrategy: 'upsert' });
327
- ctx.dbset(User).seed({ id: 1, name: 'Admin' });
328
-
329
- const strategy = ctx.__contextSeedData.User[0].__seedStrategy;
330
- assert.strictEqual(strategy.type, 'upsert');
331
- });
332
- });
333
-
334
- describe('Combined Features', function() {
335
- it('should support all features together', function() {
336
- const ctx = new TestContext();
337
- ctx.seedConfig({
338
- generateDownMigrations: true,
339
- defaultStrategy: 'upsert',
340
- detectCircularDependencies: true,
341
- circularStrategy: 'warn'
342
- });
343
-
344
- // Feature 3 (Dependency Ordering) + Feature 4 (Factory) + Feature 2 (Conditional) + Feature 5 (Upsert)
345
- ctx.dbset(Organization)
346
- .seed({ id: 1, name: 'Default Org', slug: 'default' })
347
- .upsert({ conflictKey: 'slug' });
348
-
349
- ctx.dbset(User)
350
- .seedFactory(3, i => ({ id: i + 1, name: `Admin ${i}`, org_id: 1 }))
351
- .when('development')
352
- .upsert();
353
-
354
- ctx.dbset(Post)
355
- .seed({ id: 1, title: 'Welcome', user_id: 1 })
356
- .when('development');
357
-
358
- const ordered = ctx.getOrderedSeedData();
359
- const keys = Object.keys(ordered);
360
-
361
- // Verify ordering
362
- assert.strictEqual(keys[0], 'Organization');
363
- assert.strictEqual(keys[1], 'User');
364
- assert.strictEqual(keys[2], 'Post');
365
-
366
- // Verify features applied
367
- assert.ok(ordered.Organization[0].__seedStrategy, 'Org should have upsert');
368
- assert.ok(ordered.User[0].__seedMeta?.generated, 'User should be factory-generated');
369
- assert.ok(ordered.User[0].__seedEnv, 'User should have env condition');
370
- assert.ok(ordered.Post[0].__seedEnv, 'Post should have env condition');
371
- });
372
-
373
- it('should chain all methods together', function() {
374
- const ctx = new TestContext();
375
- ctx.dbset(User)
376
- .seedFactory(5, i => ({ id: i + 1, name: `User ${i}` }))
377
- .when('development', 'test')
378
- .upsert({ conflictKey: 'id' });
379
-
380
- const record = ctx.__contextSeedData.User[0];
381
- assert.ok(record.__seedMeta?.generated, 'Should have factory metadata');
382
- assert.ok(record.__seedEnv, 'Should have environment metadata');
383
- assert.ok(record.__seedStrategy, 'Should have upsert strategy');
384
- });
385
- });
386
-
387
- describe('Backward Compatibility', function() {
388
- it('should work without any configuration', function() {
389
- const ctx = new TestContext();
390
- ctx.dbset(User).seed({ name: 'Simple User' });
391
-
392
- assert.ok(ctx.__contextSeedData.User);
393
- assert.strictEqual(ctx.__contextSeedData.User.length, 1);
394
- });
395
-
396
- it('should support array syntax', function() {
397
- const ctx = new TestContext();
398
- ctx.dbset(User).seed([
399
- { name: 'User 1' },
400
- { name: 'User 2' }
401
- ]);
402
-
403
- assert.strictEqual(ctx.__contextSeedData.User.length, 2);
404
- });
405
-
406
- it('should support chaining without features', function() {
407
- const ctx = new TestContext();
408
- ctx.dbset(User)
409
- .seed({ name: 'User 1' })
410
- .seed({ name: 'User 2' });
411
-
412
- assert.strictEqual(ctx.__contextSeedData.User.length, 2);
413
- });
414
- });
415
- });
416
-
417
- console.log('✓ All seed data integration tests defined');
418
- console.log('Run with: npm test or node test/seed-features-integration-test.js');
@@ -1,220 +0,0 @@
1
- /**
2
- * Test: Seed Data Migration Template Generation
3
- *
4
- * Verifies that seed data correctly generates ORM-based migration code
5
- */
6
-
7
- const MigrationTemplate = require('../Migrations/migrationTemplate');
8
- const os = require('os');
9
-
10
- console.log("╔════════════════════════════════════════════════════════════════╗");
11
- console.log("║ Seed Data Migration Template Generation Test ║");
12
- console.log("╚════════════════════════════════════════════════════════════════╝\n");
13
-
14
- let passed = 0;
15
- let failed = 0;
16
-
17
- function test(description, fn) {
18
- try {
19
- fn();
20
- console.log(`✓ ${description}`);
21
- passed++;
22
- } catch (error) {
23
- console.log(`✗ ${description}`);
24
- console.log(` Error: ${error.message}`);
25
- failed++;
26
- }
27
- }
28
-
29
- function assertContains(haystack, needle, message) {
30
- if (!haystack.includes(needle)) {
31
- throw new Error(`${message}: expected to find "${needle}" in output`);
32
- }
33
- }
34
-
35
- function assertNotContains(haystack, needle, message) {
36
- if (haystack.includes(needle)) {
37
- throw new Error(`${message}: did not expect to find "${needle}" in output`);
38
- }
39
- }
40
-
41
- // Run tests
42
- console.log("Running tests...\n");
43
-
44
- test("Single seed record generates single-line create call", () => {
45
- const MT = new MigrationTemplate('TestMigration');
46
-
47
- const seedData = [
48
- { name: 'Admin', email: 'admin@example.com' }
49
- ];
50
-
51
- MT.seedData('up', 'User', seedData);
52
-
53
- const output = MT.get();
54
-
55
- assertContains(output, 'await table.User.create(', 'Should contain create call');
56
- assertContains(output, '"name":"Admin"', 'Should contain name field');
57
- assertContains(output, '"email":"admin@example.com"', 'Should contain email field');
58
- });
59
-
60
- test("Multiple seed records generate multiple create calls", () => {
61
- const MT = new MigrationTemplate('TestMigration');
62
-
63
- const seedData = [
64
- { title: 'Post 1', content: 'Content 1' },
65
- { title: 'Post 2', content: 'Content 2' }
66
- ];
67
-
68
- MT.seedData('up', 'Post', seedData);
69
-
70
- const output = MT.get();
71
-
72
- assertContains(output, 'await table.Post.create(', 'Should contain create calls');
73
- assertContains(output, '"title":"Post 1"', 'Should contain Post 1');
74
- assertContains(output, '"title":"Post 2"', 'Should contain Post 2');
75
- });
76
-
77
- test("Large record generates multi-line formatted create call", () => {
78
- const MT = new MigrationTemplate('TestMigration');
79
-
80
- const seedData = [
81
- {
82
- user_name: 'admin',
83
- first_name: 'System',
84
- last_name: 'Administrator',
85
- email: 'admin@bookbag.ai',
86
- system_role: 'system_admin',
87
- admin_type: 'engineering'
88
- }
89
- ];
90
-
91
- MT.seedData('up', 'User', seedData);
92
-
93
- const output = MT.get();
94
-
95
- // Large record (> 80 chars) should be multi-line
96
- assertContains(output, 'await table.User.create(', 'Should contain create call');
97
- assertContains(output, '"user_name"', 'Should contain user_name field');
98
- assertContains(output, '"system_role"', 'Should contain system_role field');
99
- });
100
-
101
- test("Empty seed data generates nothing", () => {
102
- const MT = new MigrationTemplate('TestMigration');
103
-
104
- MT.seedData('up', 'User', []);
105
-
106
- const output = MT.get();
107
-
108
- // Should not contain any User create calls
109
- assertNotContains(output, 'await table.User.create(', 'Should not contain create call');
110
- });
111
-
112
- test("Down migration does not generate seed code", () => {
113
- const MT = new MigrationTemplate('TestMigration');
114
-
115
- const seedData = [
116
- { name: 'Admin', email: 'admin@example.com' }
117
- ];
118
-
119
- MT.seedData('down', 'User', seedData);
120
-
121
- const output = MT.get();
122
-
123
- // Down migrations should not contain seed data deletion
124
- // (as per design - seed data not removed in down migrations)
125
- const downSection = output.split('async down(table)')[1];
126
- assertNotContains(downSection, 'await table.User.create(', 'Down migration should not create seed data');
127
- });
128
-
129
- test("Seed data with special characters is properly escaped", () => {
130
- const MT = new MigrationTemplate('TestMigration');
131
-
132
- const seedData = [
133
- { name: 'Test "Quote"', description: "It's working" }
134
- ];
135
-
136
- MT.seedData('up', 'Item', seedData);
137
-
138
- const output = MT.get();
139
-
140
- assertContains(output, 'await table.Item.create(', 'Should contain create call');
141
- // JSON.stringify handles escaping automatically
142
- assertContains(output, 'Test \\"Quote\\"', 'Should escape double quotes');
143
- });
144
-
145
- test("Seed data with null values is preserved", () => {
146
- const MT = new MigrationTemplate('TestMigration');
147
-
148
- const seedData = [
149
- { name: 'Test', optional_field: null }
150
- ];
151
-
152
- MT.seedData('up', 'Item', seedData);
153
-
154
- const output = MT.get();
155
-
156
- assertContains(output, 'await table.Item.create(', 'Should contain create call');
157
- assertContains(output, '"optional_field":null', 'Should preserve null value');
158
- });
159
-
160
- test("Seed data with boolean values is preserved", () => {
161
- const MT = new MigrationTemplate('TestMigration');
162
-
163
- const seedData = [
164
- { name: 'Admin', is_active: true, is_deleted: false }
165
- ];
166
-
167
- MT.seedData('up', 'User', seedData);
168
-
169
- const output = MT.get();
170
-
171
- assertContains(output, '"is_active":true', 'Should preserve true value');
172
- assertContains(output, '"is_deleted":false', 'Should preserve false value');
173
- });
174
-
175
- test("Seed data with numbers is preserved", () => {
176
- const MT = new MigrationTemplate('TestMigration');
177
-
178
- const seedData = [
179
- { name: 'Product', price: 19.99, quantity: 100, rating: 4.5 }
180
- ];
181
-
182
- MT.seedData('up', 'Product', seedData);
183
-
184
- const output = MT.get();
185
-
186
- assertContains(output, '"price":19.99', 'Should preserve decimal number');
187
- assertContains(output, '"quantity":100', 'Should preserve integer');
188
- assertContains(output, '"rating":4.5', 'Should preserve float');
189
- });
190
-
191
- test("Migration template structure is valid", () => {
192
- const MT = new MigrationTemplate('TestMigration_123');
193
-
194
- const seedData = [
195
- { name: 'Test User' }
196
- ];
197
-
198
- MT.seedData('up', 'User', seedData);
199
-
200
- const output = MT.get();
201
-
202
- // Verify basic structure
203
- assertContains(output, "class TestMigration_123 extends masterrecord.schema", 'Should have class definition');
204
- assertContains(output, "async up(table)", 'Should have up method');
205
- assertContains(output, "async down(table)", 'Should have down method');
206
- assertContains(output, "this.init(table)", 'Should initialize table');
207
- assertContains(output, "module.exports = TestMigration_123", 'Should export class');
208
- });
209
-
210
- // Print summary
211
- console.log("\n" + "─".repeat(64));
212
- console.log(`Tests completed: ${passed} passed, ${failed} failed`);
213
-
214
- if (failed > 0) {
215
- console.log("\n❌ Some tests failed");
216
- process.exit(1);
217
- } else {
218
- console.log("\n✅ All tests passed!");
219
- process.exit(0);
220
- }