You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.9 KiB

9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
  1. package db
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type DBBackendType string
  7. // These are valid backend types.
  8. const (
  9. // GoLevelDBBackend represents goleveldb (github.com/syndtr/goleveldb - most
  10. // popular implementation)
  11. // - pure go
  12. // - stable
  13. GoLevelDBBackend DBBackendType = "goleveldb"
  14. // CLevelDBBackend represents cleveldb (uses levigo wrapper)
  15. // - fast
  16. // - requires gcc
  17. // - use cleveldb build tag (go build -tags cleveldb)
  18. CLevelDBBackend DBBackendType = "cleveldb"
  19. // MemDBBackend represents in-memoty key value store, which is mostly used
  20. // for testing.
  21. MemDBBackend DBBackendType = "memdb"
  22. // FSDBBackend represents filesystem database
  23. // - EXPERIMENTAL
  24. // - slow
  25. FSDBBackend DBBackendType = "fsdb"
  26. // BoltDBBackend represents bolt (uses etcd's fork of bolt -
  27. // github.com/etcd-io/bbolt)
  28. // - EXPERIMENTAL
  29. // - may be faster is some use-cases (random reads - indexer)
  30. // - use boltdb build tag (go build -tags boltdb)
  31. BoltDBBackend DBBackendType = "boltdb"
  32. )
  33. type dbCreator func(name string, dir string) (DB, error)
  34. var backends = map[DBBackendType]dbCreator{}
  35. func registerDBCreator(backend DBBackendType, creator dbCreator, force bool) {
  36. _, ok := backends[backend]
  37. if !force && ok {
  38. return
  39. }
  40. backends[backend] = creator
  41. }
  42. // NewDB creates a new database of type backend with the given name.
  43. // NOTE: function panics if:
  44. // - backend is unknown (not registered)
  45. // - creator function, provided during registration, returns error
  46. func NewDB(name string, backend DBBackendType, dir string) DB {
  47. dbCreator, ok := backends[backend]
  48. if !ok {
  49. keys := make([]string, len(backends))
  50. i := 0
  51. for k := range backends {
  52. keys[i] = string(k)
  53. i++
  54. }
  55. panic(fmt.Sprintf("Unknown db_backend %s, expected either %s", backend, strings.Join(keys, " or ")))
  56. }
  57. db, err := dbCreator(name, dir)
  58. if err != nil {
  59. panic(fmt.Sprintf("Error initializing DB: %v", err))
  60. }
  61. return db
  62. }