2023-09-09 17:39:57 +00:00
|
|
|
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 {
|
2023-09-09 17:39:57 +00:00
|
|
|
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",
|
2023-09-09 17:39:57 +00:00
|
|
|
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 {
|
2023-09-09 17:39:57 +00:00
|
|
|
txn := db.Txn(true)
|
2023-09-25 16:43:55 +00:00
|
|
|
if err := txn.Insert("gist_init", &GistInit{
|
2023-09-09 17:39:57 +00:00
|
|
|
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) {
|
2023-09-09 17:39:57 +00:00
|
|
|
txn := db.Txn(true)
|
|
|
|
defer txn.Abort()
|
|
|
|
|
2023-09-25 16:43:55 +00:00
|
|
|
raw, err := txn.First("gist_init", "id", userId)
|
2023-09-09 17:39:57 +00:00
|
|
|
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 {
|
2023-09-09 17:39:57 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
txn.Commit()
|
2023-09-25 16:43:55 +00:00
|
|
|
return gistInit, nil
|
2023-09-09 17:39:57 +00:00
|
|
|
}
|