-
Notifications
You must be signed in to change notification settings - Fork 3
/
crud_repository.go
397 lines (332 loc) · 9.67 KB
/
crud_repository.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
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
package gorm_crud
import (
"database/sql"
"errors"
"fmt"
"github.com/lib/pq"
"reflect"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
)
type ListParametersInterface interface{}
type PaginationParameters struct {
Page int `form:"page,default=0" json:"page,default=0"`
PageSize int `form:"page_size,default=30" json:"page_size,default=30"`
OrderBy string `form:"order_by,default=id" json:"order_by,default=id"`
OrderDesc bool `form:"order_desc,default=false" json:"order_desc,default=false"`
}
type CrudListParameters struct {
*PaginationParameters
}
const DefaultPageSize = 30
type ListQueryBuilderInterface interface {
ListQuery(parameters ListParametersInterface) (*gorm.DB, error)
}
type BaseListQueryBuilder struct {
Db *gorm.DB
Logger LoggerInterface
ListQueryBuilderInterface
}
func NewBaseListQueryBuilder(db *gorm.DB, logger LoggerInterface) *BaseListQueryBuilder {
return &BaseListQueryBuilder{Db: db, Logger: logger}
}
func (c BaseListQueryBuilder) paginationQuery(parameters ListParametersInterface) *gorm.DB {
query := c.Db
val := reflect.ValueOf(parameters).Elem()
if val.Kind() != reflect.Struct {
c.Logger.Error("gorm-crud: Unexpected type of parameters for paginationQuery")
return query
}
paginationParameters := val.FieldByName("PaginationParameters")
hasPaginationParams := paginationParameters.IsValid() && !paginationParameters.IsNil()
var page int64
page = 0
if hasPaginationParams {
pageValue := val.FieldByName("Page")
if !pageValue.IsValid() || pageValue.Kind() != reflect.Int {
c.Logger.Error("gorm-crud: Page is not specified correctly in listQuery")
} else {
page = pageValue.Int()
}
}
var pageSize int64
pageSize = DefaultPageSize
if hasPaginationParams {
pageSizeValue := val.FieldByName("PageSize")
if !pageSizeValue.IsValid() || pageSizeValue.Kind() != reflect.Int {
c.Logger.Error("gorm-crud: PageSize is not specified in listQuery")
} else {
pageSize = pageSizeValue.Int()
}
}
limit := pageSize
offset := page * pageSize
query = query.Offset(offset).Limit(limit)
var orderBy string
if hasPaginationParams {
orderByValue := val.FieldByName("OrderBy")
if orderByValue.IsValid() && orderByValue.Kind() == reflect.String {
orderBy = orderByValue.String()
}
}
var orderDesc = false
if hasPaginationParams {
orderDescValue := val.FieldByName("OrderDesc")
if orderDescValue.IsValid() && orderDescValue.Kind() == reflect.Bool {
orderDesc = orderDescValue.Bool()
}
}
if len(orderBy) > 0 {
if orderDesc {
query = query.Order(fmt.Sprintf("%s DESC", orderBy), true)
} else {
query = query.Order(fmt.Sprintf("%s ASC", orderBy), true)
}
}
return query
}
func (c BaseListQueryBuilder) ListQuery(parameters ListParametersInterface) (*gorm.DB, error) {
return c.paginationQuery(parameters), nil
}
type CrudRepositoryInterface interface {
BaseRepositoryInterface
GetModel() InterfaceEntity
Find(id uint) (InterfaceEntity, error)
PluckBy(fieldNames []string) (map[string]int64, error)
ListAll() ([]InterfaceEntity, error)
List(parameters ListParametersInterface) ([]InterfaceEntity, error)
ListCount(parameters ListParametersInterface) (int64, error)
Create(item InterfaceEntity) InterfaceEntity
CreateOrUpdateMany(item InterfaceEntity, columns []string, values []map[string]interface{}, onConflict string) error
Update(item InterfaceEntity) InterfaceEntity
Delete(id uint) error
}
type CrudRepository struct {
CrudRepositoryInterface
*BaseRepository
Model InterfaceEntity // Dynamic typing
ListQueryBuilder ListQueryBuilderInterface
}
func NewCrudRepository(db *gorm.DB, model InterfaceEntity, listQueryBuilder ListQueryBuilderInterface, logger LoggerInterface) *CrudRepository {
repo := NewBaseRepository(db, logger)
return &CrudRepository{
BaseRepository: repo,
Model: model,
ListQueryBuilder: listQueryBuilder,
}
}
func (c CrudRepository) GetModel() InterfaceEntity {
return c.Model
}
func (c CrudRepository) Find(id uint) (InterfaceEntity, error) {
item := reflect.New(reflect.TypeOf(c.GetModel()).Elem()).Interface()
err := c.Db.First(item, id).Error
return item, NormalizeErr(err)
}
func (c CrudRepository) PluckBy(fieldNames []string) (map[string]int64, error) {
res := map[string]int64{}
items, err := c.ListAll()
if nil != err {
return res, err
}
for _, item := range items {
// build key
values := make([]string, 0)
val := reflect.ValueOf(item)
for _, fieldName := range fieldNames {
if val.FieldByName(fieldName).IsValid() {
values = append(values, val.FieldByName(fieldName).String())
} else {
return res, fmt.Errorf("field with name (%s) does not exists on entity (%s)", fieldName, reflect.TypeOf(item))
}
}
pluckKey := strings.Join(values, "_")
res[pluckKey] = Num64(val.FieldByName("ID").Interface())
}
return res, err
}
func (c CrudRepository) ListAll() ([]InterfaceEntity, error) {
entities := make([]InterfaceEntity, 0)
page := 0
pageSize := 10000
for {
parameters := new(CrudListParameters)
parameters.PaginationParameters = new(PaginationParameters)
parameters.OrderBy = "id"
parameters.OrderDesc = false
parameters.PageSize = pageSize
parameters.Page = page
items, err := c.List(parameters)
if nil != err {
return entities, err
}
for _, item := range items {
entities = append(entities, item)
}
if len(items) < pageSize {
break
}
page += 1
}
return entities, nil
}
func (c CrudRepository) List(parameters ListParametersInterface) ([]InterfaceEntity, error) {
items := reflect.New(reflect.SliceOf(reflect.TypeOf(c.GetModel()).Elem())).Interface()
query, err := c.ListQueryBuilder.ListQuery(parameters)
if err != nil {
return []InterfaceEntity{}, err
}
err = query.Find(items).Error
entities := reflect.ValueOf(items).Elem().Interface()
// Convert entities to slice
var data []InterfaceEntity
sliceValue := reflect.ValueOf(entities)
for i := 0; i < sliceValue.Len(); i++ {
data = append(data, sliceValue.Index(i).Interface())
}
return data, NormalizeErr(err)
}
func (c CrudRepository) ListCount(parameters ListParametersInterface) (int64, error) {
query, err := c.ListQueryBuilder.ListQuery(parameters)
if err != nil {
return 0, err
}
var count int64
item := reflect.New(reflect.TypeOf(c.GetModel()).Elem()).Interface()
err = query.Model(item).Count(&count).Error
return count, err
}
func (c CrudRepository) Create(item InterfaceEntity) InterfaceEntity {
c.Db.Create(item)
return item
}
func (c *CrudRepository) quote(str string) string {
// postgres style escape
str = strings.ReplaceAll(str, "'", "''")
return fmt.Sprintf("'%s'", str)
}
func (c CrudRepository) prepareTime(val time.Time) string {
return fmt.Sprintf("'%s'", val.Format("2006-01-02T15:04:05-0700"))
}
func (c CrudRepository) prepareSliceOfNumbers(values interface{}) string {
result := "{}"
switch reflect.TypeOf(values).Kind() {
case reflect.Slice:
s := reflect.ValueOf(values)
valuesText := []string{}
for i := 0; i < s.Len(); i++ {
text := fmt.Sprint(s.Index(i))
valuesText = append(valuesText, text)
}
result = fmt.Sprintf("{%s}", strings.Join(valuesText, ","))
}
return c.quote(result)
}
// CreateOrUpdateMany create or update if exists
func (c CrudRepository) CreateOrUpdateMany(
item InterfaceEntity,
columns []string,
values []map[string]interface{},
onConflict string,
) error {
if len(values) == 0 {
return nil
}
var valueStrings []string
for _, valueMap := range values {
var valueRowString []string
for _, column := range columns {
colVal, ok := valueMap[column]
if !ok {
return errors.New(fmt.Sprintf("CreateOrUpdateMany: value for column %s found", column))
}
// stringify column value
val := fmt.Sprintf("%v", colVal)
// filter column value
switch v := colVal.(type) {
case sql.NullInt32:
if !v.Valid {
val = "NULL"
} else {
val = strconv.FormatInt(int64(v.Int32), 10)
}
case sql.NullInt64:
if !v.Valid {
val = "NULL"
} else {
val = strconv.FormatInt(v.Int64, 10)
}
case sql.NullFloat64:
if !v.Valid {
val = "NULL"
} else {
val = fmt.Sprintf("%g", v.Float64)
}
case sql.NullBool:
if !v.Valid {
val = "NULL"
} else if v.Bool {
val = "TRUE"
} else {
val = "FALSE"
}
case sql.NullTime:
if !v.Valid {
val = "NULL"
} else {
val = c.prepareTime(v.Time)
}
case sql.NullString:
if !v.Valid {
val = "NULL"
} else {
val = c.quote(v.String)
}
case time.Time:
val = c.prepareTime(colVal.(time.Time))
case *time.Time:
if !reflect.ValueOf(colVal).IsNil() {
t := reflect.ValueOf(colVal).Elem().Interface().(time.Time)
val = c.prepareTime(t)
} else {
val = "NULL"
}
case []int64, []int32, []uint8, []float64, []float32, pq.Int64Array, pq.Float64Array:
val = c.prepareSliceOfNumbers(v)
default:
if reflect.TypeOf(colVal).Kind() == reflect.String {
val = c.quote(val)
}
}
valueRowString = append(valueRowString, val)
}
valueString := fmt.Sprintf("(%s)", strings.Join(valueRowString, ","))
valueStrings = append(valueStrings, valueString)
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s %s",
c.Db.NewScope(item).TableName(),
strings.Join(columns, ","),
strings.Join(valueStrings, ","),
onConflict)
err := c.Db.Exec(query).Error
err = NormalizeErr(err)
if nil != err {
c.Logger.Errorf("gorm-crud: Error in the CreateOrUpdateMany(): %v", err)
}
return err
}
func (c CrudRepository) Update(item InterfaceEntity) InterfaceEntity {
c.Db.Save(item)
return item
}
func (c CrudRepository) Delete(id uint) error {
item, err := c.Find(id)
err = NormalizeErr(err)
if err != nil {
return err
}
c.Db.Delete(item)
return nil
}