orchid-orm 1.5.29 → 1.5.31

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 (59) hide show
  1. package/dist/index.d.ts +6 -14
  2. package/dist/index.js +26 -21
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +26 -21
  5. package/dist/index.mjs.map +1 -1
  6. package/package.json +12 -22
  7. package/.env.example +0 -1
  8. package/.turbo/turbo-check.log +0 -26
  9. package/.turbo/turbo-test.log +0 -26
  10. package/.turbo/turbo-test:ci.log +0 -26
  11. package/CHANGELOG.md +0 -382
  12. package/coverage/coverage-summary.json +0 -28
  13. package/jest-setup.ts +0 -11
  14. package/rollup.config.js +0 -18
  15. package/src/bin/bin.ts +0 -3
  16. package/src/bin/init.test.ts +0 -810
  17. package/src/bin/init.ts +0 -529
  18. package/src/codegen/appCodeUpdater.test.ts +0 -75
  19. package/src/codegen/appCodeUpdater.ts +0 -53
  20. package/src/codegen/createBaseTableFile.test.ts +0 -53
  21. package/src/codegen/createBaseTableFile.ts +0 -31
  22. package/src/codegen/fileChanges.ts +0 -41
  23. package/src/codegen/testUtils.ts +0 -56
  24. package/src/codegen/tsUtils.ts +0 -180
  25. package/src/codegen/updateMainFile.test.ts +0 -253
  26. package/src/codegen/updateMainFile.ts +0 -210
  27. package/src/codegen/updateTableFile/changeTable.test.ts +0 -804
  28. package/src/codegen/updateTableFile/changeTable.ts +0 -536
  29. package/src/codegen/updateTableFile/createTable.test.ts +0 -139
  30. package/src/codegen/updateTableFile/createTable.ts +0 -51
  31. package/src/codegen/updateTableFile/renameTable.test.ts +0 -124
  32. package/src/codegen/updateTableFile/renameTable.ts +0 -67
  33. package/src/codegen/updateTableFile/updateTableFile.ts +0 -22
  34. package/src/codegen/utils.ts +0 -13
  35. package/src/index.ts +0 -5
  36. package/src/orm.test.ts +0 -92
  37. package/src/orm.ts +0 -98
  38. package/src/relations/belongsTo.test.ts +0 -1122
  39. package/src/relations/belongsTo.ts +0 -352
  40. package/src/relations/hasAndBelongsToMany.test.ts +0 -1335
  41. package/src/relations/hasAndBelongsToMany.ts +0 -472
  42. package/src/relations/hasMany.test.ts +0 -2616
  43. package/src/relations/hasMany.ts +0 -401
  44. package/src/relations/hasOne.test.ts +0 -1701
  45. package/src/relations/hasOne.ts +0 -351
  46. package/src/relations/relations.test.ts +0 -37
  47. package/src/relations/relations.ts +0 -363
  48. package/src/relations/utils.ts +0 -162
  49. package/src/repo.test.ts +0 -200
  50. package/src/repo.ts +0 -119
  51. package/src/table.test.ts +0 -121
  52. package/src/table.ts +0 -184
  53. package/src/test-utils/test-db.ts +0 -32
  54. package/src/test-utils/test-tables.ts +0 -194
  55. package/src/test-utils/test-utils.ts +0 -119
  56. package/src/transaction.test.ts +0 -47
  57. package/src/transaction.ts +0 -27
  58. package/src/utils.ts +0 -9
  59. package/tsconfig.json +0 -14
