fixed db issues

This commit is contained in:
2026-02-05 20:07:37 +11:00
parent 4c31c24069
commit 697bef80e9
9 changed files with 140 additions and 61 deletions

View File

@@ -1,6 +1,10 @@
package db
import "github.com/uptrace/bun"
import (
"strings"
"github.com/uptrace/bun"
)
type PageOpts struct {
Page int
@@ -15,7 +19,7 @@ type OrderOpts struct {
Label string
}
func setDefaultPageOpts(p *PageOpts, page, perpage int, order bun.Order, orderby string) *PageOpts {
func setPageOpts(q *bun.SelectQuery, p *PageOpts, page, perpage int, order bun.Order, orderby string) (*bun.SelectQuery, *PageOpts) {
if p == nil {
p = new(PageOpts)
}
@@ -31,7 +35,46 @@ func setDefaultPageOpts(p *PageOpts, page, perpage int, order bun.Order, orderby
if p.OrderBy == "" {
p.OrderBy = orderby
}
return p
p.OrderBy = sanitiseOrderBy(p.OrderBy)
q = q.OrderBy(p.OrderBy, p.Order).
Limit(p.PerPage).
Offset(p.PerPage * (p.Page - 1))
return q, p
}
func sanitiseOrderBy(orderby string) string {
result := strings.ToLower(orderby)
var builder strings.Builder
for _, r := range result {
if isValidChar(r) {
builder.WriteRune(r)
}
}
sanitized := builder.String()
if sanitized == "" {
return "_"
}
if !isValidFirstChar(rune(sanitized[0])) {
sanitized = "_" + sanitized
}
if len(sanitized) > 63 {
sanitized = sanitized[:63]
}
return sanitized
}
func isValidChar(r rune) bool {
return (r >= 'a' && r <= 'z') ||
(r >= '0' && r <= '9') ||
r == '_'
}
func isValidFirstChar(r rune) bool {
return (r >= 'a' && r <= 'z') || r == '_'
}
// TotalPages calculates the total number of pages