-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinsert.go
87 lines (68 loc) · 1.89 KB
/
insert.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
package qb
type defaultField struct{}
// Default uses a field's default value
func Default() Field {
return defaultField{}
}
// QueryString implements Field
func (f defaultField) QueryString(_ *Context) string {
return `DEFAULT`
}
// InsertBuilder builds an INSERT query
type InsertBuilder struct {
table *Table
fields []Field
values [][]Field
conflict []Field
update Query
ignoreConflict bool
}
// Values adds values to the query
func (q *InsertBuilder) Values(values ...interface{}) *InsertBuilder {
if len(values) != len(q.fields) {
panic(`Number of values has to match the number of fields`)
}
list := make([]Field, len(values))
for k, v := range values {
list[k] = MakeField(v)
}
q.values = append(q.values, list)
return q
}
// Upsert turns the INSERT query into an upsert query, only usable if your driver supports it
func (q *InsertBuilder) Upsert(query Query, conflict ...Field) *InsertBuilder {
if q.ignoreConflict {
panic(`can't upsert and ignore conflicts at the same time`)
}
q.update = query
q.conflict = conflict
return q
}
// IgnoreConflict ignores conflicts from the insert query
func (q *InsertBuilder) IgnoreConflict(conflict ...Field) *InsertBuilder {
if q.update != nil {
panic(`can't upsert and ignore conflicts at the same time`)
}
q.ignoreConflict = true
q.conflict = conflict
return q
}
// SQL returns a query string and a list of values
func (q *InsertBuilder) SQL(b SQLBuilder) (string, []interface{}) {
if len(q.values) == 0 {
panic(`Cannot exectue insert without values`)
}
b.Insert(q.table, q.fields)
b.Values(q.values)
sql := b.w.String()
if q.update != nil {
s, v := b.Context.Driver.UpsertSQL(q.table, q.conflict, q.update)
b.Context.Add(v...)
sql += s
} else if q.ignoreConflict {
s, v := b.Context.Driver.IgnoreConflictSQL(q.table, q.conflict)
b.Context.Add(v...)
sql += s
}
return sql, *b.Context.Values
}