basic_ds.go 2.02 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
package datastore

import (
  "log"
)

// Here are some basic datastore implementations.

// MapDatastore uses a standard Go map for internal storage.
type keyMap map[Key]interface{}
type MapDatastore struct {
  values keyMap
}

func NewMapDatastore() (d *MapDatastore) {
  return &MapDatastore{
    values: keyMap{},
  }
}

func (d *MapDatastore) Put(key Key, value interface{}) (err error) {
  d.values[key] = value
  return nil
}

func (d *MapDatastore) Get(key Key) (value interface{}, err error) {
  val, found := d.values[key]
  if !found {
    return nil, ErrNotFound
  }
  return val, nil
}

func (d *MapDatastore) Has(key Key) (exists bool, err error) {
  _, found := d.values[key]
  return found, nil
}

func (d *MapDatastore) Delete(key Key) (err error) {
  delete(d.values, key)
  return nil
}

// NullDatastore stores nothing, but conforms to the API.
// Useful to test with.
type NullDatastore struct {
}

func NewNullDatastore() (*NullDatastore) {
  return &NullDatastore{}
}

func (d *NullDatastore) Put(key Key, value interface{}) (err error) {
  return nil
}

func (d *NullDatastore) Get(key Key) (value interface{}, err error) {
  return nil, nil
}

func (d *NullDatastore) Has(key Key) (exists bool, err error) {
  return false, nil
}

func (d *NullDatastore) Delete(key Key) (err error) {
  return nil
}

// LogDatastore logs all accesses through the datastore.
type LogDatastore struct {
  Child Datastore
}

func NewLogDatastore(ds Datastore) (*LogDatastore) {
  return &LogDatastore{Child: ds}
}

func (d *LogDatastore) Put(key Key, value interface{}) (err error) {
  log.Printf("LogDatastore: Put %s", key)
  return d.Child.Put(key, value)
}

func (d *LogDatastore) Get(key Key) (value interface{}, err error) {
  log.Printf("LogDatastore: Get %s", key)
  return d.Child.Get(key)
}

func (d *LogDatastore) Has(key Key) (exists bool, err error) {
  log.Printf("LogDatastore: Has %s", key)
  return d.Child.Has(key)
}

func (d *LogDatastore) Delete(key Key) (err error) {
  log.Printf("LogDatastore: Delete %s", key)
  return d.Child.Delete(key)
}