Add state
This commit is contained in:
@ -1,4 +1,58 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/dialect/sqlitedialect"
|
||||
"github.com/uptrace/bun/driver/sqliteshim"
|
||||
)
|
||||
|
||||
type Persistence interface {
|
||||
CreateCapture(context.Context, *Capture) error
|
||||
GetCaptures(context.Context) ([]Capture, error)
|
||||
}
|
||||
|
||||
type SQLitePersistence struct {
|
||||
db *bun.DB
|
||||
}
|
||||
|
||||
func NewSQLitePersistence(dbloc string) (*SQLitePersistence, error) {
|
||||
sqldb, err := sql.Open(sqliteshim.ShimName, fmt.Sprintf("file:%s", dbloc))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db := bun.NewDB(sqldb, sqlitedialect.New())
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
for _, model := range []interface{}{(*Capture)(nil), (*MapScore)(nil), (*Score)(nil)} {
|
||||
_, err := db.NewCreateTable().Model(model).IfNotExists().Exec(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &SQLitePersistence{
|
||||
db,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SQLitePersistence) GetCaptures(ctx context.Context) ([]Capture, error) {
|
||||
var captures []Capture
|
||||
err := s.db.NewSelect().Model(&captures).Scan(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return captures, nil
|
||||
}
|
||||
|
||||
func (s *SQLitePersistence) CreateCapture(ctx context.Context, capture *Capture) error {
|
||||
_, err := s.db.NewInsert().Model(capture).Exec(ctx)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user