/
migration-integration.spec.js
1357 lines (1228 loc) · 47.3 KB
/
migration-integration.spec.js
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
'use strict';
const chai = require('chai');
chai.use(require('chai-as-promised'));
const { expect } = chai;
const { FileTestHelper } = require('cli-testlab');
const equal = require('assert').equal;
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const knexLib = require('../../../knex');
const logger = require('../../integration/logger');
const config = require('../../knexfile');
const delay = require('../../../lib/execution/internal/delay');
const _ = require('lodash');
const testMemoryMigrations = require('./memory-migrations');
const {
isPostgreSQL,
isOracle,
isMssql,
isMysql,
isSQLite,
isRedshift,
} = require('../../util/db-helpers');
const { assertNumber } = require('../../util/assertHelper');
const { getAllDbs, getKnexForDb } = require('../util/knex-instance-provider');
const {
ensureTable,
} = require('../../../lib/migrations/migrate/table-creator');
describe('Migrations', function () {
getAllDbs().forEach((db) => {
describe(db, () => {
let knex;
before(async () => {
rimraf.sync(path.join(__dirname, './migration'));
knex = logger(getKnexForDb(db));
// make sure lock was not left from previous failed test run
await knex.schema.dropTableIfExists('knex_migrations');
await knex.schema.dropTableIfExists('migration_test_1');
await knex.schema.dropTableIfExists('migration_test_2');
await knex.schema.dropTableIfExists('migration_test_2_1');
await knex.migrate.forceFreeMigrationsLock({
directory: 'test/integration2/migrate/test',
});
});
describe('knex.migrate', function () {
it('should not fail on null default for timestamp', async () => {
try {
await knex.schema.dropTableIfExists('null_date');
await knex.migrate.latest({
directory: 'test/integration2/migrate/null_timestamp_default',
});
await knex.into('null_date').insert({
dummy: 'cannot insert empty object',
});
const rows = await knex('null_date').first();
expect(rows.deleted_at).to.equal(null);
} finally {
await knex.migrate.rollback({
directory: 'test/integration2/migrate/null_timestamp_default',
});
}
});
it('should not fail drop-and-recreate-column operation when using promise chain', () => {
return knex.migrate
.latest({
directory: 'test/integration2/migrate/drop-and-recreate',
})
.then(() => {
return knex.migrate.rollback({
directory: 'test/integration2/migrate/drop-and-recreate',
});
});
});
if (isPostgreSQL(knex)) {
it('should not fail drop-and-recreate-column operation when using promise chain and schema', () => {
return knex.migrate
.latest({
directory:
'test/integration2/migrate/drop-and-recreate-with-schema',
})
.then(() => {
return knex.migrate.rollback({
directory:
'test/integration2/migrate/drop-and-recreate-with-schema',
});
});
});
}
if (isSQLite(knex)) {
it('should not fail rename-and-drop-column with multiline sql from legacy db', async () => {
const knexConfig = _.extend({}, config.sqlite3, {
connection: {
filename: __dirname + '/../../multilineCreateMaster.sqlite3',
},
migrations: {
directory:
'test/integration2/migrate/rename-and-drop-column-with-multiline-sql-from-legacy-db',
},
});
const knexInstance = knexLib(knexConfig);
const db = logger(knexInstance);
await db.migrate.latest();
await db.migrate.rollback();
await knexInstance.destroy();
});
}
it('should not fail drop-and-recreate-column operation when using async/await', () => {
return knex.migrate
.latest({
directory:
'test/integration2/migrate/async-await-drop-and-recreate',
})
.then(() => {
return knex.migrate.rollback({
directory:
'test/integration2/migrate/async-await-drop-and-recreate',
});
});
});
if (isPostgreSQL(knex)) {
it('should not fail drop-and-recreate-column operation when using async/await and schema', () => {
return knex.migrate
.latest({
directory:
'test/integration2/migrate/async-await-drop-and-recreate-with-schema',
})
.then(() => {
return knex.migrate.rollback({
directory:
'test/integration2/migrate/async-await-drop-and-recreate-with-schema',
});
});
});
}
it('should create a new migration file with the create method', function () {
return knex.migrate.make('test').then(function (name) {
name = path.basename(name);
expect(name.split('_')[0]).to.have.length(14);
expect(name.split('_')[1].split('.')[0]).to.equal('test');
});
});
it('should list the current migration state with the currentVersion method', function () {
return knex.migrate.currentVersion().then(function (version) {
equal(version, 'none');
});
});
const tables = [
'migration_test_1',
'migration_test_2',
'migration_test_2_1',
];
describe('knex.migrate.status', function () {
this.timeout(process.env.KNEX_TEST_TIMEOUT || 30000);
beforeEach(function () {
return knex.migrate.latest({
directory: 'test/integration2/migrate/test',
});
});
afterEach(function () {
return knex.migrate.rollback({
directory: 'test/integration2/migrate/test',
});
});
it('should create a migrations lock table', function () {
return knex.schema
.hasTable('knex_migrations_lock')
.then(function (exists) {
expect(exists).to.equal(true);
return knex.schema
.hasColumn('knex_migrations_lock', 'is_locked')
.then(function (exists) {
expect(exists).to.equal(true);
});
});
});
it('should return 0 if code matches DB', function () {
return knex.migrate
.status({ directory: 'test/integration2/migrate/test' })
.then(function (migrationLevel) {
expect(migrationLevel).to.equal(0);
});
});
it('should return a negative number if the DB is behind', function () {
return knex.migrate
.rollback({ directory: 'test/integration2/migrate/test' })
.then(function () {
return knex.migrate
.status({ directory: 'test/integration2/migrate/test' })
.then(function (migrationLevel) {
expect(migrationLevel).to.equal(-2);
});
});
});
it('should return a positive number if the DB is ahead', async () => {
const [migration1, migration2, migration3] = await Promise.all([
knex('knex_migrations').returning('id').insert({
name: 'foobar',
batch: 5,
migration_time: new Date(),
}),
knex('knex_migrations').returning('id').insert({
name: 'foobar',
batch: 5,
migration_time: new Date(),
}),
knex('knex_migrations').returning('id').insert({
name: 'foobarbaz',
batch: 6,
migration_time: new Date(),
}),
]);
return knex.migrate
.status({ directory: 'test/integration2/migrate/test' })
.then(function (migrationLevel) {
expect(migrationLevel).to.equal(3);
})
.then(function () {
// Cleanup the added migrations
if (isRedshift(knex)) {
return knex('knex_migrations')
.where('name', 'like', '%foobar%')
.del();
}
return knex('knex_migrations')
.where('id', migration1[0])
.orWhere('id', migration2[0])
.orWhere('id', migration3[0])
.del();
});
});
});
describe('knex.migrate.latest', function () {
before(function () {
return knex.migrate.latest({
directory: 'test/integration2/migrate/test',
});
});
it('should remove the record in the lock table once finished', function () {
return knex('knex_migrations_lock')
.select('*')
.then(function (data) {
expect(data[0]).to.have.property('is_locked');
expect(Number.parseInt(data[0].is_locked)).to.not.be.ok;
});
});
it('should throw error if the migrations are already running', function () {
return knex('knex_migrations_lock')
.update({ is_locked: 1 })
.then(function () {
return knex.migrate
.latest({ directory: 'test/integration2/migrate/test' })
.then(function () {
throw new Error('then should not execute');
});
})
.catch(function (error) {
expect(error).to.have.property(
'message',
'Migration table is already locked'
);
return knex('knex_migrations_lock').select('*');
})
.then(function (data) {
assertNumber(knex, data[0].is_locked, 1);
// Clean up lock for other tests
return knex('knex_migrations_lock').update({ is_locked: 0 });
});
});
it('should work with concurent calls to _lockMigrations', async function () {
if (isSQLite(knex)) {
// sqlite doesn't support concurrency
this.skip();
return;
}
const migrator = knex.migrate;
try {
// Start two transactions and call _lockMigrations in each of them.
// Simulate a race condition by waiting until both are started before
// attempting to commit either one. Exactly one should succeed.
//
// Both orderings are legitimate, but in practice the first transaction
// to start will be the one that succeeds in all currently supported
// databases (CockroachDB 1.x is an example of a database where the
// second transaction would win, but this changed in 2.0). This test
// assumes the first transaction wins, but could be refactored to support
// both orderings if desired.
const trx1 = await knex.transaction();
await migrator._lockMigrations(trx1);
const trx2 = await knex.transaction();
// trx1 has a pending write lock, so the second call to _lockMigrations
// will block (unless we're on a DB that resolves the transaction in
// the other order as mentioned above).
// Save the promise, then wait a short time to ensure it's had time
// to start its query and get blocked.
const trx2Promise = migrator._lockMigrations(trx2);
await delay(100);
const isTrx2PromisePending = await Promise.race([
delay(10).then(() => true),
trx2Promise.catch(() => {}).then(() => false),
]);
if (!isTrx2PromisePending) {
throw new Error('expected trx2 to be pending');
}
await trx1.commit();
// trx1 has completed and unblocked trx2, which should now fail.
try {
await trx2Promise;
throw new Error('expected trx2 to fail');
} catch (error) {
expect(error)
.to.have.property('message')
.that.includes('already locked');
await trx2.rollback();
}
} finally {
// Clean up after ourselves (I'm not sure why the before() at the
// top of this file isn't doing it, but if this test fails without
// this call it tends to cause cascading failures).
await migrator._freeLock();
}
});
it('should report failing migration', function () {
const migrator = knex.migrate;
return migrator
.latest({
directory: 'test/integration2/migrate/test_with_invalid',
})
.then(function () {
throw new Error('then should not execute');
})
.catch(function (error) {
// This will fail because of the invalid migration
expect(error)
.to.have.property('message')
.that.includes('unknown_table');
expect(migrator)
.to.have.property('_activeMigration')
.to.have.property(
'fileName',
'20150109002832_invalid_migration.js'
);
})
.then(function (data) {
// Clean up lock for other tests
// TODO: Remove this code to reproduce https://github.com/tgriesser/knex/issues/2925
// It is only relevant for Oracle, most likely there is a bug somewhere that needs fixing
return knex('knex_migrations_lock').update({ is_locked: 0 });
});
});
it('should release lock if non-locking related error is thrown', function () {
return knex('knex_migrations_lock')
.select('*')
.then(function (data) {
expect(Number.parseInt(data[0].is_locked)).to.not.be.ok;
});
});
it('should run all migration files in the specified directory', function () {
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(2);
});
});
it('should run the migrations from oldest to newest', function () {
if (isOracle(knex)) {
return knex('knex_migrations')
.orderBy('migration_time', 'asc')
.select('*')
.then(function (data) {
expect(path.basename(data[0].name)).to.equal(
'20131019235242_migration_1.js'
);
expect(path.basename(data[1].name)).to.equal(
'20131019235306_migration_2.js'
);
});
} else {
return knex('knex_migrations')
.orderBy('id', 'asc')
.select('*')
.then(function (data) {
expect(path.basename(data[0].name)).to.equal(
'20131019235242_migration_1.js'
);
expect(path.basename(data[1].name)).to.equal(
'20131019235306_migration_2.js'
);
});
}
});
it('should create all specified tables and columns', function () {
// Map the table names to promises that evaluate chai expectations to
// confirm that the table exists and the 'id' and 'name' columns exist
// within the table
return Promise.all(
tables.map(function (table) {
return knex.schema.hasTable(table).then(function (exists) {
expect(exists).to.equal(true);
if (exists) {
return Promise.all([
knex.schema
.hasColumn(table, 'id')
.then(function (exists) {
expect(exists).to.equal(true);
}),
knex.schema
.hasColumn(table, 'name')
.then(function (exists) {
expect(exists).to.equal(true);
}),
]);
}
});
})
);
});
});
describe('knex.migrate.latest - multiple directories', () => {
before(() => {
return knex.migrate.latest({
directory: [
'test/integration2/migrate/test',
'test/integration2/migrate/test2',
],
});
});
after(() => {
return knex.migrate.rollback({
directory: [
'test/integration2/migrate/test',
'test/integration2/migrate/test2',
],
});
});
it('should create tables specified in both directories', () => {
// Map the table names to promises that evaluate chai expectations to
// confirm that the table exists
const expectedTables = [
'migration_test_1',
'migration_test_2',
'migration_test_2_1',
'migration_test_3',
'migration_test_4',
'migration_test_4_1',
];
return Promise.all(
expectedTables.map(function (table) {
return knex.schema.hasTable(table).then(function (exists) {
expect(exists).to.equal(true);
});
})
);
});
});
describe('knex.migrate.rollback', function () {
it('should delete the most recent batch from the migration log', function () {
return knex.migrate
.rollback({ directory: 'test/integration2/migrate/test' })
.then(([batchNo, log]) => {
assertNumber(knex, batchNo, 1);
expect(log).to.have.length(2);
expect(log[0]).to.contain(batchNo);
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(0);
});
});
});
it('should drop tables as specified in the batch', function () {
return Promise.all(
tables.map(function (table) {
return knex.schema.hasTable(table).then(function (exists) {
expect(!!exists).to.equal(false);
});
})
);
});
});
describe('knex.migrate.rollback - all', () => {
before(() => {
return knex.migrate
.latest({
directory: ['test/integration2/migrate/test'],
})
.then(function () {
return knex.migrate.latest({
directory: [
'test/integration2/migrate/test',
'test/integration2/migrate/test2',
],
});
});
});
it('should delete all batches from the migration log', () => {
return knex.migrate
.rollback(
{
directory: [
'test/integration2/migrate/test',
'test/integration2/migrate/test2',
],
},
true
)
.then(([batchNo, log]) => {
assertNumber(knex, batchNo, 2);
expect(log).to.have.length(4);
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(0);
});
});
});
it('should drop tables as specified in the batch', () => {
return Promise.all(
tables.map(function (table) {
return knex.schema.hasTable(table).then(function (exists) {
expect(!!exists).to.equal(false);
});
})
);
});
});
describe('knex.migrate.rollback - all', () => {
before(() => {
return knex.migrate.latest({
directory: ['test/integration2/migrate/test'],
});
});
it('should only rollback migrations that have been completed and in reverse chronological order', () => {
return knex.migrate
.rollback(
{
directory: [
'test/integration2/migrate/test',
'test/integration2/migrate/test2',
],
},
true
)
.then(([batchNo, log]) => {
assertNumber(knex, batchNo, 1);
expect(log).to.have.length(2);
fs.readdirSync('test/integration2/migrate/test')
.reverse()
.forEach((fileName, index) => {
expect(fileName).to.equal(log[index]);
});
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(0);
});
});
});
it('should drop tables as specified in the batch', () => {
return Promise.all(
tables.map(function (table) {
return knex.schema.hasTable(table).then(function (exists) {
expect(!!exists).to.equal(false);
});
})
);
});
});
describe('knex.migrate.up', () => {
afterEach(() => {
return knex.migrate.rollback(
{ directory: 'test/integration2/migrate/test' },
true
);
});
it('should only run the first migration if no migrations have run', function () {
return knex.migrate
.up({
directory: 'test/integration2/migrate/test',
})
.then(() => {
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data).to.have.length(1);
expect(path.basename(data[0].name)).to.equal(
'20131019235242_migration_1.js'
);
});
});
});
it('should only run the next migration that has not yet run if other migrations have already run', function () {
return knex.migrate
.up({
directory: 'test/integration2/migrate/test',
})
.then(() => {
return knex.migrate
.up({
directory: 'test/integration2/migrate/test',
})
.then(() => {
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data).to.have.length(2);
expect(path.basename(data[0].name)).to.equal(
'20131019235242_migration_1.js'
);
expect(path.basename(data[1].name)).to.equal(
'20131019235306_migration_2.js'
);
});
});
});
});
it('should not error if all migrations have already been run', function () {
return knex.migrate
.latest({
directory: 'test/integration2/migrate/test',
})
.then(() => {
return knex.migrate
.up({
directory: 'test/integration2/migrate/test',
})
.then((data) => {
expect(data).to.be.an('array');
});
});
});
it('should drop a column with a default constraint (mssql)', async () => {
await knex.migrate.latest({
directory:
'test/integration2/migrate/drop-with-default-constraint',
});
await knex.migrate.rollback({
directory:
'test/integration2/migrate/drop-with-default-constraint',
});
});
describe('with transactions disabled', () => {
beforeEach(async () => {
await knex.migrate.up({
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
name: 'create_table.js',
});
await knex.table('test_transactions').insert({ value: 0 });
});
afterEach(async () => {
await knex.migrate.rollback(
{
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
},
true
);
});
it('should partially run', async () => {
await expect(
knex.migrate.up({
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
name: 'up.js',
})
).to.eventually.be.rejected;
const { value } = await knex
.table('test_transactions')
.select('value')
.first();
assertNumber(knex, value, 1); // updated by migration before error
});
});
});
describe('knex.migrate.down', () => {
describe('with transactions enabled', () => {
beforeEach(async () => {
await knex.migrate.latest({
directory: ['test/integration2/migrate/test'],
});
});
afterEach(async () => {
await knex.migrate.rollback(
{ directory: ['test/integration2/migrate/test'] },
true
);
});
it('should only undo the last migration that was run if all migrations have run', async () => {
await knex.migrate.down({
directory: ['test/integration2/migrate/test'],
});
const data = await knex('knex_migrations').select('*');
expect(data).to.have.length(1);
expect(path.basename(data[0].name)).to.equal(
'20131019235242_migration_1.js'
);
});
it('should only undo the last migration that was run if there are other migrations that have not yet run', async () => {
await knex.migrate.down({
directory: ['test/integration2/migrate/test'],
});
await knex.migrate.down({
directory: ['test/integration2/migrate/test'],
});
const data = await knex('knex_migrations').select('*');
expect(data).to.have.length(0);
});
it('should not error if all migrations have already been undone', async () => {
await knex.migrate.rollback(
{ directory: ['test/integration2/migrate/test'] },
true
);
const data = await knex.migrate.down({
directory: ['test/integration2/migrate/test'],
});
expect(data).to.be.an('array');
});
});
describe('with transactions disabled', () => {
beforeEach(async () => {
await knex.migrate.up({
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
name: 'create_table.js',
});
await knex.table('test_transactions').insert({ value: 0 });
});
afterEach(async () => {
await knex.migrate.rollback(
{
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled/rollback',
},
true
);
});
it('should partially run', async () => {
await knex.migrate.up({
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
name: 'down.js',
});
await expect(
knex.migrate.down({
directory:
'test/integration2/migrate/test_single_per_migration_trx_disabled',
name: 'down.js',
})
).to.eventually.be.rejected;
const { value } = await knex
.table('test_transactions')
.select('value')
.first();
assertNumber(knex, value, -1); // updated by migration before error
});
});
});
describe('knex.migrate.list', () => {
const availableMigrations = [
'20131019235242_migration_1.js',
'20131019235306_migration_2.js',
];
const knexConfig = {
directory: ['test/integration2/migrate/test'],
};
beforeEach(async () => {
await knex.migrate.rollback(knexConfig, true);
});
describe('should list pending and completed migrations', () => {
it('as an array of arrays of pending and completed migrations', async () => {
const listedMigrations = await knex.migrate.list(knexConfig);
expect(listedMigrations).to.have.lengthOf(2);
expect(listedMigrations[0]).to.be.an.instanceof(Array);
expect(listedMigrations[1]).to.be.an.instanceof(Array);
});
it('in the right quantity', async () => {
let [completed, pending] = await knex.migrate.list(knexConfig);
expect(completed).to.have.lengthOf(0);
expect(pending).to.have.lengthOf(2);
await knex.migrate.latest(knexConfig);
[completed, pending] = await knex.migrate.list(knexConfig);
expect(completed).to.have.lengthOf(2);
expect(pending).to.have.lengthOf(0);
});
it('with the right object structure for pending migrations', async () => {
const [completed, pending] = await knex.migrate.list(knexConfig);
expect(completed).to.deep.equal([]);
expect(pending).to.deep.equal(
availableMigrations.map((migration) => ({
file: migration,
directory: knexConfig.directory[0],
}))
);
});
it('with the right object structure for completed migrations', async () => {
await knex.migrate.latest(knexConfig);
const [completed, pending] = await knex.migrate.list(knexConfig);
expect(completed).to.deep.equal(
availableMigrations.map((migration) => ({
name: migration,
}))
);
expect(pending).to.deep.equal([]);
});
});
});
after(function () {
rimraf.sync(path.join(__dirname, './migration'));
});
});
describe('knex.migrate.latest in parallel', function () {
afterEach(function () {
return knex.migrate.rollback({
directory: 'test/integration2/migrate/test',
});
});
if (isPostgreSQL(knex) || isMssql(knex)) {
it('is able to run two migrations in parallel (if no implicit DDL commits)', function () {
return Promise.all([
knex.migrate.latest({
directory: 'test/integration2/migrate/test',
}),
knex.migrate.latest({
directory: 'test/integration2/migrate/test',
}),
]).then(function () {
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(2);
});
});
});
}
/** TODO : fix me and enabled it.
* Fail randomly with (mostly with PostgreSQL, PgNative, CockroachDb):
* knex.migrate.latest in parallel
* is not able to run two migrations in parallel when transactions are disabled:
* AssertionError: expected false to equal true
* + expected - actual
* -false
* +true
* at /home/runner/work/knex/knex/test/integration2/migrate/migration-integration.spec.js:944:37
* at runMicrotasks (<anonymous>)
* at processTicksAndRejections (internal/process/task_queues.js:95:5)
*/
it.skip('is not able to run two migrations in parallel when transactions are disabled', function () {
const migrations = [
knex.migrate
.latest({
directory: 'test/integration2/migrate/test',
disableTransactions: true,
})
.catch(function (err) {
return err;
}),
knex.migrate
.latest({
directory: 'test/integration2/migrate/test',
disableTransactions: true,
})
.catch(function (err) {
return err;
}),
];
return Promise.all(
migrations.map((migration) =>
migration.then((res) => res && res.name)
)
).then(function (res) {
// One should fail:
const hasLockError =
res[0] === 'MigrationLocked' || res[1] === 'MigrationLocked';
expect(hasLockError).to.equal(true);
// But the other should succeed:
return knex('knex_migrations')
.select('*')
.then(function (data) {
expect(data.length).to.equal(2);
});
});
});
});
describe('knex.migrate (transactions disabled)', function () {
describe('knex.migrate.latest (all transactions disabled)', function () {
before(function () {
return knex.migrate
.latest({
directory: 'test/integration2/migrate/test_with_invalid',
disableTransactions: true,
})
.catch(function () {});
});
// Same test as before, but this time, because
// transactions are off, the column gets created for all dialects always.
it('should create column even in invalid migration', function () {
return knex.schema
.hasColumn('migration_test_1', 'transaction')
.then(function (exists) {
expect(exists).to.equal(true);
});
});
after(function () {
return knex.migrate.rollback({
directory: 'test/integration2/migrate/test_with_invalid',
});
});
});