merp/models/db.go

63 lines
1.2 KiB
Go
Raw Normal View History

2019-10-27 12:38:03 +00:00
package models
import "os"
import "time"
import "github.com/astaxie/beego/orm"
import "github.com/rs/zerolog/log"
import _ "github.com/lib/pq"
var ormObject orm.Ormer
2019-11-07 20:54:49 +00:00
func initialize() {
2019-10-27 13:26:07 +00:00
if os.Getenv("DEBUG") != "" {
orm.Debug = true
}
2019-11-07 20:54:49 +00:00
connectToDb()
syncDB()
2019-10-27 12:38:03 +00:00
}
// ConnectToDb - Initializes the ORM and Connection to the postgres DB
2019-11-07 20:54:49 +00:00
func connectToDb() {
2019-10-27 13:26:07 +00:00
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(Merp))
ormObject = orm.NewOrm()
ormObject.Using("default")
}
2019-11-07 20:54:49 +00:00
// SyncDB() is responsible for creating the schema in the database
func syncDB() {
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())
}
}
// GetOrmObject - Getter function for the ORM object with which we can query the database
func GetOrmObject() orm.Ormer {
if ormObject == nil {
2019-11-07 20:54:49 +00:00
initialize()
2019-10-27 12:38:03 +00:00
}
return ormObject
}