-
Notifications
You must be signed in to change notification settings - Fork 15
/
database.go
94 lines (81 loc) · 2.3 KB
/
database.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
85
86
87
88
89
90
91
92
93
94
package database
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
migrate "github.com/rubenv/sql-migrate"
)
// Connection contains the infrastructure needed to manage the database connection
type Connection struct {
DB *sql.DB
Sqlx *sqlx.DB
migrationsDirPath string
}
// NewConnection establishes a new connection to the databse server
func NewConnection(dsn string, migrationsDirPath string) (*Connection, error) {
config, err := mysql.ParseDSN(dsn)
if err != nil {
return nil, err
}
return newConnection(config, migrationsDirPath)
}
func newConnection(config *mysql.Config, migrationsDirPath string) (*Connection, error) {
config.ParseTime = true
db, err := sql.Open("mysql", config.FormatDSN())
if err != nil {
return nil, err
}
sqlxDB := sqlx.NewDb(db, "mysql")
return &Connection{db, sqlxDB, migrationsDirPath}, nil
}
// CheckSchema checks the database schema against the migrations
// and returns an error if they don't match
func (c *Connection) CheckSchema() error {
m, err := c.migrationSource()
if err != nil {
return err
}
allMigrations, err := m.FindMigrations()
if err != nil {
return err
}
ranMigrations, err := migrate.GetMigrationRecords(c.DB, "mysql")
if err != nil {
return err
}
if len(ranMigrations) != len(allMigrations) {
var suggestedFix string
if len(ranMigrations) > len(allMigrations) {
suggestedFix = "Check that you have deployed the latest version"
} else {
suggestedFix = "Run migrate up"
}
return fmt.Errorf(
"Database has %d applied migrations but codebase expects %d migrations. %s",
len(ranMigrations), len(allMigrations), suggestedFix,
)
}
for i := range ranMigrations {
if ranMigrations[i].Id != allMigrations[i].Id {
return fmt.Errorf(
"Ran migration id %s and codebase migration id %s do not match!",
ranMigrations[i].Id, allMigrations[i].Id,
)
}
}
return nil
}
// MigrateUp performs all migrations
func (c *Connection) MigrateUp() error {
m, err := c.migrationSource()
if err != nil {
return err
}
_, err = migrate.Exec(c.DB, "mysql", m, migrate.Up)
return err
}
func (c *Connection) migrationSource() (migrate.MigrationSource, error) {
migrationSource := &migrate.FileMigrationSource{Dir: c.migrationsDirPath}
return migrationSource, nil
}