117 lines
3.5 KiB
Go
117 lines
3.5 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 AND deleted_at IS NULL`, 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 {
|
|
return Delete(ctx, r.client, r.table, id)
|
|
}
|
|
|
|
// Delete runs the soft-delete-by-id pattern shared by every module that
|
|
// doesn't need the full Repository[T] (e.g. association tables, or entities
|
|
// whose List/GetByID require joins genericrepo doesn't model). Rows are never
|
|
// hard-deleted so foreign keys pointing at them never break, and deletes are
|
|
// recoverable.
|
|
func Delete(ctx context.Context, client postgresql.Client, table string, id int64) error {
|
|
tag, err := client.Exec(ctx, `UPDATE `+table+` SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return pgx.ErrNoRows
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// withDeletedAtFilter folds a mandatory "deleted_at IS NULL" condition into a
|
|
// caller-supplied where clause (empty or starting with " WHERE ", see List).
|
|
func withDeletedAtFilter(where string) string {
|
|
if where == "" {
|
|
return " WHERE deleted_at IS NULL"
|
|
}
|
|
return where + " AND deleted_at IS NULL"
|
|
}
|
|
|
|
// 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"
|
|
}
|
|
where = withDeletedAtFilter(where)
|
|
|
|
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
|
|
}
|