blog/bootstrap/InitDatabase.go

71 lines
1.5 KiB
Go
Raw 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 bootstrap
import (
"os"
"sync"
sqliteDB "github.com/glebarez/sqlite"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
var BlogDB *DB
var FileDB *DB
type DB struct {
Gorm *gorm.DB
Mutex *sync.RWMutex
}
// sqlite无法同时多个线程写入需要上锁保护读操作无需考虑
func (db *DB) WGorm(txFunc func(tx *gorm.DB) error) error {
db.Mutex.Lock()
err := db.Gorm.Transaction(txFunc)
db.Mutex.Unlock()
return err
}
func initBlogGorm() {
path := Config.Database.Sqlite.BlogPath
logrus.Info("数据库文件位置:", path)
_, err := os.Stat(path)
if err != nil || os.IsNotExist(err) {
panic("SQLite数据库文件不存在!")
}
orm, err := gorm.Open(sqliteDB.Open(path), &gorm.Config{})
if err != nil {
panic("BlogGorm初始化异常!" + err.Error())
}
// orm.Exec("PRAGMA journal_mode=WAL;")
BlogDB = &DB{
Gorm: orm,
Mutex: &sync.RWMutex{},
}
logrus.Info("SQLite连接成功,BlogGorm初始化完成")
}
func initFileGorm() {
path := Config.Database.Sqlite.FilePath
logrus.Info("数据库文件位置:", path)
// path := "./sqlite.db"
_, err := os.Stat(path)
if err != nil || os.IsNotExist(err) {
panic("sqlite数据库文件不存在!")
}
orm, err := gorm.Open(sqliteDB.Open(path), &gorm.Config{})
if err != nil {
panic("Gorm初始化异常!" + err.Error())
}
// orm.Exec("PRAGMA journal_mode=WAL;")
FileDB = &DB{
Gorm: orm,
Mutex: &sync.RWMutex{},
}
logrus.Info("SQLite连接成功,FileGorm初始化完成")
}