46 lines
864 B
Go
46 lines
864 B
Go
// Package dbclient provides the database client used by the API server
|
|
package dbclient
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.agecem.com/agecem/bottin-ag/dbschema"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// DBClient holds a *sqlx.DB and implements methods to manipulate the database
|
|
type DBClient struct {
|
|
DB *sqlx.DB
|
|
}
|
|
|
|
func New(host, database, user, password string, port int, useSSL bool) (*DBClient, error) {
|
|
var SSLMode string
|
|
|
|
switch useSSL {
|
|
case true:
|
|
SSLMode = "enable"
|
|
case false:
|
|
SSLMode = "disable"
|
|
}
|
|
|
|
connectionString := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s",
|
|
user,
|
|
password,
|
|
host,
|
|
port,
|
|
database,
|
|
SSLMode,
|
|
)
|
|
|
|
db, err := sqlx.Connect("pgx", connectionString)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &DBClient{DB: db}, nil
|
|
}
|
|
|
|
func (d *DBClient) CreateTablesIfNotExist() error {
|
|
_, err := d.DB.Exec(dbschema.Schema)
|
|
return err
|
|
}
|