golang-lib/database/main.go

53 lines
1.2 KiB
Go
Raw Normal View History

2017-05-17 16:17:02 +02:00
package database
import (
2021-06-01 10:51:35 +02:00
gormigrate "github.com/go-gormigrate/gormigrate/v2"
"gorm.io/driver/postgres"
2021-06-01 10:15:46 +02:00
"gorm.io/gorm"
2021-06-01 10:51:35 +02:00
"gorm.io/gorm/logger"
2017-05-17 16:17:02 +02:00
)
2021-06-01 17:41:05 +02:00
// Database struct to read from config
2021-06-01 10:51:35 +02:00
type Database struct {
DB *gorm.DB
Connection string `toml:"connection"`
Debug bool `toml:"debug"`
Testdata bool `toml:"testdata"`
LogLevel logger.LogLevel `toml:"log_level"`
migrations map[string]*gormigrate.Migration
migrationTestdata map[string]*gormigrate.Migration
2017-05-17 16:17:02 +02:00
}
2021-06-01 17:41:05 +02:00
// Run database config - connect and migrate
2021-06-01 10:51:35 +02:00
func (config *Database) Run() error {
db, err := gorm.Open(postgres.Open(config.Connection), &gorm.Config{
Logger: logger.Default.LogMode(config.LogLevel),
})
2017-05-17 16:17:02 +02:00
if err != nil {
2021-06-01 10:51:35 +02:00
return err
2017-05-17 16:17:02 +02:00
}
2021-06-01 10:51:35 +02:00
db.Debug().Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
if config.Debug {
db = db.Debug()
2017-05-17 16:17:02 +02:00
}
2021-06-01 10:51:35 +02:00
config.DB = db
if err = config.migrate(config.Testdata); err != nil {
return err
2017-05-17 16:17:02 +02:00
}
2021-06-01 10:51:35 +02:00
return nil
2017-05-17 16:17:02 +02:00
}
2021-06-01 17:41:05 +02:00
// Status get status - is database pingable
2021-06-01 10:51:35 +02:00
func (config *Database) Status() error {
sqlDB, err := config.DB.DB()
if err != nil {
return err
}
if err = sqlDB.Ping(); err != nil {
return err
}
return nil
2017-05-17 16:17:02 +02:00
}