focalboard/server/services/store/sqlstore/sqlstore.go

90 lines
1.7 KiB
Go
Raw Normal View History

package sqlstore
import (
"database/sql"
"log"
2020-10-20 20:00:46 +02:00
sq "github.com/Masterminds/squirrel"
)
const (
mysqlDBType = "mysql"
sqliteDBType = "sqlite3"
postgresDBType = "postgres"
)
// SQLStore is a SQL database.
type SQLStore struct {
2021-04-17 09:06:57 +02:00
db *sql.DB
dbType string
tablePrefix string
connectionString string
}
// New creates a new SQL implementation of the store.
2021-04-17 09:06:57 +02:00
func New(dbType, connectionString string, tablePrefix string) (*SQLStore, error) {
log.Println("connectDatabase", dbType, connectionString)
var err error
db, err := sql.Open(dbType, connectionString)
if err != nil {
2021-04-17 09:06:57 +02:00
log.Print("connectDatabase: ", err)
return nil, err
}
err = db.Ping()
if err != nil {
2020-10-22 17:41:47 +02:00
log.Printf(`Database Ping failed: %v`, err)
return nil, err
}
store := &SQLStore{
db: db,
dbType: dbType,
tablePrefix: tablePrefix,
connectionString: connectionString,
}
err = store.Migrate()
if err != nil {
2020-10-22 17:41:47 +02:00
log.Printf(`Table creation / migration failed: %v`, err)
return nil, err
}
err = store.InitializeTemplates()
if err != nil {
log.Printf(`InitializeTemplates failed: %v`, err)
return nil, err
}
return store, nil
}
// Shutdown close the connection with the store.
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
if s.dbType == postgresDBType || s.dbType == sqliteDBType {
builder = builder.PlaceholderFormat(sq.Dollar)
}
2020-10-20 20:00:46 +02:00
return builder.RunWith(s.db)
}
func (s *SQLStore) escapeField(fieldName string) string {
if s.dbType == mysqlDBType {
return "`" + fieldName + "`"
}
if s.dbType == postgresDBType || s.dbType == sqliteDBType {
return "\"" + fieldName + "\""
}
return fieldName
}