-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
open.go
42 lines (35 loc) · 1.17 KB
/
open.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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)
}