Created
November 16, 2018 01:48
-
-
Save niski84/68532e206017b5534b0caf2eb27d140f to your computer and use it in GitHub Desktop.
Execute Install.sql line by line using regex (match full path (linux/win))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Execute Install.sql line by line | |
// (install.sql still needed for test cases) | |
func ExecInstallSqlbyLine(instance *confighelper.Instance, dbcfg *dbhelper.DbConfig, installSqlf string, packageRoot string, logDirRoot string, logSuffix string) (err error) { | |
// logging for instance | |
log := instance.Logger | |
// read install.sql | |
raw, err := ioutil.ReadFile(installSqlf) | |
if err != nil { | |
return | |
} | |
installSql := string(raw) | |
filepattern := regexp.MustCompile(`[a-zA-Z]?:?/[^']*.sql`) // regex: match full path (linux/win) | |
sqlpattern := regexp.MustCompile(`(ALTER|SELECT|CREATE|INSERT|DELETE)\s[^\n]*`) // regex: match sql statement | |
// iterate over install.sql lines and execute psql with either -c or -f | |
for _, line := range strings.Split(installSql, "\n") { | |
if len(filepattern.FindAllString(line, -1)) > 0 { | |
sqlFile := filepattern.FindAllString(line, -1)[0] | |
sqlPath := filepath.Dir(sqlFile) | |
err := os.Chdir(sqlPath) // cwd to dir of .sql. needed for /ir meta commands (relative includes) | |
if err != nil { | |
return err | |
} | |
cmdArgs := []string{"-f", sqlFile} | |
dbhelper.ExecSQL(instance.Logger, dbcfg, cmdArgs, packageRoot, logSuffix, true) | |
} else if len(sqlpattern.FindAllString(line, -1)) > 0 { | |
log.Println(sqlpattern.FindAllString(line, -1)) | |
cmdArgs := []string{"-c", "" + sqlpattern.FindAllString(line, -1)[0] + ""} | |
dbhelper.ExecSQL(instance.Logger, dbcfg, cmdArgs, "", logSuffix, true) | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment