-
Notifications
You must be signed in to change notification settings - Fork 6
/
query.go
2038 lines (1922 loc) · 53.9 KB
/
query.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rethinkgo
// Let user create queries as RQL Exp trees, any errors are deferred
// until the query is run, so most all functions take interface{} types.
// interface{} is effectively a void* type that we look at later to determine
// the underlying type and perform any conversions.
// Map is a shorter name for a mapping from strings to arbitrary objects
type Map map[string]interface{}
// List is a shorter name for an array of arbitrary objects
type List []interface{}
type expressionKind int
const (
addKind expressionKind = iota
allKind
anyKind
appendKind
ascendingKind
betweenKind
branchKind
changeAtKind
coerceToKind
concatMapKind
containsKind
countKind
databaseCreateKind
databaseDropKind
databaseKind
databaseListKind
deleteAtKind
deleteKind
descendingKind
differenceKind
distinctKind
divideKind
defaultKind
eqJoinKind
equalityKind
errorKind
filterKind
forEachKind
funcallKind
funcKind
getAllKind
getFieldKind
getKind
greaterThanKind
greaterThanOrEqualKind
groupByKind
groupedMapReduceKind
hasFieldsKind
implicitVariableKind
indexCreateKind
indexDropKind
indexesOfKind
indexListKind
inequalityKind
infoKind
innerJoinKind
insertAtKind
insertKind
isEmptyKind
javascriptKind
jsonKind
keysKind
lessThanKind
lessThanOrEqualKind
limitKind
logicalNotKind
mapKind
matchKind
mergeKind
moduloKind
multiplyKind
nthKind
orderByKind
outerJoinKind
pluckKind
prependKind
reduceKind
returnValuesKind
replaceKind
sampleKind
setDifferenceKind
setInsertKind
setIntersectionKind
setUnionKind
skipKind
sliceKind
spliceAtKind
subtractKind
tableCreateKind
tableDropKind
tableKind
tableListKind
typeOfKind
unionKind
updateKind
variableKind
withFieldsKind
withoutKind
zipKind
// custom rethinkgo ones
upsertKind
atomicKind
useOutdatedKind
durabilityKind
literalKind
)
func nullaryOperator(kind expressionKind) Exp {
return Exp{kind: kind}
}
func naryOperator(kind expressionKind, operand interface{}, operands ...interface{}) Exp {
args := []interface{}{operand}
args = append(args, operands...)
return Exp{kind: kind, args: args}
}
func stringsToInterfaces(strings []string) []interface{} {
interfaces := make([]interface{}, len(strings))
for i, v := range strings {
interfaces[i] = interface{}(v)
}
return interfaces
}
func funcWrapper(f interface{}, arity int) Exp {
return naryOperator(funcKind, f, arity)
}
// Exp represents an RQL expression, such as the return value of
// r.Expr(). Exp has all the RQL methods on it, such as .Add(), .Attr(),
// .Filter() etc.
//
// To create an Exp from a native or user-defined type, or function, use
// r.Expr().
//
// Example usage:
//
// r.Expr(2).Mul(2) => 4
//
// Exp is the type used for the arguments to any functions that are used
// in RQL.
//
// Example usage:
//
// var response []interface{}
// // Get the intelligence rating for each of our heroes
// getIntelligence := func(row r.Exp) r.Exp {
// return row.Attr("intelligence")
// }
// err := r.Table("heroes").Map(getIntelligence).Run(session).All(&response)
//
// Example response:
//
// [7, 5, 4, 6, 2, 2, 6, 4, ...]
//
// Literal Expressions can be used directly for queries.
//
// Example usage:
//
// var squares []int
// // Square a series of numbers
// square := func(row r.Exp) r.Exp { return row.Mul(row) }
// err := r.Expr(1,2,3).Map(square).Run(session).One(&squares)
//
// Example response:
//
// [1, 2, 3]
type Exp struct { // this would be Expr, but then it would conflict with the function that creates Exp instances
args []interface{}
kind expressionKind
}
// Row supplies access to the current row in any query, even if there's no go
// func with a reference to it.
//
// Example without Row:
//
// var response []interface{}
// // Get the real names of all the villains
// err := r.Table("villains").Map(func(row r.Exp) r.Exp {
// return row.Attr("real_name")
// }).Run(session).All(&response)
//
// Example with Row:
//
// var response []interface{}
// // Get the real names of all the villains
// err := r.Table("employees").Map(Row.Attr("real_name")).Run(session).All(&response)
//
// Example response:
//
// ["En Sabah Nur", "Victor von Doom", ...]
var Row = Exp{kind: implicitVariableKind}
// Expr converts any value to an expression. Internally it uses the `json`
// module to convert any literals, so any type annotations or methods understood
// by that module can be used. If the value cannot be converted, an error is
// returned at query .Run(session) time.
//
// If you want to call expression methods on an object that is not yet an
// expression, this is the function you want.
//
// Example usage:
//
// var response interface{}
// rows := r.Expr(r.Map{"go": "awesome", "rethinkdb": "awesomer"}).Run(session).One(&response)
//
// Example response:
//
// {"go": "awesome", "rethinkdb": "awesomer"}
func Expr(value interface{}) Exp {
v, ok := value.(Exp) // check if it's already an Exp
if ok {
return v
}
return naryOperator(literalKind, value)
}
// Json creates an object using a literal json string.
//
// Example usage:
//
// var response interface{}
// rows := r.Json(`"go": "awesome", "rethinkdb": "awesomer"}`).Run(session).One(&response)
//
// Example response:
//
// {"go": "awesome", "rethinkdb": "awesomer"}
func Json(value string) Exp {
return naryOperator(jsonKind, value)
}
///////////
// Terms //
///////////
// Js creates an expression using Javascript code. The code is executed
// on the server (using eval() https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval)
// and can be used in a couple of roles, as value or as a function. When used
// as a function, it receives two named arguments, 'row' and/or 'acc' (used for
// reductions).
//
// JsWithTimeout lets you specify a timeout for the javascript expression.
//
// The value of the 'this' object inside Javascript code is the current row.
//
// Example usages:
//
// // (same effect as r.Expr(1,2,3))
// r.Js(`[1,2,3]`).Run(session)
// // Parens are required here, otherwise eval() thinks it's a block.
// r.Js(`({name: 2})`).Run(session)
// // String concatenation is possible using r.Js
// r.Table("employees").Map(r.Js(`this.first_name[0] + ' Fucking ' + this.last_name[0]`)).Run(session)
//
// Example without Js:
//
// var response []interface{}
// // Combine each hero's strength and durability
// err := r.Table("heroes").Map(func(row r.Exp) r.Exp {
// return row.Attr("strength").Add(row.Attr("durability"))
// }).Run(session).All(&response)
//
// Example with Js:
//
// var response []interface{}
// // Combine each hero's strength and durability
// err := r.Table("heroes").Map(
// r.Js(`(function (row) { return row.strength + row.durability; })`),
// ).Run(session).All(&response)
//
// Example response:
//
// [11, 6, 9, 11, ...]
func Js(body string) Exp {
return naryOperator(javascriptKind, body)
}
// JsWithTimeout lets you specify the timeout for a javascript expression to run
// (in seconds). The default value is 5 seconds.
func JsWithTimeout(body string, timeout float64) Exp {
return naryOperator(javascriptKind, body, timeout)
}
// RuntimeError tells the server to respond with a ErrRuntime, useful for
// testing.
//
// Example usage:
//
// err := r.RuntimeError("hi there").Run(session).Err()
func RuntimeError(message string) Exp {
return Exp{kind: errorKind, args: List{message}}
}
// Branch checks a test expression, evaluating the trueBranch expression if it's
// true and falseBranch otherwise.
//
// Example usage:
//
// // Roughly equivalent RQL expression
// r.Branch(r.Row.Attr("first_name").Eq("Marc"), "is probably marc", "who cares")
func Branch(test, trueBranch, falseBranch interface{}) Exp {
return naryOperator(branchKind, test, trueBranch, falseBranch)
}
// Get retrieves a single row by primary key.
//
// Example usage:
//
// var response map[string]interface{}
// err := r.Table("heroes").Get("Doctor Strange").Run(session).One(&response)
//
// Example response:
//
// {
// "strength": 3,
// "name": "Doctor Strange",
// "durability": 6,
// "intelligence": 4,
// "energy": 7,
// "fighting": 7,
// "real_name": "Stephen Vincent Strange",
// "speed": 5,
// "id": "edc3a46b-95a0-4f64-9d1c-0dd7d83c4bcd"
// }
func (e Exp) Get(key interface{}) Exp {
return naryOperator(getKind, e, key)
}
// GetAll retrieves all documents where the given value matches the requested
// index.
//
// Example usage (awesomeness is a secondary index defined as speed * strength):
//
// var response []interface{}
// err := r.Table("heroes").GetAll("awesomeness", 10).Run(session).All(&response)
//
// Example response:
//
// {
// "strength": 2,
// "name": "Storm",
// "durability": 3,
// "intelligence": 5,
// "energy": 6,
// "fighting": 5,
// "real_name": "Ororo Munroe",
// "speed": 5,
// "id": "59d1ad55-a61e-49d9-a375-0fb014b0e6ea"
// }
func (e Exp) GetAll(index string, values ...interface{}) Exp {
return naryOperator(getAllKind, e, append(values, index)...)
}
// GroupBy does a sort of grouped map reduce. First the server groups all rows
// that have the same value for `attribute`, then it applys the map reduce to
// each group. It takes one of the following reductions: r.Count(),
// r.Sum(string), r.Avg(string)
//
// `attribute` must be a single attribute (string) or a list of attributes
// ([]string)
//
// Example usage:
//
// var response []interface{}
// // Find all heroes with the same durability, calculate their average speed
// // to see if more durable heroes are slower.
// err := r.Table("heroes").GroupBy("durability", r.Avg("speed")).Run(session).One(&response)
//
// Example response:
//
// [
// {
// "group": 1, // this is the strength attribute for every member of this group
// "reduction": 1.5 // this is the sum of the intelligence attribute of all members of the group
// },
// {
// "group": 2,
// "reduction": 3.5
// },
// ...
// ]
//
// Example with multiple attributes:
//
// // Find all heroes with the same strength and speed, sum their intelligence
// rows := r.Table("heroes").GroupBy([]string{"strength", "speed"}, r.Count()).Run(session)
func (e Exp) GroupBy(attribute, groupedMapReduce interface{}) Exp {
_, ok := attribute.(string)
if ok {
attribute = List{attribute}
}
return naryOperator(groupByKind, e, attribute, groupedMapReduce)
}
// UseOutdated tells the server to use potentially out-of-date data from all
// tables already specified in this query. The advantage is that read queries
// may be faster if this is set.
//
// Example with single table:
//
// rows := r.Table("heroes").UseOutdated(true).Run(session)
//
// Example with multiple tables (all tables would be allowed to use outdated data):
//
// villain_strength := r.Table("villains").Get("Doctor Doom", "name").Attr("strength")
// compareFunc := r.Row.Attr("strength").Eq(villain_strength)
// rows := r.Table("heroes").Filter(compareFunc).UseOutdated(true).Run(session)
func (e Exp) UseOutdated(useOutdated bool) Exp {
return naryOperator(useOutdatedKind, e, useOutdated)
}
// Durability sets the durability for the expression, this can be set to either
// "soft" or "hard".
//
// Example usage:
//
// var response r.WriteResponse
// r.Table("heroes").Insert(r.Map{"superhero": "Iron Man"}).Durability("soft").Run(session).One(&response)
//
// Example response:
func (e Exp) Durability(durability string) Exp {
return naryOperator(durabilityKind, e, durability)
}
// Attr gets an attribute's value from the row.
//
// Example usage:
//
// r.Expr(r.Map{"key": "value"}).Attr("key") => "value"
func (e Exp) Attr(name string) Exp {
return naryOperator(getFieldKind, e, name)
}
// Add sums two numbers or concatenates two arrays.
//
// Example usage:
//
// r.Expr(1,2,3).Add(r.Expr(4,5,6)) => [1,2,3,4,5,6]
// r.Expr(2).Add(2) => 4
func (e Exp) Add(operand interface{}) Exp {
return naryOperator(addKind, e, operand)
}
// Sub subtracts two numbers.
//
// Example usage:
//
// r.Expr(2).Sub(2) => 0
func (e Exp) Sub(operand interface{}) Exp {
return naryOperator(subtractKind, e, operand)
}
// Mul multiplies two numbers.
//
// Example usage:
//
// r.Expr(2).Mul(3) => 6
func (e Exp) Mul(operand interface{}) Exp {
return naryOperator(multiplyKind, e, operand)
}
// Div divides two numbers.
//
// Example usage:
//
// r.Expr(3).Div(2) => 1.5
func (e Exp) Div(operand interface{}) Exp {
return naryOperator(divideKind, e, operand)
}
// Mod divides two numbers and returns the remainder.
//
// Example usage:
//
// r.Expr(23).Mod(10) => 3
func (e Exp) Mod(operand interface{}) Exp {
return naryOperator(moduloKind, e, operand)
}
// And performs a logical and on two values.
//
// Example usage:
//
// r.Expr(true).And(true) => true
func (e Exp) And(operand interface{}) Exp {
return naryOperator(allKind, e, operand)
}
// Or performs a logical or on two values.
//
// Example usage:
//
// r.Expr(true).Or(false) => true
func (e Exp) Or(operand interface{}) Exp {
return naryOperator(anyKind, e, operand)
}
// Eq returns true if two values are equal.
//
// Example usage:
//
// r.Expr(1).Eq(1) => true
func (e Exp) Eq(operand interface{}) Exp {
return naryOperator(equalityKind, e, operand)
}
// Ne returns true if two values are not equal.
//
// Example usage:
//
// r.Expr(1).Ne(-1) => true
func (e Exp) Ne(operand interface{}) Exp {
return naryOperator(inequalityKind, e, operand)
}
// Gt returns true if the first value is greater than the second.
//
// Example usage:
//
// r.Expr(2).Gt(1) => true
func (e Exp) Gt(operand interface{}) Exp {
return naryOperator(greaterThanKind, e, operand)
}
// Gt returns true if the first value is greater than or equal to the second.
//
// Example usage:
//
// r.Expr(2).Gt(2) => true
func (e Exp) Ge(operand interface{}) Exp {
return naryOperator(greaterThanOrEqualKind, e, operand)
}
// Lt returns true if the first value is less than the second.
//
// Example usage:
//
// r.Expr(1).Lt(2) => true
func (e Exp) Lt(operand interface{}) Exp {
return naryOperator(lessThanKind, e, operand)
}
// Le returns true if the first value is less than or equal to the second.
//
// Example usage:
//
// r.Expr(2).Lt(2) => true
func (e Exp) Le(operand interface{}) Exp {
return naryOperator(lessThanOrEqualKind, e, operand)
}
// Not performs a logical not on a value.
//
// Example usage:
//
// r.Expr(true).Not() => false
func (e Exp) Not() Exp {
return naryOperator(logicalNotKind, e)
}
// Distinct removes duplicate elements from a sequence.
//
// Example usage:
//
// var response []interface{}
// // Get a list of all possible strength values for our heroes
// err := r.Table("heroes").Map(r.Row.Attr("strength")).Distinct().Run(session).All(&response)
//
// Example response:
//
// [7, 1, 6, 4, 2, 5, 3]
func (e Exp) Distinct() Exp {
return naryOperator(distinctKind, e)
}
// Count returns the number of elements in the response.
//
// Example usage:
//
// var response int
// err := r.Table("heroes").Count().Run(session).One(&response)
//
// Example response:
//
// 42
func (e Exp) Count() Exp {
return naryOperator(countKind, e)
}
// Merge combines an object with another object, overwriting properties from
// the first with properties from the second.
//
// Example usage:
//
// var response interface{}
// firstMap := r.Map{"name": "HAL9000", "role": "Support System"}
// secondMap := r.Map{"color": "Red", "role": "Betrayal System"}
// err := r.Expr(firstMap).Merge(secondMap).Run(session).One(&response)
//
// Example response:
//
// {
// "color": "Red",
// "name": "HAL9000",
// "role": "Betrayal System"
// }
func (e Exp) Merge(operand interface{}) Exp {
return naryOperator(mergeKind, e, operand)
}
// Append appends a value to an array.
//
// Example usage:
//
// var response []interface{}
// err := r.Expr(r.List{1, 2, 3, 4}).Append(5).Run(session).One(&response)
//
// Example response:
//
// [1, 2, 3, 4, 5]
func (e Exp) Append(value interface{}) Exp {
return naryOperator(appendKind, e, value)
}
// Union concatenates two sequences.
//
// Example usage:
//
// var response []interface{}
// // Retrieve all heroes and villains
// r.Table("heroes").Union(r.Table("villains")).Run(session).All(&response)
//
// Example response:
//
// [
// {
// "durability": 6,
// "energy": 6,
// "fighting": 3,
// "id": "1a760d0b-57ef-42a8-9fec-c3a1f34930aa",
// "intelligence": 6,
// "name": "Iron Man",
// "real_name": "Anthony Edward \"Tony\" Stark",
// "speed": 5,
// "strength": 6
// },
// ...
// ]
func (e Exp) Union(operands ...interface{}) Exp {
return naryOperator(unionKind, e, operands...)
}
// Nth returns the nth element in sequence, zero-indexed.
//
// Example usage:
//
// var response int
// // Get the second element of an array
// err := r.Expr(4,3,2,1).Nth(1).Run(session).One(&response)
//
// Example response:
//
// 3
func (e Exp) Nth(operand interface{}) Exp {
return naryOperator(nthKind, e, operand)
}
// Slice returns a section of a sequence, with bounds [lower, upper), where
// lower bound is inclusive and upper bound is exclusive.
//
// Example usage:
//
// var response []int
// err := r.Expr(1,2,3,4,5).Slice(2,4).Run(session).One(&response)
//
// Example response:
//
// [3, 4]
func (e Exp) Slice(lower, upper interface{}) Exp {
return naryOperator(sliceKind, e, lower, upper)
}
// Limit returns only the first `limit` results from the query.
//
// Example usage:
//
// var response []int
// err := r.Expr(1,2,3,4,5).Limit(3).Run(session).One(&response)
//
// Example response:
//
// [1, 2, 3]
func (e Exp) Limit(limit interface{}) Exp {
return naryOperator(limitKind, e, limit)
}
// Skip returns all results after the first `start` results. Basically it's the
// opposite of .Limit().
//
// Example usage:
//
// var response []int
// err := r.Expr(1,2,3,4,5).Skip(3).Run(session).One(&response)
//
// Example response:
//
// [4, 5]
func (e Exp) Skip(start interface{}) Exp {
return naryOperator(skipKind, e, start)
}
// Map transforms a sequence by applying the given function to each row.
//
// Example usage:
//
// var squares []int
// // Square a series of numbers
// square := func(row r.Exp) r.Exp { return row.Mul(row) }
// err := r.Expr(1,2,3).Map(square).Run(session).One(&squares)
//
// Example response:
//
// [1, 2, 3]
//
// Example usage:
//
// var heroes []interface{}
// // Fetch multiple rows by primary key
// heroNames := []string{"Iron Man", "Colossus"}
// getHero := func (name r.Exp) r.Exp { return r.Table("heroes").Get(name, "name") }
// err := r.Expr(heroNames).Map(getHero).Run(session).One(&heroes)
//
// Example response:
//
// [
// {
// "durability": 6,
// "energy": 6,
// "fighting": 3,
// "intelligence": 6,
// "name": "Iron Man",
// "real_name": "Anthony Edward \"Tony\" Stark",
// "speed": 5,
// "strength": 6
// },
// ...
// ]
func (e Exp) Map(operand interface{}) Exp {
return naryOperator(mapKind, e, funcWrapper(operand, 1))
}
// ConcatMap constructs a sequence by running the provided function on each row,
// then concatenating all the results.
//
// Example usage:
//
// var flattened []int
// // Flatten some nested lists
// flatten := func(row r.Exp) r.Exp { return row }
// err := r.Expr(r.List{1,2}, r.List{3,4}).ConcatMap(flatten).Run(session).One(&flattened)
//
// Example response:
//
// [1, 2, 3, 4]
//
// Example usage:
//
// var names []string
// // Get all hero real names and aliases in a list
// getNames := func(row r.Exp) interface{} {
// return r.List{row.Attr("name"), row.Attr("real_name")}
// }
// err := r.Table("heroes").ConcatMap(getNames).Run(session).All(&names)
//
// Example response:
//
// ["Captain Britain", "Brian Braddock", "Iceman", "Robert \"Bobby\" Louis Drake", ...]
func (e Exp) ConcatMap(operand interface{}) Exp {
return naryOperator(concatMapKind, e, funcWrapper(operand, 1))
}
// Filter removes all objects from a sequence that do not match the given
// condition. The condition can be an RQL expression, an r.Map, or a function
// that returns true or false.
//
// Example with an RQL expression:
//
// var response []interface{}
// // Get all heroes with durability 6
// err := r.Table("heroes").Filter(r.Row.Attr("durability").Eq(6)).Run(session).All(&response)
//
// Example with r.Map:
//
// err := r.Table("heroes").Filter(r.Map{"durability": 6}).Run(session).All(&response)
//
// Example with function:
//
// filterFunc := func (row r.Exp) r.Exp { return row.Attr("durability").Eq(6) }
// err := r.Table("heroes").Filter(filterFunc).Run(session).All(&response)
//
// Example response:
//
// [
// {
// "durability": 6,
// "energy": 6,
// "fighting": 3,
// "id": "1a760d0b-57ef-42a8-9fec-c3a1f34930aa",
// "intelligence": 6,
// "name": "Iron Man",
// "real_name": "Anthony Edward \"Tony\" Stark",
// "speed": 5,
// "strength": 6
// }
// ...
// ]
func (e Exp) Filter(operand interface{}) Exp {
return naryOperator(filterKind, e, funcWrapper(operand, 1))
}
// HasFields returns true if an object has all the given attributes.
//
// Example usage:
//
// hero := r.Map{"name": "Iron Man", "energy": 6, "speed": 5}
// r.Expr(hero).HasFields("energy", "speed") => true
// r.Expr(hero).HasFields("energy", "guns") => false
func (e Exp) HasFields(keys ...string) Exp {
return naryOperator(hasFieldsKind, e, stringsToInterfaces(keys)...)
}
// Between gets all rows where the key attribute's value falls between the
// lowerbound and upperbound (inclusive). Use nil to represent no upper or
// lower bound. Requires an index on the key (primary keys already have an
// index with the name of the primary key).
//
// Example usage:
//
// var response []interface{}
// // Retrieve all heroes with names between "E" and "F"
// err := r.Table("heroes").Between("name", "E", "F").Run(session).All(&response)
//
// Example response:
//
// {
// "strength": 4,
// "name": "Elektra",
// "durability": 2,
// "intelligence": 4,
// "energy": 3,
// "fighting": 7,
// "real_name": "Elektra Natchios",
// "speed": 6,
// }
func (e Exp) Between(index string, lowerbound, upperbound interface{}) Exp {
return naryOperator(betweenKind, e, lowerbound, upperbound, index)
}
// OrderBy sort the sequence by the values of the given key(s) in each row. The
// default sort is increasing.
//
// Example usage:
//
// var response []interface{}
// // Retrieve villains in order of increasing strength
// err := r.Table("villains").OrderBy("strength").Run(session).All(&response)
//
// // Retrieve villains in order of decreasing strength, then increasing intelligence
// query := r.Table("villains").OrderBy(r.Desc("strength"), "intelligence")
// err := query.Run(session).All(&response)
func (e Exp) OrderBy(orderings ...interface{}) Exp {
// These are not required to be strings because they could also be
// orderByAttr structs which specify the direction of sorting
return naryOperator(orderByKind, e, orderings...)
}
// Asc tells OrderBy to sort a particular attribute in ascending order. This is
// the default sort.
//
// Example usage:
//
// var response []interface{}
// // Retrieve villains in order of increasing fighting ability (worst fighters first)
// err := r.Table("villains").OrderBy(r.Asc("fighting")).Run(session).All(&response)
func Asc(attr string) Exp {
return naryOperator(ascendingKind, attr)
}
// Desc tells OrderBy to sort a particular attribute in descending order.
//
// Example usage:
//
// var response []interface{}
// // Retrieve villains in order of decreasing speed (fastest villains first)
// err := r.Table("villains").OrderBy(r.Desc("speed")).Run(session).All(&response)
func Desc(attr string) Exp {
return naryOperator(descendingKind, attr)
}
// Reduce iterates over a sequence, starting with a base value and applying a
// reduction function to the value so far and the next row of the sequence.
//
// Example usage:
//
// var sum int
// // Add the numbers 1-4 together
// reduction := func(acc, val r.Exp) r.Exp { return acc.Add(val) }
// err := r.Expr(1,2,3,4).Reduce(reduction, 0).Run(session).One(&sum)
//
// Example response:
//
// 10
//
// Example usage:
//
// var totalSpeed int
// // Compute the total speed for all heroes, the types of acc and val should
// // be the same, so we extract the speed first with a .Map()
// mapping := func(row r.Exp) r.Exp { return row.Attr("speed") }
// reduction := func(acc, val r.Exp) r.Exp { return acc.Add(val) }
// err := r.Table("heroes").Map(mapping).Reduce(reduction, 0).Run(session).One(&totalSpeed)
//
// Example response:
//
// 232
func (e Exp) Reduce(reduction, base interface{}) Exp {
return naryOperator(reduceKind, e, funcWrapper(reduction, 2), base)
}
// GroupedMapReduce partitions a sequence into groups, then performs a map and a
// reduction on each group. See also .Map() and .GroupBy().
//
// Example usage:
//
// // Find the sum of the even and odd numbers separately
// grouping := func(row r.Exp) r.Exp { return r.Branch(row.Mod(2).Eq(0), "even", "odd") }
// mapping := func(row r.Exp) r.Exp { return row }
// base := 0
// reduction := func(acc, row r.Exp) r.Exp {
// return acc.Add(row)
// }
//
// var response []interface{}
// query := r.Expr(1,2,3,4,5).GroupedMapReduce(grouping, mapping, reduction, base)
// err := query.Run(session).One(&response)
//
// Example response:
//
// [
// {
// "group": "even",
// "reduction": 6
// },
// {
// "group": "odd",
// "reduction": 9
// }
// ]
//
// Example usage:
//
// // Group all heroes by intelligence, then find the fastest one in each group
// grouping := func(row r.Exp) r.Exp { return row.Attr("intelligence") }
// mapping := func(row r.Exp) r.Exp { return row.Pluck("name", "speed") }
// base := r.Map{"name": nil, "speed": 0}
// reduction := func(acc, row r.Exp) r.Exp {
// return r.Branch(acc.Attr("speed").Lt(row.Attr("speed")), row, acc)
// }
//
// var response []interface{}
// query := r.Table("heroes").GroupedMapReduce(grouping, mapping, reduction, base)
// err := query.Run(session).One(&response)
//
// Example response:
//
// [
// {
// "group": 1,
// "reduction": {
// "name": "Northstar",
// "speed": 2
// }
// },
// {
// "group": 2,
// "reduction": {
// "name": "Thor",
// "speed": 6
// }
// },
// ...