This repository has been archived by the owner on Oct 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.go
141 lines (127 loc) · 4.08 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/georgysavva/scany/pgxscan"
)
type genericRequestParams struct {
tableName string
limitClamp int
columnMappings map[string]string
sortDefaultOrder string
sortDefaultColumn string
sortColumns []string
filterColumnsFull []string
filterColumnsStartsWith []string
searchColumn string
searchSimilarity float64
addWhereCase string
columnsSpecifier string
}
func genericViewRequest[T any](r *http.Request, params genericRequestParams) (int, any) {
reqLimit := max(1, parseQueryInt(r, "limit", 50))
if reqLimit > params.limitClamp {
reqLimit = params.limitClamp
}
reqOffset := max(0, parseQueryInt(r, "offset", 0))
reqSortOrder := parseQueryStringFiltered(r, "order", "desc", "asc")
if params.sortDefaultOrder != "asc" {
reqSortOrder = parseQueryStringFiltered(r, "order", "asc", "desc")
}
reqSortField := parseQueryStringFiltered(r, "sort", params.sortDefaultColumn, params.sortColumns...)
if mapped, ok := params.columnMappings[reqSortField]; ok {
reqSortField = mapped
}
wherecase := ""
whereargs := []any{}
reqFilterJ := parseQueryString(r, "filter", "")
reqFilterFieldsUnmapped := map[string]string{}
reqDoFilters := false
if reqFilterJ != "" {
err := json.Unmarshal([]byte(reqFilterJ), &reqFilterFieldsUnmapped)
if err == nil && len(reqFilterFieldsUnmapped) > 0 {
reqDoFilters = true
}
}
reqFilterFields := map[string]string{}
for k, v := range reqFilterFieldsUnmapped {
m, ok := params.columnMappings[k]
if ok {
reqFilterFields[m] = v
}
}
if reqDoFilters {
for _, v := range params.filterColumnsFull {
val, ok := reqFilterFields[v]
if ok {
whereargs = append(whereargs, val)
if wherecase == "" {
wherecase = "WHERE " + v + " = $1"
} else {
wherecase += " AND " + v + " = $1"
}
}
}
for _, v := range params.filterColumnsStartsWith {
val, ok := reqFilterFields[v]
if ok {
whereargs = append(whereargs, val)
if wherecase == "" {
wherecase = "WHERE starts_with(" + v + ", $1)"
} else {
wherecase += fmt.Sprintf(" AND starts_with("+v+", $%d)", len(whereargs))
}
}
}
}
reqSearch := parseQueryString(r, "search", "")
similarity := params.searchSimilarity
if reqSearch != "" && params.searchColumn != "" {
whereargs = append(whereargs, reqSearch)
if wherecase == "" {
wherecase = fmt.Sprintf("WHERE similarity("+params.searchColumn+", $1::text) > %f or "+params.searchColumn+" ~ $1::text", similarity)
} else {
wherecase += fmt.Sprintf(" AND similarity("+params.searchColumn+", $%d::text) > %f or "+params.searchColumn+" ~ $1::text", len(whereargs), similarity)
}
}
if params.addWhereCase != "" {
if wherecase == "" {
wherecase = "WHERE " + params.addWhereCase
} else {
wherecase += " AND " + params.addWhereCase
}
}
ordercase := fmt.Sprintf("ORDER BY %s %s", reqSortField, reqSortOrder)
limiter := fmt.Sprintf("LIMIT %d", reqLimit)
offset := fmt.Sprintf("OFFSET %d", reqOffset)
columnsSpecifier := "*"
if params.columnsSpecifier != "" {
columnsSpecifier = params.columnsSpecifier
}
tn := params.tableName
var totalsNoFilter int
var totals int
var rows []*T
// log.Println(`SELECT * FROM ` + tn + ` ` + wherecase + ` ` + ordercase + ` ` + offset + ` ` + limiter)
err := RequestMultiple(func() error {
return dbpool.QueryRow(r.Context(), `SELECT count(`+tn+`) FROM `+tn).Scan(&totalsNoFilter)
}, func() error {
return dbpool.QueryRow(r.Context(), `SELECT count(`+tn+`) FROM `+tn+` `+wherecase, whereargs...).Scan(&totals)
}, func() error {
req := `SELECT ` + columnsSpecifier + ` FROM ` + tn + ` ` + wherecase + ` ` + ordercase + ` ` + offset + ` ` + limiter
if cfg.GetDSBool(false, "displayQuery") {
log.Printf("req %s args %#+v", req, whereargs)
}
return pgxscan.Select(r.Context(), dbpool, &rows, req, whereargs...)
})
if err != nil {
return 500, err
}
return 200, map[string]any{
"total": totals,
"totalNotFiltered": totalsNoFilter,
"rows": rows,
}
}