Skip to content

Commit

Permalink
split sql scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
Sagleft committed Sep 22, 2021
1 parent 6c25758 commit a6bac77
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"io/ioutil"
"path/filepath"
"strings"
)

// NewMigrationHandler - create new migration handler.
Expand Down Expand Up @@ -95,15 +96,39 @@ func (m *MigrationHandler) runScript(scriptName string) error {
return err
}

// EXEC SCRIPT
// split script
scriptsQuery := strings.Split(string(fileBytes), ";")
for _, sqlQuery := range scriptsQuery {
// EXEC SCRIPT
err := m.runTx(sqlQuery)
if err != nil {
return err
}
}

// update version
sqlQuery := "INSERT INTO " + versionsTableName + " SET name=?"
_, err = m.Data.DBDriver.Exec(sqlQuery, scriptName)
if err != nil {
return errors.New("failed to exec query: " + err.Error())
}
return nil
}

func (m *MigrationHandler) runTx(sqlQuery string) error {
if sqlQuery == "" {
// skip empty script
return nil
}

// begin tx
tx, err := m.Data.DBDriver.Begin()
if err != nil {
return errors.New("failed to begin tx: " + err.Error())
}

// exec query
_, err = tx.Exec(string(fileBytes))
_, err = tx.Exec(sqlQuery)
if err != nil {
return errors.New("failed to exec script: " + err.Error())
}
Expand All @@ -114,13 +139,6 @@ func (m *MigrationHandler) runScript(scriptName string) error {
tx.Rollback()
return errors.New("failed to commit tx: " + err.Error())
}

// update version
sqlQuery := "INSERT INTO " + versionsTableName + " SET name=?"
_, err = m.Data.DBDriver.Exec(sqlQuery, scriptName)
if err != nil {
return errors.New("failed to exec query: " + err.Error())
}
return nil
}

Expand Down

0 comments on commit a6bac77

Please sign in to comment.