51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package global
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"electricity_bill_calc/config"
|
|
"electricity_bill_calc/logger"
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
"github.com/jackc/pgx/v4/log/zapadapter"
|
|
"github.com/jackc/pgx/v4/stdlib"
|
|
_ "github.com/lib/pq"
|
|
"github.com/uptrace/bun"
|
|
"github.com/uptrace/bun/dialect/pgdialect"
|
|
)
|
|
|
|
var (
|
|
DB *bun.DB
|
|
)
|
|
|
|
func SetupDatabaseConnection() error {
|
|
var err error
|
|
connStr := fmt.Sprintf(
|
|
"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai connect_timeout=0 tcp_user_timeout=180000",
|
|
config.DatabaseSettings.Host,
|
|
config.DatabaseSettings.User,
|
|
config.DatabaseSettings.Pass,
|
|
config.DatabaseSettings.DB,
|
|
config.DatabaseSettings.Port,
|
|
)
|
|
pgxConn, err := pgx.ParseConfig(connStr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
pgxConn.PreferSimpleProtocol = true
|
|
if config.ServerSettings.RunMode == "debug" {
|
|
pgxConn.Logger = zapadapter.NewLogger(logger.Named("PGX"))
|
|
pgxConn.LogLevel = pgx.LogLevelDebug
|
|
}
|
|
sqldb := stdlib.OpenDB(*pgxConn)
|
|
DB = bun.NewDB(sqldb, pgdialect.New())
|
|
DB.SetMaxIdleConns(config.DatabaseSettings.MaxIdleConns)
|
|
DB.SetMaxOpenConns(config.DatabaseSettings.MaxOpenConns)
|
|
DB.SetConnMaxIdleTime(10 * time.Minute)
|
|
DB.SetConnMaxLifetime(60 * time.Minute)
|
|
DB.Ping()
|
|
|
|
return nil
|
|
}
|