2023-09-17 03:52:37 -04:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
2023-09-17 04:14:31 -04:00
|
|
|
"github.com/glebarez/sqlite"
|
2023-09-20 21:08:02 -04:00
|
|
|
"go.uber.org/zap"
|
2023-09-17 03:52:37 -04:00
|
|
|
"gorm.io/gorm"
|
2023-09-20 21:08:02 -04:00
|
|
|
"path/filepath"
|
|
|
|
"sub2clash/logger"
|
2023-09-17 03:52:37 -04:00
|
|
|
"sub2clash/model"
|
2023-09-20 21:08:02 -04:00
|
|
|
"sub2clash/utils"
|
2023-09-17 03:52:37 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
var DB *gorm.DB
|
|
|
|
|
|
|
|
func ConnectDB() error {
|
2023-09-17 04:14:31 -04:00
|
|
|
// 用上面的数据库连接初始化 gorm
|
2023-09-20 21:08:02 -04:00
|
|
|
err := utils.MKDir("data")
|
2023-09-17 04:14:31 -04:00
|
|
|
if err != nil {
|
2023-09-20 21:08:02 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
db, err := gorm.Open(
|
|
|
|
sqlite.Open(filepath.Join("data", "sub2clash.db")), &gorm.Config{
|
|
|
|
Logger: nil,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-09-17 04:14:31 -04:00
|
|
|
}
|
2023-09-17 03:52:37 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
DB = db
|
|
|
|
err = db.AutoMigrate(&model.ShortLink{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2023-09-20 21:08:02 -04:00
|
|
|
|
|
|
|
func FindShortLinkByUrl(url string, shortLink *model.ShortLink) *gorm.DB {
|
|
|
|
logger.Logger.Debug("find short link by url", zap.String("url", url))
|
|
|
|
return DB.Where("url = ?", url).First(&shortLink)
|
|
|
|
}
|
|
|
|
|
|
|
|
func FindShortLinkByHash(hash string, shortLink *model.ShortLink) *gorm.DB {
|
|
|
|
logger.Logger.Debug("find short link by hash", zap.String("hash", hash))
|
|
|
|
return DB.Where("hash = ?", hash).First(&shortLink)
|
|
|
|
}
|
|
|
|
|
|
|
|
func SaveShortLink(shortLink *model.ShortLink) {
|
|
|
|
logger.Logger.Debug("save short link", zap.String("hash", shortLink.Hash))
|
|
|
|
DB.Save(shortLink)
|
|
|
|
}
|
|
|
|
|
|
|
|
func FirstOrCreateShortLink(shortLink *model.ShortLink) {
|
|
|
|
logger.Logger.Debug("first or create short link", zap.String("hash", shortLink.Hash))
|
|
|
|
DB.FirstOrCreate(shortLink)
|
|
|
|
}
|