wikingo/model/store_gorm.go

83 lines
1.6 KiB
Go
Raw Normal View History

2022-03-18 13:15:55 +01:00
package model
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type StoreGorm struct {
db *gorm.DB
store Store
}
func (s *StoreGorm) Open() error {
var err error
s.db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
return err
}
// Migrate the Schema
s.db.AutoMigrate(&Page{})
return nil
}
2022-03-22 16:36:18 +01:00
func (s *StoreGorm) AddPage(name string, body string) error {
var home Page
home.Name = name
home.Body = body
home.Version = 1
tx := s.db.Create(&home)
if tx.Error != nil {
return tx.Error
}
return nil
2022-03-18 13:15:55 +01:00
}
2022-03-22 16:36:18 +01:00
func (s *StoreGorm) CreatePage(page Page) error {
2022-03-23 00:26:17 +01:00
newversion := new(Page)
newversion.Name = page.Name
newversion.Body = page.Body
newversion.Version = page.Version + 1
2022-03-28 17:14:01 +02:00
tx := s.db.Create(&newversion)
2022-03-22 16:36:18 +01:00
return tx.Error
}
func (s *StoreGorm) GetPage(name string) (Page, error) {
2022-03-18 13:15:55 +01:00
var page Page
2022-03-23 00:26:17 +01:00
tx := s.db.Where("Name = ?", name).Order("Version desc").First(&page)
2022-03-22 16:36:18 +01:00
if tx.Error != nil {
return Page{}, tx.Error
}
return page, nil
2022-03-18 13:15:55 +01:00
}
2022-03-28 17:14:01 +02:00
func (s *StoreGorm) GetPageVersion(name string, version string) (Page, error) {
var page Page
tx := s.db.Where("Name = ?", name).Where("Version = ?", version).First(&page)
if tx.Error != nil {
return Page{}, tx.Error
}
return page, nil
}
2022-03-18 13:15:55 +01:00
func (s *StoreGorm) GetAllPages() ([]Page, error) {
var pages []Page
2022-04-04 22:16:07 +02:00
tx := s.db.Select("*, max(Version)").Group("Name").Find(&pages)
if tx.Error != nil {
return []Page{}, tx.Error
}
return pages, nil
}
func (s *StoreGorm) GetPageHistory(name string) ([]Page, error) {
var pages []Page
tx := s.db.Debug().Where("Name = ?", name).Order("Version desc").Find(&pages)
2022-03-18 13:15:55 +01:00
if tx.Error != nil {
return []Page{}, tx.Error
}
return pages, nil
}