How to tell a single key exists or not using golang binding

With go binding, given the code like this

package main

import (
  "github.com/apple/foundationdb/bindings/go/src/fdb"
  "fmt"
)

func main() {
  db.MustAPIVersion(510)
  db := fdb.MustOpenDefault()
  _, err = db.Transact(func (tr fdb.Transaction) (ret interface{}, e error) {
    fmt.Printf("hello: %v\n", tr.Get(fdb.Key("hello")).MustGet())
  }
}

If the key “hello” is not set yet, the output is

hello: []

Even if I set the empty value for the key

tr.Set(fdb.Key("hello"), []byte{})

I get same result

hello: []

However, with fdbcli command, I can tell the key exists or not,

fdb> get hello
`hello': not found
fdb> set hello ""
Committed (29036447425)
fdb> get hello
`hello' is `'

How can I tell a key exists or not with the golang binding?

1 Like

Go’s %v print formatter is displaying a nil byte slice and an empty byte slice the same way. If you perform an explicit nil check, you can confirm that tr.Get().MustGet() returns nil if the key doesn’t exist.

package main

import (
  "fmt"
  "github.com/apple/foundationdb/bindings/go/src/fdb"
)

func main() {
  fdb.MustAPIVersion(510)
  db := fdb.MustOpenDefault()

  db.Transact(func(tr fdb.Transaction) (interface{}, error) {
    // Ensure that key 'hello' is gone
    tr.Clear(fdb.Key("hello"))

    hello := tr.Get(fdb.Key("hello")).MustGet()
    if hello == nil {
      fmt.Println("Hello does not exist.")
    } else {
      fmt.Println("Hello exists.")
    }

    // Note that the empty byte slice is different than nil
    if []byte{} == nil {
      panic("This is never true.")
    }

    // This is maintained through FoundationDB:
    tr.Set(fdb.Key("hello"), []byte{})
    hello = tr.Get(fdb.Key("hello")).MustGet()
    if hello == nil {
      fmt.Println("Hello does not exist.")
    } else {
      fmt.Println("Hello exists.")
    }

    return nil, nil
  })
}

Running this program, the output is as expected: we can detect that the key doesn’t exist after the first get, and that it does exist after the second get:

Hello does not exist.
Hello exists.
2 Likes

@mwilson
Thanks for your reply. I’ll try it.