2023-09-15 17:10:57 -04:00
|
|
|
// Package dbclient provides the database client used by the API server
|
|
|
|
package dbclient
|
2023-09-16 16:28:18 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2023-09-16 17:13:51 -04:00
|
|
|
"git.agecem.com/agecem/bottin-ag/dbschema"
|
2023-09-16 23:06:24 -04:00
|
|
|
"git.agecem.com/agecem/bottin-ag/dbstruct"
|
2023-09-16 16:28:18 -04:00
|
|
|
"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
|
|
|
|
}
|
2023-09-16 17:13:51 -04:00
|
|
|
|
|
|
|
func (d *DBClient) CreateTablesIfNotExist() error {
|
|
|
|
_, err := d.DB.Exec(dbschema.Schema)
|
|
|
|
return err
|
|
|
|
}
|
2023-09-16 23:06:24 -04:00
|
|
|
|
|
|
|
/*
|
|
|
|
InsertPresence inserts a dbstruct.Presence into the database, returning the
|
|
|
|
values of the inserted presence and any error that occured.
|
|
|
|
*/
|
|
|
|
func (d *DBClient) InsertPresence(presence dbstruct.Presence) (dbstruct.Presence, error) {
|
|
|
|
var insertedPresence dbstruct.Presence
|
|
|
|
var rows *sqlx.Rows
|
|
|
|
|
|
|
|
rows, err := d.DB.NamedQuery(`
|
|
|
|
INSERT INTO presences (id, at, name, programme_id)
|
|
|
|
VALUES (:id, current_timestamp, :name, :programme_id)
|
|
|
|
RETURNING id, at, name, programme_id
|
|
|
|
`, presence)
|
|
|
|
if err != nil {
|
|
|
|
return insertedPresence, err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
if err := rows.Scan(&insertedPresence.ID, &insertedPresence.At, &insertedPresence.Name, &insertedPresence.ProgrammeID); err != nil {
|
|
|
|
return insertedPresence, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return insertedPresence, nil
|
|
|
|
}
|