package main import ( "context" "fmt" "git.agecem.com/bottin/presences/queries" "github.com/jackc/pgx/v5/pgxpool" ) type DBClient struct { Pool *pgxpool.Pool } func nilDBErrorf(failedAction string) error { return fmt.Errorf("db: cannot %s using nil connection pool", failedAction) } func (d DBClient) Init(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() default: if d.Pool == nil { return nilDBErrorf("init") } if _, err := d.Pool.Exec(ctx, queries.SQLSchema()); err != nil { return err } return nil } } func (d DBClient) CreatePresence(ctx context.Context, membreID string) error { select { case <-ctx.Done(): return ctx.Err() default: if d.Pool == nil { return nilDBErrorf("check health") } // CreatePresence commandTag, err := d.Pool.Exec(ctx, ` INSERT INTO "presences" (id) VALUES ($1); `, membreID) if err != nil { if err.Error() == `ERROR: duplicate key value violates unique constraint "presences_pkey" (SQLSTATE 23505)` { return fmt.Errorf("Membre '%s' a déjà été enregistré·e", membreID) } return err } if commandTag.RowsAffected() == 0 { return fmt.Errorf("No rows inserted") } return nil } } func (d DBClient) CountPresences(ctx context.Context) (presencesAmount int, err error) { select { case <-ctx.Done(): err = ctx.Err() return default: if d.Pool == nil { return 0, nilDBErrorf("count presences") } if err := d.Pool.QueryRow(ctx, ` SELECT COUNT(presences.id) FROM presences; `).Scan(&presencesAmount); err != nil { return 0, err } return } }