Files
atomctl/templates/project/providers/postgres/config.go.tpl

137 lines
3.2 KiB
Smarty
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package postgres
import (
"fmt"
"strconv"
"time"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/opt"
"gorm.io/gorm/logger"
)
const DefaultPrefix = "Database"
func DefaultProvider() container.ProviderContainer {
return container.ProviderContainer{
Provider: Provide,
Options: []opt.Option{
opt.Prefix(DefaultPrefix),
},
}
}
type Config struct {
Username string
Password string
Database string
Schema string
Host string
Port uint
SslMode string
TimeZone string
Prefix string //
Singular bool // true表示开启
MaxIdleConns int //
MaxOpenConns int //
// 0
ConnMaxLifetimeSeconds uint
ConnMaxIdleTimeSeconds uint
// GORM
LogLevel string // silent|error|warn|infoinfo
SlowThresholdMs uint // 200
ParameterizedQueries bool // 便
PrepareStmt bool //
SkipDefaultTransaction bool //
// DSN
UseSearchPath bool // DSN search_path
ApplicationName string // application_name
}
func (m Config) GormSlowThreshold() time.Duration {
if m.SlowThresholdMs == 0 {
return 200 * time.Millisecond // 200ms
}
return time.Duration(m.SlowThresholdMs) * time.Millisecond
}
func (m Config) GormLogLevel() logger.LogLevel {
switch m.LogLevel {
case "silent":
return logger.Silent
case "error":
return logger.Error
case "warn":
return logger.Warn
case "info", "":
return logger.Info
default:
return logger.Info
}
}
func (m *Config) checkDefault() {
if m.MaxIdleConns == 0 {
m.MaxIdleConns = 10
}
if m.MaxOpenConns == 0 {
m.MaxOpenConns = 100
}
if m.Username == "" {
m.Username = "postgres"
}
if m.SslMode == "" {
m.SslMode = "disable"
}
if m.TimeZone == "" {
m.TimeZone = "Asia/Shanghai"
}
if m.Port == 0 {
m.Port = 5432
}
if m.Schema == "" {
m.Schema = "public"
}
}
func (m *Config) EmptyDsn() string {
// DSN
dsnTpl := "host=%s user=%s password=%s port=%d dbname=%s sslmode=%s TimeZone=%s"
m.checkDefault()
base := fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Port, m.Database, m.SslMode, m.TimeZone)
//
extras := ""
if m.UseSearchPath && m.Schema != "" {
extras += " search_path=" + m.Schema
}
if m.ApplicationName != "" {
extras += " application_name=" + strconv.Quote(m.ApplicationName)
}
return base + extras
}
// DSN connection dsn
func (m *Config) DSN() string {
// DSN
dsnTpl := "host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s"
m.checkDefault()
base := fmt.Sprintf(dsnTpl, m.Host, m.Username, m.Password, m.Database, m.Port, m.SslMode, m.TimeZone)
//
extras := ""
if m.UseSearchPath && m.Schema != "" {
extras += " search_path=" + m.Schema
}
if m.ApplicationName != "" {
extras += " application_name=" + strconv.Quote(m.ApplicationName)
}
return base + extras
}