36 lines
704 B
Go
36 lines
704 B
Go
|
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
|
||
|
}
|