This commit is contained in:
dpurbosakti
2025-10-08 13:25:04 +07:00
parent bd7ff974b1
commit a8c79238d5
9 changed files with 68 additions and 1 deletions
+55
View File
@@ -3,6 +3,8 @@ package libhelper
import (
"fmt"
pl "simrs-vx/pkg/logger"
"strings"
"unicode"
"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
@@ -16,6 +18,59 @@ func SearchCodeOrName(search string, tx *gorm.DB) *gorm.DB {
return tx
}
func Sort(sort string, tx *gorm.DB) *gorm.DB {
if sort == "" {
return tx
}
pairs := strings.Split(sort, ",")
for _, pair := range pairs {
parts := strings.Split(strings.TrimSpace(pair), "=")
if len(parts) != 2 {
continue // skip invalid format
}
field := strings.TrimSpace(parts[0])
direction := strings.ToUpper(strings.TrimSpace(parts[1]))
if direction != "ASC" && direction != "DESC" {
continue
}
field = normalizeColumnName(field)
tx = tx.Order(fmt.Sprintf("\"%s\" %s", field, direction))
}
return tx
}
func normalizeColumnName(input string) string {
if input == "" {
return input
}
input = strings.ReplaceAll(input, "-", "_")
runes := []rune(input)
var out []rune
upperNext := true
for _, r := range runes {
if r == '_' {
out = append(out, r)
upperNext = true
continue
}
if upperNext {
out = append(out, unicode.ToUpper(r))
upperNext = false
} else {
out = append(out, r)
}
}
return string(out)
}
func HandleCreateError(input any, event *pl.Event, err error) error {
e, ok := err.(*pgconn.PgError)
if !ok {