81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.secnex.io/secnex/gogwapi/config"
|
|
"git.secnex.io/secnex/gogwapi/utils"
|
|
|
|
"git.secnex.io/secnex/masterlog"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type DatabaseConfiguration struct {
|
|
Host string
|
|
Port string
|
|
User string
|
|
Password string
|
|
Database string
|
|
}
|
|
|
|
var DB *gorm.DB
|
|
|
|
func NewDatabaseConfiguration(host, port, user, password, database string) *DatabaseConfiguration {
|
|
return &DatabaseConfiguration{
|
|
Host: host,
|
|
Port: port,
|
|
User: user,
|
|
Password: password,
|
|
Database: database,
|
|
}
|
|
}
|
|
|
|
func NewDatabaseConfigurationFromEnvAndConfig(config *config.YAMLConfig) *DatabaseConfiguration {
|
|
return &DatabaseConfiguration{
|
|
Host: config.Database.Host,
|
|
Port: config.Database.Port,
|
|
User: config.Database.User,
|
|
Password: config.Database.Password,
|
|
Database: config.Database.Database,
|
|
}
|
|
}
|
|
|
|
func NewDatabaseConfigurationFromEnv() *DatabaseConfiguration {
|
|
return &DatabaseConfiguration{
|
|
Host: utils.GetEnv("DB_HOST", "localhost"),
|
|
Port: utils.GetEnv("DB_PORT", "5432"),
|
|
User: utils.GetEnv("DB_USER", "postgres"),
|
|
Password: utils.GetEnv("DB_PASSWORD", "postgres"),
|
|
Database: utils.GetEnv("DB_DATABASE", "odobase"),
|
|
}
|
|
}
|
|
|
|
func (c *DatabaseConfiguration) String() string {
|
|
return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", c.Host, c.Port, c.User, c.Password, c.Database)
|
|
}
|
|
|
|
func (c *DatabaseConfiguration) Connect(models ...interface{}) error {
|
|
db, err := gorm.Open(postgres.Open(c.String()), &gorm.Config{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := AutoMigrate(db, models...); err != nil {
|
|
return err
|
|
}
|
|
|
|
DB = db
|
|
|
|
return nil
|
|
}
|
|
|
|
type SchemaProvider interface {
|
|
Schema() string
|
|
}
|
|
|
|
func AutoMigrate(conn *gorm.DB, models ...interface{}) error {
|
|
masterlog.Debug("Auto-migrating models")
|
|
return conn.AutoMigrate(models...)
|
|
}
|