This repository has been archived by the owner on Nov 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
82 lines (73 loc) · 1.79 KB
/
update.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
package chem
import (
"database/sql"
"fmt"
"strings"
)
type UpdateStmt struct {
table Table
filters []Filter
}
func Update(table Table) UpdateStmt {
return UpdateStmt{
table: table,
}
}
func (stmt UpdateStmt) Where(filters ...Filter) UpdateStmt {
stmt.filters = append(stmt.filters, filters...)
return stmt
}
func toColumnsAndBinds(values map[Column]interface{}) (columns []Column, binds []interface{}) {
columns = make([]Column, 0, len(values))
for column := range values {
columns = append(columns, column)
}
// sort so we can have predictable output
columns = sortColumns(columns)
for _, column := range columns {
binds = append(binds, values[column])
}
return
}
func toSetColumnExpressions(columns []Column) []string {
out := make([]string, 0, len(columns))
for _, column := range columns {
expression := fmt.Sprintf("%v = ?", column.toColumnExpression(false))
out = append(out, expression)
}
return out
}
func allBinds(bindLists ...[]interface{}) []interface{} {
out := make([]interface{}, 0)
for _, list := range bindLists {
for _, bind := range list {
out = append(out, bind)
}
}
return out
}
func (stmt UpdateStmt) Set(db DB, values map[Column]interface{}) (sql.Result, error) {
if len(values) == 0 {
return BadResult{ErrTooFewValues}, ErrTooFewValues
}
columns, bindValues := toColumnsAndBinds(values)
combinedFilter := AND(stmt.filters...)
queryString := strings.Join(
filterEmptyStrings(
fmt.Sprintf("UPDATE %v", stmt.table.Name()),
fmt.Sprintf("SET %v", strings.Join(toSetColumnExpressions(columns), ", ")),
makeWhereClause(combinedFilter, false),
),
" ",
)
preparedStmt, err := db.Prepare(queryString)
if err != nil {
return BadResult{err}, err
}
return preparedStmt.Exec(
allBinds(
bindValues,
combinedFilter.binds(),
)...,
)
}