Initial commit
This commit is contained in:
69
app/database/conn.go
Normal file
69
app/database/conn.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"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 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...)
|
||||
}
|
||||
8
app/database/exec.go
Normal file
8
app/database/exec.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package database
|
||||
|
||||
import "git.secnex.io/secnex/masterlog"
|
||||
|
||||
func Execute(query string) error {
|
||||
masterlog.Debug("Executing query", map[string]interface{}{"query": query})
|
||||
return DB.Exec(query).Error
|
||||
}
|
||||
Reference in New Issue
Block a user