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.

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