This is primarily focused towards having setup() and teardown() methods for a test suite that I'm planning on writing that involves creation of a DB.
I've figured out how to create a DB using GORM. However, I'm not sure if this is the best approach.
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
)
func main() {
db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=postgres password='' sslmode=disable")
capture(err)
db = db.Exec("CREATE DATABASE test_db;")
if db.Error != nil {
fmt.Println("Unable to create DB test_db, attempting to connect assuming it exists...")
db, err = gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=test_db password='' sslmode=disable")
if err != nil {
fmt.Println("Unable to connect to test_db")
capture(err)
}
}
defer db.Close()
}
func capture(err error) {
if err != nil {
log.Fatalf("%s", err)
}
}
I'm connecting to the default postgres
DB first, after which I'm creating a second test DB which I'm planning on using.
Is this the best approach ? Or is there a way to connect to Postgres without having a pre-existing DB.
NOTE: I've already looked up answers where people have used SQL driver to connect to a DB using only the connection string user:password@/
. That has not worked in my case.(like here)
I've alse tried a connection string without having a DB name, that results in the driver trying to connect to a DB with the same name as the user. Which fails since such a DB does not exist.