sorarebuddy/db/repository.go

36 lines
704 B
Go
Raw Permalink Normal View History

2024-05-23 04:18:54 +00:00
package db
import (
"context"
"fmt"
"strings"
"github.com/uptrace/bun"
)
type Repository[T any] struct {
db *bun.DB
pkFieldList []string
}
func NewRepository[T any](db *bun.DB, pkFieldList []string) *Repository[T] {
return &Repository[T]{db: db, pkFieldList: pkFieldList}
}
func (r *Repository[T]) CreateOrUpdateMany(ctx context.Context, list []T) error {
if len(list) == 0 {
return nil
}
_, err := r.db.NewInsert().Model(&list).
On(fmt.Sprintf("CONFLICT (%s) DO UPDATE", strings.Join(r.pkFieldList, ","))).
Exec(ctx)
return err
}
func (r *Repository[T]) GetAll(ctx context.Context) ([]T, error) {
var list []T
err := r.db.NewSelect().Model(&list).Scan(ctx)
return list, err
}