76 lines
1.9 KiB
Go
76 lines
1.9 KiB
Go
package models
|
|
|
|
import (
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
type Setting struct {
|
|
gorm.Model
|
|
Name string `json:"name"`
|
|
Key string `json:"key"`
|
|
Value string `json:"value"`
|
|
}
|
|
|
|
var db *gorm.DB
|
|
var err error
|
|
|
|
func InitDB() {
|
|
db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Info),
|
|
})
|
|
if err != nil {
|
|
panic("failed to connect database")
|
|
}
|
|
// Migrate the schema
|
|
db.AutoMigrate(&Setting{})
|
|
//// 插入内容
|
|
//db.Create(&Product{Title: "新款手机", Code: "D42", Price: 1000})
|
|
//db.Create(&Product{Title: "新款电脑", Code: "D43", Price: 3500})
|
|
//
|
|
//// 读取内容
|
|
//var product Product
|
|
//db.First(&product, 1) // find product with integer primary key
|
|
//log.Println(product.Title)
|
|
//db.First(&product, "code = ?", "D42") // find product with code D42
|
|
//
|
|
//// 更新操作:更新单个字段
|
|
//db.Model(&product).Update("Price", 2000)
|
|
//
|
|
//// 更新操作:更新多个字段
|
|
//db.Model(&product).Updates(Product{Price: 2000, Code: "F42"}) // non-zero fields
|
|
//db.Model(&product).Updates(map[string]interface{}{"Price": 2000, "Code": "F42"})
|
|
//
|
|
//// 删除操作:
|
|
//db.Delete(&product, 1)
|
|
}
|
|
func FindSettingList() ([]Setting, error) {
|
|
var setting []Setting
|
|
if err := db.Find(&setting).Error; err != nil {
|
|
return setting, err
|
|
}
|
|
return setting, nil
|
|
}
|
|
func AddSetting(name, key, val string) {
|
|
var setting Setting
|
|
db.First(&setting, "key = ?", key)
|
|
if setting.ID != 0 {
|
|
db.Model(&setting).Updates(map[string]interface{}{"Name": name, "Key": key, "Value": val})
|
|
} else {
|
|
db.Create(&Setting{Name: name, Key: key, Value: val})
|
|
}
|
|
}
|
|
func FindSetting(key string) Setting {
|
|
var setting Setting
|
|
db.First(&setting, "key = ?", key)
|
|
return setting
|
|
}
|
|
func FindSettingDefault(key string, def string) string {
|
|
val := FindSetting(key).Value
|
|
if val == "" {
|
|
return def
|
|
}
|
|
return val
|
|
}
|