2020-10-16 22:26:47 +02:00
|
|
|
package sqlstore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"log"
|
2020-10-20 20:00:46 +02:00
|
|
|
|
|
|
|
sq "github.com/Masterminds/squirrel"
|
2020-10-16 22:26:47 +02:00
|
|
|
)
|
|
|
|
|
2020-10-22 15:22:36 +02:00
|
|
|
// SQLStore is a SQL database.
|
2020-10-16 22:26:47 +02:00
|
|
|
type SQLStore struct {
|
|
|
|
db *sql.DB
|
|
|
|
dbType string
|
|
|
|
}
|
|
|
|
|
2020-10-22 15:22:36 +02:00
|
|
|
// New creates a new SQL implementation of the store.
|
2020-10-16 22:26:47 +02:00
|
|
|
func New(dbType, connectionString string) (*SQLStore, error) {
|
|
|
|
log.Println("connectDatabase")
|
|
|
|
var err error
|
|
|
|
|
|
|
|
db, err := sql.Open(dbType, connectionString)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("connectDatabase: ", err)
|
2020-10-22 15:22:36 +02:00
|
|
|
|
2020-10-16 22:26:47 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = db.Ping()
|
|
|
|
if err != nil {
|
2020-10-22 17:41:47 +02:00
|
|
|
log.Printf(`Database Ping failed: %v`, err)
|
2020-10-22 15:22:36 +02:00
|
|
|
|
2020-10-16 22:26:47 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
store := &SQLStore{
|
|
|
|
db: db,
|
|
|
|
dbType: dbType,
|
|
|
|
}
|
|
|
|
|
|
|
|
err = store.Migrate()
|
|
|
|
if err != nil {
|
2020-10-22 17:41:47 +02:00
|
|
|
log.Printf(`Table creation / migration failed: %v`, err)
|
2020-10-22 15:22:36 +02:00
|
|
|
|
2020-10-16 22:26:47 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2020-10-22 15:22:36 +02:00
|
|
|
|
2020-12-10 22:41:06 +02:00
|
|
|
err = store.InitializeTemplates()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf(`InitializeTemplates failed: %v`, err)
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-10-16 22:26:47 +02:00
|
|
|
return store, nil
|
|
|
|
}
|
|
|
|
|
2020-10-22 15:22:36 +02:00
|
|
|
// Shutdown close the connection with the store.
|
2020-10-16 22:26:47 +02:00
|
|
|
func (s *SQLStore) Shutdown() error {
|
|
|
|
return s.db.Close()
|
|
|
|
}
|
2020-10-20 20:00:46 +02:00
|
|
|
|
|
|
|
func (s *SQLStore) getQueryBuilder() sq.StatementBuilderType {
|
|
|
|
builder := sq.StatementBuilder.PlaceholderFormat(sq.Dollar)
|
2020-10-22 15:22:36 +02:00
|
|
|
|
2020-10-20 20:00:46 +02:00
|
|
|
return builder.RunWith(s.db)
|
|
|
|
}
|