-
Notifications
You must be signed in to change notification settings - Fork 36
/
write.go
330 lines (284 loc) · 12.2 KB
/
write.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package gorqlite
import (
"context"
"encoding/json"
"errors"
"fmt"
)
/* *****************************************************************
method: Connection.Write()
This is the JSON we get back:
{
"results": [
{
"last_insert_id": 1,
"rows_affected": 1,
"time": 0.00759015
},
{
"last_insert_id": 2,
"rows_affected": 1,
"time": 0.00669015
}
],
"time": 0.869015
}
or
{
"results": [
{
"error": "table foo already exists"
}
],
"time": 0.18472685400000002
}
We don't care about the overall time. We just want the results,
so we'll take those and put each into a WriteResult
Because the results themselves are smaller than the JSON
(which repeats strings like "last_insert_id" frequently),
we'll just parse everything at once.
* *****************************************************************/
// WriteOne wraps Write() into a single-statement
// method.
//
// WriteOne uses context.Background() internally; to specify the context, use WriteOneContext.
func (conn *Connection) WriteOne(sqlStatement string) (wr WriteResult, err error) {
wra, err := conn.Write([]string{sqlStatement})
return wra[0], err
}
// WriteOneContext wraps WriteContext() into a single-statement
func (conn *Connection) WriteOneContext(ctx context.Context, sqlStatement string) (wr WriteResult, err error) {
wra, err := conn.WriteContext(ctx, []string{sqlStatement})
return wra[0], err
}
// WriteOneParameterized wraps WriteParameterized() into a single-statement method.
//
// WriteOneParameterized uses context.Background() internally; to specify the context, use WriteOneParameterizedContext.
func (conn *Connection) WriteOneParameterized(statement ParameterizedStatement) (wr WriteResult, err error) {
wra, err := conn.WriteParameterized([]ParameterizedStatement{statement})
return wra[0], err
}
// WriteOneParameterizedContext wraps WriteParameterizedContext into
// a single-statement method.
func (conn *Connection) WriteOneParameterizedContext(ctx context.Context, statement ParameterizedStatement) (wr WriteResult, err error) {
wra, err := conn.WriteParameterizedContext(ctx, []ParameterizedStatement{statement})
return wra[0], err
}
// Write is used to perform DDL/DML in the database synchronously without parameters.
//
// Write uses context.Background() internally; to specify the context, use WriteContext.
// To use Write with parameterized queries, use WriteParameterized.
func (conn *Connection) Write(sqlStatements []string) (results []WriteResult, err error) {
parameterizedStatements := make([]ParameterizedStatement, 0, len(sqlStatements))
for _, sqlStatement := range sqlStatements {
parameterizedStatements = append(parameterizedStatements, ParameterizedStatement{
Query: sqlStatement,
})
}
return conn.WriteParameterized(parameterizedStatements)
}
// WriteContext is used to perform DDL/DML in the database synchronously without parameters.
//
// To use WriteContext with parameterized queries, use WriteParameterizedContext.
func (conn *Connection) WriteContext(ctx context.Context, sqlStatements []string) (results []WriteResult, err error) {
parameterizedStatements := make([]ParameterizedStatement, 0, len(sqlStatements))
for _, sqlStatement := range sqlStatements {
parameterizedStatements = append(parameterizedStatements, ParameterizedStatement{
Query: sqlStatement,
})
}
return conn.WriteParameterizedContext(ctx, parameterizedStatements)
}
// WriteParameterized is used to perform DDL/DML in the database synchronously.
//
// WriteParameterized takes an array of SQL statements, and returns an equal-sized array of WriteResults,
// each corresponding to the SQL statement that produced it.
//
// All statements are executed as a single transaction.
//
// WriteParameterized returns an error if one is encountered during its operation.
// If it's something like a call to the rqlite API, then it'll return that error.
// If one statement out of several has an error, it will return a generic
// "there were %d statement errors" and you'll have to look at the individual statement's Err for more info.
//
// WriteParameterized uses context.Background() internally; to specify the context, use WriteParameterizedContext.
func (conn *Connection) WriteParameterized(sqlStatements []ParameterizedStatement) (results []WriteResult, err error) {
return conn.WriteParameterizedContext(context.Background(), sqlStatements)
}
func (conn *Connection) parseWriteResult(thisResult map[string]interface{}) WriteResult {
var wr WriteResult
// did we get an error?
_, ok := thisResult["error"]
if ok {
trace("%s: have an error on this result: %s", conn.ID, thisResult["error"].(string))
wr.Err = errors.New(thisResult["error"].(string))
return wr
}
_, ok = thisResult["last_insert_id"]
if ok {
wr.LastInsertID = int64(thisResult["last_insert_id"].(float64))
}
_, ok = thisResult["rows_affected"] // could be zero for a CREATE
if ok {
wr.RowsAffected = int64(thisResult["rows_affected"].(float64))
}
_, ok = thisResult["time"] // could be nil
if ok {
wr.Timing = thisResult["time"].(float64)
}
trace("%s: this result (LII,RA,T): %d %d %f", conn.ID, wr.LastInsertID, wr.RowsAffected, wr.Timing)
return wr
}
// WriteParameterizedContext is used to perform DDL/DML in the database synchronously.
//
// WriteParameterizedContext takes an array of SQL statements, and returns an equal-sized array of WriteResults,
// each corresponding to the SQL statement that produced it.
//
// All statements are executed as a single transaction.
//
// WriteParameterizedContext returns an error if one is encountered during its operation.
// If it's something like a call to the rqlite API, then it'll return that error.
// If one statement out of several has an error, it will return a generic
// "there were %d statement errors" and you'll have to look at the individual statement's Err for more info.
func (conn *Connection) WriteParameterizedContext(ctx context.Context, sqlStatements []ParameterizedStatement) (results []WriteResult, err error) {
results = make([]WriteResult, 0)
if conn.hasBeenClosed {
var errResult WriteResult
errResult.Err = ErrClosed
results = append(results, errResult)
return results, ErrClosed
}
trace("%s: Write() for %d statements", conn.ID, len(sqlStatements))
response, err := conn.rqliteApiPost(ctx, api_WRITE, sqlStatements)
if err != nil {
trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error())
var errResult WriteResult
errResult.Err = err
results = append(results, errResult)
return results, err
}
trace("%s: rqliteApiCall() OK", conn.ID)
var sections map[string]interface{}
err = json.Unmarshal(response, §ions)
if err != nil {
trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error())
var errResult WriteResult
errResult.Err = err
results = append(results, errResult)
return results, err
}
// at this point, we have a "results" section and
// a "time" section. we can igore the latter.
resultsArray, ok := sections["results"].([]interface{})
if !ok {
err = errors.New("result key is missing from response")
trace("%s: sections[\"results\"] ERROR: %s", conn.ID, err)
var errResult WriteResult
errResult.Err = err
results = append(results, errResult)
return results, err
}
trace("%s: I have %d result(s) to parse", conn.ID, len(resultsArray))
numStatementErrors := 0
for n, k := range resultsArray {
trace("%s: starting on result %d", conn.ID, n)
wr := conn.parseWriteResult(k.(map[string]interface{}))
wr.conn = conn
results = append(results, wr)
if wr.Err != nil {
numStatementErrors += 1
}
}
trace("%s: finished parsing, returning %d results", conn.ID, len(results))
if numStatementErrors > 0 {
return results, fmt.Errorf("there were %d statement errors", numStatementErrors)
} else {
return results, nil
}
}
// QueueOne is a convenience method that wraps Queue into a single-statement.
//
// QueueOne uses context.Background() internally; to specify the context, use QueueOneContext.
func (conn *Connection) QueueOne(sqlStatement string) (seq int64, err error) {
sqlStatements := make([]string, 0)
sqlStatements = append(sqlStatements, sqlStatement)
return conn.Queue(sqlStatements)
}
// QueueOneContext is a convenience method that wraps QueueContext into a single-statement
func (conn *Connection) QueueOneContext(ctx context.Context, sqlStatement string) (seq int64, err error) {
return conn.QueueContext(ctx, []string{sqlStatement})
}
// QueueOneParameterized is a convenience method that wraps QueueParameterized into a single-statement method.
//
// QueueOneParameterized uses context.Background() internally; to specify the context, use QueueOneParameterizedContext.
func (conn *Connection) QueueOneParameterized(statement ParameterizedStatement) (seq int64, err error) {
return conn.QueueParameterized([]ParameterizedStatement{statement})
}
// QueueOneParameterizedContext is a convenience method that wraps QueueParameterizedContext() into a single-statement method.
func (conn *Connection) QueueOneParameterizedContext(ctx context.Context, statement ParameterizedStatement) (seq int64, err error) {
return conn.QueueParameterizedContext(ctx, []ParameterizedStatement{statement})
}
// Queue is used to perform asynchronous writes to the rqlite database as defined in the documentation:
// https://github.com/rqlite/rqlite/blob/master/DOC/QUEUED_WRITES.md
//
// Queue uses context.Background() internally; to specify the context, use QueueContext.
// To use Queue with parameterized queries, use QueueParameterized.
func (conn *Connection) Queue(sqlStatements []string) (seq int64, err error) {
return conn.QueueContext(context.Background(), sqlStatements)
}
// QueueContext is used to perform asynchronous writes to the rqlite database as defined in the documentation:
// https://github.com/rqlite/rqlite/blob/master/DOC/QUEUED_WRITES.md
//
// To use QueueContext with parameterized queries, use QueueParameterizedContext.
func (conn *Connection) QueueContext(ctx context.Context, sqlStatements []string) (seq int64, err error) {
parameterizedStatements := make([]ParameterizedStatement, 0)
for _, sqlStatement := range sqlStatements {
parameterizedStatements = append(parameterizedStatements, ParameterizedStatement{Query: sqlStatement})
}
return conn.QueueParameterizedContext(ctx, parameterizedStatements)
}
// QueueParameterized is used to perform asynchronous writes with parameterized queries
// to the rqlite database as defined in the documentation:
// https://github.com/rqlite/rqlite/blob/master/DOC/QUEUED_WRITES.md
//
// QueueParameterized uses context.Background() internally; to specify the context, use QueueParameterizedContext.
func (conn *Connection) QueueParameterized(sqlStatements []ParameterizedStatement) (seq int64, err error) {
return conn.QueueParameterizedContext(context.Background(), sqlStatements)
}
// QueueParameterizedContext is used to perform asynchronous writes with parameterized queries
// to the rqlite database as defined in the documentation:
// https://github.com/rqlite/rqlite/blob/master/DOC/QUEUED_WRITES.md
func (conn *Connection) QueueParameterizedContext(ctx context.Context, sqlStatements []ParameterizedStatement) (seq int64, err error) {
if conn.hasBeenClosed {
return 0, ErrClosed
}
trace("%s: Write() for %d statements", conn.ID, len(sqlStatements))
// Set queuing mode just for this call.
conn.wantsQueueing = true
defer func() {
conn.wantsQueueing = false
}()
response, err := conn.rqliteApiPost(ctx, api_WRITE, sqlStatements)
if err != nil {
trace("%s: rqliteApiCall() ERROR: %s", conn.ID, err.Error())
return 0, err
}
trace("%s: rqliteApiCall() OK", conn.ID)
var sections map[string]interface{}
err = json.Unmarshal(response, §ions)
if err != nil {
trace("%s: json.Unmarshal() ERROR: %s", conn.ID, err.Error())
return 0, err
}
return int64(sections["sequence_number"].(float64)), nil
}
// WriteResult holds the result of a single statement sent to Write().
//
// Write() returns an array of WriteResult vars, while WriteOne() returns a single WriteResult.
type WriteResult struct {
Err error // don't trust the rest if this isn't nil
Timing float64
RowsAffected int64 // affected by the change
LastInsertID int64 // if relevant, otherwise zero value
conn *Connection
}