Allow nil Snapshot for most ops, CRUD for collection

This commit is contained in:
jdl
2023-11-21 17:41:55 +01:00
parent 3c9e5505ab
commit 9078335d70
8 changed files with 110 additions and 98 deletions

View File

@@ -63,6 +63,7 @@ func NewUniquePartialIndex[T any](
// ----------------------------------------------------------------------------
type Index[T any] struct {
db *Database
name string
collectionID uint64
indexID uint64
@@ -70,12 +71,19 @@ type Index[T any] struct {
copy func(*T) *T
}
func (i *Index[T]) Get(tx *Snapshot, in *T) (item *T, ok bool) {
tPtr, ok := i.get(tx, in)
if !ok {
return item, false
func (i *Index[T]) ensureSnapshot(tx *Snapshot) *Snapshot {
if tx == nil {
tx = i.db.Snapshot()
}
return i.copy(tPtr), true
return tx
}
func (i *Index[T]) Get(tx *Snapshot, in *T) *T {
tx = i.ensureSnapshot(tx)
if tPtr, ok := i.get(tx, in); ok {
return i.copy(tPtr)
}
return nil
}
func (i *Index[T]) get(tx *Snapshot, in *T) (*T, bool) {
@@ -83,44 +91,49 @@ func (i *Index[T]) get(tx *Snapshot, in *T) (*T, bool) {
}
func (i *Index[T]) Has(tx *Snapshot, in *T) bool {
tx = i.ensureSnapshot(tx)
return i.btree(tx).Has(in)
}
func (i *Index[T]) Min(tx *Snapshot) (item *T, ok bool) {
tPtr, ok := i.btree(tx).Min()
if !ok {
return item, false
func (i *Index[T]) Min(tx *Snapshot) *T {
tx = i.ensureSnapshot(tx)
if tPtr, ok := i.btree(tx).Min(); ok {
return i.copy(tPtr)
}
return i.copy(tPtr), true
return nil
}
func (i *Index[T]) Max(tx *Snapshot) (item *T, ok bool) {
tPtr, ok := i.btree(tx).Max()
if !ok {
return item, false
func (i *Index[T]) Max(tx *Snapshot) *T {
tx = i.ensureSnapshot(tx)
if tPtr, ok := i.btree(tx).Max(); ok {
return i.copy(tPtr)
}
return i.copy(tPtr), true
return nil
}
func (i *Index[T]) Ascend(tx *Snapshot, each func(*T) bool) {
tx = i.ensureSnapshot(tx)
i.btreeForIter(tx).Ascend(func(t *T) bool {
return each(i.copy(t))
})
}
func (i *Index[T]) AscendAfter(tx *Snapshot, after *T, each func(*T) bool) {
tx = i.ensureSnapshot(tx)
i.btreeForIter(tx).AscendGreaterOrEqual(after, func(t *T) bool {
return each(i.copy(t))
})
}
func (i *Index[T]) Descend(tx *Snapshot, each func(*T) bool) {
tx = i.ensureSnapshot(tx)
i.btreeForIter(tx).Descend(func(t *T) bool {
return each(i.copy(t))
})
}
func (i *Index[T]) DescendAfter(tx *Snapshot, after *T, each func(*T) bool) {
tx = i.ensureSnapshot(tx)
i.btreeForIter(tx).DescendLessOrEqual(after, func(t *T) bool {
return each(i.copy(t))
})
@@ -133,7 +146,12 @@ type ListArgs[T any] struct {
Limit int // Maximum number of items to return. 0 => All.
}
func (i *Index[T]) List(tx *Snapshot, args ListArgs[T], out []*T) []*T {
func (i *Index[T]) List(tx *Snapshot, args *ListArgs[T], out []*T) []*T {
tx = i.ensureSnapshot(tx)
if args == nil {
args = &ListArgs[T]{}
}
if args.Limit < 0 {
return nil
}