-
Notifications
You must be signed in to change notification settings - Fork 7
/
stmt_collection.go
371 lines (331 loc) · 10.7 KB
/
stmt_collection.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package gocosmos
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
// StmtCreateCollection implements "CREATE COLLECTION" statement.
//
// Syntax:
//
// CREATE COLLECTION|TABLE [IF NOT EXISTS] [<db-name>.]<collection-name>
// <WITH PK=partitionKey>
// [[,] WITH RU|MAXRU=ru]
// [[,] WITH UK=/path1:/path2,/path3;/path4]
//
// - ru: an integer specifying CosmosDB's collection throughput expressed in RU/s. Supply either RU or MAXRU, not both!
//
// - partitionKey is either single (single value of /path) or hierarchical, up to 3 path levels, levels are separated by commas, for example: /path1,/path2,/path3.
//
// - If "IF NOT EXISTS" is specified, Exec will silently swallow the error "409 Conflict".
//
// - Use UK to define unique keys. Each unique key consists a list of paths separated by comma (,). Unique keys are separated by colons (:) or semi-colons (;).
type StmtCreateCollection struct {
*Stmt
dbName string
collName string // collection name
ifNotExists bool
ru, maxru int
pk string // partition key
uk [][]string // unique keys
}
// String implements fmt.Stringer/String.
//
// @Available since v1.1.0
func (s *StmtCreateCollection) String() string {
return fmt.Sprintf(`StmtCreateCollection{Stmt: %s, db: %q, collection: %q, if_not_exists: %t, ru: %d, maxru: %d, pk: %q, uk: %v}`,
s.Stmt, s.dbName, s.collName, s.ifNotExists, s.ru, s.maxru, s.pk, s.uk)
}
func (s *StmtCreateCollection) parse(withOptsStr string) error {
if err := s.Stmt.parseWithOpts(withOptsStr); err != nil {
return err
}
for k, v := range s.withOpts {
switch k {
case "PK", "LARGEPK":
if s.pk != "" {
return fmt.Errorf("only one of PK or LARGEPK must be specified")
}
s.pk = v
case "RU":
ru, err := strconv.ParseInt(v, 10, 32)
if err != nil || ru < 0 {
return fmt.Errorf("invalid RU value: %s", v)
}
s.ru = int(ru)
case "MAXRU":
maxru, err := strconv.ParseInt(v, 10, 32)
if err != nil || maxru < 0 {
return fmt.Errorf("invalid MAXRU value: %s", v)
}
s.maxru = int(maxru)
case "UK":
tokens := regexp.MustCompile(`[;:]+`).Split(v, -1)
for _, token := range tokens {
paths := regexp.MustCompile(`[,\s]+`).Split(token, -1)
s.uk = append(s.uk, paths)
}
default:
return fmt.Errorf("invalid query, parsing error at WITH %s=%s", k, v)
}
}
return nil
}
func (s *StmtCreateCollection) validate() error {
if s.pk == "" {
return fmt.Errorf("missing PartitionKey value")
}
if s.ru > 0 && s.maxru > 0 {
return errors.New("only one of RU or MAXRU should be specified")
}
if s.dbName == "" || s.collName == "" {
return errors.New("database/collection is missing")
}
return nil
}
// Query implements driver.Stmt/Query.
// This function is not implemented, use Exec instead.
func (s *StmtCreateCollection) Query(_ []driver.Value) (driver.Rows, error) {
return nil, ErrQueryNotSupported
}
// Exec implements driver.Stmt/Exec.
func (s *StmtCreateCollection) Exec(args []driver.Value) (driver.Result, error) {
return s.ExecContext(context.Background(), _valuesToNamedValues(args))
}
// ExecContext implements driver.StmtExecContext/ExecContext.
//
// @Available since v1.1.0
func (s *StmtCreateCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error) {
if len(args) != 0 {
return nil, fmt.Errorf("expected 0 input value, got %d", len(args))
}
pkPaths := strings.Split(s.pk, ",")
pkType := "Hash"
if len(pkPaths) > 1 {
pkType = "MultiHash"
}
spec := CollectionSpec{DbName: s.dbName, CollName: s.collName, Ru: s.ru, MaxRu: s.maxru,
PartitionKeyInfo: map[string]interface{}{
"paths": pkPaths,
"kind": pkType,
"version": 2,
},
}
if len(s.uk) > 0 {
uniqueKeys := make([]interface{}, 0)
for _, uk := range s.uk {
uniqueKeys = append(uniqueKeys, map[string][]string{"paths": uk})
}
spec.UniqueKeyPolicy = map[string]interface{}{"uniqueKeys": uniqueKeys}
}
// TODO: pass ctx to REST API client
restResult := s.conn.restClient.CreateCollection(spec)
ignoreErrorCode := 0
if s.ifNotExists {
ignoreErrorCode = 409
}
result := buildResultNoResultSet(&restResult.RestResponse, true, restResult.Rid, ignoreErrorCode)
return result, result.err
}
/*----------------------------------------------------------------------*/
// StmtAlterCollection implements "ALTER COLLECTION" statement.
//
// Syntax:
//
// ALTER COLLECTION|TABLE [<db-name>.]<collection-name> WITH RU|MAXRU=<ru>
//
// - ru: an integer specifying CosmosDB's collection throughput expressed in RU/s. Supply either RU or MAXRU, not both!
//
// Available since v0.1.1
type StmtAlterCollection struct {
*Stmt
dbName string
collName string // collection name
ru, maxru int
}
// String implements fmt.Stringer/String.
//
// @Available since v1.1.0
func (s *StmtAlterCollection) String() string {
return fmt.Sprintf(`StmtAlterCollection{Stmt: %s, db: %q, collection: %q, ru: %d, maxru: %d}`,
s.Stmt, s.dbName, s.collName, s.ru, s.maxru)
}
func (s *StmtAlterCollection) parse(withOptsStr string) error {
if err := s.Stmt.parseWithOpts(withOptsStr); err != nil {
return err
}
for k, v := range s.withOpts {
switch k {
case "RU":
ru, err := strconv.ParseInt(v, 10, 32)
if err != nil || ru < 0 {
return fmt.Errorf("invalid RU value: %s", v)
}
s.ru = int(ru)
case "MAXRU":
maxru, err := strconv.ParseInt(v, 10, 32)
if err != nil || maxru < 0 {
return fmt.Errorf("invalid MAXRU value: %s", v)
}
s.maxru = int(maxru)
default:
return fmt.Errorf("invalid query, parsing error at WITH %s=%s", k, v)
}
}
return nil
}
func (s *StmtAlterCollection) validate() error {
if (s.ru <= 0 && s.maxru <= 0) || (s.ru > 0 && s.maxru > 0) {
return errors.New("only one of RU or MAXRU should be specified")
}
if s.dbName == "" || s.collName == "" {
return errors.New("database/collection is missing")
}
return nil
}
// Query implements driver.Stmt/Query.
// This function is not implemented, use Exec instead.
func (s *StmtAlterCollection) Query(_ []driver.Value) (driver.Rows, error) {
return nil, ErrQueryNotSupported
}
// Exec implements driver.Stmt/Exec.
func (s *StmtAlterCollection) Exec(args []driver.Value) (driver.Result, error) {
return s.ExecContext(context.Background(), _valuesToNamedValues(args))
}
// ExecContext implements driver.StmtExecContext/ExecContext.
//
// @Available since v1.1.0
func (s *StmtAlterCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error) {
if len(args) != 0 {
return nil, fmt.Errorf("expected 0 input value, got %d", len(args))
}
getResult := s.conn.restClient.GetCollection(s.dbName, s.collName)
if err := getResult.Error(); err != nil {
switch getResult.StatusCode {
case 403:
return nil, ErrForbidden
case 404:
return nil, ErrNotFound
}
return nil, err
}
// TODO: pass ctx to REST API client
restResult := s.conn.restClient.ReplaceOfferForResource(getResult.Rid, s.ru, s.maxru)
result := buildResultNoResultSet(&restResult.RestResponse, true, restResult.Rid, 0)
return result, result.err
}
/*----------------------------------------------------------------------*/
// StmtDropCollection implements "DROP COLLECTION" statement.
//
// Syntax:
//
// DROP COLLECTION|TABLE [IF EXISTS] [<db-name>.]<collection-name>
//
// If "IF EXISTS" is specified, Exec will silently swallow the error "404 Not Found".
type StmtDropCollection struct {
*Stmt
dbName string
collName string
ifExists bool
}
// String implements fmt.Stringer/String.
//
// @Available since v1.1.0
func (s *StmtDropCollection) String() string {
return fmt.Sprintf(`StmtDropCollection{Stmt: %s, db: %q, collection: %q, if_exists: %t}`,
s.Stmt, s.dbName, s.collName, s.ifExists)
}
func (s *StmtDropCollection) validate() error {
if s.dbName == "" || s.collName == "" {
return errors.New("database/collection is missing")
}
return nil
}
// Query implements driver.Stmt/Query.
// This function is not implemented, use Exec instead.
func (s *StmtDropCollection) Query(_ []driver.Value) (driver.Rows, error) {
return nil, ErrQueryNotSupported
}
// Exec implements driver.Stmt/Exec.
func (s *StmtDropCollection) Exec(args []driver.Value) (driver.Result, error) {
return s.ExecContext(context.Background(), _valuesToNamedValues(args))
}
// ExecContext implements driver.StmtExecContext/ExecContext.
//
// @Available since v1.1.0
func (s *StmtDropCollection) ExecContext(_ context.Context, args []driver.NamedValue) (driver.Result, error) {
if len(args) != 0 {
return nil, fmt.Errorf("expected 0 input value, got %d", len(args))
}
// TODO: pass ctx to REST API client
restResult := s.conn.restClient.DeleteCollection(s.dbName, s.collName)
ignoreErrorCode := 0
if s.ifExists {
ignoreErrorCode = 404
}
result := buildResultNoResultSet(&restResult.RestResponse, false, "", ignoreErrorCode)
return result, result.err
}
/*----------------------------------------------------------------------*/
// StmtListCollections implements "LIST DATABASES" statement.
//
// Syntax:
//
// LIST COLLECTIONS|TABLES|COLLECTION|TABLE [FROM <db-name>]
type StmtListCollections struct {
*Stmt
dbName string
}
// String implements fmt.Stringer/String.
//
// @Available since v1.1.0
func (s *StmtListCollections) String() string {
return fmt.Sprintf(`StmtListCollections{Stmt: %s, db: %q}`, s.Stmt, s.dbName)
}
func (s *StmtListCollections) validate() error {
if s.dbName == "" {
return errors.New("database is missing")
}
return nil
}
// Exec implements driver.Stmt/Exec.
// This function is not implemented, use Query instead.
func (s *StmtListCollections) Exec(_ []driver.Value) (driver.Result, error) {
return nil, ErrExecNotSupported
}
// Query implements driver.Stmt/Query.
func (s *StmtListCollections) Query(args []driver.Value) (driver.Rows, error) {
return s.QueryContext(context.Background(), _valuesToNamedValues(args))
}
// QueryContext implements driver.StmtQueryContext/QueryContext.
//
// @Available since v1.1.0
func (s *StmtListCollections) QueryContext(_ context.Context, args []driver.NamedValue) (driver.Rows, error) {
if len(args) != 0 {
return nil, fmt.Errorf("expected 0 input value, got %d", len(args))
}
// TODO: pass ctx to REST API client
restResult := s.conn.restClient.ListCollections(s.dbName)
result := &ResultResultSet{
err: restResult.Error(),
columnList: []string{"id", "indexingPolicy", "_rid", "_ts", "_self", "_etag", "_docs", "_sprocs", "_triggers", "_udfs", "_conflicts"},
}
if result.err == nil {
result.count = len(restResult.Collections)
result.rows = make([]DocInfo, result.count)
for i, coll := range restResult.Collections {
result.rows[i] = coll.toMap()
}
}
switch restResult.StatusCode {
case 403:
result.err = ErrForbidden
case 404:
result.err = ErrNotFound
}
return result, result.err
}