ledisdb/store/store.go

88 lines
1.4 KiB
Go
Raw Normal View History

2014-07-25 13:58:00 +04:00
package store
import (
"fmt"
"github.com/siddontang/ledisdb/config"
2014-07-25 13:58:00 +04:00
"github.com/siddontang/ledisdb/store/driver"
"os"
"path"
2014-07-25 13:58:00 +04:00
)
type Config config.Config
2014-07-25 13:58:00 +04:00
type Store interface {
String() string
Open(path string, cfg *config.Config) (driver.IDB, error)
Repair(paht string, cfg *config.Config) error
2014-07-25 13:58:00 +04:00
}
var dbs = map[string]Store{}
func Register(s Store) {
name := s.String()
2014-07-25 13:58:00 +04:00
if _, ok := dbs[name]; ok {
panic(fmt.Errorf("store %s is registered", s))
2014-07-25 13:58:00 +04:00
}
dbs[name] = s
2014-07-25 13:58:00 +04:00
}
2014-07-25 20:46:03 +04:00
func ListStores() []string {
s := []string{}
for k, _ := range dbs {
s = append(s, k)
2014-07-25 13:58:00 +04:00
}
2014-07-25 20:46:03 +04:00
return s
}
func getStore(cfg *config.Config) (Store, error) {
if len(cfg.DBName) == 0 {
cfg.DBName = config.DefaultDBName
2014-07-25 13:58:00 +04:00
}
s, ok := dbs[cfg.DBName]
2014-07-25 13:58:00 +04:00
if !ok {
return nil, fmt.Errorf("store %s is not registered", cfg.DBName)
2014-07-25 20:46:03 +04:00
}
return s, nil
}
func getStorePath(cfg *config.Config) string {
return path.Join(cfg.DataDir, fmt.Sprintf("%s_data", cfg.DBName))
}
func Open(cfg *config.Config) (*DB, error) {
s, err := getStore(cfg)
if err != nil {
return nil, err
}
path := getStorePath(cfg)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
2014-07-25 20:46:03 +04:00
return nil, err
2014-07-25 13:58:00 +04:00
}
idb, err := s.Open(path, cfg)
2014-07-25 13:58:00 +04:00
if err != nil {
return nil, err
}
db := &DB{idb}
return db, nil
}
func Repair(cfg *config.Config) error {
s, err := getStore(cfg)
if err != nil {
return err
2014-07-25 13:58:00 +04:00
}
path := getStorePath(cfg)
2014-07-25 13:58:00 +04:00
return s.Repair(path, cfg)
2014-07-25 13:58:00 +04:00
}