gf-common/db/database.go

61 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package db
import (
"database/sql"
"fmt"
"git.magicany.cc/black1552/gf-common/log"
"github.com/glebarez/sqlite"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
var (
Type gorm.Dialector
Db *gorm.DB
err error
sqlDb *sql.DB
dns = gfile.Join(gfile.Pwd(), "db", "database.db")
)
func init() {
if g.IsEmpty(dns) {
log.Error("gormDns未配置", "请检查配置文件")
return
}
sqliteInit()
Db, err = gorm.Open(Type, &gorm.Config{
SkipDefaultTransaction: true,
// 命名策略:保持与模型一致,避免字段/表名转换问题
NamingStrategy: schema.NamingStrategy{
SingularTable: true, // 表名禁用复数形式(例如 User 对应 user 表,而非 users
},
})
if err != nil {
log.Error("数据库连接失败: ", err)
return
}
sqlDb, err = Db.DB()
if err != nil {
log.Error("获取sqlDb失败", err)
return
}
if err = sqlDb.Ping(); err != nil {
log.Error("数据库未正常连接", err)
return
}
}
func sqliteInit() {
if !gfile.Exists(dns) {
_, err = gfile.Create(dns)
if err != nil {
log.Error("创建数据库文件失败: ", err)
return
}
}
Type = sqlite.Open(fmt.Sprintf("%s?cache=shared&mode=rwc&_busy_timeout=10000&_fk=1&_journal=WAL&_sync=FULL", dns))
}