diff --git a/conf/artalk.example.simple.yml b/conf/artalk.example.simple.yml index 18d0bf5fe..c66f6c323 100644 --- a/conf/artalk.example.simple.yml +++ b/conf/artalk.example.simple.yml @@ -17,6 +17,7 @@ db: password: "" charset: "utf8mb4" ssl: false + prepare_stmt: true log: enabled: true filename: "./data/artalk.log" diff --git a/conf/artalk.example.yml b/conf/artalk.example.yml index e20dadaf2..b0beeca06 100644 --- a/conf/artalk.example.yml +++ b/conf/artalk.example.yml @@ -47,6 +47,8 @@ db: charset: "utf8mb4" # Enable SSL mode ssl: false + # Prepared Statement + prepare_stmt: true # Logging log: diff --git a/conf/artalk.example.zh-CN.yml b/conf/artalk.example.zh-CN.yml index 2c13f0802..a855e1dc4 100644 --- a/conf/artalk.example.zh-CN.yml +++ b/conf/artalk.example.zh-CN.yml @@ -44,6 +44,8 @@ db: table_prefix: "" # 启用 SSL ssl: false + # 预编译语句 + prepare_stmt: true # 日志 log: diff --git a/docs/docs/guide/backend/config.md b/docs/docs/guide/backend/config.md index 1709dc456..0f67de12b 100644 --- a/docs/docs/guide/backend/config.md +++ b/docs/docs/guide/backend/config.md @@ -96,6 +96,7 @@ db: charset: "utf8mb4" # 编码格式 table_prefix: "" # 表前缀 (例如:"atk_") ssl: false # 启用 SSL + prepare_stmt: true # 预编译语句 ``` 数据表将在 Artalk 启动时自动完成创建,无需额外操作。 diff --git a/internal/config/config.go b/internal/config/config.go index 8e1808031..a9c0c26af 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -57,6 +57,7 @@ type DBConf struct { TablePrefix string `koanf:"table_prefix" json:"table_prefix"` Charset string `koanf:"charset" json:"charset"` SSL bool `koanf:"ssl" json:"ssl"` + PrepareStmt *bool `koanf:"prepare_stmt" json:"prepare_stmt"` } type CacheConf struct { diff --git a/internal/db/db.go b/internal/db/db.go index 1851df6b3..b4746ce72 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -17,6 +17,13 @@ func NewDB(conf config.DBConf) (*gorm.DB, error) { }, } + // Enable Prepared Statement by default + if prepareStmt := conf.PrepareStmt; prepareStmt != nil { + gormConfig.PrepareStmt = *prepareStmt + } else { + gormConfig.PrepareStmt = true + } + var dsn string if conf.Dsn != "" { dsn = conf.Dsn diff --git a/internal/db/open.go b/internal/db/open.go index ca0c23a2b..dc79a6b83 100644 --- a/internal/db/open.go +++ b/internal/db/open.go @@ -27,7 +27,14 @@ func OpenMySql(dsn string, gormConfig *gorm.Config) (*gorm.DB, error) { } func OpenPostgreSQL(dsn string, gormConfig *gorm.Config) (*gorm.DB, error) { - return gorm.Open(postgres.Open(dsn), gormConfig) + return gorm.Open(postgres.New(postgres.Config{ + DSN: dsn, + + // gorm v2 use `pgx` as postgres’s database/sql driver, + // it enables prepared statement cache by default, + // disable it when `PrepareStmt` is false by following code: + PreferSimpleProtocol: !gormConfig.PrepareStmt, + }), gormConfig) } func OpenSqlServer(dsn string, gormConfig *gorm.Config) (*gorm.DB, error) {