-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgoqu.go
67 lines (59 loc) · 1.65 KB
/
goqu.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
package goqux
import (
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
"github.com/doug-martin/goqu/v9"
"github.com/doug-martin/goqu/v9/exp"
"github.com/google/uuid"
"github.com/iancoleman/strcase"
"github.com/lib/pq"
)
var defaultDialect = "postgres"
func init() {
goqu.SetColumnRenameFunction(strcase.ToSnake)
goqu.SetDefaultPrepared(true)
}
// Column is shorthand for goqu.T(table).Col(column).
func Column(table string, column string) exp.IdentifierExpression {
return goqu.T(table).Col(column)
}
// SetDefaultDialect sets the default dialect for goqux.
func SetDefaultDialect(dialect string) {
defaultDialect = dialect
}
// SQLValuer is the valuer struct that is used for goqu rows conversion.
type SQLValuer struct {
V interface{}
}
// Value converts the given value to the correct drive.Value.
func (t SQLValuer) Value() (driver.Value, error) {
if valuer, ok := t.V.(driver.Valuer); ok {
if reflect.TypeOf(t.V).Kind() == reflect.Pointer && reflect.ValueOf(t.V).IsZero() {
return nil, nil
}
return valuer.Value()
}
switch t.V.(type) {
case []string, []bool, []float32, []float64, []int, []int64, []int32:
value, err := pq.Array(t.V).Value()
if err != nil {
return nil, fmt.Errorf("failed to convert value: %w", err)
}
return value, nil
case map[string]interface{}, []map[string]interface{}, []interface{}, map[string]string:
return json.Marshal(t.V)
case uuid.UUID:
if t.V == uuid.Nil {
return nil, nil
}
return t.V, nil
default:
// if we didn't find a common type use reflection to guess if the type is of map
if reflect.TypeOf(t.V).Kind() == reflect.Map {
return json.Marshal(t.V)
}
return t.V, nil
}
}