Files
artalkjs/internal/db/open.go
T
qwqcode 9c3228b8fc feat(config): add db.prepare_stmt config option (#760) (#762)
The Prepared Statement database feature is enabled by default. You can disable it in config file or a env variable `ATK_DB_PREPARE__STMT=0`.
2024-02-03 19:19:00 +08:00

43 lines
1.2 KiB
Go
Raw Permalink 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 db
import (
"fmt"
"path/filepath"
"github.com/ArtalkJS/Artalk/internal/utils"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
)
func OpenSQLite(filename string, gormConfig *gorm.Config) (*gorm.DB, error) {
if filename == "" {
return nil, fmt.Errorf("please set `db.file` option in config file to specify a sqlite database path")
}
if err := utils.EnsureDir(filepath.Dir(filename)); err != nil {
return nil, err
}
return gorm.Open(sqlite.Open(filename), gormConfig)
}
func OpenMySql(dsn string, gormConfig *gorm.Config) (*gorm.DB, error) {
return gorm.Open(mysql.Open(dsn), gormConfig)
}
func OpenPostgreSQL(dsn string, gormConfig *gorm.Config) (*gorm.DB, error) {
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) {
return gorm.Open(sqlserver.Open(dsn), gormConfig)
}