badger: support temporary in-memory databases

This commit is contained in:
mappu 2024-06-23 16:29:11 +12:00
parent d7c2282335
commit f79d17afed
2 changed files with 28 additions and 6 deletions

View File

@ -12,7 +12,6 @@ import (
type badgerLoadedDatabase struct {
displayName string
path string
db *badger.DB
nav *vcl.TTreeNode
@ -117,18 +116,30 @@ var _ loadedDatabase = &badgerLoadedDatabase{} // interface assertion
//
func (f *TMainForm) badgerAddDatabaseFromMemory() {
f.badgerAddDatabaseFrom(badger.DefaultOptions("").WithInMemory(true))
}
func (f *TMainForm) badgerAddDatabaseFromDirectory(path string) {
f.badgerAddDatabaseFrom(badger.DefaultOptions(path))
}
func (f *TMainForm) badgerAddDatabaseFrom(opts badger.Options) {
// TODO load in background thread to stop blocking the UI
db, err := badger.Open(badger.DefaultOptions(path))
db, err := badger.Open(opts)
if err != nil {
vcl.ShowMessage(fmt.Sprintf("Failed to load database '%s': %s", path, err.Error()))
vcl.ShowMessage(fmt.Sprintf("Failed to load database: %s", err.Error()))
return
}
ld := &badgerLoadedDatabase{
path: path,
displayName: filepath.Base(path),
db: db,
db: db,
}
if opts.Dir == "" {
ld.displayName = ":memory:" // SQLite-style naming
} else {
ld.displayName = filepath.Base(opts.Dir)
}
ld.nav = f.Buckets.Items().Add(nil, ld.displayName)

11
main.go
View File

@ -57,6 +57,12 @@ func (f *TMainForm) OnFormCreate(sender vcl.IObject) {
mnuFileBadgerOpen.SetOnClick(f.OnMnuFileBadgerOpenClick)
mnuFileBadger.Add(mnuFileBadgerOpen)
mnuFileBadgerMemory := vcl.NewMenuItem(mnuFileBadger)
mnuFileBadgerMemory.SetCaption("New in-memory database")
mnuFileBadgerMemory.SetImageIndex(imgDatabaseAdd)
mnuFileBadgerMemory.SetOnClick(f.OnMnuFileBadgerMemoryClick)
mnuFileBadger.Add(mnuFileBadgerMemory)
//
mnuFileBolt := vcl.NewMenuItem(mnuFile)
@ -277,6 +283,11 @@ func (f *TMainForm) OnMnuFileBadgerOpenClick(sender vcl.IObject) {
}
}
func (f *TMainForm) OnMnuFileBadgerMemoryClick(sender vcl.IObject) {
f.badgerAddDatabaseFromMemory()
}
func (f *TMainForm) OnMnuFileSqliteMemoryClick(sender vcl.IObject) {
f.sqliteAddDatabaseFromFile(`:memory:`)
}