agendas/db.go

115 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-12-30 15:00:42 -05:00
package main
import (
"context"
"fmt"
2024-12-30 19:13:05 -05:00
"log"
2024-12-30 15:00:42 -05:00
2024-12-30 19:13:05 -05:00
"git.agecem.com/bottin/agendas/queries"
2024-12-30 15:00:42 -05:00
"github.com/jackc/pgx/v5/pgxpool"
)
type DBClient struct {
Pool *pgxpool.Pool
}
func (d DBClient) Ping(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
if d.Pool == nil {
return fmt.Errorf("db: cannot check health using nil connection pool")
}
return d.Pool.Ping(ctx)
}
}
func (d DBClient) Init(ctx context.Context) error {
//TODO check context is not closed
//TODO check *DB is not nil
2024-12-30 19:13:05 -05:00
log.Println("warning: DBClient [Init] not properly checked")
// Init
if _, err := d.Pool.Exec(ctx, queries.SQLSchema()); err != nil {
return err
}
return nil
2024-12-30 15:00:42 -05:00
}
func (d DBClient) CreateTransaction(ctx context.Context, transaction Transaction) error {
2024-12-30 19:38:01 -05:00
select {
case <-ctx.Done():
return ctx.Err()
default:
if d.Pool == nil {
return fmt.Errorf("db: cannot check health using nil connection pool")
}
// CreateTransaction
commandTag, err := d.Pool.Exec(ctx, `
INSERT INTO "transactions" (
membre_id,
is_perpetual
)
VALUES (
$1,
$2
);
`, transaction.MembreID, transaction.IsPerpetual)
if err != nil {
2024-12-30 19:44:56 -05:00
if err.Error() == `ERROR: duplicate key value violates unique constraint "transactions_pkey" (SQLSTATE 23505)` {
return fmt.Errorf("Membre '%s' a déjà reçu son agenda %s.",
transaction.MembreID,
func() string {
if transaction.IsPerpetual {
return "perpétuel"
} else {
return "non-perpétuel"
}
}(),
)
}
2024-12-30 19:38:01 -05:00
return err
}
if commandTag.RowsAffected() == 0 {
return fmt.Errorf("No rows inserted")
}
return nil
}
2024-12-30 15:00:42 -05:00
}
2024-12-30 19:38:01 -05:00
func (d DBClient) ReadTransaction(ctx context.Context, membreID string, isPerpetual bool) (Transaction, error) {
select {
case <-ctx.Done():
return Transaction{}, ctx.Err()
default:
if d.Pool == nil {
return Transaction{}, fmt.Errorf("db: cannot check health using nil connection pool")
}
//TODO ReadTransaction
return Transaction{}, fmt.Errorf("db: ReadTransaction not implemented")
}
2024-12-30 15:00:42 -05:00
}
func (d DBClient) CountTransactions(ctx context.Context) (membresSansAgenda, membresAvecPerpetuel, membresAvecNonPerpetuel, membresAvecTout int, err error) {
2024-12-30 19:38:01 -05:00
select {
case <-ctx.Done():
err = ctx.Err()
return
default:
if d.Pool == nil {
err = fmt.Errorf("db: cannot check health using nil connection pool")
return
}
//TODO CountTransactions
err = fmt.Errorf("db: CountTransactions not implemented")
return
}
2024-12-30 15:00:42 -05:00
}