71 lines
1.7 KiB
Go
Raw Normal View History

2021-12-28 01:05:05 +08:00
package pgsqldb
import (
"fmt"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"git.esin.io/kimbon/weapp/internal/pkg/logging/gormlogrus"
)
func DefaultDBWithGORM() *gorm.DB {
url := NewConnectionString()
logger := logrus.StandardLogger()
db, err := NewGORM(url, logger)
if err != nil {
panic(err)
}
return db
}
func NewGORM(url string, logger logrus.FieldLogger) (*gorm.DB, error) {
db, err := gorm.Open(
postgres.Open(url),
&gorm.Config{
FullSaveAssociations: true,
Logger: gormlogrus.New(logger),
})
if err != nil {
return nil, err
}
return db, nil
}
type connectionString struct {
host string
port int32
user string
password string
database string
applicationName string
timezone string
sslModel string
}
func NewConnectionString() string {
c := connectionString{
host: viper.GetString("db.postgres.host"),
port: viper.GetInt32("db.postgres.port"),
database: viper.GetString("db.postgres.database"),
user: viper.GetString("db.postgres.user"),
password: viper.GetString("db.postgres.password"),
applicationName: viper.GetString("db.postgres.application_name"),
timezone: viper.GetString("db.postgres.tz"),
sslModel: viper.GetString("db.postgres.ssl.mode"),
}
return c.URLString()
}
func (c connectionString) URLString() string {
return fmt.Sprintf(c.Format(),
c.user, c.password, c.host, c.port, c.database, c.sslModel, c.applicationName, c.timezone)
}
func (c connectionString) Format() string {
return "postgres://%s:%s@%s:%d/%s?sslmode=%s&application_name=%s&timezone=%s"
}