|
|
@@ -2,10 +2,12 @@ package model
|
|
|
|
|
|
import (
|
|
|
"gorm.io/driver/mysql"
|
|
|
+ "gorm.io/driver/postgres"
|
|
|
"gorm.io/driver/sqlite"
|
|
|
"gorm.io/gorm"
|
|
|
"one-api/common"
|
|
|
"os"
|
|
|
+ "strings"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
@@ -34,28 +36,35 @@ func createRootAccountIfNeed() error {
|
|
|
return nil
|
|
|
}
|
|
|
|
|
|
-func CountTable(tableName string) (num int64) {
|
|
|
- DB.Table(tableName).Count(&num)
|
|
|
- return
|
|
|
-}
|
|
|
-
|
|
|
-func InitDB() (err error) {
|
|
|
- var db *gorm.DB
|
|
|
+func chooseDB() (*gorm.DB, error) {
|
|
|
if os.Getenv("SQL_DSN") != "" {
|
|
|
+ dsn := os.Getenv("SQL_DSN")
|
|
|
+ if strings.HasPrefix(dsn, "postgres://") {
|
|
|
+ // Use PostgreSQL
|
|
|
+ common.SysLog("using PostgreSQL as database")
|
|
|
+ return gorm.Open(postgres.New(postgres.Config{
|
|
|
+ DSN: dsn,
|
|
|
+ PreferSimpleProtocol: true, // disables implicit prepared statement usage
|
|
|
+ }), &gorm.Config{
|
|
|
+ PrepareStmt: true, // precompile SQL
|
|
|
+ })
|
|
|
+ }
|
|
|
// Use MySQL
|
|
|
common.SysLog("using MySQL as database")
|
|
|
- db, err = gorm.Open(mysql.Open(os.Getenv("SQL_DSN")), &gorm.Config{
|
|
|
- PrepareStmt: true, // precompile SQL
|
|
|
- })
|
|
|
- } else {
|
|
|
- // Use SQLite
|
|
|
- common.SysLog("SQL_DSN not set, using SQLite as database")
|
|
|
- common.UsingSQLite = true
|
|
|
- db, err = gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
|
|
|
+ return gorm.Open(mysql.Open(dsn), &gorm.Config{
|
|
|
PrepareStmt: true, // precompile SQL
|
|
|
})
|
|
|
}
|
|
|
- common.SysLog("database connected")
|
|
|
+ // Use SQLite
|
|
|
+ common.SysLog("SQL_DSN not set, using SQLite as database")
|
|
|
+ common.UsingSQLite = true
|
|
|
+ return gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{
|
|
|
+ PrepareStmt: true, // precompile SQL
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+func InitDB() (err error) {
|
|
|
+ db, err := chooseDB()
|
|
|
if err == nil {
|
|
|
if common.DebugEnabled {
|
|
|
db = db.Debug()
|