67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package models
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/wader/gormstore/v2"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var db *gorm.DB
|
|
var store *gormstore.Store
|
|
|
|
func Init() {
|
|
if _, err := os.Stat("/data/database.db"); errors.Is(err, os.ErrNotExist) {
|
|
log.Printf("Creating sqlite database")
|
|
_, err := os.Create("/data/database.db")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
var err error
|
|
|
|
db, err = gorm.Open(sqlite.Open("/data/database.db"), &gorm.Config{})
|
|
if err != nil {
|
|
log.Println("Failed to connect to db")
|
|
}
|
|
migrate()
|
|
}
|
|
|
|
func DB() *gorm.DB {
|
|
if db == nil {
|
|
Init()
|
|
}
|
|
return db
|
|
}
|
|
|
|
func Store() *gormstore.Store {
|
|
if store == nil {
|
|
store = gormstore.NewOptions(DB(), gormstore.Options{}, []byte(os.Getenv("HASHKEY")), []byte("BLOCKKEY"))
|
|
}
|
|
return store
|
|
}
|
|
|
|
func Create(d interface{}) error {
|
|
return DB().Create(d).Error
|
|
}
|
|
|
|
func Read(d interface{}) error {
|
|
return DB().First(d, d).Error
|
|
}
|
|
|
|
func ReadAll(d interface{}, offset, limit int) error {
|
|
return DB().Offset(offset).Limit(limit).Find(d).Error
|
|
}
|
|
|
|
func Update(d interface{}, where string, f interface{}) error {
|
|
return DB().Model(d).Where(where+" = ?", f).Updates(d).Error
|
|
}
|
|
|
|
func Delete(d interface{}) error {
|
|
|
|
return DB().Delete(d).Error
|
|
}
|