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.

54 lines
1.3 KiB

9 years ago
7 years ago
9 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. //----------------------------------------
  7. // Main entry
  8. type DBBackendType string
  9. const (
  10. LevelDBBackend DBBackendType = "leveldb" // legacy, defaults to goleveldb unless +gcc
  11. CLevelDBBackend DBBackendType = "cleveldb"
  12. GoLevelDBBackend DBBackendType = "goleveldb"
  13. MemDBBackend DBBackendType = "memdb"
  14. FSDBBackend DBBackendType = "fsdb" // using the filesystem naively
  15. )
  16. type dbCreator func(name string, dir string) (DB, error)
  17. var backends = map[DBBackendType]dbCreator{}
  18. func registerDBCreator(backend DBBackendType, creator dbCreator, force bool) {
  19. _, ok := backends[backend]
  20. if !force && ok {
  21. return
  22. }
  23. backends[backend] = creator
  24. }
  25. // NewDB creates a new database of type backend with the given name.
  26. // NOTE: function panics if:
  27. // - backend is unknown (not registered)
  28. // - creator function, provided during registration, returns error
  29. func NewDB(name string, backend DBBackendType, dir string) DB {
  30. dbCreator, ok := backends[backend]
  31. if !ok {
  32. keys := make([]string, len(backends))
  33. i := 0
  34. for k := range backends {
  35. keys[i] = string(k)
  36. i++
  37. }
  38. panic(fmt.Sprintf("Unknown db_backend %s, expected either %s", backend, strings.Join(keys, " or ")))
  39. }
  40. db, err := dbCreator(name, dir)
  41. if err != nil {
  42. panic(fmt.Sprintf("Error initializing DB: %v", err))
  43. }
  44. return db
  45. }