This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 215
/
writer.go
201 lines (177 loc) · 5.09 KB
/
writer.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
195
196
197
198
199
200
201
package postgres
import (
"database/sql"
"encoding/json"
"fmt"
"strings"
"github.com/compose/mejson"
"github.com/compose/transporter/client"
"github.com/compose/transporter/log"
"github.com/compose/transporter/message"
"github.com/compose/transporter/message/ops"
)
var _ client.Writer = &Writer{}
// Writer implements client.Writer for use with MongoDB
type Writer struct {
writeMap map[ops.Op]func(message.Msg, *sql.DB) error
}
func newWriter() *Writer {
w := &Writer{}
w.writeMap = map[ops.Op]func(message.Msg, *sql.DB) error{
ops.Insert: insertMsg,
ops.Update: updateMsg,
ops.Delete: deleteMsg,
}
return w
}
func (w *Writer) Write(msg message.Msg) func(client.Session) (message.Msg, error) {
return func(s client.Session) (message.Msg, error) {
writeFunc, ok := w.writeMap[msg.OP()]
if !ok {
log.Infof("no function registered for operation, %s", msg.OP())
if msg.Confirms() != nil {
msg.Confirms() <- struct{}{}
}
return msg, nil
}
if err := writeFunc(msg, s.(*Session).pqSession); err != nil {
return nil, err
}
if msg.Confirms() != nil {
msg.Confirms() <- struct{}{}
}
return msg, nil
}
}
func insertMsg(m message.Msg, s *sql.DB) error {
log.With("table", m.Namespace()).Debugln("INSERT")
var (
keys []string
placeholders []string
data []interface{}
)
i := 1
for key, value := range m.Data() {
keys = append(keys, key)
placeholders = append(placeholders, fmt.Sprintf("$%v", i))
switch value.(type) {
case map[string]interface{}, mejson.M, []map[string]interface{}, mejson.S:
value, _ = json.Marshal(value)
case []interface{}:
value, _ = json.Marshal(value)
value = string(value.([]byte))
value = fmt.Sprintf("{%v}", value.(string)[1:len(value.(string))-1])
}
data = append(data, value)
i = i + 1
}
query := fmt.Sprintf("INSERT INTO %v (%v) VALUES (%v);", m.Namespace(), strings.Join(keys, ", "), strings.Join(placeholders, ", "))
_, err := s.Exec(query, data...)
return err
}
func deleteMsg(m message.Msg, s *sql.DB) error {
log.With("table", m.Namespace()).With("values", m.Data()).Debugln("DELETE")
var (
ckeys []string
vals []interface{}
)
pkeys, err := primaryKeys(m.Namespace(), s)
if err != nil {
return err
}
i := 1
for key, value := range m.Data() {
if pkeys[key] { // key is primary key
ckeys = append(ckeys, fmt.Sprintf("%v = $%v", key, i))
}
switch value.(type) {
case map[string]interface{}, mejson.M, []map[string]interface{}, mejson.S:
value, _ = json.Marshal(value)
case []interface{}:
value, _ = json.Marshal(value)
value = string(value.([]byte))
value = fmt.Sprintf("{%v}", value.(string)[1:len(value.(string))-1])
}
vals = append(vals, value)
i = i + 1
}
if len(pkeys) != len(ckeys) {
return fmt.Errorf("All primary keys were not accounted for. Provided: %v; Required; %v", ckeys, pkeys)
}
query := fmt.Sprintf("DELETE FROM %v WHERE %v;", m.Namespace(), strings.Join(ckeys, " AND "))
_, err = s.Exec(query, vals...)
return err
}
func updateMsg(m message.Msg, s *sql.DB) error {
log.With("table", m.Namespace()).Debugln("UPDATE")
var (
ckeys []string
ukeys []string
vals []interface{}
)
pkeys, err := primaryKeys(m.Namespace(), s)
if err != nil {
return err
}
i := 1
for key, value := range m.Data() {
if pkeys[key] { // key is primary key
ckeys = append(ckeys, fmt.Sprintf("%v=$%v", key, i))
} else {
ukeys = append(ukeys, fmt.Sprintf("%v=$%v", key, i))
}
switch value.(type) {
case map[string]interface{}, mejson.M, []map[string]interface{}, mejson.S:
value, _ = json.Marshal(value)
case []interface{}:
value, _ = json.Marshal(value)
value = string(value.([]byte))
value = fmt.Sprintf("{%v}", value.(string)[1:len(value.(string))-1])
}
vals = append(vals, value)
i = i + 1
}
if len(pkeys) != len(ckeys) {
return fmt.Errorf("All primary keys were not accounted for. Provided: %v; Required; %v", ckeys, pkeys)
}
query := fmt.Sprintf("UPDATE %v SET %v WHERE %v;", m.Namespace(), strings.Join(ukeys, ", "), strings.Join(ckeys, " AND "))
_, err = s.Exec(query, vals...)
return err
}
func primaryKeys(namespace string, db *sql.DB) (primaryKeys map[string]bool, err error) {
primaryKeys = map[string]bool{}
namespaceArray := strings.SplitN(namespace, ".", 2)
var (
tableSchema string
tableName string
columnName string
)
if namespaceArray[1] == "" {
tableSchema = "public"
tableName = namespaceArray[0]
} else {
tableSchema = namespaceArray[0]
tableName = namespaceArray[1]
}
tablesResult, err := db.Query(fmt.Sprintf(`
SELECT
column_name
FROM information_schema.table_constraints constraints
INNER JOIN information_schema.constraint_column_usage column_map
ON column_map.constraint_name = constraints.constraint_name
WHERE constraints.constraint_type = 'PRIMARY KEY'
AND constraints.table_schema = '%v'
AND constraints.table_name = '%v'
`, tableSchema, tableName))
if err != nil {
return primaryKeys, err
}
for tablesResult.Next() {
err = tablesResult.Scan(&columnName)
if err != nil {
return primaryKeys, err
}
primaryKeys[columnName] = true
}
return primaryKeys, err
}