Merge pull request #1046 from micro/storefix

Fix cockroachdb store implementation
This commit is contained in:
Asim Aslam 2019-12-16 17:24:53 +00:00 committed by GitHub
commit 1c8d15fe4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -32,13 +32,9 @@ type sqlStore struct {
// List all the known records // List all the known records
func (s *sqlStore) List() ([]*store.Record, error) { func (s *sqlStore) List() ([]*store.Record, error) {
q, err := s.db.Prepare(fmt.Sprintf("SELECT key, value, expiry FROM %s.%s;", s.database, s.table)) rows, err := s.db.Query(fmt.Sprintf("SELECT key, value, expiry FROM %s.%s;", s.database, s.table))
if err != nil {
return nil, err
}
var records []*store.Record var records []*store.Record
var timehelper pq.NullTime var timehelper pq.NullTime
rows, err := q.Query()
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return records, nil return records, nil
@ -152,30 +148,25 @@ func (s *sqlStore) Delete(keys ...string) error {
} }
func (s *sqlStore) initDB() { func (s *sqlStore) initDB() {
// Create "micro" schema // Create the namespace's database
schema, err := s.db.Prepare(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s ;", s.database)) _, err := s.db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s ;", s.database))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
_, err = schema.Exec() _, err = s.db.Exec(fmt.Sprintf("SET DATABASE = %s ;", s.database))
if err != nil { if err != nil {
log.Fatal(errors.Wrap(err, "Couldn't create database")) log.Fatal(errors.Wrap(err, "Couldn't set database"))
} }
// Create a table for the Store namespace // Create a table for the namespace's prefix
tableq, err := s.db.Prepare(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s.%s _, err = s.db.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s
( (
key text COLLATE "default" NOT NULL, key text NOT NULL,
value bytea, value bytea,
expiry timestamp with time zone, expiry timestamp with time zone,
CONSTRAINT %s_pkey PRIMARY KEY (key) CONSTRAINT %s_pkey PRIMARY KEY (key)
);`, s.database, s.table, s.table)) );`, s.table, s.table))
if err != nil {
log.Fatal(errors.Wrap(err, "SQL statement preparation failed"))
}
_, err = tableq.Exec()
if err != nil { if err != nil {
log.Fatal(errors.Wrap(err, "Couldn't create table")) log.Fatal(errors.Wrap(err, "Couldn't create table"))
} }
@ -228,6 +219,6 @@ func New(opts ...store.Option) store.Store {
database: namespace, database: namespace,
table: prefix, table: prefix,
} }
s.initDB()
return s return s
} }