-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_builder.go
More file actions
409 lines (345 loc) · 10.8 KB
/
Copy pathquery_builder.go
File metadata and controls
409 lines (345 loc) · 10.8 KB
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package pagination
import (
"fmt"
"strings"
"gorm.io/gorm"
)
type QueryBuilder interface {
ApplyFilters(query *gorm.DB) *gorm.DB
GetTableName() string
GetDefaultSort() string
GetSearchFields() []string
}
type IncludableQueryBuilder interface {
QueryBuilder
GetIncludes() []string
GetPagination() PaginationRequest
Validate()
}
type AllowedIncludesProvider interface {
GetAllowedIncludes() map[string]bool
}
// DatabaseProvider interface for query builders that need database access
type DatabaseProvider interface {
GetDB() *gorm.DB
}
// QueryLayerBuilder interface that combines query building with database access
type QueryLayerBuilder interface {
IncludableQueryBuilder
DatabaseProvider
}
// applyAutoSearch applies search automatically based on provided search fields
func applyAutoSearch(query *gorm.DB, searchTerm string, searchFields []string, dialect DatabaseDialect) *gorm.DB {
if len(searchFields) == 0 || searchTerm == "" {
return query
}
searchPattern := "%" + searchTerm + "%"
operator := getSearchOperator(dialect)
if len(searchFields) == 1 {
return query.Where(searchFields[0]+" "+operator+" ?", searchPattern)
}
conditions := make([]string, len(searchFields))
args := make([]interface{}, len(searchFields))
for i, field := range searchFields {
conditions[i] = field + " " + operator + " ?"
args[i] = searchPattern
}
whereClause := "(" + strings.Join(conditions, " OR ") + ")"
return query.Where(whereClause, args...)
}
func getSearchOperator(dialect DatabaseDialect) string {
switch dialect {
case PostgreSQL:
return "ILIKE"
case MySQL, SQLite, SQLServer:
return "LIKE"
default:
return "LIKE"
}
}
// DatabaseDialect represents different database types for compatibility
type DatabaseDialect string
const (
MySQL DatabaseDialect = "mysql"
PostgreSQL DatabaseDialect = "postgresql"
SQLite DatabaseDialect = "sqlite"
SQLServer DatabaseDialect = "sqlserver"
)
// PaginatedQueryOptions provides configuration for paginated queries
type PaginatedQueryOptions struct {
Dialect DatabaseDialect
EnableSoftDelete bool
CustomCountQuery string
}
func PaginatedQuery[T any](
db *gorm.DB,
builder QueryBuilder,
pagination PaginationRequest,
includes []string,
) ([]T, int64, error) {
return PaginatedQueryWithOptions[T](db, builder, pagination, includes, PaginatedQueryOptions{
Dialect: MySQL, // Default to MySQL for backward compatibility
})
}
// PaginatedQueryWithIncludable handles queries with includable query builders
func PaginatedQueryWithIncludable[T any](
db *gorm.DB,
builder IncludableQueryBuilder,
) ([]T, int64, error) {
// If db is nil, try to get it from the builder (for query layer pattern)
if db == nil {
if dbProvider, ok := builder.(DatabaseProvider); ok {
db = dbProvider.GetDB()
} else {
return nil, 0, fmt.Errorf("database connection not provided")
}
}
// Validate the builder
builder.Validate()
// Get pagination and includes from the builder
pagination := builder.GetPagination()
includes := builder.GetIncludes()
return PaginatedQueryWithOptions[T](db, builder, pagination, includes, PaginatedQueryOptions{
Dialect: MySQL, // Default to MySQL for backward compatibility
})
}
// PaginatedQueryWithIncludableAndOptions handles queries with includable query builders and custom options
func PaginatedQueryWithIncludableAndOptions[T any](
db *gorm.DB,
builder IncludableQueryBuilder,
options PaginatedQueryOptions,
) ([]T, int64, error) {
// Validate the builder
builder.Validate()
// Get pagination and includes from the builder
pagination := builder.GetPagination()
includes := builder.GetIncludes()
return PaginatedQueryWithOptions[T](db, builder, pagination, includes, options)
}
func PaginatedQueryWithOptions[T any](
db *gorm.DB,
builder QueryBuilder,
pagination PaginationRequest,
includes []string,
options PaginatedQueryOptions,
) ([]T, int64, error) {
var result []T
var totalCount int64
// Build count query
countQuery := db.Table(builder.GetTableName())
countQuery = builder.ApplyFilters(countQuery)
// Apply soft delete handling if enabled
if options.EnableSoftDelete {
countQuery = countQuery.Where("deleted_at IS NULL")
}
// Execute count query
if options.CustomCountQuery != "" {
if err := countQuery.Raw(options.CustomCountQuery).Count(&totalCount).Error; err != nil {
return nil, 0, fmt.Errorf("failed to count records: %w", err)
}
} else {
if err := countQuery.Count(&totalCount).Error; err != nil {
return nil, 0, fmt.Errorf("failed to count records: %w", err)
}
}
// Build data query
dataQuery := db.Table(builder.GetTableName())
dataQuery = builder.ApplyFilters(dataQuery)
if pagination.Search != "" {
dataQuery = applyAutoSearch(dataQuery, pagination.Search, builder.GetSearchFields(), options.Dialect)
}
// Apply soft delete handling if enabled
if options.EnableSoftDelete {
dataQuery = dataQuery.Where("deleted_at IS NULL")
}
// Apply sorting
if pagination.Sort != "" {
// Validate sort field to prevent SQL injection
if isValidSortField(pagination.Sort) {
orderClause := pagination.Sort + " " + pagination.Order
dataQuery = dataQuery.Order(orderClause)
} else {
dataQuery = dataQuery.Order(builder.GetDefaultSort())
}
} else {
dataQuery = dataQuery.Order(builder.GetDefaultSort())
}
// Apply pagination unless disabled
if !pagination.IsDisabled {
dataQuery = dataQuery.Offset(pagination.GetOffset()).Limit(pagination.GetLimit())
}
// Validate and apply preloads
validatedIncludes := validateIncludes(builder, includes)
for _, include := range validatedIncludes {
dataQuery = dataQuery.Preload(include)
}
// Execute data query
if err := dataQuery.Find(&result).Error; err != nil {
return nil, 0, fmt.Errorf("failed to fetch records: %w", err)
}
return result, totalCount, nil
}
// isValidSortField validates sort field to prevent SQL injection
func isValidSortField(field string) bool {
// Allow only alphanumeric characters, underscores, and dots
for _, char := range field {
if !((char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9') ||
char == '_' || char == '.') {
return false
}
}
return len(field) > 0
}
// isValidInclude validates include field to prevent SQL injection
func isValidInclude(include string) bool {
// Allow only alphanumeric characters, underscores, and dots
for _, char := range include {
if !((char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9') ||
char == '_' || char == '.') {
return false
}
}
return len(include) > 0
}
// validateIncludes validates includes against allowed includes for the builder
func validateIncludes(builder interface{}, includes []string) []string {
if includeValidator, ok := builder.(AllowedIncludesProvider); ok {
allowedIncludes := includeValidator.GetAllowedIncludes()
var validIncludes []string
for _, include := range includes {
if isValidInclude(include) && allowedIncludes[include] {
validIncludes = append(validIncludes, include)
}
}
return validIncludes
}
// Fallback: just validate syntax if no allowed includes defined
var validIncludes []string
for _, include := range includes {
if isValidInclude(include) {
validIncludes = append(validIncludes, include)
}
}
return validIncludes
}
type SimpleQueryBuilder struct {
TableName string
FilterFunc func(*gorm.DB) *gorm.DB
SearchFields []string
DefaultSort string
Dialect DatabaseDialect
}
func (s *SimpleQueryBuilder) ApplyFilters(query *gorm.DB) *gorm.DB {
if s.FilterFunc != nil {
return s.FilterFunc(query)
}
return query
}
func (s *SimpleQueryBuilder) GetSearchFields() []string {
return s.SearchFields
}
func (s *SimpleQueryBuilder) GetTableName() string {
return s.TableName
}
func (s *SimpleQueryBuilder) GetDefaultSort() string {
if s.DefaultSort == "" {
return "id asc"
}
return s.DefaultSort
}
// NewSimpleQueryBuilder creates a new SimpleQueryBuilder with default settings
func NewSimpleQueryBuilder(tableName string) *SimpleQueryBuilder {
return &SimpleQueryBuilder{
TableName: tableName,
DefaultSort: "id asc",
Dialect: MySQL,
}
}
// WithSearchFields sets the search fields for the query builder
func (s *SimpleQueryBuilder) WithSearchFields(fields ...string) *SimpleQueryBuilder {
s.SearchFields = fields
return s
}
// WithDefaultSort sets the default sort for the query builder
func (s *SimpleQueryBuilder) WithDefaultSort(sort string) *SimpleQueryBuilder {
s.DefaultSort = sort
return s
}
// WithDialect sets the database dialect for the query builder
func (s *SimpleQueryBuilder) WithDialect(dialect DatabaseDialect) *SimpleQueryBuilder {
s.Dialect = dialect
return s
}
// WithFilters sets the filter function for the query builder
func (s *SimpleQueryBuilder) WithFilters(filterFunc func(*gorm.DB) *gorm.DB) *SimpleQueryBuilder {
s.FilterFunc = filterFunc
return s
}
// GetSearchOperator returns the search operator based on the current dialect
func (s *SimpleQueryBuilder) GetSearchOperator() string {
return getSearchOperator(s.Dialect)
}
// ChainableQueryBuilder allows for method chaining to build complex queries
type ChainableQueryBuilder struct {
*SimpleQueryBuilder
joins []string
groupBy []string
having []string
selects []string
}
// NewChainableQueryBuilder creates a new ChainableQueryBuilder
func NewChainableQueryBuilder(tableName string) *ChainableQueryBuilder {
return &ChainableQueryBuilder{
SimpleQueryBuilder: NewSimpleQueryBuilder(tableName),
joins: make([]string, 0),
groupBy: make([]string, 0),
having: make([]string, 0),
selects: make([]string, 0),
}
}
// Join adds a JOIN clause to the query
func (c *ChainableQueryBuilder) Join(join string) *ChainableQueryBuilder {
c.joins = append(c.joins, join)
return c
}
// GroupBy adds a GROUP BY clause to the query
func (c *ChainableQueryBuilder) GroupBy(field string) *ChainableQueryBuilder {
c.groupBy = append(c.groupBy, field)
return c
}
// Having adds a HAVING clause to the query
func (c *ChainableQueryBuilder) Having(condition string) *ChainableQueryBuilder {
c.having = append(c.having, condition)
return c
}
// Select adds a SELECT clause to the query
func (c *ChainableQueryBuilder) Select(fields ...string) *ChainableQueryBuilder {
c.selects = append(c.selects, fields...)
return c
}
// ApplyFilters applies all the configured filters including joins, group by, etc.
func (c *ChainableQueryBuilder) ApplyFilters(query *gorm.DB) *gorm.DB {
// Apply base filters first
query = c.SimpleQueryBuilder.ApplyFilters(query)
// Apply selects
if len(c.selects) > 0 {
query = query.Select(c.selects)
}
// Apply joins
for _, join := range c.joins {
query = query.Joins(join)
}
// Apply group by
for _, groupBy := range c.groupBy {
query = query.Group(groupBy)
}
// Apply having
for _, having := range c.having {
query = query.Having(having)
}
return query
}