You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.2 KiB
56 lines
1.2 KiB
|
1 month ago
|
package database
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"auroragolang/internal/config"
|
||
|
|
|
||
|
|
"gorm.io/driver/mysql"
|
||
|
|
"gorm.io/driver/postgres"
|
||
|
|
"gorm.io/driver/sqlite"
|
||
|
|
"gorm.io/gorm"
|
||
|
|
)
|
||
|
|
|
||
|
|
func Connect(cfg config.DatabaseConfig) (*gorm.DB, error) {
|
||
|
|
driver := strings.ToLower(cfg.Driver)
|
||
|
|
switch driver {
|
||
|
|
case "sqlite":
|
||
|
|
dbPath := cfg.SQLite.Path
|
||
|
|
if !filepath.IsAbs(dbPath) {
|
||
|
|
dbPath = filepath.Join(".", dbPath)
|
||
|
|
}
|
||
|
|
if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil {
|
||
|
|
return nil, fmt.Errorf("创建SQLite目录失败: %w", err)
|
||
|
|
}
|
||
|
|
return gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
|
||
|
|
case "mysql":
|
||
|
|
dsn := fmt.Sprintf(
|
||
|
|
"%s:%s@tcp(%s:%d)/%s?%s",
|
||
|
|
cfg.MySQL.User,
|
||
|
|
cfg.MySQL.Password,
|
||
|
|
cfg.MySQL.Host,
|
||
|
|
cfg.MySQL.Port,
|
||
|
|
cfg.MySQL.DBName,
|
||
|
|
cfg.MySQL.Params,
|
||
|
|
)
|
||
|
|
return gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||
|
|
case "postgres", "postgresql":
|
||
|
|
dsn := fmt.Sprintf(
|
||
|
|
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
||
|
|
cfg.Postgres.Host,
|
||
|
|
cfg.Postgres.Port,
|
||
|
|
cfg.Postgres.User,
|
||
|
|
cfg.Postgres.Password,
|
||
|
|
cfg.Postgres.DBName,
|
||
|
|
cfg.Postgres.SSLMode,
|
||
|
|
)
|
||
|
|
return gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||
|
|
default:
|
||
|
|
return nil, fmt.Errorf("未知的数据库驱动: %s", cfg.Driver)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|