golang-lib/database/main.go

75 lines
1.6 KiB
Go
Raw Normal View History

2017-05-17 16:17:02 +02:00
package database
import (
gormigrate "github.com/genofire/gormigrate/v2"
2021-06-01 10:51:35 +02:00
"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 {
2021-07-14 12:29:58 +02:00
if err := config.run(); err != nil {
return err
}
return config.migrate(config.Testdata)
}
// ReRun database config - connect and re migration
func (config *Database) ReRun() error {
if err := config.run(); err != nil {
return err
}
m, err := config.setupMigrator(true)
if err != nil {
return err
}
if err := m.RollbackAll(); err != nil {
2021-07-14 12:29:58 +02:00
return err
}
return config.migrate(config.Testdata)
}
func (config *Database) run() error {
2021-06-01 10:51:35 +02:00
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
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 {
2021-06-02 18:00:53 +02:00
if config.DB == nil {
return ErrNotConnected
}
2021-06-01 10:51:35 +02:00
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
}