opengist/internal/memdb/memdb.go

73 lines
1.2 KiB
Go
Raw Normal View History

package memdb
import "github.com/hashicorp/go-memdb"
import ogdb "github.com/thomiceli/opengist/internal/db"
var db *memdb.MemDB
2023-09-25 16:43:55 +00:00
type GistInit struct {
UserID uint
Gist *ogdb.Gist
}
func Setup() error {
var err error
schema := &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
2023-09-25 16:43:55 +00:00
"gist_init": {
Name: "gist_init",
Indexes: map[string]*memdb.IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &memdb.UintFieldIndex{Field: "UserID"},
},
},
},
},
}
db, err = memdb.NewMemDB(schema)
if err != nil {
return err
}
return nil
}
2023-09-25 16:43:55 +00:00
func InsertGistInit(userId uint, gist *ogdb.Gist) error {
txn := db.Txn(true)
2023-09-25 16:43:55 +00:00
if err := txn.Insert("gist_init", &GistInit{
UserID: userId,
Gist: gist,
}); err != nil {
txn.Abort()
return err
}
txn.Commit()
return nil
}
2023-09-25 16:43:55 +00:00
func GetGistInitAndDelete(userId uint) (*GistInit, error) {
txn := db.Txn(true)
defer txn.Abort()
2023-09-25 16:43:55 +00:00
raw, err := txn.First("gist_init", "id", userId)
if err != nil {
return nil, err
}
if raw == nil {
return nil, nil
}
2023-09-25 16:43:55 +00:00
gistInit := raw.(*GistInit)
if err := txn.Delete("gist_init", gistInit); err != nil {
return nil, err
}
txn.Commit()
2023-09-25 16:43:55 +00:00
return gistInit, nil
}