2018-04-30 18:42:17 +05:00
|
|
|
package goose
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"text/template"
|
2019-10-13 13:55:38 +05:00
|
|
|
"time"
|
2018-04-30 18:42:17 +05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Create writes a new blank migration file.
|
2019-10-13 13:55:38 +05:00
|
|
|
func CreateWithTemplate(db *sql.DB, dir string, migrationTemplate *template.Template, name, migrationType string) error {
|
|
|
|
version := time.Now().Format(timestampFormat)
|
2018-04-30 18:42:17 +05:00
|
|
|
filename := fmt.Sprintf("%v_%v.%v", version, name, migrationType)
|
|
|
|
|
|
|
|
fpath := filepath.Join(dir, filename)
|
2019-10-13 13:55:38 +05:00
|
|
|
|
2018-04-30 18:42:17 +05:00
|
|
|
tmpl := sqlMigrationTemplate
|
|
|
|
if migrationType == "go" {
|
|
|
|
tmpl = goSQLMigrationTemplate
|
|
|
|
}
|
|
|
|
|
2019-10-13 13:55:38 +05:00
|
|
|
if migrationTemplate != nil {
|
|
|
|
tmpl = migrationTemplate
|
|
|
|
}
|
|
|
|
|
2018-04-30 18:42:17 +05:00
|
|
|
path, err := writeTemplateToFile(fpath, tmpl, version)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-10-13 13:55:38 +05:00
|
|
|
log.Printf("Created new file: %s\n", path)
|
2018-04-30 18:42:17 +05:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-13 13:55:38 +05:00
|
|
|
// Create writes a new blank migration file.
|
|
|
|
func Create(db *sql.DB, dir, name, migrationType string) error {
|
|
|
|
return CreateWithTemplate(db, dir, nil, name, migrationType)
|
|
|
|
}
|
|
|
|
|
2018-04-30 18:42:17 +05:00
|
|
|
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/pressly/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
|
|
|
|
}
|
|
|
|
`))
|