-
-
Notifications
You must be signed in to change notification settings - Fork 160
/
umzug.test.ts
1190 lines (984 loc) · 35.7 KB
/
umzug.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {expectTypeOf} from 'expect-type'
import {fsSyncer} from 'fs-syncer'
import * as path from 'path'
import VError from 'verror'
import {vi as jest, describe, test, expect} from 'vitest'
import {memoryStorage, RerunBehavior, Umzug as Base, UmzugOptions} from '../src'
// To avoid having to manaully pass memoryStorage() to every instance, subclass umzug and override the default of JSONStorage.
// Otherwise we'd have to clean up the generated json file for every test
class Umzug<Ctx extends object = object> extends Base<Ctx> {
constructor(options: UmzugOptions<Ctx>) {
super({storage: memoryStorage(), ...options})
}
}
const names = (migrations: Array<{name: string}>) => migrations.map(m => m.name)
describe('basic usage', () => {
test('requires script files', async () => {
const spy = jest.spyOn(console, 'log').mockImplementation(() => {})
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/globjs'), {
'm1.js': `exports.up = async params => console.log('up1', params)`,
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.js', {cwd: syncer.baseDir}],
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1.js'])
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenNthCalledWith(1, 'up1', {
context: {someCustomSqlClient: {}},
name: 'm1.js',
path: path.join(syncer.baseDir, 'm1.js'),
})
})
test('imports esm files', async () => {
const spy = jest.spyOn(console, 'log').mockReset()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/esm'), {
'm1.mjs': `
export const up = async params => console.log('up1', params)
export const down = async params => console.log('down1', params)
`,
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.mjs', {cwd: syncer.baseDir}],
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1.mjs'])
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenNthCalledWith(1, 'up1', {
context: {someCustomSqlClient: {}},
name: 'm1.mjs',
path: path.join(syncer.baseDir, 'm1.mjs'),
})
await umzug.down()
expect(names(await umzug.executed())).toEqual([])
})
test('imports typescript esm files', async () => {
const spy = jest.spyOn(console, 'log').mockReset()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/esm'), {
'm1.mts': `export const up = async (params: {}) => console.log('up1', params)`,
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.mts', {cwd: syncer.baseDir}],
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1.mts'])
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenNthCalledWith(1, 'up1', {
context: {someCustomSqlClient: {}},
name: 'm1.mts',
path: path.join(syncer.baseDir, 'm1.mts'),
})
})
})
describe('custom context', () => {
test(`mutating context doesn't affect separate invocations`, async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: [{name: 'm1', up: spy}],
context: () => ({counter: 0}),
logger: undefined,
})
umzug.on('beforeCommand', ev => {
ev.context.counter++
})
await Promise.all([umzug.up(), umzug.up()])
expect(spy).toHaveBeenCalledTimes(2)
expect(spy.mock.calls).toMatchObject([
// because the context is lazy (returned by an inline function), both `up()` calls should
// get a fresh counter set to 0, which they each increment to 1
[{context: {counter: 1}}],
[{context: {counter: 1}}],
])
})
test(`create doesn't spawn multiple contexts`, async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/create-context'), {})
syncer.sync()
const spy = jest.fn()
const umzug = new Umzug({
migrations: {
glob: ['*.js', {cwd: syncer.baseDir}],
},
context: spy,
logger: undefined,
create: {
folder: syncer.baseDir,
},
})
await umzug.create({name: 'm1.js'})
expect(spy).toHaveBeenCalledTimes(1)
})
test(`create with custom template extension doesn't cause bogus warning`, async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/create-custom-template'), {})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.js', {cwd: syncer.baseDir}],
},
logger: undefined,
create: {
folder: syncer.baseDir,
template: filepath => [[`${filepath}.x.js`, `/* custom template */`]],
},
})
await umzug.create({name: 'test'})
const pending = names(await umzug.pending())
expect(pending).toHaveLength(1)
expect(pending[0]).toContain('test.x.js')
})
test(`create with custom content`, async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/create-custom-content'), {})
syncer.sync()
const umzug = new Umzug({
logger: undefined,
migrations: {
glob: ['*.js', {cwd: syncer.baseDir}],
},
create: {
folder: syncer.baseDir,
},
})
await umzug.create({name: 'abc.js', content: 'exports.up = () => 123'})
const pending = names(await umzug.pending())
expect(pending).toHaveLength(1)
expect(syncer.read()[pending[0]]).toEqual('exports.up = () => 123')
})
test(`create with custom template async method`, async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/create-custom-template-async'), {})
syncer.sync()
const template = async () => `/* custom template async */`
const umzug = new Umzug({
migrations: {
glob: ['*.js', {cwd: syncer.baseDir}],
},
logger: undefined,
create: {
folder: syncer.baseDir,
template: async filepath => [[`${filepath}.x.js`, await template()]],
},
})
await umzug.create({name: 'testAsync'})
const pending = names(await umzug.pending())
expect(pending).toHaveLength(1)
expect(pending[0]).toContain('testAsync.x.js')
})
test(`create doesn't cause "confusing oredering" warning when migrations are nested in folders`, async () => {
const syncer = fsSyncer(path.join(__dirname, 'generated/create-nested-folders'), {})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*/*.js', {cwd: syncer.baseDir}],
resolve(params) {
const name = path.basename(path.dirname(params.path!))
return {name, path: params.path, async up() {}}
},
},
logger: undefined,
create: {
folder: syncer.baseDir,
template: filepath => [[`${filepath}/migration.js`, `/* custom template */`]],
},
})
await umzug.create({name: 'test1'})
await umzug.create({name: 'test2'})
const pending = names(await umzug.pending())
expect(pending).toHaveLength(2)
expect(pending[0]).toContain('test1')
expect(pending[1]).toContain('test2')
})
describe(`resolve asynchronous context getter before the migrations run`, () => {
const sleep = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const getContext = async () => {
// It guarantees the initialization scripts or asynchronous stuff finished their work
// before the actual migrations workflow begins.
// Eg: const externalData = await retrieveExternalData();
await sleep(100)
return {innerValue: 'text'}
}
test(`context specified as a function`, async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: [{name: 'm2', up: spy}],
context: getContext,
logger: undefined,
})
await umzug.up()
expect(spy.mock.calls).toMatchObject([[{context: {innerValue: 'text'}}]])
})
test(`context specified as a function call`, async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: [{name: 'm3', up: spy}],
context: getContext(),
logger: undefined,
})
await umzug.up()
expect(spy.mock.calls).toMatchObject([[{context: {innerValue: 'text'}}]])
})
})
})
describe('alternate migration inputs', () => {
test('with file globbing', async () => {
const spy = jest.fn()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/glob'), {
'migration1.sql': 'select true',
'migration2.sql': 'select true',
'should-be-ignored.txt': 'abc',
'migration3.sql': 'select true',
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.sql', {cwd: syncer.baseDir}],
resolve: params => ({
...params,
up: async () => spy(params),
}),
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['migration1.sql', 'migration2.sql', 'migration3.sql'])
expect(spy).toHaveBeenCalledTimes(3)
expect(spy).toHaveBeenNthCalledWith(1, {
context: {someCustomSqlClient: {}},
name: 'migration1.sql',
path: path.join(syncer.baseDir, 'migration1.sql'),
})
})
test('up and down functions using `resolve` should receive parameters', async () => {
const spy = jest.fn()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/parameterless-fns'), {
'migration1.sql': 'select true',
})
syncer.sync()
const context = {someCustomSqlClient: {}}
const umzug = new Umzug({
migrations: {
glob: ['*.sql', {cwd: syncer.baseDir}],
resolve: resolveParams => ({
...resolveParams,
up: async upParams => spy('up', {resolveParams, upParams}),
down: async downParams => spy('down', {resolveParams, downParams}),
}),
},
context,
logger: undefined,
})
await umzug.up()
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenNthCalledWith(1, 'up', {
resolveParams: {name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context},
upParams: {name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context},
})
spy.mockClear()
await umzug.down()
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenNthCalledWith(1, 'down', {
resolveParams: {name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context},
downParams: {name: 'migration1.sql', path: path.join(syncer.baseDir, 'migration1.sql'), context},
})
})
test('up and down "to"', async () => {
const noop = async () => {}
const umzug = new Umzug({
migrations: [
{name: 'm1', up: noop},
{name: 'm2', up: noop},
{name: 'm3', up: noop},
{name: 'm4', up: noop},
{name: 'm5', up: noop},
{name: 'm6', up: noop},
{name: 'm7', up: noop},
],
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'])
expect(names(await umzug.pending())).toEqual([])
await umzug.down({})
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6'])
expect(names(await umzug.pending())).toEqual(['m7'])
await umzug.down({to: undefined})
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5'])
expect(names(await umzug.pending())).toEqual(['m6', 'm7'])
await umzug.down({to: 'm3'})
expect(names(await umzug.executed())).toEqual(['m1', 'm2'])
expect(names(await umzug.pending())).toEqual(['m3', 'm4', 'm5', 'm6', 'm7'])
await umzug.down({to: 0})
expect(names(await umzug.executed())).toEqual([])
expect(names(await umzug.pending())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'])
await umzug.up({to: 'm4'})
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4'])
expect(names(await umzug.pending())).toEqual(['m5', 'm6', 'm7'])
})
test('up and down with step', async () => {
const umzug = new Umzug({
migrations: [
{name: 'm1', async up() {}},
{name: 'm2', async up() {}},
{name: 'm3', async up() {}},
{name: 'm4', async up() {}},
],
logger: undefined,
})
await umzug.up({step: 3})
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3'])
expect(names(await umzug.pending())).toEqual(['m4'])
await umzug.down({step: 2})
expect(names(await umzug.executed())).toEqual(['m1'])
expect(names(await umzug.pending())).toEqual(['m2', 'm3', 'm4'])
})
test('up and down options', async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: Array.from({length: 7})
.map((_, i) => `m${i + 1}`)
.map(name => ({
name,
up: async () => spy('up-' + name),
down: async () => spy('down-' + name),
})),
logger: undefined,
})
await umzug.up({migrations: ['m2', 'm4']})
expect(names(await umzug.executed())).toEqual(['m2', 'm4'])
expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4']])
await expect(umzug.up({migrations: ['m2', 'm4']})).rejects.toThrow(
/Couldn't find migration to apply with name "m2"/,
)
// rerun behavior 'SKIP' silently ignores already-executed migrations
await umzug.up({migrations: ['m2', 'm4'], rerun: RerunBehavior.SKIP})
expect(names(await umzug.executed())).toEqual(['m2', 'm4'])
expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4']])
// rerun behavior 'ALLOW' runs already-executed migrations again
await umzug.up({migrations: ['m2', 'm4'], rerun: RerunBehavior.ALLOW})
expect(names(await umzug.executed())).toEqual(['m2', 'm4'])
expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4']])
// you can use migration names to run migrations in the "wrong" order:
await umzug.up({migrations: ['m5', 'm3'], rerun: RerunBehavior.ALLOW})
expect(names(await umzug.executed())).toEqual(['m2', 'm3', 'm4', 'm5'])
expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4'], ['up-m5'], ['up-m3']])
// invalid migration names result in an error:
await expect(umzug.up({migrations: ['m1', 'typo'], rerun: RerunBehavior.ALLOW})).rejects.toThrow(
/Couldn't find migration to apply with name "typo"/,
)
// even though m1 _is_ a valid name, it shouldn't have been called - all listed migrations are verified before running any
expect(spy.mock.calls).toEqual([['up-m2'], ['up-m4'], ['up-m2'], ['up-m4'], ['up-m5'], ['up-m3']])
expect(JSON.stringify(spy.mock.calls)).not.toContain('up-m1')
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7'])
spy.mockClear()
await umzug.down({migrations: ['m1', 'm3', 'm5', 'm7']})
expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6'])
expect(spy.mock.calls).toEqual([['down-m1'], ['down-m3'], ['down-m5'], ['down-m7']])
// rerun behavior 'SKIP' ignores down migrations that have already been reverted
await umzug.down({migrations: ['m1', 'm3', 'm5', 'm7'], rerun: RerunBehavior.SKIP})
expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6'])
expect(spy.mock.calls).toEqual([['down-m1'], ['down-m3'], ['down-m5'], ['down-m7']])
await expect(umzug.down({migrations: ['m1', 'm3', 'm5', 'm7']})).rejects.toThrow(
/Couldn't find migration to apply with name "m1"/,
)
await umzug.down({migrations: ['m1', 'm3', 'm5', 'm7'], rerun: RerunBehavior.ALLOW})
expect(names(await umzug.executed())).toEqual(['m2', 'm4', 'm6'])
expect(spy.mock.calls).toEqual([
['down-m1'],
['down-m3'],
['down-m5'],
['down-m7'],
['down-m1'],
['down-m3'],
['down-m5'],
['down-m7'],
])
})
test('up and down return migration meta array', async () => {
const umzug = new Umzug({
migrations: [
{name: 'm1', path: 'm1.sql', async up() {}},
{name: 'm2', path: 'm2.sql', async up() {}},
],
logger: undefined,
})
const upResults = await umzug.up()
expect(upResults).toEqual([
{name: 'm1', path: 'm1.sql'},
{name: 'm2', path: 'm2.sql'},
])
const downResults = await umzug.down({to: 0})
expect(downResults).toEqual([
{name: 'm2', path: 'm2.sql'},
{name: 'm1', path: 'm1.sql'},
])
})
test('custom storage', async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: [{name: 'm1', async up() {}}],
context: {someCustomSqlClient: {}},
storage: {
executed: async (...args) => spy('executed', ...args),
logMigration: async (...args) => spy('logMigration', ...args),
unlogMigration: async (...args) => spy('unlogMigration', ...args),
},
logger: undefined,
})
await umzug.up()
expect(spy.mock.calls).toEqual([
['executed', {context: {someCustomSqlClient: {}}}],
['logMigration', {name: 'm1', context: {someCustomSqlClient: {}}}],
])
spy.mockClear()
spy.mockReturnValueOnce(['m1'])
await umzug.down()
expect(spy.mock.calls).toEqual([
['executed', {context: {someCustomSqlClient: {}}}],
['unlogMigration', {name: 'm1', context: {someCustomSqlClient: {}}}],
])
})
test('with migrations array', async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations: [
{
name: 'migration1',
up: async () => spy('migration1-up'),
},
{
name: 'migration2',
up: async () => spy('migration2-up'),
},
],
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['migration1', 'migration2'])
expect(spy).toHaveBeenCalledTimes(2)
expect(spy).toHaveBeenNthCalledWith(1, 'migration1-up')
})
test('with function returning migrations array', async () => {
const spy = jest.fn()
const umzug = new Umzug({
migrations(context) {
expect(context).toEqual({someCustomSqlClient: {}})
return [
{
name: 'migration1',
up: async () => spy('migration1-up'),
},
{
name: 'migration2',
up: async () => spy('migration2-up'),
},
]
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['migration1', 'migration2'])
expect(spy).toHaveBeenCalledTimes(2)
expect(spy).toHaveBeenNthCalledWith(1, 'migration1-up')
})
test('errors are wrapped helpfully', async () => {
// Raw errors usually won't tell you which migration threw. This test ensures umzug adds that information.
const umzug = new Umzug({
migrations: [
{
name: 'm1',
async up() {},
async down() {
throw new Error('Some cryptic failure')
},
},
{
name: 'm2',
async up() {
throw new Error('Some cryptic failure')
},
async down() {},
},
],
logger: undefined,
})
await expect(umzug.up()).rejects.toThrowError('Migration m2 (up) failed: Original error: Some cryptic failure')
await expect(umzug.down()).rejects.toThrowError('Migration m1 (down) failed: Original error: Some cryptic failure')
})
test('Error causes are propagated properly', async () => {
const umzug = new Umzug({
migrations: [
{
name: 'm1',
async up() {},
async down() {
throw new VError({info: {extra: 'detail'}}, 'Some cryptic failure')
},
},
{
name: 'm2',
async up() {
throw new VError({info: {extra: 'detail'}}, 'Some cryptic failure')
},
async down() {},
},
],
logger: undefined,
})
await expect(umzug.up()).rejects.toThrow(/Migration m2 \(up\) failed: Original error: Some cryptic failure/)
// slightly weird format verror uses, not worth validating much more than that the `cause` is captured
await expect(umzug.up()).rejects.toMatchObject({
jse_cause: {
jse_info: {extra: 'detail'},
},
})
await expect(umzug.down()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Migration m1 (down) failed: Original error: Some cryptic failure"`,
)
await expect(umzug.down()).rejects.toMatchObject({
jse_cause: {
jse_info: {extra: 'detail'},
},
})
})
test('non-error throwables are wrapped helpfully', async () => {
// Migration errors usually won't tell you which migration threw. This test ensures umzug adds that information.
const umzug = new Umzug({
migrations: [
{
name: 'm1',
async up() {},
async down() {
throw 'Some cryptic failure'
},
},
{
name: 'm2',
async up() {
throw 'Some cryptic failure'
},
async down() {},
},
],
logger: undefined,
})
await expect(umzug.up()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Migration m2 (up) failed: Non-error value thrown. See info for full props: Some cryptic failure"`,
)
await expect(umzug.down()).rejects.toThrowErrorMatchingInlineSnapshot(
`"Migration m1 (down) failed: Non-error value thrown. See info for full props: Some cryptic failure"`,
)
})
test('typescript migration files', async () => {
require('ts-node/register')
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/typescript'), {
'm1.ts': `export const up = () => {}; export const down = () => {}`,
'm2.ts': `throw SyntaxError('Fake syntax error to simulate typescript modules not being registered')`,
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.ts', {cwd: syncer.baseDir}],
},
logger: undefined,
})
expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m1.ts', 'm2.ts'], []])
await umzug.up({to: 'm1.ts'})
expect([names(await umzug.pending()), names(await umzug.executed())]).toEqual([['m2.ts'], ['m1.ts']])
const err = await umzug.up().catch(String)
expect(err).toContain(
'Migration m2.ts (up) failed: Original error: Fake syntax error to simulate typescript modules not being registered',
)
expect(err).toContain(
"TypeScript files can be required by adding `ts-node` as a dependency and calling `require('ts-node/register')` at the program entrypoint before running migrations.",
)
})
test('with custom file globbing options', async () => {
const spy = jest.fn()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/glob'), {
'migration1.sql': 'select true',
'migration2.sql': 'select true',
'should-be-ignored.txt': 'abc',
'migration3.sql': 'select true',
'ignoreme1.sql': 'select false',
'ignoreme2.sql': 'select false',
})
syncer.sync()
const umzug = new Umzug({
migrations: {
glob: ['*.sql', {cwd: syncer.baseDir, ignore: ['ignoreme*.sql']}],
resolve: params => ({
...params,
up: async () => spy(params),
}),
},
context: {someCustomSqlClient: {}},
logger: undefined,
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['migration1.sql', 'migration2.sql', 'migration3.sql'])
expect(spy).toHaveBeenCalledTimes(3)
expect(spy).toHaveBeenNthCalledWith(1, {
context: {someCustomSqlClient: {}},
name: 'migration1.sql',
path: path.join(syncer.baseDir, 'migration1.sql'),
})
})
test('allows customization via parent instance', async () => {
const spy = jest.fn()
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/customOrdering'), {
'migration1.sql': 'select true',
'migration2.sql': 'select true',
'should-be-ignored.txt': 'abc',
'migration3.sql': 'select true',
})
syncer.sync()
const parent = new Umzug({
migrations: {
glob: ['*.sql', {cwd: syncer.baseDir}],
resolve: ({context, ...params}) => ({
...params,
up: async () => context.spy(params),
}),
},
context: {spy},
logger: undefined,
})
const umzug = new Umzug({
...parent.options,
migrations: async context => (await parent.migrations(context)).slice().reverse(),
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['migration3.sql', 'migration2.sql', 'migration1.sql'])
expect(spy).toHaveBeenCalledTimes(3)
expect(spy).toHaveBeenNthCalledWith(1, {
name: 'migration3.sql',
path: path.join(syncer.baseDir, 'migration3.sql'),
})
})
test('supports nested directories via getMigrations', async () => {
const spy = jest.fn()
// folder structure splitting migrations into separate directories, with the filename determining the order:
const syncer = fsSyncer(path.join(__dirname, 'generated/umzug/customOrdering'), {
directory1: {
'm1.sql': 'select true',
'm1.down.sql': 'select false',
'm4.sql': 'select true',
},
deeply: {
nested: {
directory2: {
'm2.sql': 'select true',
'm3.sql': 'select true',
},
},
},
})
syncer.sync()
const withDefaultOrdering = new Umzug({
migrations: {
glob: ['**/*.sql', {cwd: syncer.baseDir, ignore: '**/*.down.sql'}],
resolve: params => ({
...params,
up: async () => spy(params),
}),
},
logger: undefined,
})
const umzug = new Umzug({
...withDefaultOrdering.options,
migrations: async ctx =>
(await withDefaultOrdering.migrations(ctx)).slice().sort((a, b) => a.name.localeCompare(b.name)),
})
await umzug.up()
expect(names(await umzug.executed())).toEqual(['m1.sql', 'm2.sql', 'm3.sql', 'm4.sql'])
expect(spy).toHaveBeenCalledTimes(4)
expect(spy).toHaveBeenNthCalledWith(1, {
name: 'm1.sql',
path: path.join(syncer.baseDir, 'directory1/m1.sql'),
context: {},
})
expect(spy).toHaveBeenNthCalledWith(2, {
name: 'm2.sql',
path: path.join(syncer.baseDir, 'deeply/nested/directory2/m2.sql'),
context: {},
})
})
})
describe('types', () => {
test('constructor function', () => {
expectTypeOf(Umzug).constructorParameters.toMatchTypeOf<{length: 1}>()
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: {glob: '*/*.js'},
storage: memoryStorage(),
logger: undefined,
})
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: {glob: ['*/*.js', {cwd: 'x/y/z'}]},
logger: undefined,
})
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: {glob: ['*/*.js', {ignore: ['**/*ignoreme*.js']}]},
logger: undefined,
})
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: [
{name: 'm1', async up() {}},
{name: 'm2', async up() {}, async down() {}},
],
logger: undefined,
})
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: [],
storage: memoryStorage(),
context: {foo: 123},
logger: console,
})
expectTypeOf(Umzug)
.constructorParameters.toHaveProperty('0')
.toHaveProperty('logger')
.toMatchTypeOf<undefined | Pick<typeof console, 'info' | 'warn' | 'error'>>()
expectTypeOf(Umzug).toBeConstructibleWith({
migrations: [],
storage: memoryStorage(),
context: {foo: 123},
logger: {
...console,
info: (...args) => expectTypeOf(args).toEqualTypeOf<[Record<string, unknown>]>(),
},
})
})
test('rerun behavior is a map of its keys to themselves', () => {
expectTypeOf(RerunBehavior).toEqualTypeOf<{readonly [K in RerunBehavior]: K}>()
})
test('up and down', () => {
const up = expectTypeOf(Umzug).instance.toHaveProperty('up')
const down = expectTypeOf(Umzug).instance.toHaveProperty('down')
up.toBeCallableWith({to: 'migration123'})
up.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.ALLOW})
up.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.SKIP})
up.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.THROW})
up.toBeCallableWith({migrations: ['m1'], rerun: 'ALLOW'})
up.toBeCallableWith({migrations: ['m1'], rerun: 'SKIP'})
up.toBeCallableWith({migrations: ['m1'], rerun: 'THROW'})
// @ts-expect-error (don't allow general strings for rerun behavior)
up.toBeCallableWith({migrations: ['m1'], rerun: 'xyztypo'})
// @ts-expect-error (rerun must be specified with `migrations`)
up.toBeCallableWith({rerun: 'ALLOW'})
// @ts-expect-error (can't go up "to" 0)
up.toBeCallableWith({to: 0})
down.toBeCallableWith({to: 'migration123'})
down.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.ALLOW})
down.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.SKIP})
down.toBeCallableWith({migrations: ['m1'], rerun: RerunBehavior.THROW})
down.toBeCallableWith({migrations: ['m1'], rerun: 'ALLOW'})
down.toBeCallableWith({migrations: ['m1'], rerun: 'SKIP'})
down.toBeCallableWith({migrations: ['m1'], rerun: 'THROW'})
// @ts-expect-error (don't allow general strings for rerun behavior)
down.toBeCallableWith({migrations: ['m1'], rerun: 'xyztypo'})
// @ts-expect-error (rerun can only be specified with `migrations`)
down.toBeCallableWith({rerun: 'ALLOW'})
down.toBeCallableWith({to: 0})
// @ts-expect-error (`{ to: 0 }` is a special case. `{ to: 1 }` shouldn't be allowed)
down.toBeCallableWith({to: 1})
// @ts-expect-error (`{ to: 0 }` is a special case. `{ to: 1 }` shouldn't be allowed)
up.toBeCallableWith({to: 1})
up.returns.toEqualTypeOf<Promise<Array<{name: string; path?: string}>>>()
down.returns.toEqualTypeOf<Promise<Array<{name: string; path?: string}>>>()
})
test('pending', () => {
expectTypeOf(Umzug).instance.toHaveProperty('pending').returns.resolves.items.toEqualTypeOf<{
name: string
path?: string
}>()
})
test('executed', () => {
expectTypeOf(Umzug).instance.toHaveProperty('executed').returns.resolves.items.toEqualTypeOf<{
name: string
path?: string
}>()
})
test('migration type', () => {
const umzug = new Umzug({
migrations: {glob: '*/*.ts'},
context: {someCustomSqlClient: {}},
logger: undefined,
})
type Migration = typeof umzug._types.migration
expectTypeOf<Migration>()
.parameter(0)
.toMatchTypeOf<{name: string; path?: string; context: {someCustomSqlClient: {}}}>()
expectTypeOf<Migration>().returns.toEqualTypeOf<Promise<unknown>>()