-
Notifications
You must be signed in to change notification settings - Fork 3
/
service.go
84 lines (72 loc) · 1.77 KB
/
service.go
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
package dbmigrator
import (
"context"
"github.com/raoptimus/db-migrator.go/internal/migrator"
"github.com/raoptimus/db-migrator.go/internal/validator"
)
type (
Options struct {
DSN string
// table name to history of migrations
TableName string
// cluster name to clickhouse
ClusterName string
// is replicated used to clickhouse?
Replicated bool
}
DBService struct {
dbs *migrator.DBService
opts *Options
}
)
func NewDBService(opts *Options) *DBService {
return &DBService{
dbs: migrator.New(&migrator.Options{
DSN: opts.DSN,
Directory: "",
TableName: opts.TableName,
ClusterName: opts.ClusterName,
Replicated: opts.Replicated,
Compact: true,
Interactive: true,
MaxSQLOutputLength: 0,
}),
opts: opts,
}
}
// Upgrade apply changes to db. apply specific version of migration.
func (d *DBService) Upgrade(ctx context.Context, version, sql string, safety bool) error {
if err := validator.ValidateVersion(version); err != nil {
return err
}
ms, err := d.dbs.MigrationService()
if err != nil {
return err
}
exists, err := ms.Exists(ctx, version)
if err != nil {
return err
}
if exists {
return ErrMigrationAlreadyExists
}
return ms.ApplySQL(ctx, safety, version, sql)
}
// Downgrade revert changes to db. revert specific version of migration.
func (d *DBService) Downgrade(ctx context.Context, version, sql string, safety bool) error {
if err := validator.ValidateVersion(version); err != nil {
return err
}
ms, err := d.dbs.MigrationService()
if err != nil {
return err
}
exists, err := ms.Exists(ctx, version)
if err != nil {
return err
}
if !exists {
return ErrAppliedMigrationNotFound
}
return ms.RevertSQL(ctx, safety, version, sql)
}