wikingo/model/store_gorm.go

70 lines
1.2 KiB
Go
Raw Normal View History

2022-03-18 13:15:55 +01:00
package model
import (
"fmt"
2022-03-22 16:36:18 +01:00
2022-03-18 13:15:55 +01:00
"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
}
fmt.Printf("%s\n", s.db.Name())
// 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
}
2022-03-18 13:15:55 +01:00
fmt.Println("Page created")
2022-03-22 16:36:18 +01:00
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
tx := s.db.Save(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
}
fmt.Println(page)
return page, nil
2022-03-18 13:15:55 +01:00
}
func (s *StoreGorm) GetAllPages() ([]Page, error) {
var pages []Page
tx := s.db.Find(&pages)
if tx.Error != nil {
return []Page{}, tx.Error
}
return pages, nil
}