multitenantStack/scripts/migrateTenants.go

79 lines
1.7 KiB
Go
Raw Normal View History

2018-11-13 18:03:47 +00:00
package main
import (
"fmt"
companyDB "multitenantStack/services/companydb"
"os"
"os/exec"
"strings"
_ "github.com/lib/pq"
)
var conf companyDB.DBConfig
func main() {
migType := ""
if len(os.Args) > 1 {
migType = os.Args[1]
}
companyDB.InitCompanyDBService()
conf = companyDB.Conf
systemDB := companyDB.GetSystemDatabase()
result, err := systemDB.Query("SELECT datname FROM pg_database WHERE datistemplate = false;")
if err != nil {
panic(err.Error())
}
fmt.Printf("migrate %s\n", migType)
for result.Next() {
var dbName string
result.Scan(&dbName)
if strings.HasPrefix(dbName, "company_") {
fmt.Printf(" migrating...")
migrateDbName(dbName, migType)
}
fmt.Printf("\n")
}
}
func printCommand(cmd *exec.Cmd) {
fmt.Printf("==> Executing: %s\n", strings.Join(cmd.Args, " "))
}
func printError(err error) {
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("==> Error: %s\n", err.Error()))
}
}
func printOutput(outs []byte) {
if len(outs) > 0 {
fmt.Printf("==> Output: %s\n", string(outs))
}
}
func migrateDbName(dbName, migType string) {
connString := fmt.Sprintf("--conn=\"postgres://%s:%s@%s:%d/%s?sslmode=%s\"", conf.User, conf.Password, conf.Host, conf.Port, dbName, conf.Ssl)
fmt.Println(connString)
cmdString := fmt.Sprintf("%s%s", os.Getenv("GOPATH"), "/bin/bee")
cmd := exec.Command(cmdString, "migrate", migType, connString)
// Combine stdout and stderr
printCommand(cmd)
_, err := cmd.CombinedOutput()
printError(err)
// printOutput(output)
// check what migration type
// query system table
// //run all or single tenant, check if tenant exists
// execute commands (blocking!)
// print out all states in new lines with green or red and error
}