2021-08-26 10:01:42 +02:00
|
|
|
package sql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
log "github.com/Sirupsen/logrus"
|
2022-01-23 09:22:12 +01:00
|
|
|
"github.com/ansible-semaphore/semaphore/db"
|
2021-08-26 10:01:42 +02:00
|
|
|
"github.com/go-gorp/gorp/v3"
|
|
|
|
"regexp"
|
2022-01-20 15:53:48 +01:00
|
|
|
"strings"
|
2021-08-26 10:01:42 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2022-02-06 10:29:56 +01:00
|
|
|
autoIncrementRE = regexp.MustCompile(`(?i)\bautoincrement\b`)
|
|
|
|
serialRE = regexp.MustCompile(`(?i)\binteger primary key autoincrement\b`)
|
|
|
|
dateTimeTypeRE = regexp.MustCompile(`(?i)\bdatetime\b`)
|
|
|
|
tinyintRE = regexp.MustCompile(`(?i)\btinyint\b`)
|
|
|
|
longtextRE = regexp.MustCompile(`(?i)\blongtext\b`)
|
|
|
|
ifExistsRE = regexp.MustCompile(`(?i)\bif exists\b`)
|
|
|
|
changeRE = regexp.MustCompile(`^alter table \x60(\w+)\x60 change \x60(\w+)\x60 \x60(\w+)\x60 ([\w\(\)]+)( not null)?$`)
|
|
|
|
//dropForeignKeyRE = regexp.MustCompile(`^alter table \x60(\w+)\x60 drop foreign key \x60(\w+)\x60 /\* postgres:\x60(\w*)\x60 mysql:\x60(\w*)\x60 \*/$`)
|
2022-02-04 18:35:08 +01:00
|
|
|
dropForeignKey2RE = regexp.MustCompile(`(?i)\bdrop foreign key\b`)
|
2021-08-26 10:01:42 +02:00
|
|
|
)
|
|
|
|
|
2022-01-23 09:22:12 +01:00
|
|
|
// getVersionPath is the humanoid version with the file format appended
|
2022-01-23 14:03:23 +01:00
|
|
|
func getVersionPath(version db.Migration) string {
|
2022-01-23 09:22:12 +01:00
|
|
|
return version.HumanoidVersion() + ".sql"
|
|
|
|
}
|
|
|
|
|
|
|
|
// getVersionErrPath is the humanoid version with '.err' and file format appended
|
2022-01-23 14:03:23 +01:00
|
|
|
func getVersionErrPath(version db.Migration) string {
|
2022-01-23 09:22:12 +01:00
|
|
|
return version.HumanoidVersion() + ".err.sql"
|
|
|
|
}
|
|
|
|
|
|
|
|
// getVersionSQL takes a path to an SQL file and returns it from packr as
|
|
|
|
// a slice of strings separated by newlines
|
|
|
|
func getVersionSQL(path string) (queries []string) {
|
|
|
|
sql, err := dbAssets.MustString(path)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
queries = strings.Split(strings.ReplaceAll(sql, ";\r\n", ";\n"), ";\n")
|
2022-02-03 08:05:13 +01:00
|
|
|
for i := range queries {
|
2022-02-04 18:35:08 +01:00
|
|
|
queries[i] = strings.Trim(queries[i], "\r\n\t ")
|
2022-02-03 08:05:13 +01:00
|
|
|
}
|
2022-01-23 09:22:12 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-08-26 10:01:42 +02:00
|
|
|
// prepareMigration converts migration SQLite-query to current dialect.
|
|
|
|
// Supported MySQL and Postgres dialects.
|
|
|
|
func (d *SqlDb) prepareMigration(query string) string {
|
|
|
|
switch d.sql.Dialect.(type) {
|
|
|
|
case gorp.MySQLDialect:
|
|
|
|
query = autoIncrementRE.ReplaceAllString(query, "auto_increment")
|
2021-08-30 17:11:08 +02:00
|
|
|
query = ifExistsRE.ReplaceAllString(query, "")
|
2021-08-26 10:01:42 +02:00
|
|
|
case gorp.PostgresDialect:
|
2022-02-06 10:29:56 +01:00
|
|
|
m := changeRE.FindStringSubmatch(query)
|
2022-02-03 08:05:13 +01:00
|
|
|
if m != nil {
|
|
|
|
tableName := m[1]
|
|
|
|
oldColumnName := m[2]
|
|
|
|
newColumnName := m[3]
|
|
|
|
columnType := m[4]
|
|
|
|
columnNotNull := m[5] != ""
|
|
|
|
|
2022-02-04 18:35:08 +01:00
|
|
|
var queries []string
|
2022-02-03 08:05:13 +01:00
|
|
|
queries = append(queries,
|
|
|
|
"alter table `"+tableName+"` alter column `"+oldColumnName+"` type "+columnType)
|
|
|
|
|
|
|
|
if columnNotNull {
|
|
|
|
queries = append(queries,
|
|
|
|
"alter table `"+tableName+"` alter column `"+oldColumnName+"` set not null")
|
|
|
|
} else {
|
|
|
|
queries = append(queries,
|
|
|
|
"alter table `"+tableName+"` alter column `"+oldColumnName+"` drop not null")
|
|
|
|
}
|
|
|
|
|
|
|
|
if oldColumnName != newColumnName {
|
|
|
|
queries = append(queries,
|
|
|
|
"alter table `"+tableName+"` rename column `"+oldColumnName+"` to `"+newColumnName+"`")
|
|
|
|
}
|
|
|
|
|
|
|
|
query = strings.Join(queries, "; ")
|
|
|
|
}
|
|
|
|
|
2021-08-26 10:01:42 +02:00
|
|
|
query = dateTimeTypeRE.ReplaceAllString(query, "timestamp")
|
|
|
|
query = tinyintRE.ReplaceAllString(query, "smallint")
|
|
|
|
query = longtextRE.ReplaceAllString(query, "text")
|
2022-02-03 08:05:13 +01:00
|
|
|
query = serialRE.ReplaceAllString(query, "serial primary key")
|
2022-02-04 18:35:08 +01:00
|
|
|
query = dropForeignKey2RE.ReplaceAllString(query, "drop constraint")
|
2022-02-03 08:05:13 +01:00
|
|
|
query = identifierQuoteRE.ReplaceAllString(query, "\"")
|
2021-08-26 10:01:42 +02:00
|
|
|
}
|
|
|
|
return query
|
|
|
|
}
|
|
|
|
|
2022-01-23 14:03:23 +01:00
|
|
|
// IsMigrationApplied queries the database to see if a migration table with this version id exists already
|
|
|
|
func (d *SqlDb) IsMigrationApplied(migration db.Migration) (bool, error) {
|
2022-01-23 17:34:42 +01:00
|
|
|
initialized, err := d.IsInitialized()
|
2021-08-26 10:01:42 +02:00
|
|
|
|
2022-01-23 17:34:42 +01:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if !initialized {
|
|
|
|
return false, nil
|
2022-01-23 16:36:32 +01:00
|
|
|
}
|
2021-08-26 10:01:42 +02:00
|
|
|
|
2022-01-23 17:34:42 +01:00
|
|
|
exists, err := d.sql.SelectInt(
|
2022-01-31 22:30:36 +01:00
|
|
|
d.PrepareQuery("select count(1) as ex from migrations where version = ?"),
|
2022-01-23 17:34:42 +01:00
|
|
|
migration.Version)
|
|
|
|
|
2022-01-23 16:36:32 +01:00
|
|
|
if err != nil {
|
2022-01-23 17:34:42 +01:00
|
|
|
return false, err
|
2021-08-26 10:01:42 +02:00
|
|
|
}
|
|
|
|
|
2022-01-23 17:34:42 +01:00
|
|
|
return exists > 0, nil
|
2021-08-26 10:01:42 +02:00
|
|
|
}
|
|
|
|
|
2022-01-23 14:03:23 +01:00
|
|
|
// ApplyMigration runs executes a database migration
|
|
|
|
func (d *SqlDb) ApplyMigration(migration db.Migration) error {
|
2022-01-23 17:34:42 +01:00
|
|
|
initialized, err := d.IsInitialized()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if !initialized {
|
|
|
|
fmt.Println("Creating migrations table")
|
|
|
|
query := d.prepareMigration(initialSQL)
|
2022-02-04 18:35:08 +01:00
|
|
|
if query == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2022-01-23 17:34:42 +01:00
|
|
|
_, err = d.exec(query)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-26 10:01:42 +02:00
|
|
|
tx, err := d.sql.Begin()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-23 16:36:32 +01:00
|
|
|
queries := getVersionSQL(getVersionPath(migration))
|
|
|
|
for i, query := range queries {
|
2021-08-26 10:01:42 +02:00
|
|
|
fmt.Printf("\r [%d/%d]", i+1, len(query))
|
|
|
|
|
|
|
|
if len(query) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
q := d.prepareMigration(query)
|
2022-02-04 18:35:08 +01:00
|
|
|
if q == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-09-06 13:05:10 +02:00
|
|
|
_, err = tx.Exec(q)
|
|
|
|
if err != nil {
|
2021-08-26 10:01:42 +02:00
|
|
|
handleRollbackError(tx.Rollback())
|
2021-10-26 11:36:07 +02:00
|
|
|
log.Warnf("\n ERR! Query: %s\n\n", q)
|
|
|
|
log.Fatalf(err.Error())
|
2021-08-26 10:01:42 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-31 22:30:36 +01:00
|
|
|
_, err = tx.Exec(d.PrepareQuery("insert into migrations(version, upgraded_date) values (?, ?)"), migration.Version, time.Now())
|
2022-01-23 16:36:32 +01:00
|
|
|
if err != nil {
|
2021-08-26 10:01:42 +02:00
|
|
|
handleRollbackError(tx.Rollback())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-01-23 14:03:23 +01:00
|
|
|
switch migration.Version {
|
2022-01-20 15:53:48 +01:00
|
|
|
case "2.8.26":
|
2022-02-03 08:05:13 +01:00
|
|
|
err = migration_2_8_26{db: d}.Apply(tx)
|
2022-02-06 10:29:56 +01:00
|
|
|
case "2.8.42":
|
|
|
|
err = migration_2_8_42{db: d}.Apply(tx)
|
2022-01-23 16:36:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-01-20 15:53:48 +01:00
|
|
|
}
|
|
|
|
|
2021-08-26 10:01:42 +02:00
|
|
|
fmt.Println()
|
|
|
|
|
|
|
|
return tx.Commit()
|
|
|
|
}
|
|
|
|
|
2022-01-23 14:03:23 +01:00
|
|
|
// TryRollbackMigration attempts to rollback the database to an earlier version if a rollback exists
|
|
|
|
func (d *SqlDb) TryRollbackMigration(version db.Migration) {
|
2022-01-23 09:22:12 +01:00
|
|
|
data := dbAssets.Bytes(getVersionErrPath(version))
|
2021-08-26 10:01:42 +02:00
|
|
|
if len(data) == 0 {
|
|
|
|
fmt.Println("Rollback SQL does not exist.")
|
|
|
|
fmt.Println()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-02-04 18:35:08 +01:00
|
|
|
queries := getVersionSQL(getVersionErrPath(version))
|
|
|
|
for _, query := range queries {
|
2021-08-26 10:01:42 +02:00
|
|
|
fmt.Printf(" [ROLLBACK] > %v\n", query)
|
2022-02-04 18:35:08 +01:00
|
|
|
q := d.prepareMigration(query)
|
|
|
|
if q == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if _, err := d.exec(q); err != nil {
|
2021-08-26 10:01:42 +02:00
|
|
|
fmt.Println(" [ROLLBACK] - Stopping")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|