forked from slicebit/qb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
upsert.go
49 lines (42 loc) · 1.43 KB
/
upsert.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
package qb
// Upsert generates an insert ... on (duplicate key/conflict) update statement
func Upsert(table TableElem) UpsertStmt {
return UpsertStmt{
Table: table,
ValuesMap: map[string]interface{}{},
ReturningCols: []ColumnElem{},
}
}
// UpsertStmt is the base struct for any insert ... on conflict/duplicate key ... update ... statements
type UpsertStmt struct {
Table TableElem
ValuesMap map[string]interface{}
ReturningCols []ColumnElem
}
// Values accepts map[string]interface{} and forms the values map of insert statement
func (s UpsertStmt) Values(values map[string]interface{}) UpsertStmt {
for k, v := range values {
s.ValuesMap[k] = v
}
return s
}
// Returning accepts the column names as strings and forms the returning array of insert statement
// NOTE: Please use it in only postgres dialect, otherwise it'll crash
func (s UpsertStmt) Returning(cols ...ColumnElem) UpsertStmt {
for _, c := range cols {
s.ReturningCols = append(s.ReturningCols, c)
}
return s
}
// Accept calls the compiler VisitUpsert function
func (s UpsertStmt) Accept(context *CompilerContext) string {
return context.Compiler.VisitUpsert(context, s)
}
// Build generates a statement out of UpdateStmt object
func (s UpsertStmt) Build(dialect Dialect) *Stmt {
context := NewCompilerContext(dialect)
statement := Statement()
statement.AddSQLClause(s.Accept(context))
statement.AddBinding(context.Binds...)
return statement
}