This repository has been archived by the owner on Jun 1, 2022. It is now read-only.
forked from lonja/goose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
88 lines (69 loc) · 1.94 KB
/
create.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
package goose
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"text/template"
"time"
)
// Create writes a new blank migration file.
func CreateWithTemplate(db *sql.DB, dir string, migrationTemplate *template.Template, name, migrationType string) error {
version := time.Now().Format(timestampFormat)
filename := fmt.Sprintf("%v_%v.%v", version, name, migrationType)
fpath := filepath.Join(dir, filename)
tmpl := sqlMigrationTemplate
if migrationType == "go" {
tmpl = goSQLMigrationTemplate
}
if migrationTemplate != nil {
tmpl = migrationTemplate
}
path, err := writeTemplateToFile(fpath, tmpl, version)
if err != nil {
return err
}
log.Printf("Created new file: %s\n", path)
return nil
}
// Create writes a new blank migration file.
func Create(db *sql.DB, dir, name, migrationType string) error {
return CreateWithTemplate(db, dir, nil, name, migrationType)
}
func writeTemplateToFile(path string, t *template.Template, version string) (string, error) {
if _, err := os.Stat(path); !os.IsNotExist(err) {
return "", fmt.Errorf("failed to create file: %v already exists", path)
}
f, err := os.Create(path)
if err != nil {
return "", err
}
defer f.Close()
err = t.Execute(f, version)
if err != nil {
return "", err
}
return f.Name(), nil
}
var sqlMigrationTemplate = template.Must(template.New("goose.sql-migration").Parse(`-- +goose Up
-- SQL in this section is executed when the migration is applied.
-- +goose Down
-- SQL in this section is executed when the migration is rolled back.
`))
var goSQLMigrationTemplate = template.Must(template.New("goose.go-migration").Parse(`package migration
import (
"database/sql"
"github.com/lonja/goose"
)
func init() {
goose.AddMigration(Up{{.}}, Down{{.}})
}
func Up{{.}}(tx *sql.Tx) error {
// This code is executed when the migration is applied.
return nil
}
func Down{{.}}(tx *sql.Tx) error {
// This code is executed when the migration is rolled back.
return nil
}
`))