@@ -1,810 +0,0 @@
1
- import { initOrchidORM } from './init';
2
- import fs from 'fs/promises';
3
- import { asMock } from '../codegen/testUtils';
4
- import path from 'path';
5
-
6
- jest.mock('https', () => ({
7
- get(
8
- this: { result: string },
9
- _: string,
10
- cb: (res: {
11
- on(event: string, cb: (chunk?: string) => void): void;
12
- }) => void,
13
- ) {
14
- cb({
15
- on: (event: string, cb: (chunk?: string) => void) => {
16
- if (event === 'data') {
17
- cb(`{"version":"1.2.3"}`);
18
- } else if (event === 'end') {
19
- cb();
20
- }
21
- },
22
- });
23
- },
24
- }));
25
-
26
- jest.mock('fs/promises', () => ({
27
- readFile: jest.fn(),
28
- writeFile: jest.fn(),
29
- mkdir: jest.fn(),
30
- }));
31
-
32
- class EnoentError extends Error {
33
- code = 'ENOENT';
34
- }
35
-
36
- const packageJSONPath = path.resolve(process.cwd(), 'package.json');
37
- const tsConfigPath = path.resolve(process.cwd(), 'tsconfig.json');
38
- const envPath = path.resolve(process.cwd(), '.env');
39
- const gitignorePath = path.resolve(process.cwd(), '.gitignore');
40
- const dbDirPath = path.resolve(process.cwd(), 'src', 'db');
41
- const baseTablePath = path.resolve(dbDirPath, 'baseTable.ts');
42
- const tablesDir = path.resolve(dbDirPath, 'tables');
43
- const postTablePath = path.resolve(tablesDir, 'post.table.ts');
44
- const commentTablePath = path.resolve(tablesDir, 'comment.table.ts');
45
- const configPath = path.join(dbDirPath, 'config.ts');
46
- const dbPath = path.join(dbDirPath, 'db.ts');
47
- const migrationScriptPath = path.join(dbDirPath, 'dbScripts.ts');
48
- const migrationsPath = path.join(dbDirPath, 'migrations');
49
- const seedPath = path.join(dbDirPath, 'seed.ts');
50
-
51
- console.log = jest.fn();
52
-
53
- describe('initOrchidORM', () => {
54
- beforeEach(jest.clearAllMocks);
55
-
56
- it('should create db directory', async () => {
57
- await initOrchidORM({});
58
-
59
- expect(fs.mkdir).toBeCalledWith(dbDirPath, { recursive: true });
60
- });
61
-
62
- describe('package.json', () => {
63
- const packageJSONWithoutAdditional = `{
64
- "scripts": {
65
- "db": "ts-node src/db/dbScripts.ts"
66
- },
67
- "dependencies": {
68
- "dotenv": "^1.2.3",
69
- "orchid-orm": "^1.2.3",
70
- "pqb": "^1.2.3",
71
- "pg": "^1.2.3"
72
- },
73
- "devDependencies": {
74
- "rake-db": "^1.2.3",
75
- "@swc/core": "^1.2.3",
76
- "@types/node": "^1.2.3",
77
- "ts-node": "^1.2.3",
78
- "typescript": "^1.2.3"
79
- }
80
- }
81
- `;
82
-
83
- const fullPackageJSON = `{
84
- "scripts": {
85
- "db": "ts-node src/db/dbScripts.ts"
86
- },
87
- "dependencies": {
88
- "dotenv": "^1.2.3",
89
- "orchid-orm": "^1.2.3",
90
- "pqb": "^1.2.3",
91
- "pg": "^1.2.3",
92
- "orchid-orm-schema-to-zod": "^1.2.3"
93
- },
94
- "devDependencies": {
95
- "rake-db": "^1.2.3",
96
- "orchid-orm-test-factory": "^1.2.3",
97
- "@swc/core": "^1.2.3",
98
- "@types/node": "^1.2.3",
99
- "ts-node": "^1.2.3",
100
- "typescript": "^1.2.3"
101
- }
102
- }
103
- `;
104
-
105
- it('should create package.json if not exist', async () => {
106
- asMock(fs.readFile).mockImplementation((path: string) => {
107
- if (path.endsWith('package.json')) {
108
- throw new EnoentError();
109
- }
110
- });
111
-
112
- await initOrchidORM({});
113
-
114
- const [, content] = asMock(fs.writeFile).mock.calls.find(
115
- ([to]) => to === packageJSONPath,
116
- );
117
- expect(content).toBe(packageJSONWithoutAdditional);
118
- });
119
-
120
- it('should create package.json with additional deps if not exist', async () => {
121
- asMock(fs.readFile).mockImplementation((path: string) => {
122
- if (path.endsWith('package.json')) {
123
- throw new EnoentError();
124
- }
125
- });
126
-
127
- await initOrchidORM({
128
- addSchemaToZod: true,
129
- addTestFactory: true,
130
- });
131
-
132
- const [, content] = asMock(fs.writeFile).mock.calls.find(
133
- ([to]) => to === packageJSONPath,
134
- );
135
- expect(content).toBe(fullPackageJSON);
136
- });
137
-
138
- it('should add scripts, dependencies and devDependencies if they are not present in package.json', async () => {
139
- asMock(fs.readFile).mockImplementation((path: string) => {
140
- if (path.endsWith('package.json')) {
141
- return '{}';
142
- }
143
- return;
144
- });
145
-
146
- await initOrchidORM({
147
- addSchemaToZod: true,
148
- addTestFactory: true,
149
- });
150
-
151
- const [, content] = asMock(fs.writeFile).mock.calls.find(
152
- ([to]) => to === packageJSONPath,
153
- );
154
- expect(content).toBe(fullPackageJSON);
155
- });
156
-
157
- it('should insert scripts and dependencies', async () => {
158
- asMock(fs.readFile).mockImplementation((path: string) => {
159
- if (path.endsWith('package.json')) {
160
- return `{
161
- "scripts": {
162
- "ko": "ko"
163
- },
164
- "dependencies": {
165
- "ko": "ko"
166
- },
167
- "devDependencies": {
168
- "ko": "ko"
169
- }
170
- }`;
171
- }
172
- return;
173
- });
174
-
175
- await initOrchidORM({
176
- addSchemaToZod: true,
177
- addTestFactory: true,
178
- });
179
-
180
- const [, content] = asMock(fs.writeFile).mock.calls.find(
181
- ([to]) => to === packageJSONPath,
182
- );
183
- expect(content).toBe(
184
- `{
185
- "scripts": {
186
- "ko": "ko",
187
- "db": "ts-node src/db/dbScripts.ts"
188
- },
189
- "dependencies": {
190
- "ko": "ko",
191
- "dotenv": "^1.2.3",
192
- "orchid-orm": "^1.2.3",
193
- "pqb": "^1.2.3",
194
- "pg": "^1.2.3",
195
- "orchid-orm-schema-to-zod": "^1.2.3"
196
- },
197
- "devDependencies": {
198
- "ko": "ko",
199
- "rake-db": "^1.2.3",
200
- "orchid-orm-test-factory": "^1.2.3",
201
- "@swc/core": "^1.2.3",
202
- "@types/node": "^1.2.3",
203
- "ts-node": "^1.2.3",
204
- "typescript": "^1.2.3"
205
- }
206
- }
207
- `,
208
- );
209
- });
210
- });
211
-
212
- describe('tsconfig.json', () => {
213
- it('should create tsconfig.json if not not exist', async () => {
214
- await initOrchidORM({});
215
-
216
- const [, content] = asMock(fs.writeFile).mock.calls.find(
217
- ([to]) => to === tsConfigPath,
218
- );
219
- expect(content).toBe(`{
220
- "ts-node": {
221
- "swc": true
222
- },
223
- "compilerOptions": {
224
- "strict": true
225
- }
226
- }
227
- `);
228
- });
229
-
230
- it('should update tsconfig.json if it exists', async () => {
231
- asMock(fs.readFile).mockImplementation((path: string) => {
232
- if (path.endsWith('tsconfig.json')) {
233
- return `{"compilerOptions":{"ko":"ko"}}`;
234
- }
235
- return;
236
- });
237
-
238
- await initOrchidORM({});
239
-
240
- const [, content] = asMock(fs.writeFile).mock.calls.find(
241
- ([to]) => to === tsConfigPath,
242
- );
243
- expect(content).toBe(`{
244
- "compilerOptions": {
245
- "ko": "ko",
246
- "strict": true
247
- },
248
- "ts-node": {
249
- "swc": true
250
- }
251
- }
252
- `);
253
- });
254
- });
255
-
256
- describe('.env', () => {
257
- it('should create .env if not exist', async () => {
258
- asMock(fs.readFile).mockImplementation((path: string) => {
259
- if (path.endsWith('.env')) {
260
- throw new EnoentError();
261
- }
262
- });
263
-
264
- await initOrchidORM({});
265
-
266
- const [, content] = asMock(fs.writeFile).mock.calls.find(
267
- ([to]) => to === envPath,
268
- );
269
- expect(content)
270
- .toBe(`DATABASE_URL=postgres://user:password@localhost:5432/dbname?ssl=false
271
- `);
272
- });
273
-
274
- it('should append DATABASE_URL to existing .env', async () => {
275
- asMock(fs.readFile).mockImplementation((path: string) => {
276
- if (path.endsWith('.env')) {
277
- return 'KO=KO';
278
- }
279
- return '';
280
- });
281
-
282
- await initOrchidORM({});
283
-
284
- const [, content] = asMock(fs.writeFile).mock.calls.find(
285
- ([to]) => to === envPath,
286
- );
287
- expect(content).toBe(`KO=KO
288
- DATABASE_URL=postgres://user:password@localhost:5432/dbname?ssl=false
289
- `);
290
- });
291
-
292
- it('should append DATABASE_TEST_URL if testDatabase specified', async () => {
293
- asMock(fs.readFile).mockImplementation((path: string) => {
294
- if (path.endsWith('.env')) {
295
- return 'KO=KO';
296
- }
297
- return '';
298
- });
299
-
300
- await initOrchidORM({
301
- testDatabase: true,
302
- });
303
-
304
- const [, content] = asMock(fs.writeFile).mock.calls.find(
305
- ([to]) => to === envPath,
306
- );
307
- expect(content).toBe(`KO=KO
308
- DATABASE_URL=postgres://user:password@localhost:5432/dbname?ssl=false
309
- DATABASE_TEST_URL=postgres://user:password@localhost:5432/dbname-test?ssl=false
310
- `);
311
- });
312
- });
313
-
314
- describe('.gitignore', () => {
315
- it('should create .gitignore if not exists', async () => {
316
- asMock(fs.readFile).mockImplementation((path: string) => {
317
- if (path.endsWith('.gitignore')) {
318
- throw new EnoentError();
319
- }
320
- });
321
-
322
- await initOrchidORM({});
323
-
324
- const [, content] = asMock(fs.writeFile).mock.calls.find(
325
- ([to]) => to === gitignorePath,
326
- );
327
- expect(content).toBe(`node_modules
328
- .env
329
- `);
330
- });
331
-
332
- it('should append missing entries if .gitignore exists', async () => {
333
- asMock(fs.readFile).mockImplementation((path: string) => {
334
- if (path.endsWith('.gitignore')) {
335
- return 'node_modules/\nko';
336
- }
337
- return;
338
- });
339
-
340
- await initOrchidORM({});
341
-
342
- const [, content] = asMock(fs.writeFile).mock.calls.find(
343
- ([to]) => to === gitignorePath,
344
- );
345
- expect(content).toBe(`node_modules/
346
- ko
347
- .env
348
- `);
349
- });
350
- });
351
-
352
- describe('baseTable', () => {
353
- it('should create base table', async () => {
354
- await initOrchidORM({});
355
-
356
- const [, content] = asMock(fs.writeFile).mock.calls.find(
357
- ([to]) => to === baseTablePath,
358
- );
359
- expect(content).toBe(`import { createBaseTable } from 'orchid-orm';
360
-
361
- export const BaseTable = createBaseTable({
362
- columnTypes: (t) => ({
363
- ...t,
364
- text: (min = 0, max = Infinity) => t.text(min, max),
365
- }),
366
- });
367
- `);
368
- });
369
-
370
- it('should create base table with timestamp as date', async () => {
371
- await initOrchidORM({
372
- timestamp: 'date',
373
- });
374
-
375
- const [, content] = asMock(fs.writeFile).mock.calls.find(
376
- ([to]) => to === baseTablePath,
377
- );
378
- expect(content).toBe(`import { createBaseTable } from 'orchid-orm';
379
-
380
- export const BaseTable = createBaseTable({
381
- columnTypes: (t) => ({
382
- ...t,
383
- text: (min = 0, max = Infinity) => t.text(min, max),
384
- timestamp: <P extends number>(precision?: P) =>
385
- t.timestamp<P>(precision).asDate(),
386
- }),
387
- });
388
- `);
389
- });
390
-
391
- it('should create base table with timestamp as number', async () => {
392
- await initOrchidORM({
393
- timestamp: 'number',
394
- });
395
-
396
- const [, content] = asMock(fs.writeFile).mock.calls.find(
397
- ([to]) => to === baseTablePath,
398
- );
399
- expect(content).toBe(`import { createBaseTable } from 'orchid-orm';
400
-
401
- export const BaseTable = createBaseTable({
402
- columnTypes: (t) => ({
403
- ...t,
404
- text: (min = 0, max = Infinity) => t.text(min, max),
405
- timestamp: <P extends number>(precision?: P) =>
406
- t.timestamp<P>(precision).asNumber(),
407
- }),
408
- });
409
- `);
410
- });
411
- });
412
-
413
- describe('tables', () => {
414
- it('should do nothing if demoTables is not specified', async () => {
415
- await initOrchidORM({});
416
-
417
- expect(fs.mkdir).not.toBeCalledWith(tablesDir, { recursive: true });
418
- });
419
-
420
- it('should create tables dir', async () => {
421
- await initOrchidORM({
422
- demoTables: true,
423
- });
424
-
425
- expect(fs.mkdir).toBeCalledWith(tablesDir, { recursive: true });
426
- });
427
-
428
- it('should create post table', async () => {
429
- await initOrchidORM({
430
- demoTables: true,
431
- });
432
-
433
- const [, content] = asMock(fs.writeFile).mock.calls.find(
434
- ([to]) => to === postTablePath,
435
- );
436
- expect(content).toBe(`import { BaseTable } from '../baseTable';
437
- import { CommentTable } from './comment.table';
438
-
439
- export type Post = PostTable['columns']['type'];
440
- export class PostTable extends BaseTable {
441
- table = 'post';
442
- columns = this.setColumns((t) => ({
443
- id: t.serial().primaryKey(),
444
- title: t.text(3, 100).unique(),
445
- text: t.text(20, 10000),
446
- ...t.timestamps(),
447
- }));
448
-
449
- relations = {
450
- comments: this.hasMany(() => CommentTable, {
451
- primaryKey: 'id',
452
- foreignKey: 'postId',
453
- }),
454
- };
455
- }
456
- `);
457
- });
458
-
459
- it('should create post table with zod schema', async () => {
460
- await initOrchidORM({
461
- demoTables: true,
462
- addSchemaToZod: true,
463
- });
464
-
465
- const [, content] = asMock(fs.writeFile).mock.calls.find(
466
- ([to]) => to === postTablePath,
467
- );
468
- expect(content).toBe(`import { BaseTable } from '../baseTable';
469
- import { CommentTable } from './comment.table';
470
- import { tableToZod } from 'orchid-orm-schema-to-zod';
471
-
472
- export type Post = PostTable['columns']['type'];
473
- export class PostTable extends BaseTable {
474
- table = 'post';
475
- columns = this.setColumns((t) => ({
476
- id: t.serial().primaryKey(),
477
- title: t.text(3, 100).unique(),
478
- text: t.text(20, 10000),
479
- ...t.timestamps(),
480
- }));
481
-
482
- relations = {
483
- comments: this.hasMany(() => CommentTable, {
484
- primaryKey: 'id',
485
- foreignKey: 'postId',
486
- }),
487
- };
488
- }
489
-
490
- export const postSchema = tableToZod(PostTable);
491
- `);
492
- });
493
-
494
- it('should create comment table', async () => {
495
- await initOrchidORM({
496
- demoTables: true,
497
- });
498
-
499
- const [, content] = asMock(fs.writeFile).mock.calls.find(
500
- ([to]) => to === commentTablePath,
501
- );
502
- expect(content).toBe(`import { BaseTable } from '../baseTable';
503
- import { PostTable } from './post.table';
504
-
505
- export type Comment = CommentTable['columns']['type'];
506
- export class CommentTable extends BaseTable {
507
- table = 'comment';
508
- columns = this.setColumns((t) => ({
509
- id: t.serial().primaryKey(),
510
- postId: t
511
- .integer()
512
- .foreignKey(() => PostTable, 'id')
513
- .index(),
514
- text: t.text(5, 1000),
515
- ...t.timestamps(),
516
- }));
517
-
518
- relations = {
519
- post: this.belongsTo(() => PostTable, {
520
- primaryKey: 'id',
521
- foreignKey: 'postId',
522
- }),
523
- };
524
- }
525
- `);
526
- });
527
-
528
- it('should create post table with zod schema', async () => {
529
- await initOrchidORM({
530
- demoTables: true,
531
- addSchemaToZod: true,
532
- });
533
-
534
- const [, content] = asMock(fs.writeFile).mock.calls.find(
535
- ([to]) => to === commentTablePath,
536
- );
537
- expect(content).toBe(`import { BaseTable } from '../baseTable';
538
- import { PostTable } from './post.table';
539
- import { tableToZod } from 'orchid-orm-schema-to-zod';
540
-
541
- export type Comment = CommentTable['columns']['type'];
542
- export class CommentTable extends BaseTable {
543
- table = 'comment';
544
- columns = this.setColumns((t) => ({
545
- id: t.serial().primaryKey(),
546
- postId: t
547
- .integer()
548
- .foreignKey(() => PostTable, 'id')
549
- .index(),
550
- text: t.text(5, 1000),
551
- ...t.timestamps(),
552
- }));
553
-
554
- relations = {
555
- post: this.belongsTo(() => PostTable, {
556
- primaryKey: 'id',
557
- foreignKey: 'postId',
558
- }),
559
- };
560
- }
561
-
562
- export const commentSchema = tableToZod(CommentTable);
563
- `);
564
- });
565
- });
566
-
567
- describe('config', () => {
568
- it('should create config file', async () => {
569
- await initOrchidORM({});
570
-
571
- const [, content] = asMock(fs.writeFile).mock.calls.find(
572
- ([to]) => to === configPath,
573
- );
574
- expect(content).toBe(`import 'dotenv/config';
575
-
576
- const database = {
577
- databaseURL: process.env.DATABASE_URL,
578
- };
579
- if (!database.databaseURL) throw new Error('DATABASE_URL is missing in .env');
580
-
581
- export const config = {
582
- database,
583
- };
584
- `);
585
- });
586
-
587
- it('should add test database config if specified', async () => {
588
- await initOrchidORM({
589
- testDatabase: true,
590
- });
591
-
592
- const [, content] = asMock(fs.writeFile).mock.calls.find(
593
- ([to]) => to === configPath,
594
- );
595
- expect(content).toBe(`import 'dotenv/config';
596
-
597
- const database = {
598
- databaseURL: process.env.DATABASE_URL,
599
- };
600
- if (!database.databaseURL) throw new Error('DATABASE_URL is missing in .env');
601
-
602
- const testDatabase = {
603
- databaseURL: process.env.DATABASE_TEST_URL,
604
- };
605
-
606
- const allDatabases = [database];
607
-
608
- if (testDatabase.databaseURL) {
609
- allDatabases.push(testDatabase);
610
- }
611
-
612
- export const config = {
613
- allDatabases,
614
- database: process.env.NODE_ENV === 'test' ? testDatabase : database,
615
- };
616
- `);
617
- });
618
- });
619
-
620
- describe('db.ts', () => {
621
- it('should create db.ts', async () => {
622
- await initOrchidORM({});
623
-
624
- const [, content] = asMock(fs.writeFile).mock.calls.find(
625
- ([to]) => to === dbPath,
626
- );
627
- expect(content).toBe(`import { orchidORM } from 'orchid-orm';
628
- import { config } from './config';
629
-
630
- export const db = orchidORM(config.database, {
631
- });
632
- `);
633
- });
634
-
635
- it('should create db.ts with demo tables', async () => {
636
- await initOrchidORM({
637
- demoTables: true,
638
- });
639
-
640
- const [, content] = asMock(fs.writeFile).mock.calls.find(
641
- ([to]) => to === dbPath,
642
- );
643
- expect(content).toBe(`import { orchidORM } from 'orchid-orm';
644
- import { config } from './config';
645
- import { PostTable } from './tables/post.table';
646
- import { CommentTable } from './tables/comment.table';
647
-
648
- export const db = orchidORM(config.database, {
649
- post: PostTable,
650
- comment: CommentTable,
651
- });
652
- `);
653
- });
654
- });
655
-
656
- describe('migrationScript', () => {
657
- it('should create script', async () => {
658
- await initOrchidORM({});
659
-
660
- const [, content] = asMock(fs.writeFile).mock.calls.find(
661
- ([to]) => to === migrationScriptPath,
662
- );
663
- expect(content).toBe(`import { rakeDb } from 'rake-db';
664
- import { config } from './config';
665
- import { appCodeUpdater } from 'orchid-orm';
666
-
667
- rakeDb(config.database, {
668
- migrationsPath: './migrations',
669
- appCodeUpdater: appCodeUpdater({
670
- tablePath: (tableName) => \`./tables/\${tableName}.table.ts\`,
671
- baseTablePath: './baseTable.ts',
672
- baseTableName: 'BaseTable',
673
- mainFilePath: './db.ts',
674
- }),
675
- useCodeUpdater: true, // set to false to disable code updater
676
- commands: {
677
- async seed() {
678
- const { seed } = await import('./seed');
679
- await seed();
680
- },
681
- },
682
- });
683
- `);
684
- });
685
-
686
- it('should create script with multiple databases', async () => {
687
- await initOrchidORM({
688
- testDatabase: true,
689
- });
690
-
691
- const [, content] = asMock(fs.writeFile).mock.calls.find(
692
- ([to]) => to === migrationScriptPath,
693
- );
694
- expect(content).toBe(`import { rakeDb } from 'rake-db';
695
- import { config } from './config';
696
- import { appCodeUpdater } from 'orchid-orm';
697
-
698
- rakeDb(config.allDatabases, {
699
- migrationsPath: './migrations',
700
- appCodeUpdater: appCodeUpdater({
701
- tablePath: (tableName) => \`./tables/\${tableName}.table.ts\`,
702
- baseTablePath: './baseTable.ts',
703
- baseTableName: 'BaseTable',
704
- mainFilePath: './db.ts',
705
- }),
706
- useCodeUpdater: true, // set to false to disable code updater
707
- commands: {
708
- async seed() {
709
- const { seed } = await import('./seed');
710
- await seed();
711
- },
712
- },
713
- });
714
- `);
715
- });
716
- });
717
-
718
- describe('migrations', () => {
719
- it('should create migrations directory', async () => {
720
- await initOrchidORM({});
721
-
722
- expect(fs.mkdir).toBeCalledWith(migrationsPath);
723
- });
724
-
725
- it('should create migrations if demoTables specified', async () => {
726
- await initOrchidORM({
727
- demoTables: true,
728
- });
729
-
730
- const [, post] = asMock(fs.writeFile).mock.calls.find(([to]) =>
731
- to.endsWith('createPost.ts'),
732
- );
733
- expect(post).toBe(`import { change } from 'rake-db';
734
-
735
- change(async (db) => {
736
- await db.createTable('post', (t) => ({
737
- id: t.serial().primaryKey(),
738
- title: t.text().unique(),
739
- text: t.text(),
740
- ...t.timestamps(),
741
- }));
742
- });
743
- `);
744
-
745
- const [, comment] = asMock(fs.writeFile).mock.calls.find(([to]) =>
746
- to.endsWith('createComment.ts'),
747
- );
748
- expect(comment).toBe(`import { change } from 'rake-db';
749
-
750
- change(async (db) => {
751
- await db.createTable('comment', (t) => ({
752
- id: t.serial().primaryKey(),
753
- postId: t.integer().foreignKey('post', 'id').index(),
754
- text: t.text(),
755
- ...t.timestamps(),
756
- }));
757
- });
758
- `);
759
- });
760
- });
761
-
762
- describe('seed', () => {
763
- it('should create seed file', async () => {
764
- await initOrchidORM({});
765
-
766
- const [, content] = asMock(fs.writeFile).mock.calls.find(
767
- ([to]) => to === seedPath,
768
- );
769
- expect(content).toBe(`import { db } from './db';
770
-
771
- export const seed = async () => {
772
- // create records here
773
-
774
- await db.$close();
775
- };
776
- `);
777
- });
778
-
779
- it('should create seed file with sample records when demoTables is set to true', async () => {
780
- await initOrchidORM({
781
- demoTables: true,
782
- });
783
-
784
- const [, content] = asMock(fs.writeFile).mock.calls.find(
785
- ([to]) => to === seedPath,
786
- );
787
- expect(content).toBe(`import { db } from './db';
788
-
789
- export const seed = async () => {
790
- await db.post.findBy({ title: 'Sample post' }).orCreate({
791
- title: 'Post',
792
- text: 'This is a text for a sample post. It contains words, spaces, and punctuation.',
793
- comments: {
794
- create: [
795
- {
796
- text: 'Nice post!',
797
- },
798
- {
799
- text: \`Too long, didn't read\`,
800
- },
801
- ],
802
- },
803
- });
804
-
805
- await db.$close();
806
- };
807
- `);
808
- });
809
- });
810
- });