multitenantStack/scripts/migrateTenants/migrateTenants.go

106 lines
2.1 KiB
Go

package main
import (
"fmt"
companyDB "multitenantStack/services/companydb"
"os"
"os/exec"
"strings"
_ "github.com/lib/pq"
)
var conf companyDB.DBConfig
func main() {
migrateSystem := false
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]
}
}
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
}
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"
}
connString := fmt.Sprintf("--conn=postgres://%s:%s@%s:%d/%s?sslmode=%s", conf.User, conf.Password, conf.Host, conf.Port, dbName, conf.Ssl)
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 {
fmt.Println("no command")
if dir == "" {
cmd = exec.Command(cmdString, "migrate", connString)
} else {
cmd = exec.Command(cmdString, "migrate", connString, dir)
}
}
// Combine stdout and stderr
printCommand(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
printError(err)
printOutput(output)
} else {
fmt.Println("Success")
}
}