Files
online-backend/pkg/repository/genericrepo/repository.go
2026-07-15 18:08:19 +05:00

98 lines
2.7 KiB
Go

// Package genericrepo factors out the List/GetByID/Delete/pagination
// pattern that was previously copy-pasted across every CRUD module's
// db/postgresql.go. Create and Update stay hand-written per module since
// their column lists and DTO mapping genuinely differ per entity.
package genericrepo
import (
"context"
"errors"
"fmt"
"online-back/pkg/client/postgresql"
"github.com/jackc/pgx/v4"
)
// Scanner is satisfied by both pgx.Row and pgx.Rows.
type Scanner interface {
Scan(dest ...interface{}) error
}
type Repository[T any] struct {
client postgresql.Client
table string
columns string
scan func(Scanner) (T, error)
}
func New[T any](client postgresql.Client, table, columns string, scan func(Scanner) (T, error)) *Repository[T] {
return &Repository[T]{client: client, table: table, columns: columns, scan: scan}
}
func (r *Repository[T]) GetByID(ctx context.Context, id int64) (T, error) {
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1`, id)
item, err := r.scan(row)
if errors.Is(err, pgx.ErrNoRows) {
var zero T
return zero, err
}
return item, err
}
func (r *Repository[T]) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM `+r.table+` WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
// List runs a paginated query. where must be empty or start with " WHERE "
// (see province's buildListQuery for the convention); args are the
// positional parameters referenced by where, in order. orderBy is the raw
// ORDER BY clause body (e.g. "id" or "id DESC"); pass "" to default to "id".
func (r *Repository[T]) List(ctx context.Context, where string, args []interface{}, page, limit int, orderBy string) ([]T, int64, error) {
if orderBy == "" {
orderBy = "id"
}
var count int64
countQuery := `SELECT COUNT(*) FROM ` + r.table + where
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
return nil, 0, err
}
offset := (page - 1) * limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
listQuery := fmt.Sprintf(
`SELECT %s FROM %s%s ORDER BY %s LIMIT $%d OFFSET $%d`,
r.columns, r.table, where, orderBy, limitPlaceholder, offsetPlaceholder,
)
listArgs := append(append([]interface{}{}, args...), limit, offset)
rows, err := r.client.Query(ctx, listQuery, listArgs...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var items []T
for rows.Next() {
item, err := r.scan(rows)
if err != nil {
return nil, 0, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return nil, 0, err
}
return items, count, nil
}