2019-11-09 05:30:54 +00:00
|
|
|
package merp
|
2019-10-27 12:38:03 +00:00
|
|
|
|
|
|
|
import "os"
|
|
|
|
import "time"
|
|
|
|
import "github.com/astaxie/beego/orm"
|
2019-11-09 05:30:54 +00:00
|
|
|
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
|
2019-11-09 05:30:54 +00:00
|
|
|
func GetDB() orm.Ormer {
|
2019-10-27 13:26:07 +00:00
|
|
|
if os.Getenv("DEBUG") != "" {
|
|
|
|
orm.Debug = true
|
|
|
|
}
|
|
|
|
|
2019-11-09 05:30:54 +00:00
|
|
|
o := connectDB()
|
|
|
|
syncDB(o)
|
|
|
|
|
|
|
|
return o
|
2019-10-27 12:38:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ConnectToDb - Initializes the ORM and Connection to the postgres DB
|
2019-11-09 05:30:54 +00:00
|
|
|
func connectDB() orm.Ormer {
|
2019-10-27 12:38:03 +00:00
|
|
|
orm.DefaultTimeLoc = time.UTC
|
2019-11-07 20:57:50 +00:00
|
|
|
dbURL := os.Getenv("POSTGRES_DB_URL")
|
2019-10-27 12:38:03 +00:00
|
|
|
orm.RegisterDriver("postgres", orm.DRPostgres)
|
2019-11-07 20:57:50 +00:00
|
|
|
orm.RegisterDataBase("default", "postgres", dbURL)
|
2019-10-27 12:38:03 +00:00
|
|
|
orm.SetMaxIdleConns("default", 1)
|
|
|
|
orm.SetMaxOpenConns("default", 5)
|
2019-11-09 05:30:54 +00:00
|
|
|
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
|
2019-11-09 05:30:54 +00:00
|
|
|
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())
|
|
|
|
}
|
|
|
|
}
|