multitenantStack/scripts/migrateTenants/migrateTenants.go

106 lines
2.1 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() {
migrateSystem := false
2018-11-13 18:03:47 +00:00
migType := ""
if len(os.Args) > 1 {
if os.Args[1] == "system" {
migrateSystem = true
if len(os.Args) > 2 {
migType = os.Args[2]
}
} else {
migType = os.Args[1]
}
2018-11-13 18:03:47 +00:00
}
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())
}
if migrateSystem {
fmt.Printf("SYSTEM DB: migrate %s\n", migType)
migrateDbName("system", migType)
return
}
2018-11-13 18:03:47 +00:00
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) {
dir := ""
if dbName == "system" {
dir = "--dir=database/systemmigrations"
}
2018-11-13 18:03:47 +00:00
connString := fmt.Sprintf("--conn=postgres://%s:%s@%s:%d/%s?sslmode=%s", conf.User, conf.Password, conf.Host, conf.Port, dbName, conf.Ssl)
2018-11-13 18:03:47 +00:00
cmdString := fmt.Sprintf("%s%s", os.Getenv("GOPATH"), "/bin/bee")
var cmd *exec.Cmd
if migType != "" {
cmd = exec.Command(cmdString, "migrate", migType, connString, dir)
} else {
2018-11-16 12:37:18 +00:00
fmt.Println("no command")
if dir == "" {
cmd = exec.Command(cmdString, "migrate", connString)
} else {
cmd = exec.Command(cmdString, "migrate", connString, dir)
}
}
2018-11-13 18:03:47 +00:00
// Combine stdout and stderr
printCommand(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
printError(err)
printOutput(output)
} else {
fmt.Println("Success")
}
2018-11-13 18:03:47 +00:00
}