timshannon / badgerhold

BadgerHold is an embeddable NoSQL store for querying Go types built on Badger
MIT License
520 stars 51 forks source link

Custom Storer interface inconsistent value type #43

Closed Ale1ster closed 3 years ago

Ale1ster commented 3 years ago

When implementing custom Storer for a type, the IndexFunc receives a value of the provided type with an extra pointer indirection (**Local instead of *Local), which seems to be relevant to issue timshannon/bolthold#115.

This happens when building against 8addb9de1e75385ec2019a92afc81b398fa4437f (v1.0.0)

package main

import (
    //"fmt"
    "io/ioutil"
    "os"
    "testing"

    "github.com/timshannon/badgerhold"
)

type Local struct {
    Reference string
}

func (l *Local) Type() string {
    return "Local"
}

func (l *Local) Indexes() map[string]badgerhold.Index {
    refIdxFunc := func(name string, value interface{}) ([]byte, error) {
        /*
        if loc, ok := value.(*Local); ok {
            return []byte(loc.Reference), nil
        }
        return nil, fmt.Errorf("IndexFunc: expected *Local, got %T", value)
        */
        ref := value.(*Local).Reference
        return []byte(ref), nil
    }

    return map[string]badgerhold.Index{
        "Reference": badgerhold.Index{
            IndexFunc: refIdxFunc,
            Unique: true,
        },
    }
}

func TestStorerDelete(t *testing.T) {
    path, _ := ioutil.TempDir(os.TempDir(), "store-*")
    os.Remove(path)

    opts := badgerhold.DefaultOptions
    opts.Dir, opts.ValueDir = path, path

    store, err := badgerhold.Open(opts)
    if err != nil {
        t.Fatalf("Failed to open store: %v", err)
    }
    defer store.Close()

    local := Local{
        Reference: "a unique string",
    }
    err = store.Insert(1, &local)
    if err != nil {
        t.Fatalf("Unable to insert: %v", err)
    }

    err = store.Delete(1, &local)
    if err != nil {
        t.Fatalf("Unable to delete: %v", err)
    }

    err = store.Insert(32, &local)
    if err != nil {
        t.Fatalf("Unable to reinsert: %v", err)
    }
}
timshannon commented 3 years ago

Give master a try, this issue should be fixed now.

Thanks for reporting the issue, and sorry it took so long for me to get around to fixing it.