merp/db.go

51 lines
1.1 KiB
Go
Raw Permalink Normal View History

package merp
2019-10-27 12:38:03 +00:00
import "os"
import "time"
import "github.com/astaxie/beego/orm"
import "github.com/sneak/merp/models"
2019-10-27 12:38:03 +00:00
import "github.com/rs/zerolog/log"
2019-11-07 21:04:57 +00:00
import _ "github.com/lib/pq" //revive:disable-line
2019-10-27 12:38:03 +00:00
2019-11-09 06:01:59 +00:00
// GetDB returns an orm.Ormer so that the API server can talk to the
// database
func GetDB() orm.Ormer {
2019-10-27 13:26:07 +00:00
if os.Getenv("DEBUG") != "" {
orm.Debug = true
}
o := connectDB()
syncDB(o)
return o
2019-10-27 12:38:03 +00:00
}
// ConnectToDb - Initializes the ORM and Connection to the postgres DB
func connectDB() orm.Ormer {
2019-10-27 12:38:03 +00:00
orm.DefaultTimeLoc = time.UTC
dbURL := os.Getenv("POSTGRES_DB_URL")
2019-10-27 12:38:03 +00:00
orm.RegisterDriver("postgres", orm.DRPostgres)
orm.RegisterDataBase("default", "postgres", dbURL)
2019-10-27 12:38:03 +00:00
orm.SetMaxIdleConns("default", 1)
orm.SetMaxOpenConns("default", 5)
orm.RegisterModel(new(models.Merp))
o := orm.NewOrm()
o.Using("default")
return o
2019-10-27 12:38:03 +00:00
}
2019-11-07 20:54:49 +00:00
// SyncDB() is responsible for creating the schema in the database
func syncDB(o orm.Ormer) {
2019-10-27 12:38:03 +00:00
// Database alias.
name := "default"
// Drop table and re-create.
force := false
// Print log.
verbose := true
// Error.
err := orm.RunSyncdb(name, force, verbose)
if err != nil {
log.Fatal().Msg(err.Error())
}
}