Your code is generally well-structured, but there's some room for improvements in error handling, SQL composition, and code clarity. Below are suggestions and an optimized version of your repository code:
Main improvements
- Use consistent parameter placeholders (Postgres uses
$1, $2, ... instead of :named in some parts—choose one style for readability and consistency).
- Avoid building SQL queries with string concatenation. Use query builders or conditionally build parts but keep final queries simple and safe.
- DRY counting queries for pagination — put common count query in one place and reuse.
- Simplify SQL and Go interaction —
SelectAssignedButtonsByRoleIDs uses IN (?), but IN with variable length params needs dynamic query or query builder (or use pgx with sqlx helper). Implement to safely handle multiple role IDs.
- Improve parameter checking and error messages.
- Fix the
SelectButtonsByRoleID logic where you check roleID <0, consider <=0.
- Fix SQL in
SelectButtonsByRoleID so that you don’t append WHERE to an SQL that ends with LEFT JOIN, or construct full query correctly.
- Possibly, cache frequently used SQL and avoid re-building strings repeatedly.
- Add
context in generic calls where missing.
Optimized code
package repository
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"github.com/jmoiron/sqlx"
"github.com/spf13/viper"
v1 "template-plus/api/v1"
"template-plus/internal/model"
"template-plus/pkg/sid"
)
// ButtonRepository defines button-specific database operations.
type ButtonRepository interface {
InsertButton(ctx context.Context, button *model.Button) (sql.Result, error)
UpdateButton(ctx context.Context, button *model.Button) (sql.Result, error)
DeleteButton(ctx context.Context, id int64) (sql.Result, error)
GetButtonByID(ctx context.Context, id int64) (*model.Button, error)
SelectButtonPage(ctx context.Context, pageInfo *v1.ButtonPageInfo) ([]model.Button, int64, error)
SelectAssignedButtonsByRoleIDs(ctx context.Context, roleIDs []int64) ([]model.Button, error)
SelectButtonsByRoleID(ctx context.Context, menuID, roleID int64) ([]model.Button, error)
}
// buttonRepository implements ButtonRepository.
type buttonRepository struct {
generic GenericRepository[model.Button]
}
func NewButtonRepository(r *Repository, v *viper.Viper, s *sid.Sid) ButtonRepository {
return &buttonRepository{generic: NewGenericRepository[model.Button](r, v, s)}
}
const (
insertButtonSQL = `
INSERT INTO sys_button (
id, menu_id, name, code, description,
created_at, created_by, updated_at, updated_by
) VALUES (
:id, :menu_id, :name, :code, :description,
:created_at, :created_by, :updated_at, :updated_by
)`
updateButtonSQL = `
UPDATE sys_button
SET
menu_id = :menu_id,
code = :code,
name = :name,
description = :description,
updated_at = :updated_at,
updated_by = :updated_by
WHERE id = :id`
deleteButtonSQL = `DELETE FROM sys_button WHERE id = $1`
getButtonByIDSQL = `
SELECT id, menu_id, code, name, description,
created_at,
COALESCE(created_by, 0) AS created_by,
updated_at,
COALESCE(updated_by, 0) AS updated_by
FROM sys_button
WHERE id = $1`
countButtonSQL = `SELECT COUNT(*) FROM sys_button`
selectButtonsPageSQLBase = `
SELECT b.id, b.menu_id, b.code, b.name, b.description,
b.created_at,
COALESCE(creator.username, 'Unknown') AS creator,
b.updated_at,
COALESCE(updater.username, 'Unknown') AS updater
FROM sys_button b
LEFT JOIN sys_user creator ON b.created_by = creator.id
LEFT JOIN sys_user updater ON b.updated_by = updater.id`
selectButtonByRolesIDSQLBase = `
SELECT sb.id, sb.code, sb.name,
COALESCE(sb.description, '') AS description,
CASE WHEN srbp.role_id IS NOT NULL THEN TRUE ELSE FALSE END AS checked
FROM sys_button sb
LEFT JOIN sys_role_button_permission srbp
ON srbp.button_id = sb.id
AND srbp.role_id = $1`
selectButtonsByRoleIDsSQL = `
SELECT sb.code
FROM sys_button sb
JOIN sys_role_button_permission srbp ON srbp.button_id = sb.id
WHERE srbp.role_id IN (?)`
)
// InsertButton inserts a new button.
func (br *buttonRepository) InsertButton(ctx context.Context, button *model.Button) (sql.Result, error) {
if button == nil {
return nil, errors.New("button cannot be nil")
}
return br.generic.Insert(ctx, insertButtonSQL, button)
}
// UpdateButton updates an existing button.
func (br *buttonRepository) UpdateButton(ctx context.Context, button *model.Button) (sql.Result, error) {
if button == nil {
return nil, errors.New("button cannot be nil")
}
return br.generic.Update(ctx, updateButtonSQL, button)
}
// DeleteButton deletes a button by ID.
func (br *buttonRepository) DeleteButton(ctx context.Context, id int64) (sql.Result, error) {
if id <= 0 {
return nil, errors.New("invalid button ID")
}
return br.generic.Delete(ctx, deleteButtonSQL, id)
}
// GetButtonByID retrieves a button by ID.
func (br *buttonRepository) GetButtonByID(ctx context.Context, id int64) (*model.Button, error) {
if id <= 0 {
return nil, errors.New("invalid button ID")
}
return br.generic.Get(ctx, getButtonByIDSQL, id)
}
// SelectButtonPage returns buttons paginated.
func (br *buttonRepository) SelectButtonPage(ctx context.Context, pageInfo *v1.ButtonPageInfo) ([]model.Button, int64, error) {
if pageInfo == nil {
return nil, 0, errors.New("pageInfo cannot be nil")
}
if pageInfo.Size <= 0 {
pageInfo.Size = 10
}
if pageInfo.Sort == "" {
pageInfo.Sort = "id"
}
order := "DESC"
if pageInfo.Asc {
order = "ASC"
}
var (
sqlBuilder strings.Builder
params = make(map[string]interface{})
total int64
err error
buttons []model.Button
)
sqlBuilder.WriteString(selectButtonsPageSQLBase)
// Add WHERE clause conditionally
if pageInfo.MenuID > 0 {
sqlBuilder.WriteString(" WHERE b.menu_id = :menu_id")
params["menu_id"] = pageInfo.MenuID
// Count with filter
countSQL := countButtonSQL + " WHERE menu_id = $1"
total, err = br.generic.Count(ctx, countSQL, pageInfo.MenuID)
if err != nil {
return nil, 0, fmt.Errorf("count buttons with menu_id: %w", err)
}
} else {
total, err = br.generic.Count(ctx, countButtonSQL)
if err != nil {
return nil, 0, fmt.Errorf("count buttons: %w", err)
}
}
// Add ORDER BY, LIMIT, OFFSET
// Make sure sort column is safe (prevent SQL injection)
allowedSortFields := map[string]bool{
"id": true, "menu_id": true, "code": true, "name": true, "created_at": true, "updated_at": true,
}
sortField := pageInfo.Sort
if !allowedSortFields[sortField] {
sortField = "id" // fallback
}
sqlBuilder.WriteString(fmt.Sprintf(" ORDER BY b.%s %s", sortField, order))
sqlBuilder.WriteString(" LIMIT :size OFFSET :offset")
params["size"] = pageInfo.Size
params["offset"] = pageInfo.Offset
buttons, err = br.generic.SelectNamed(ctx, sqlBuilder.String(), params)
if err != nil {
return nil, 0, fmt.Errorf("select buttons page: %w", err)
}
return buttons, total, nil
}
// SelectAssignedButtonsByRoleIDs returns buttons assigned to any of the given roleIDs.
//
// Uses dynamic SQL building with query args for IN clause.
func (br *buttonRepository) SelectAssignedButtonsByRoleIDs(ctx context.Context, roleIDs []int64) ([]model.Button, error) {
if len(roleIDs) == 0 {
return nil, errors.New("roleIDs cannot be empty")
}
// Build the IN clause placeholders.
placeholders := make([]string, len(roleIDs))
args := make([]interface{}, len(roleIDs))
for i, id := range roleIDs {
placeholders[i] = fmt.Sprintf("$%d", i+1) // $1, $2...
args[i] = id
}
query := fmt.Sprintf(`
SELECT sb.id, sb.menu_id, sb.code, sb.name, COALESCE(sb.description, '') AS description
FROM sys_button sb
JOIN sys_role_button_permission srbp ON srbp.button_id = sb.id
WHERE srbp.role_id IN (%s)
`, strings.Join(placeholders, ","))
var buttons []model.Button
err := br.generic.Select(ctx, query, &buttons, args...)
if err != nil {
return nil, fmt.Errorf("select assigned buttons by role IDs: %w", err)
}
return buttons, nil
}
// SelectButtonsByRoleID returns buttons assigned to a role, optionally filtered by menu.
func (br *buttonRepository) SelectButtonsByRoleID(ctx context.Context, menuID, roleID int64) ([]model.Button, error) {
if roleID <= 0 {
return nil, errors.New("invalid role ID")
}
var (
queryBuilder strings.Builder
args = []interface{}{roleID}
)
queryBuilder.WriteString(selectButtonByRolesIDSQLBase)
if menuID > 0 {
queryBuilder.WriteString(" AND sb.menu_id = $2")
args = append(args, menuID)
}
var buttons []model.Button
err := br.generic.Select(ctx, queryBuilder.String(), &buttons, args...)
if err != nil {
return nil, fmt.Errorf("select buttons by roleID: %w", err)
}
return buttons, nil
}
Summary of changes:
- Context passed in all generic calls.
- Used valid placeholders
$1, $2 consistently in SQL with positional args.
- Safe construction of
IN clause in SelectAssignedButtonsByRoleIDs with placeholders.
- Validation and fallback for sort fields in pagination.
- Combined WHERE clauses correctly (using
AND in SelectButtonsByRoleID).
- Moved SQL constants formatting and combined them into readable blocks.
- More explicit error wrapping.
- Added
nil checks for arguments where needed.
This version should be safer, cleaner, and easier to maintain. Consider adding unit tests covering edge cases, especially for SQL building and input validation.