Certainly! Here's an optimized version of your repository code with improvements on:
- Removing redundant error checks and improving parameter validation.
- Simplifying strings.Builder usage.
- Minor style improvements (consistent error messages, comments).
- Reduce unnecessary variable creation.
- Improved code readability and performance.
package repository
import (
"context"
"database/sql"
"errors"
"fmt"
v1 "template-plus/api/v1"
"template-plus/internal/model"
"template-plus/pkg/sid"
"github.com/spf13/viper"
)
// DictTypeRepository defines methods for CRUD operations on DictType entities.
type DictTypeRepository interface {
InsertDictType(ctx context.Context, dictType *model.DictType) (sql.Result, error)
UpdateDictType(ctx context.Context, dictType *model.DictType) (sql.Result, error)
DeleteDictType(ctx context.Context, id int64) (sql.Result, error)
GetDictTypeByID(ctx context.Context, id int64) (*model.DictType, error)
SelectDictTypesPage(ctx context.Context, pageInfo *v1.DictTypePageInfo) ([]model.DictType, int64, error)
SelectDictTypesWithDatas(ctx context.Context) ([]model.DictType, error)
}
type dictTypeRepository struct {
generic GenericRepository[model.DictType]
}
// NewDictTypeRepository creates a new DictTypeRepository instance.
func NewDictTypeRepository(r *Repository, v *viper.Viper, s *sid.Sid) DictTypeRepository {
return &dictTypeRepository{generic: NewGenericRepository[model.DictType](r, v, s)}
}
const (
sqlInsertDictType = `INSERT INTO sys_dict_type (
id, type, name, description, created_at, created_by, updated_at, updated_by
) VALUES (
:id, :type, :name, :description, :created_at, :created_by, :updated_at, :updated_by
)`
sqlUpdateDictType = `UPDATE sys_dict_type SET
type = :type,
name = :name,
description = :description,
updated_at = :updated_at,
updated_by = :updated_by
WHERE id = :id`
sqlDeleteDictType = `DELETE FROM sys_dict_type WHERE id = $1`
sqlGetDictTypeByID = `SELECT id, type, name, description FROM sys_dict_type WHERE id = $1`
sqlCountDictType = `SELECT COUNT(*) FROM sys_dict_type`
sqlSelectDictTypePage = `SELECT
dt.id, dt.type, dt.name, dt.description, dt.created_at,
COALESCE(creator.username, 'Unknown') AS creator,
dt.updated_at, COALESCE(updater.username, 'Unknown') AS updater
FROM sys_dict_type dt
LEFT JOIN sys_user creator ON dt.created_by = creator.id
LEFT JOIN sys_user updater ON dt.updated_by = updater.id`
sqlSelectDictTypesWithDatas = `SELECT
dt.type,
dd.label AS dd_label,
dd.value AS dd_value
FROM sys_dict_type dt
LEFT JOIN sys_dict_data dd ON dt.id = dd.type_id`
)
// DeleteDictType deletes dict type by id.
func (d *dictTypeRepository) DeleteDictType(ctx context.Context, id int64) (sql.Result, error) {
if id <= 0 {
return nil, errors.New("invalid dict_type id")
}
return d.generic.Delete(ctx, sqlDeleteDictType, id)
}
// GetDictTypeByID retrieves dict type by id.
func (d *dictTypeRepository) GetDictTypeByID(ctx context.Context, id int64) (*model.DictType, error) {
if id <= 0 {
return nil, errors.New("invalid dict_type id")
}
return d.generic.Get(ctx, sqlGetDictTypeByID, id)
}
// InsertDictType inserts a new dict type.
func (d *dictTypeRepository) InsertDictType(ctx context.Context, dictType *model.DictType) (sql.Result, error) {
if dictType == nil {
return nil, errors.New("dictType cannot be nil")
}
return d.generic.Insert(ctx, sqlInsertDictType, dictType)
}
// UpdateDictType updates an existing dict type.
func (d *dictTypeRepository) UpdateDictType(ctx context.Context, dictType *model.DictType) (sql.Result, error) {
if dictType == nil {
return nil, errors.New("dictType cannot be nil")
}
return d.generic.Update(ctx, sqlUpdateDictType, dictType)
}
// SelectDictTypesPage returns paginated dict types with sorting.
func (d *dictTypeRepository) SelectDictTypesPage(ctx context.Context, pageInfo *v1.DictTypePageInfo) ([]model.DictType, int64, error) {
if pageInfo == nil {
return nil, 0, errors.New("pageInfo cannot be nil")
}
order := "DESC"
if pageInfo.Asc {
order = "ASC"
}
// Validate sort column to prevent SQL injection (optional but recommended)
validSortColumns := map[string]struct{}{
"id": {}, "type": {}, "name": {}, "created_at": {}, "updated_at": {},
}
if _, ok := validSortColumns[pageInfo.Sort]; !ok {
pageInfo.Sort = "id"
}
// Count total records once
total, err := d.generic.Count(ctx, sqlCountDictType)
if err != nil {
return nil, 0, fmt.Errorf("count dict types: %w", err)
}
// Compose query with order, limit, offset
query := fmt.Sprintf("%s ORDER BY %s %s LIMIT :size OFFSET :offset", sqlSelectDictTypePage, pageInfo.Sort, order)
params := map[string]interface{}{
"size": pageInfo.Size,
"offset": pageInfo.Offset,
}
dictTypes, err := d.generic.SelectNamed(ctx, query, params)
if err != nil {
return nil, 0, fmt.Errorf("select dict types page: %w", err)
}
return dictTypes, total, nil
}
// SelectDictTypesWithDatas retrieves dict types including their dict datas.
func (d *dictTypeRepository) SelectDictTypesWithDatas(ctx context.Context) ([]model.DictType, error) {
type rowStruct struct {
Type string `db:"type"`
Label string `db:"dd_label"`
Value string `db:"dd_value"`
}
var rows []rowStruct
db := d.generic.GetDB(ctx)
if err := db.Select(&rows, sqlSelectDictTypesWithDatas); err != nil {
return nil, err
}
dictTypeMap := make(map[string]*model.DictType, len(rows))
for _, r := range rows {
dt, exists := dictTypeMap[r.Type]
if !exists {
dt = &model.DictType{Type: r.Type, DictDatas: make([]model.DictData, 0, 4)}
dictTypeMap[r.Type] = dt
}
if r.Label != "" {
dt.DictDatas = append(dt.DictDatas, model.DictData{Label: r.Label, Value: r.Value})
}
}
result := make([]model.DictType, 0, len(dictTypeMap))
for _, dt := range dictTypeMap {
result = append(result, *dt)
}
return result, nil
}
Summary of changes:
- Grouped SQL constants with shorter variable names (conventionally all lowercase with
sql prefix).
- Added a small validation for the sort column in pagination to prevent SQL injection.
- Removed redundant string builders when simple
fmt.Sprintf is cleaner.
- In
SelectDictTypesWithDatas, used a capacity hint for slice allocation inside the map.
- Minor fixes in parameter naming (
dictType instead of dict_type) to keep consistent Go-style.
- Wrapping errors in
SelectDictTypesPage to improve debugging.
This keeps your repository clean, concise and safe. Let me know if you'd also want improvements/additions for unit tests or interface mocks!