48 lines
914 B
Go
48 lines
914 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"io/ioutil"
|
|
"time"
|
|
|
|
"git.coolaj86.com/coolaj86/goserv/assets/configfs"
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
// pq injects itself into sql as 'postgres'
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
// DB is a concurrency-safe db connection instance
|
|
var DB *sqlx.DB
|
|
|
|
// Init returns a, you guessed it, New Store
|
|
func Init(pgURL string) error {
|
|
// https://godoc.org/github.com/lib/pq
|
|
|
|
f, err := configfs.Assets.Open("./postgres/init.sql")
|
|
if nil != err {
|
|
return err
|
|
}
|
|
|
|
dbtype := "postgres"
|
|
sqlBytes, err := ioutil.ReadAll(f)
|
|
if nil != err {
|
|
return err
|
|
}
|
|
|
|
ctx, done := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
|
|
defer done()
|
|
db, err := sql.Open(dbtype, pgURL)
|
|
if err := db.PingContext(ctx); nil != err {
|
|
return err
|
|
}
|
|
if _, err := db.ExecContext(ctx, string(sqlBytes)); nil != err {
|
|
return err
|
|
}
|
|
|
|
DB = sqlx.NewDb(db, dbtype)
|
|
|
|
return nil
|
|
}
|