-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathaxon_sql.go
194 lines (168 loc) · 5.91 KB
/
axon_sql.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package warppipe
import (
"fmt"
"log"
"reflect"
"regexp"
"strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
var regexSpace = regexp.MustCompile(`\s+`)
func removeDuplicateSpaces(in string) string {
return strings.TrimSpace(regexSpace.ReplaceAllString(in, " "))
}
func prepareQueryArgs(changesetCols []*ChangesetColumn) ([]string, []string, map[string]interface{}, error) {
var cols []string
var colArgs []string
values := make(map[string]interface{}, len(cols))
for _, c := range changesetCols {
t := reflect.TypeOf(c.Value)
if t != nil && t.Kind() == reflect.Map {
// Found a hashmap, this is a JSON/B field. This type is not supported
// since re-marshaling breaks md5 checksum validation. Instead pass the
// original raw json as a string.
return nil, nil, nil, fmt.Errorf("expected raw json string")
}
if t != nil && t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Interface {
// Set empty slices to pq.Array(nil) to avoid package sql error on an
// empty character varying[]: "unsupported type []interface {}, a slice of
// interface"
if reflect.ValueOf(c.Value).Len() == 0 {
c.Value = pq.Array(nil)
} else {
c.Value = pq.Array(c.Value)
}
}
cols = append(cols, c.Column)
colArgs = append(colArgs, fmt.Sprintf(":%s", c.Column))
values[c.Column] = c.Value
}
return cols, colArgs, values, nil
}
func preparePrimaryKeyWhereClause(table string, primaryKey []string) string {
clauses := make([]string, len(primaryKey))
for i, c := range primaryKey {
clauses[i] = fmt.Sprintf(`"%s".%s = :%s`, table, c, c)
}
return strings.Join(clauses, " AND ")
}
func prepareInsertQuery(schema string, change *Changeset) (string, map[string]interface{}) {
cols, colArgs, values, err := prepareQueryArgs(change.NewValues)
if err != nil {
// TODO: Is failure the best option here? Probably no way to safely save anything.
log.Fatalf("prepareQueryArgs: error in changeset %s: %s", change, err)
}
sql := fmt.Sprintf(
`INSERT INTO "%s"."%s" (%s) VALUES (%s)`,
schema,
change.Table,
strings.Join(cols, ","),
strings.Join(colArgs, ","),
)
return sql, values
}
func prepareUpdateQuery(schema string, primaryKey []string, change *Changeset) (string, map[string]interface{}) {
cols, colArgs, values, err := prepareQueryArgs(change.NewValues)
if err != nil {
log.Fatalf("prepareQueryArgs: error in changeset %s: %s", change, err)
}
setClauses := make([]string, len(cols))
for i, c := range cols {
setClauses[i] = fmt.Sprintf("%s = :%s", c, c)
}
primaryKeyWhereClauses := make([]string, len(primaryKey))
for i, c := range primaryKey {
primaryKeyWhereClauses[i] = fmt.Sprintf(`"%s".%s = :%s`, change.Table, c, c)
}
sql := fmt.Sprintf(`
INSERT INTO "%s"."%s" (%s) VALUES (%s)
ON CONFLICT (%s)
DO UPDATE SET %s WHERE %s`,
schema,
change.Table,
strings.Join(cols, ", "),
strings.Join(colArgs, ", "),
strings.Join(primaryKey, ", "),
strings.Join(setClauses, ", "),
preparePrimaryKeyWhereClause(change.Table, primaryKey),
)
return sql, values
}
func prepareDeleteQuery(schema string, primaryKey []string, change *Changeset) (string, map[string]interface{}) {
_, _, values, err := prepareQueryArgs(change.OldValues)
if err != nil {
log.Fatalf("prepareQueryArgs: error in changeset %s: %s", change, err)
}
sql := fmt.Sprintf(
`DELETE FROM "%s"."%s" WHERE %s`,
schema,
change.Table,
preparePrimaryKeyWhereClause(change.Table, primaryKey),
)
return sql, values
}
func insertRow(sourceDB *sqlx.DB, targetDB *sqlx.DB, schema string, change *Changeset) error {
query, args := prepareInsertQuery(schema, change)
_, err := targetDB.NamedExec(query, args)
if err != nil {
// PG error codes: https://www.postgresql.org/docs/9.2/errcodes-appendix.html
pqe, ok := err.(*pq.Error)
if !ok {
return fmt.Errorf("failed to insert %s for query %s args %s: %+v", change, removeDuplicateSpaces(query), args, err)
}
if pqe.Code.Name() == "unique_violation" {
// Ignore duplicates
// TODO: Should they be updated instead?
log.Printf("duplicate row insert skipped %s:", change)
// Always update, even on duplicate row.
err = updateColumnSequence(targetDB, change.Table, change.NewValues)
if err != nil {
return err
}
return nil
}
return fmt.Errorf("PG error %s:%s failed to insert %s for query %s args %s: %+v", pqe.Code, pqe.Code.Name(), change, removeDuplicateSpaces(query), args, err)
}
err = updateColumnSequence(targetDB, change.Table, change.NewValues)
if err != nil {
return err
}
err = updateOrphanSequences(sourceDB, targetDB, change.Table, change.NewValues)
if err != nil {
return err
}
log.Printf("row inserted: %s", change)
return nil
}
func updateRow(targetDB *sqlx.DB, schema string, change *Changeset, primaryKey []string) error {
query, args := prepareUpdateQuery(schema, primaryKey, change)
_, err := targetDB.NamedExec(query, args)
if err != nil {
pqe, ok := err.(*pq.Error)
if !ok {
return fmt.Errorf("failed to update %s for query %s args %s: %+v", change, removeDuplicateSpaces(query), args, err)
}
if pqe.Code.Name() == "unique_violation" {
// Ignore duplicates
log.Print("update duplicate row skipped")
return nil
}
return fmt.Errorf("PG error %s:%s failed to update %s for query %s args %s: %+v", pqe.Code, pqe.Code.Name(), change, removeDuplicateSpaces(query), args, err)
}
log.Printf("row updated: %s", change)
return nil
}
func deleteRow(targetDB *sqlx.DB, schema string, change *Changeset, primaryKey []string) error {
query, values := prepareDeleteQuery(schema, primaryKey, change)
_, err := targetDB.NamedExec(query, values)
if err != nil {
pqe, ok := err.(*pq.Error)
if !ok {
return fmt.Errorf("failed to delete %s for query %s: %+v", change, removeDuplicateSpaces(query), err)
}
return fmt.Errorf("PG error %s:%s delete to update %s for query %s: %+v", pqe.Code, pqe.Code.Name(), change, removeDuplicateSpaces(query), err)
}
log.Printf("row deleted: %s", change)
return nil
}