2019-09-04 15:22:27 +03:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/jinzhu/gorm"
|
2021-02-09 14:57:14 +03:00
|
|
|
// PostgreSQL is an default.
|
2019-09-04 15:22:27 +03:00
|
|
|
_ "github.com/jinzhu/gorm/dialects/postgres"
|
|
|
|
)
|
|
|
|
|
2021-02-09 14:57:14 +03:00
|
|
|
// ORM struct.
|
2019-09-04 15:22:27 +03:00
|
|
|
type ORM struct {
|
|
|
|
DB *gorm.DB
|
|
|
|
}
|
|
|
|
|
2021-02-09 14:57:14 +03:00
|
|
|
// NewORM will init new database connection.
|
2019-09-04 15:22:27 +03:00
|
|
|
func NewORM(config DatabaseConfig) *ORM {
|
|
|
|
orm := &ORM{}
|
|
|
|
orm.createDB(config)
|
|
|
|
return orm
|
|
|
|
}
|
|
|
|
|
|
|
|
func (orm *ORM) createDB(config DatabaseConfig) {
|
|
|
|
db, err := gorm.Open("postgres", config.Connection)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
db.DB().SetConnMaxLifetime(time.Duration(config.ConnectionLifetime) * time.Second)
|
|
|
|
db.DB().SetMaxOpenConns(config.MaxOpenConnections)
|
|
|
|
db.DB().SetMaxIdleConns(config.MaxIdleConnections)
|
|
|
|
|
|
|
|
db.SingularTable(true)
|
|
|
|
db.LogMode(config.Logging)
|
|
|
|
|
|
|
|
orm.DB = db
|
|
|
|
}
|
|
|
|
|
2021-02-09 14:57:14 +03:00
|
|
|
// CloseDB close database connection.
|
2019-09-04 15:22:27 +03:00
|
|
|
func (orm *ORM) CloseDB() {
|
|
|
|
_ = orm.DB.Close()
|
|
|
|
}
|