Repository navigation
Expand file tree
/
Copy pathmigration_test.go
More file actions
821 lines (608 loc) · 22.9 KB
/
Copy pathmigration_test.go
File metadata and controls
821 lines (608 loc) · 22.9 KB
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
// SPDX-FileCopyrightText: 2026 The DMorph contributors.
// SPDX-License-Identifier: MPL-2.0
package dmorph_test
import (
"context"
"database/sql"
"embed"
"fmt"
"io/fs"
"log/slog"
"os"
"testing"
_ "github.com/ncruces/go-sqlite3/driver"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/AlphaOne1/dmorph"
)
//go:embed testData
var testMigrationsDir embed.FS
//go:embed testDataSemVer
var testMigrationsSemVerDir embed.FS
// openTempSQLite opens a temporary in-memory SQLite database for testing and ensures it is closed after the test ends.
func openTempSQLite(t *testing.T) *sql.DB {
t.Helper()
db, err := sql.Open("sqlite3", ":memory:")
require.NoError(t, err, "DB could not be opened")
t.Cleanup(func() { _ = db.Close() })
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
return db
}
// TestMigrationNamedParams tests the happy flow.
func TestMigrationNamedParams(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeyAlphabetical()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.NoError(t, runErr, "migrations could not be run")
}
// TestMigrationNamedParamsSemVer tests the happy flow.
func TestMigrationNamedParamsSemVer(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsSemVerDir, "testDataSemVer")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeySemVerPrefix()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.NoError(t, runErr, "migrations could not be run")
}
// TestMigration tests the happy flow.
func TestMigrationNumberedParams(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLiteNumbered()),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeyAlphabetical()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.NoError(t, runErr, "migrations could not be run")
}
// TestMigrationUpdate tests the happy flow of updating on existing migrations.
func TestMigrationUpdate(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFilesFS(migrationsDir, "01_base_table.sql"))
require.NoError(t, runErr, "preparation migrations could not be run")
runErr = dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.NoError(t, runErr, "migrations could not be run")
}
type TestMigrationImpl struct{}
func (m TestMigrationImpl) Key() string { return "TestMigration" }
func (m TestMigrationImpl) Migrate(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "CREATE TABLE t0 (id INTEGER PRIMARY KEY)")
return dmorph.TwrapIfError("could not migrate", err) //nolint:wrapcheck
}
// TestWithMigrations tests the adding of migrations using WithMigrations.
func TestWithMigrations(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrations(TestMigrationImpl{}))
assert.NoError(t, runErr, "did not expect error")
}
// TestMigrationUnableToCreateMorpher tests to use the Run function without any
// useful parameter.
func TestMigrationUnableToCreateMorpher(t *testing.T) {
t.Parallel()
runErr := dmorph.Run(t.Context(), nil)
assert.Error(t, runErr, "morpher should not have run")
}
// TestMigrationTooOld tests what happens if the applied migrations are too old.
func TestMigrationTooOld(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFS(migrationsDir))
require.NoError(t, runErr, "preparation migrations could not be run")
runErr = dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFilesFS(migrationsDir, "01_base_table.sql"))
assert.ErrorIs(t, runErr, dmorph.ErrMigrationsTooOld, "migrations did not give expected error")
}
// TestMigrationUnrelated0 tests what happens if the applied migrations are unrelated to existing ones.
func TestMigrationUnrelated0(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFS(migrationsDir))
require.NoError(t, runErr, "preparation migrations could not be run")
runErr = dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFilesFS(migrationsDir, "02_addon_table.sql"))
assert.ErrorIs(t, runErr, dmorph.ErrMigrationsUnrelated, "migrations did not give expected error")
}
// TestMigrationUnrelated1 tests what happens if the applied migrations are unrelated to existing ones.
func TestMigrationUnrelated1(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFilesFS(migrationsDir, "01_base_table.sql"))
require.NoError(t, runErr, "preparation migrations could not be run")
runErr = dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFilesFS(migrationsDir, "02_addon_table.sql"))
assert.ErrorIs(t, runErr, dmorph.ErrMigrationsUnrelated, "migrations did not give expected error")
}
// TestMigrationAppliedUnordered tests the case, that somehow the migrations in the
// database are registered not in the order of their keys.
func TestMigrationAppliedUnordered(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
require.NoError(t, dmorph.DialectSQLite().EnsureMigrationTableExists(t.Context(), db, "migrations"))
_, execErr := db.ExecContext(t.Context(), `
INSERT INTO migrations (id, mgroup, create_ts) VALUES ('01_base_table', 'default', '2021-01-02 00:00:00');
INSERT INTO migrations (id, mgroup, create_ts) VALUES ('02_addon_table', 'default', '2021-01-01 00:00:00');
`)
require.NoError(t, execErr, "unordered test could not be prepared")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.ErrorIs(t,
runErr,
dmorph.ErrMigrationsUnsorted,
"migrations did not give expected error")
}
// TestMigrationOrder checks that the migrations ordering function works as expected.
func TestMigrationOrder(t *testing.T) {
t.Parallel()
tests := []struct {
m0 dmorph.Migration
m1 dmorph.Migration
order int
}{
{
m0: dmorph.FileMigration{Name: "01"},
m1: dmorph.FileMigration{Name: "01"},
order: 0,
},
{
m0: dmorph.FileMigration{Name: "01"},
m1: dmorph.FileMigration{Name: "02"},
order: -1,
},
{
m0: dmorph.FileMigration{Name: "02"},
m1: dmorph.FileMigration{Name: "01"},
order: 1,
},
}
for k, v := range tests {
t.Run(fmt.Sprintf("TestMigrationOrder %v", k), func(t *testing.T) {
t.Parallel()
res := dmorph.TmigrationOrder(v.m0, v.m1)
assert.Equal(t, v.order, res, "order of migrations is wrong for test %v", k)
})
}
}
// TestMigrationIsValid checks the validity checks for migrations.
func TestMigrationIsValid(t *testing.T) {
t.Parallel()
tests := []struct {
m dmorph.Morpher
err error
}{
{
m: dmorph.Morpher{
Dialect: dmorph.DialectSQLite(),
Migrations: []dmorph.Migration{dmorph.FileMigration{Name: "01"}},
TableName: dmorph.MigrationTableName,
GroupName: dmorph.MigrationGroupName,
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: nil,
},
{
m: dmorph.Morpher{
Dialect: dmorph.DialectSQLite(),
Migrations: []dmorph.Migration{dmorph.FileMigration{Name: "01"}},
TableName: dmorph.MigrationTableName,
GroupName: "",
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: dmorph.ErrNoMigrationGroup,
},
{
m: dmorph.Morpher{
Dialect: nil,
Migrations: []dmorph.Migration{dmorph.FileMigration{Name: "01"}},
TableName: dmorph.MigrationTableName,
GroupName: dmorph.MigrationGroupName,
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: dmorph.ErrNoDialect,
},
{
m: dmorph.Morpher{
Dialect: dmorph.DialectSQLite(),
Migrations: nil,
TableName: dmorph.MigrationTableName,
GroupName: dmorph.MigrationGroupName,
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: dmorph.ErrNoMigrations,
},
{
m: dmorph.Morpher{
Dialect: dmorph.DialectSQLite(),
Migrations: []dmorph.Migration{dmorph.FileMigration{Name: "01"}},
TableName: "",
GroupName: dmorph.MigrationGroupName,
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: dmorph.ErrNoMigrationTable,
},
{
m: dmorph.Morpher{
Dialect: dmorph.DialectSQLite(),
Migrations: []dmorph.Migration{dmorph.FileMigration{Name: "01"}},
TableName: "blah(); DROP TABLE blah;",
GroupName: dmorph.MigrationGroupName,
KeyProp: dmorph.MigrationKeyAlphabetical(),
},
err: dmorph.ErrMigrationTableNameInvalid,
},
}
for k, v := range tests {
t.Run(fmt.Sprintf("TestMigrationIsValid %v", k), func(t *testing.T) {
t.Parallel()
err := v.m.IsValid()
assert.ErrorIs(t, err, v.err, "error is wrong for test %v", k)
})
}
}
// TestMigrationWithLogger validates the creation of a Morpher with a logger and ensures
// the logger is applied correctly.
func TestMigrationWithLogger(t *testing.T) {
t.Parallel()
newLog := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelWarn,
}))
morpher, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"),
dmorph.WithLog(newLog),
)
require.NoError(t, err, "morpher could not be created")
assert.Equal(t, newLog, morpher.Log, "logger was not set correctly")
}
// TestMigrationWithoutMigrations ensures that creating a Morpher instance without migrations results in an error.
func TestMigrationWithoutMigrations(t *testing.T) {
t.Parallel()
_, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
)
assert.Error(t, err, "morpher created without migrations")
}
// TestMigrationWithTableNameValid verifies the correct creation of a Morpher
// with a valid custom table name configuration.
func TestMigrationWithTableNameValid(t *testing.T) {
t.Parallel()
morpher, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"),
dmorph.WithTableName("dimorphodon"),
)
require.NoError(t, err, "morpher could not be created")
assert.Equal(t, "dimorphodon", morpher.TableName, "table name was not set correctly")
}
// TestMigrationWithTableNameInvalidSize verifies that creating a Morpher
// with an invalid table name size produces an error.
func TestMigrationWithTableNameInvalidSize(t *testing.T) {
t.Parallel()
_, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"),
dmorph.WithTableName(""),
)
assert.Error(t, err, "morpher could be created with empty table name")
}
// TestMigrationWithTableNameInvalidChars ensures that creating a Morpher
// fails when the table name contains invalid characters.
func TestMigrationWithTableNameInvalidChars(t *testing.T) {
t.Parallel()
_, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"),
dmorph.WithTableName("di/mor/pho/don"),
)
assert.Error(t, err, "morpher could be created with invalid table name")
}
// TestMigrationRunInvalid verifies that running a Morpher with invalid configuration results in an error.
func TestMigrationRunInvalid(t *testing.T) {
t.Parallel()
morpher := dmorph.Morpher{}
runErr := morpher.Run(t.Context(), nil)
assert.Error(t, runErr, "morpher should not run")
}
// TestMigrationRunInvalidCreate tests the behavior of running a migration
// with an invalid CreateTemplate in the dialect.
func TestMigrationRunInvalidCreate(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
dialect := dmorph.DialectSQLite()
dialect.CreateTemplate = "utter nonsense 0"
morpher, morpherErr := dmorph.NewMorpher(
dmorph.WithDialect(dialect),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"))
require.NoError(t, morpherErr, "morpher could not be created")
runErr := morpher.Run(t.Context(), db)
assert.Error(t, runErr, "morpher should not run")
}
// TestMigrationRunInvalidApplied tests the failure scenario where the AppliedTemplate of the dialect is invalid.
func TestMigrationRunInvalidApplied(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
dialect := dmorph.DialectSQLite()
dialect.AppliedTemplate = "utter nonsense 1"
morpher, morpherErr := dmorph.NewMorpher(
dmorph.WithDialect(dialect),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"))
require.NoError(t, morpherErr, "morpher could not be created")
runErr := morpher.Run(t.Context(), db)
assert.Error(t, runErr, "morpher should not run")
}
// TestMigrationApplyInvalidDB verifies that applying migrations to an invalid or closed database results in an error.
func TestMigrationApplyInvalidDB(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
morpher, morpherErr := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"))
require.NoError(t, morpherErr, "morpher could not be created")
assert.Error(t,
morpher.TapplyMigrations(t.Context(), db, "irrelevant"),
"morpher should error on invalid DB")
}
// TestMigrationApplyUnableRegister tests the behavior when the migration registration fails due to an invalid template.
func TestMigrationApplyUnableRegister(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
morpher, morpherErr := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"))
require.NoError(t, morpherErr, "morpher could not be created")
d, dialectOK := morpher.Dialect.(dmorph.NamedParamsDialect)
require.True(t, dialectOK, "dialect is not a NamedParamsDialect")
d.RegisterTemplate = "utter nonsense 2"
morpher.Dialect = d
assert.Error(t,
morpher.TapplyMigrations(t.Context(), db, ""),
"morpher should fail to register")
}
// TestMigrationApplyUnableCommit tests the scenario where a migration application fails
// due to inability to commit a transaction.
func TestMigrationApplyUnableCommit(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
morpher, morpherErr := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationsFromFiles("testData/01_base_table.sql"))
require.NoError(t, morpherErr, "morpher could not be created")
_, execErr := db.ExecContext(t.Context(), "PRAGMA foreign_keys = ON")
require.NoError(t, execErr, "foreign keys checking could not be enabled")
baseDialect, dialectOK := morpher.Dialect.(dmorph.NamedParamsDialect)
require.True(t, dialectOK, "dialect is not a BaseDialect")
baseDialect.RegisterTemplate = `
CREATE TABLE t0 (
id INTEGER PRIMARY KEY
);
CREATE TABLE t1 (
id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES t0 (id) DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO t0 (id) VALUES (1);
INSERT INTO t1 (id, parent_id) VALUES (1, 1);
-- %s catching argument
DELETE FROM t0 WHERE id = 1;`
morpher.Dialect = baseDialect
assert.Error(t,
morpher.TapplyMigrations(t.Context(), db, ""),
"morpher should fail to register")
}
// TestMigrationNumberedParamsApplyInvalidParamName verifies that applying migrations with an invalid parameter name
// fails. It uses a custom SQLite dialect with numbered parameters and expects an ErrParamNameInvalid error.
func TestMigrationNumberedParamsApplyInvalidParamName(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
dialect := dmorph.DialectSQLiteNumbered()
dialect.AppliedMigrationsParamsOrder = []dmorph.ParamName{"no"}
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dialect),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeyAlphabetical()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.ErrorIs(t, runErr, dmorph.ErrParamNameInvalid, "error expected")
}
// TestMigrationNumberedParamsRegisterInvalidParamName verifies that registering migrations with an invalid parameter
// name fails. It uses a custom SQLite dialect with numbered parameters and expects an ErrParamNameInvalid error.
func TestMigrationNumberedParamsRegisterInvalidParamName(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsDir, "testData")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
dialect := dmorph.DialectSQLiteNumbered()
dialect.RegisterMigrationParamsOrder = []dmorph.ParamName{"no"}
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dialect),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeyAlphabetical()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.ErrorIs(t, runErr, dmorph.ErrParamNameInvalid, "error expected")
}
type okDialect struct{}
func (okDialect) EnsureMigrationTableExists(
_ /* ctx */ context.Context,
_ /* db */ *sql.DB,
_ /* tableName */ string) error {
return nil
}
func (okDialect) AppliedMigrations(
_ /* ctx */ context.Context,
_ /* db */ *sql.DB,
_ /* tableName */ string,
_ /* groupName */ string) ([]string, error) {
return nil, nil
}
func (okDialect) RegisterMigration(
_ /* ctx */ context.Context,
_ /* tx */ *sql.Tx,
_ /* id */ string,
_ /* tableName */ string,
_ /* groupName */ string) error {
return nil
}
type oneMigration struct {
key string
}
func (m oneMigration) Key() string {
return m.key
}
func (m oneMigration) Migrate(_ /* ctx */ context.Context, _ /* tx */ *sql.Tx) error {
return nil
}
func TestRunOneMigrationFailsOnClosedDB(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
require.NoError(t, db.Close())
logger := slog.New(slog.DiscardHandler)
err := dmorph.Run(
context.Background(),
db,
dmorph.WithDialect(okDialect{}),
dmorph.WithMigrations(oneMigration{key: "001_test"}),
dmorph.WithLog(logger),
)
require.Error(t, err)
require.ErrorContains(t, err, "begin tx")
}
func TestApplyFailsOnCanceledContext(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
logger := slog.New(slog.DiscardHandler)
ctx, ctxCancel := context.WithCancel(context.Background())
ctxCancel()
err := dmorph.Run(
ctx,
db,
dmorph.WithDialect(okDialect{}),
dmorph.WithMigrations(oneMigration{key: "001_test"}),
dmorph.WithLog(logger),
)
require.Error(t, err)
require.ErrorContains(t, err, "context cancelled")
}
func TestMigrationInvalidGroupOption(t *testing.T) {
t.Parallel()
_, err := dmorph.NewMorpher(dmorph.WithGroupName(""))
require.ErrorIs(t, err, dmorph.ErrMigrationGroupNameInvalid)
}
type TestInvalidMigrationImpl struct {
WantKey string
}
func (m TestInvalidMigrationImpl) Key() string { return m.WantKey }
func (m TestInvalidMigrationImpl) Migrate(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, `
CREATE TABLE t0 (
id INTEGER PRIMARY KEY
);
CREATE TABLE t1 (
id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES t0 (id) DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO t0 (id) VALUES (1);
INSERT INTO t1 (id, parent_id) VALUES (1, 1);
DELETE FROM t0 WHERE id = 1;`)
if err != nil {
return fmt.Errorf("could not execute migration: %w", err)
}
return nil
}
func TestInvalidMigrationKey(t *testing.T) {
t.Parallel()
_, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeySemVerPrefix()),
dmorph.WithMigrations(
TestInvalidMigrationImpl{WantKey: "xyz_test"}))
assert.ErrorIs(t, err, dmorph.ErrMigrationKeyFormat)
}
func TestUncommitableMigration(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
db.SetMaxOpenConns(1)
_, execErr := db.ExecContext(t.Context(), "PRAGMA foreign_keys = ON")
require.NoError(t, execErr, "foreign keys checking could not be enabled")
morpher, err := dmorph.NewMorpher(
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithMigrations(
TestInvalidMigrationImpl{WantKey: "0_impossible"}))
require.NoError(t, err)
err = morpher.Run(t.Context(), db)
assert.ErrorContains(t, err, "FOREIGN KEY constraint failed")
}
// TestMigrationNamedParamsSemVer tests the happy flow.
func TestMigrationInvalidAppliedSemVer(t *testing.T) {
t.Parallel()
db := openTempSQLite(t)
migrationsDir, migrationsDirErr := fs.Sub(testMigrationsSemVerDir, "testDataSemVer")
require.NoError(t, migrationsDirErr, "migrations directory could not be opened")
err := dmorph.DialectSQLite().EnsureMigrationTableExists(t.Context(), db, dmorph.MigrationTableName)
require.NoError(t, err, "preparation must succeed")
_, err = db.ExecContext(t.Context(), fmt.Sprintf(`
INSERT INTO "%s" (id, mgroup)
VALUES ('0_impossible', '%s')`, dmorph.MigrationTableName, dmorph.MigrationGroupName))
require.NoError(t, err, "preparation must succeed")
runErr := dmorph.Run(t.Context(),
db,
dmorph.WithDialect(dmorph.DialectSQLite()),
dmorph.WithGroupName(dmorph.MigrationGroupName),
dmorph.WithMigrationKeyProperties(dmorph.MigrationKeySemVerPrefix()),
dmorph.WithMigrationsFromFS(migrationsDir))
assert.ErrorIs(t, runErr, dmorph.ErrMigrationKeyFormat)
}