-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathwrite_doc.go
225 lines (167 loc) · 5.12 KB
/
write_doc.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
// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
// and to You under the Apache License, Version 2.0. See LICENSE in project root for full license + copyright.
package keynuker
import (
"context"
"fmt"
f "github.com/fauna/faunadb-go/faunadb"
"github.com/go-kivik/kivik"
_ "github.com/tleyden/couchdb" // The CouchDB driver
"strings"
"log"
)
// Write an object specified in params to the underlying database, and return the
// written object back.
func WriteDocToDb(params ParamsWriteDoc) (interface{}, error) {
switch {
case params.IsCloudantDb():
return WriteDocToCloudant(params)
case params.IsFaunaDb():
return WriteDocToFauna(params)
default:
return nil, fmt.Errorf("Unrecognized DB host: %v", params.Host)
}
}
func CreateDBClient(params ParamsWriteDoc) (db *kivik.DB, err error) {
ctx := context.TODO()
// NOTE regarding http vs https. I was previously using https, but I needed to revert to http
// due to the following issue w/ Cloudant: https://gist.github.com/tleyden/d8c69f6cee3a2b32a7a1609539a1dade (filed to Cloudant support)
dataSourceName := fmt.Sprintf(
"https://%s:%s@%s",
params.Username,
params.Password,
params.Host,
)
client, err := kivik.New(ctx, "couch", dataSourceName)
if err != nil {
return nil, err
}
return client.DB(ctx, params.DbName)
}
func WriteDocToCloudant(params ParamsWriteDoc) (interface{}, error) {
ctx := context.TODO()
db, err := CreateDBClient(params)
if err != nil {
return nil, err
}
// After maxTries, give up.. this far too many CAS errors than expected under normal operations
maxTries := 100
numTries := 0
var lastErr error
// Cas loop where we get the latest rev of the doc
for {
if numTries >= maxTries {
return nil, fmt.Errorf("Giving up after %d tries. Last error: %v", numTries, lastErr)
}
numTries++
fetchedDocRow := db.Get(ctx, params.DocId)
// Try to get existing doc
fetchedDoc := map[string]interface{}{}
scanDocErr := fetchedDocRow.ScanDoc(&fetchedDoc)
if scanDocErr != nil {
// Assume this will be the first rev of the doc, so do nothing in this case
} else {
// Got an existing doc, update the doc being inserted to be based on this rev
// we had a valid previous rev
revRaw, ok := fetchedDoc["_rev"]
if !ok {
return nil, fmt.Errorf("Doc does not have _rev field. Doc: %+v", fetchedDoc)
}
rev := revRaw.(string)
params.Doc["_rev"] = rev
}
_, err = db.Put(context.TODO(), params.DocId, params.Doc)
if err != nil {
// If it it's a bad request, abort immediately
if strings.Contains(err.Error(), "Bad Request") {
return nil, err
}
// Assume this is a 409 conflict error
// TODO: do better error matching here to distinguish 409 conflict errors, otherwise will end up in toxic busy loop
log.Printf("Error putting doc %v into db. Err: %v. Assuming 409 conflict error, retrying", params.DocId, err)
lastErr = err
continue
}
break
}
// Read the doc back from the DB
fetchedDocRow := db.Get(ctx, params.DocId)
fetchedDoc := map[string]interface{}{}
scanDocErr := fetchedDocRow.ScanDoc(&fetchedDoc)
if scanDocErr != nil {
return nil, scanDocErr
}
return fetchedDoc, nil
}
func DeleteDoc(params ParamsWriteDoc, rev string) (newRev string, err error) {
ctx := context.TODO()
db, err := CreateDBClient(params)
if err != nil {
return "", err
}
return db.Delete(ctx, params.DocId, rev)
}
type ParamsWriteDoc struct {
Username string
Password string
Host string
DbName string
Doc map[string]interface{}
DocId string
}
func (p ParamsWriteDoc) IsCloudantDb() bool {
return strings.Contains(p.Host, "cloudant")
}
func (p ParamsWriteDoc) IsFaunaDb() bool {
return strings.Contains(p.Host, "fauna")
}
// Experimenting w/ FaunaDB
var (
data = f.ObjKey("data")
ref = f.ObjKey("ref")
)
func WriteDocToFauna(params ParamsWriteDoc) (interface{}, error) {
client := f.NewFaunaClient(params.Password)
// Concats a string .. just testing
res, err := client.Query(f.Concat([]string{"Hello", "World"}))
if err != nil {
panic(err)
}
fmt.Println(res)
// TODO: how do I lazily create a class if it doesn't already exist? Just try it and ignore 400 error?
//val, err := client.Query(f.CreateClass(f.Obj{"name": params.DocId}))
//if err != nil {
// return nil, err
//}
val, err := client.Query(
f.Create(
f.Class(params.DocId),
f.Obj{"data": f.Obj(params.Doc)},
),
)
if err != nil {
return nil, err
}
fmt.Printf("Val: %v\n", val)
// TODO: I want to read the doc back out of the db, how do I get the ref?
// Read the doc back
val, err = client.Query(f.Get(f.Ref("classes/TestDoc/172286141322494465")))
if err != nil {
return nil, err
}
readTestDoc := map[string]interface{}{}
//err = val.Get(&readTestDoc)
//if err != nil {
// return nil, err
//}
_ = val.At(data).Get(&readTestDoc)
// fmt.Printf("readTestDoc: %+v", readTestDoc)
readTestDoc2 := f.ObjectV{}
_ = val.At(data).Get(&readTestDoc2)
readTestDoc2Bytes, err := readTestDoc2.MarshalJSON()
if err != nil {
return nil, err
}
fmt.Printf("readTestDoc2Bytes: %v", string(readTestDoc2Bytes))
return readTestDoc, nil
}