package companydb import ( "database/sql" "errors" "fmt" tokenTools "multitenantStack/services/tokenTools" "os" jwt "github.com/dgrijalva/jwt-go" ) var dbs map[string]*sql.DB // InitCompanyDBService Init companydb service and open system db connection func InitCompanyDBService() { dbs = make(map[string]*sql.DB) systemDB, err := sql.Open("postgres", "host=127.0.0.1 port=5435 user=postgres password=postgre dbname=system sslmode=disable") if err != nil { fmt.Println("Fatal: could not connect to db, exiting... Error:", err) os.Exit(1) } dbs["system"] = systemDB } // GetSystemDatabase returns system db func GetSystemDatabase() *sql.DB { fmt.Println(dbs) return dbs["system"] } // GetDatabaseWithName Get orm and user information func GetDatabaseWithName(companyName string) (*sql.DB, error) { if dbs[companyName] != nil { fmt.Println("DB Already open") return dbs[companyName], nil } conStr := fmt.Sprintf("host=127.0.0.1 port=5435 user=postgres password=postgre dbname=%s sslmode=disable", companyName) db, err := sql.Open("postgres", conStr) dbs[companyName] = db if err != nil { return nil, err } return db, nil } // TODO: call upper function in this one to reduce code // GetDatabase Get orm and user information func GetDatabase(tokenString string) (jwt.MapClaims, *sql.DB, error) { // validate token valid, token := tokenTools.Validate(tokenString) if !valid { return nil, nil, errors.New("Token is invalid") } tokenMap := token.Claims.(jwt.MapClaims) companyName := tokenMap["companyName"].(string) if dbs[companyName] != nil { fmt.Println("DB Already open") return tokenMap, dbs[companyName], nil } conStr := fmt.Sprintf("host=127.0.0.1 port=5435 user=postgres password=postgre dbname=%s sslmode=disable", companyName) fmt.Println(conStr) db, err := sql.Open("postgres", conStr) if err != nil { return nil, nil, err } // return db with orm or error return tokenMap, db, nil } // CreateDatabase Create a database by copying the template func CreateDatabase(companyName string) { /* if dbs[companyName] != nil { fmt.Println("DB Already open") return dbs[companyName], nil } /* db, err = sql.Open("postgres", "host=127.0.0.1 port=5435 user=postgres password=postgre dbname=company5 sslmode=disable") if err != nil { log.Fatal(err) } or, err := orm.NewOrmWithDB("postgres", "temp", db) */ } // DeleteDatabase Delete an entire database, this is very very dangerous :-) func DeleteDatabase(token string) { //_, db, err := GetDatabase(token) /* remove from map! db.Close() fmt.Println("Closed company5") //} res, err := o.Raw("DROP DATABASE company5;").Exec() if err == nil { num, _ := res.RowsAffected() fmt.Println("mysql row affected number: ", num) } */ }