forked from guypeled76/go-bigquery-driver
-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
builders.go
86 lines (74 loc) · 1.68 KB
/
builders.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
package bigquery
import (
"database/sql"
"database/sql/driver"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"reflect"
)
func initializeBuilders(db *gorm.DB) {
b := bigQueryBuilders{db}
db.ClauseBuilders["VALUES"] = b.buildValues
}
type bigQueryBuilders struct {
db *gorm.DB
}
func (b bigQueryBuilders) buildValues(c clause.Clause, builder clause.Builder) {
if c.Expression == nil {
return
}
values, ok := c.Expression.(clause.Values)
if !ok {
return
}
if len(values.Columns) > 0 {
builder.WriteByte('(')
for idx, column := range values.Columns {
if idx > 0 {
builder.WriteByte(',')
}
builder.WriteQuoted(column)
}
builder.WriteByte(')')
builder.WriteString(" VALUES ")
for idx, value := range values.Values {
if idx > 0 {
builder.WriteByte(',')
}
builder.WriteByte('(')
b.buildValuesArguments(builder, value)
builder.WriteByte(')')
}
} else {
builder.WriteString("DEFAULT VALUES")
}
}
func (bigQueryBuilders) buildValuesArguments(builder clause.Builder, vars []interface{}) {
for idx, v := range vars {
if idx > 0 {
builder.WriteByte(',')
}
switch v := v.(type) {
case sql.NamedArg, clause.Column, clause.Table, clause.Expr, driver.Valuer, []byte, []interface{}, *gorm.DB:
builder.AddVar(builder, v)
default:
switch rv := reflect.ValueOf(v); rv.Kind() {
case reflect.Slice, reflect.Array:
if rv.Len() == 0 {
builder.WriteString("[]")
} else {
builder.WriteByte('[')
for i := 0; i < rv.Len(); i++ {
if i > 0 {
builder.WriteByte(',')
}
builder.AddVar(builder, rv.Index(i).Interface())
}
builder.WriteByte(']')
}
default:
builder.AddVar(builder, v)
}
}
}
}