This repository has been archived by the owner on Mar 20, 2024. It is now read-only.
forked from tanel/dbmigrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgdbmigrate.go
130 lines (116 loc) · 3.1 KB
/
pgdbmigrate.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
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
package pgdbmigrate
import (
"database/sql"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
)
// Database interface needs to be implemented to migrate a new type of database
type Database interface {
CreateMigrationsTable() error
HasMigrated(filename string) (bool, error)
Migrate(filename string, migration string) error
}
// PostgresDatabase migrates Postgresql databases
type PostgresDatabase struct {
database *sql.DB
}
func (postgres *PostgresDatabase) CreateMigrationsTable() error {
_, err := postgres.database.Exec(`
CREATE TABLE IF NOT EXISTS migrations (
id serial,
name text NOT NULL,
created_at timestamp with time zone NOT NULL,
CONSTRAINT "PK_migrations_id" PRIMARY KEY (id)
);`)
if err != nil {
return err
}
_, err = postgres.database.Exec("create unique index idx_migrations_name on migrations(name)")
if err != nil {
if !strings.Contains(err.Error(), "already exists") {
return err
}
}
return nil
}
func (postgres *PostgresDatabase) HasMigrated(filename string) (bool, error) {
var count int
err := postgres.database.QueryRow("select count(1) from migrations where name = $1", filename).Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}
func (postgres *PostgresDatabase) Migrate(filename string, migration string) error {
_, err := postgres.database.Exec(migration)
if err != nil {
return err
}
_, err = postgres.database.Exec("insert into migrations(name, created_at) values($1, current_timestamp)", filename)
return err
}
func NewPostgresDatabase(db *sql.DB) *PostgresDatabase {
return &PostgresDatabase{database: db}
}
// By default, apply Postgresql migrations, as in older versions
func Run(db *sql.DB, migrationsFolder string) error {
postgres := NewPostgresDatabase(db)
return ApplyMigrations(postgres, migrationsFolder)
}
// Run applies migrations from migrationsFolder to database.
func ApplyMigrations(database Database, migrationsFolder string) error {
// Initialize migrations table, if it does not exist yet
if err := database.CreateMigrationsTable(); err != nil {
return err
}
// Scan migration file names in migrations folder
d, err := os.Open(migrationsFolder)
if err != nil {
return err
}
dir, err := d.Readdir(-1)
if err != nil {
return err
}
// Run migrations
sqlFiles := make([]string, 0)
for _, f := range dir {
ext := filepath.Ext(f.Name())
if ".sql" == ext || ".cql" == ext {
sqlFiles = append(sqlFiles, f.Name())
}
}
sort.Strings(sqlFiles)
for _, filename := range sqlFiles {
// if exists in migrations table, leave it
// else execute sql
migrated, err := database.HasMigrated(filename)
if err != nil {
return err
}
fullpath := filepath.Join(migrationsFolder, filename)
if migrated {
fmt.Println("Already migrated", fullpath)
continue
}
b, err := ioutil.ReadFile(fullpath)
if err != nil {
return err
}
migration := string(b)
if len(migration) == 0 {
fmt.Println("Skipping empty file", fullpath)
continue // empty file
}
err = database.Migrate(filename, migration)
if err != nil {
return err
}
fmt.Println("Migrated", fullpath)
}
return nil
}