78 lines
2.4 KiB
Go
78 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
|
|
"online-back/internal/identity/userbranch"
|
|
"online-back/pkg/client/postgresql"
|
|
"online-back/pkg/logging"
|
|
"online-back/pkg/repository/genericrepo"
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
)
|
|
|
|
type repository struct {
|
|
client postgresql.Client
|
|
logger *logging.Logger
|
|
}
|
|
|
|
func NewRepository(client postgresql.Client, logger *logging.Logger) userbranch.Repository {
|
|
return &repository{client: client, logger: logger}
|
|
}
|
|
|
|
func (r *repository) Create(ctx context.Context, dto userbranch.CreateUserBranchDTO) (userbranch.UserBranchDTO, error) {
|
|
// users <-> branches is many-to-many: a user keeps every other branch
|
|
// assignment they already have, this only adds (or, if already assigned,
|
|
// idempotently touches) the one pair given here.
|
|
query := `
|
|
WITH upserted AS (
|
|
INSERT INTO branch_user (branch_id, user_id)
|
|
VALUES ($1, $2)
|
|
ON CONFLICT (branch_id, user_id) WHERE deleted_at IS NULL
|
|
DO UPDATE SET updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
RETURNING id, branch_id, user_id, created_at, updated_at
|
|
)
|
|
SELECT upserted.id, upserted.branch_id, b.name, upserted.user_id, u.name, upserted.created_at, upserted.updated_at
|
|
FROM upserted
|
|
JOIN branches b ON b.id = upserted.branch_id
|
|
JOIN users u ON u.id = upserted.user_id`
|
|
|
|
row := r.client.QueryRow(ctx, query, dto.BranchId, dto.UserId)
|
|
return scanUserBranch(row)
|
|
}
|
|
|
|
func (r *repository) GetByID(ctx context.Context, id int64) (userbranch.UserBranchDTO, error) {
|
|
query := `
|
|
SELECT bu.id, bu.branch_id, b.name, bu.user_id, u.name, bu.created_at, bu.updated_at
|
|
FROM branch_user bu
|
|
JOIN branches b ON b.id = bu.branch_id
|
|
JOIN users u ON u.id = bu.user_id
|
|
WHERE bu.id = $1 AND bu.deleted_at IS NULL`
|
|
return scanUserBranch(r.client.QueryRow(ctx, query, id))
|
|
}
|
|
|
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
return genericrepo.Delete(ctx, r.client, "branch_user", id)
|
|
}
|
|
|
|
func scanUserBranch(row genericrepo.Scanner) (userbranch.UserBranchDTO, error) {
|
|
var item userbranch.UserBranchDTO
|
|
var branchNameJSON []byte
|
|
|
|
err := row.Scan(
|
|
&item.Id, &item.BranchId, &branchNameJSON, &item.UserId, &item.UserName, &item.CreatedAt, &item.UpdatedAt,
|
|
)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return userbranch.UserBranchDTO{}, err
|
|
}
|
|
if err != nil {
|
|
return userbranch.UserBranchDTO{}, err
|
|
}
|
|
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
|
|
return userbranch.UserBranchDTO{}, err
|
|
}
|
|
return item, nil
|
|
}
|