Explicitly set the table name during service init (#1497)

This commit is contained in:
Jake Sanders 2020-04-07 13:00:05 +01:00 committed by GitHub
parent 2ea5b33955
commit 71538adfdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 20 deletions

View File

@ -106,12 +106,9 @@ func (s *service) Init(opts ...Option) {
logger.Fatal(err)
}
// If the store has no Table set, fallback to the
// services name
if len(store.DefaultStore.Options().Table) == 0 {
name := s.opts.Cmd.App().Name
store.DefaultStore.Init(store.Table(name))
}
// Explicitly set the table name to the service name
name := s.opts.Cmd.App().Name
store.DefaultStore.Init(store.Table(name))
// TODO: replace Cmd.Init with config.Load
// Right now we're just going to load a token

View File

@ -14,11 +14,10 @@ import (
"github.com/pkg/errors"
)
// DefaultNamespace is the namespace that the sql store
// DefaultDatabase is the namespace that the sql store
// will use if no namespace is provided.
var (
DefaultNamespace = "micro"
DefaultPrefix = "micro"
DefaultDatabase = "micro"
)
type sqlStore struct {
@ -296,26 +295,26 @@ func (s *sqlStore) initDB() error {
func (s *sqlStore) configure() error {
if len(s.options.Nodes) == 0 {
s.options.Nodes = []string{"localhost:26257"}
s.options.Nodes = []string{"postgresql://root@localhost:26257"}
}
namespace := s.options.Database
if len(namespace) == 0 {
namespace = DefaultNamespace
database := s.options.Database
if len(database) == 0 {
database = DefaultDatabase
}
prefix := s.options.Table
if len(prefix) == 0 {
prefix = DefaultPrefix
if len(s.options.Table) == 0 {
return errors.New("no table set")
}
table := s.options.Table
// store.namespace must only contain letters, numbers and underscores
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
return errors.New("error compiling regex for namespace")
}
namespace = reg.ReplaceAllString(namespace, "_")
prefix = reg.ReplaceAllString(prefix, "_")
database = reg.ReplaceAllString(database, "_")
table = reg.ReplaceAllString(table, "_")
source := s.options.Nodes[0]
// check if it is a standard connection string eg: host=%s port=%d user=%s password=%s dbname=%s sslmode=disable
@ -343,8 +342,8 @@ func (s *sqlStore) configure() error {
// save the values
s.db = db
s.database = namespace
s.table = prefix
s.database = database
s.table = table
// initialise the database
return s.initDB()