package db import ( "context" "errors" "fmt" "strings" "online-back/internal/admin/role" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "github.com/jackc/pgx/v4" ) type repository struct { client postgresql.Client logger *logging.Logger } func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository { return &repository{client: client, logger: logger} } const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at` const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at` func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) { fromClause, whereClause, args := buildListQuery(filter) var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil { return role.ListRoleDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 listQuery := fmt.Sprintf( `SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`, roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...) if err != nil { return role.ListRoleDTO{}, err } defer rows.Close() var items []role.RoleDTO for rows.Next() { item, err := scanRole(rows) if err != nil { return role.ListRoleDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return role.ListRoleDTO{}, err } return role.ListRoleDTO{Count: count, Roles: items}, nil } func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) { fromClause = ` FROM roles r` var conditions []string if filter.RoleName != "" { args = append(args, likePattern(filter.RoleName)) n := len(args) conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n)) } if len(conditions) == 0 { return fromClause, "", args } return fromClause, " WHERE " + strings.Join(conditions, " AND "), args } func likePattern(term string) string { term = strings.ReplaceAll(term, `\`, `\\`) term = strings.ReplaceAll(term, `%`, `\%`) term = strings.ReplaceAll(term, `_`, `\_`) return "%" + term + "%" } func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) { query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns) item, err := scanRole(r.client.QueryRow(ctx, query, id)) if errors.Is(err, pgx.ErrNoRows) { return role.RoleDTO{}, err } return item, err } func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) { query := fmt.Sprintf(` INSERT INTO roles (code, name, guard_name) VALUES ($1, $2, $3) RETURNING %s`, roleReturningColumns) return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName)) } func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) { query := fmt.Sprintf(` UPDATE roles SET code = $1, name = $2, guard_name = $3, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $4 RETURNING %s`, roleReturningColumns) item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id)) if errors.Is(err, pgx.ErrNoRows) { return role.RoleDTO{}, err } return item, err } func (r *repository) Delete(ctx context.Context, id int64) error { tag, err := r.client.Exec(ctx, `DELETE FROM roles WHERE id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return pgx.ErrNoRows } return nil } type scannable interface { Scan(dest ...interface{}) error } func scanRole(row scannable) (role.RoleDTO, error) { var item role.RoleDTO if err := row.Scan( &item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt, ); err != nil { return role.RoleDTO{}, err } return item, nil }