-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ast.py
1834 lines (1262 loc) · 43.3 KB
/
ast.py
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
# Copyright 2010-2015 RethinkDB, all rights reserved.
__all__ = ['expr', 'RqlQuery', 'ReQLEncoder', 'ReQLDecoder']
import datetime
import collections
import base64
import binascii
import json as py_json
import threading
from .errors import ReqlDriverError, ReqlDriverCompileError, QueryPrinter, T
from . import ql2_pb2 as p
pTerm = p.Term.TermType
try:
unicode
except NameError:
unicode = str
try:
xrange
except NameError:
xrange = range
try:
{}.iteritems
dict_items = lambda d: d.iteritems()
except AttributeError:
dict_items = lambda d: d.items()
class Repl(object):
threadData = threading.local()
replActive = False
@classmethod
def get(cls):
if 'repl' in cls.threadData.__dict__:
return cls.threadData.repl
else:
return None
@classmethod
def set(cls, conn):
cls.threadData.repl = conn
cls.replActive = True
# This is both an external function and one used extensively
# internally to convert coerce python values to RQL types
def expr(val, nesting_depth=20):
'''
Convert a Python primitive into a RQL primitive value
'''
if not isinstance(nesting_depth, int):
raise ReqlDriverCompileError("Second argument to `r.expr` must be a number.")
if nesting_depth <= 0:
raise ReqlDriverCompileError("Nesting depth limit exceeded.")
if isinstance(val, RqlQuery):
return val
elif isinstance(val, collections.Callable):
return Func(val)
elif isinstance(val, (datetime.datetime, datetime.date)):
if not hasattr(val, 'tzinfo') or not val.tzinfo:
raise ReqlDriverCompileError("""Cannot convert %s to ReQL time object
without timezone information. You can add timezone information with
the third party module \"pytz\" or by constructing ReQL compatible
timezone values with r.make_timezone(\"[+-]HH:MM\"). Alternatively,
use one of ReQL's bultin time constructors, r.now, r.time,
or r.iso8601.
""" % (type(val).__name__))
return ISO8601(val.isoformat())
elif isinstance(val, RqlBinary):
return Binary(val)
elif isinstance(val, (str, unicode)):
return Datum(val)
elif isinstance(val, bytes):
return Binary(val)
elif isinstance(val, collections.Mapping):
# MakeObj doesn't take the dict as a keyword args to avoid
# conflicting with the `self` parameter.
obj = {}
for k, v in dict_items(val):
obj[k] = expr(v, nesting_depth - 1)
return MakeObj(obj)
elif isinstance(val, collections.Iterable):
val = [expr(v, nesting_depth - 1) for v in val]
return MakeArray(*val)
else:
return Datum(val)
class RqlQuery(object):
# Instantiate this AST node with the given pos and opt args
def __init__(self, *args, **optargs):
self.args = [expr(e) for e in args]
self.optargs = {}
for k, v in dict_items(optargs):
self.optargs[k] = expr(v)
# Send this query to the server to be executed
def run(self, c=None, **global_optargs):
if c is None:
c = Repl.get()
if c is None:
if Repl.replActive:
raise ReqlDriverError("RqlQuery.run must be given" +
" a connection to run on. A default connection" +
" has been set with `repl()` on another thread," +
" but not this one.")
else:
raise ReqlDriverError("RqlQuery.run must be given" +
" a connection to run on.")
return c._start(self, **global_optargs)
def __str__(self):
qp = QueryPrinter(self)
return qp.print_query()
def __repr__(self):
return "<RqlQuery instance: %s >" % str(self)
# Compile this query to a json-serializable object
def build(self):
res = [self.tt, self.args]
if len(self.optargs) > 0:
res.append(self.optargs)
return res
# The following are all operators and methods that operate on
# Rql queries to build up more complex operations
# Comparison operators
def __eq__(self, other):
return Eq(self, other)
def __ne__(self, other):
return Ne(self, other)
def __lt__(self, other):
return Lt(self, other)
def __le__(self, other):
return Le(self, other)
def __gt__(self, other):
return Gt(self, other)
def __ge__(self, other):
return Ge(self, other)
# Numeric operators
def __invert__(self):
return Not(self)
def __add__(self, other):
return Add(self, other)
def __radd__(self, other):
return Add(other, self)
def __sub__(self, other):
return Sub(self, other)
def __rsub__(self, other):
return Sub(other, self)
def __mul__(self, other):
return Mul(self, other)
def __rmul__(self, other):
return Mul(other, self)
def __div__(self, other):
return Div(self, other)
def __rdiv__(self, other):
return Div(other, self)
def __truediv__(self, other):
return Div(self, other)
def __rtruediv__(self, other):
return Div(other, self)
def __mod__(self, other):
return Mod(self, other)
def __rmod__(self, other):
return Mod(other, self)
def __and__(self, other):
query = And(self, other)
query.set_infix()
return query
def __rand__(self, other):
query = And(other, self)
query.set_infix()
return query
def __or__(self, other):
query = Or(self, other)
query.set_infix()
return query
def __ror__(self, other):
query = Or(other, self)
query.set_infix()
return query
# Non-operator versions of the above
def eq(self, *args):
return Eq(self, *args)
def ne(self, *args):
return Ne(self, *args)
def lt(self, *args):
return Lt(self, *args)
def le(self, *args):
return Le(self, *args)
def gt(self, *args):
return Gt(self, *args)
def ge(self, *args):
return Ge(self, *args)
def add(self, *args):
return Add(self, *args)
def sub(self, *args):
return Sub(self, *args)
def mul(self, *args):
return Mul(self, *args)
def div(self, *args):
return Div(self, *args)
def mod(self, *args):
return Mod(self, *args)
def floor(self, *args):
return Floor(self, *args)
def ceil(self, *args):
return Ceil(self, *args)
def round(self, *args):
return Round(self, *args)
def and_(self, *args):
return And(self, *args)
def or_(self, *args):
return Or(self, *args)
def not_(self, *args):
return Not(self, *args)
# N.B. Cannot use 'in' operator because it must return a boolean
def contains(self, *args):
return Contains(self, *[func_wrap(arg) for arg in args])
def has_fields(self, *args):
return HasFields(self, *args)
def with_fields(self, *args):
return WithFields(self, *args)
def keys(self, *args):
return Keys(self, *args)
def values(self, *args):
return Values(self, *args)
def changes(self, *args, **kwargs):
return Changes(self, *args, **kwargs)
# Polymorphic object/sequence operations
def pluck(self, *args):
return Pluck(self, *args)
def without(self, *args):
return Without(self, *args)
def do(self, *args):
return FunCall(self, *args)
def default(self, *args):
return Default(self, *args)
def update(self, *args, **kwargs):
return Update(self, *[func_wrap(arg) for arg in args], **kwargs)
def replace(self, *args, **kwargs):
return Replace(self, *[func_wrap(arg) for arg in args], **kwargs)
def delete(self, *args, **kwargs):
return Delete(self, *args, **kwargs)
# Rql type inspection
def coerce_to(self, *args):
return CoerceTo(self, *args)
def ungroup(self, *args):
return Ungroup(self, *args)
def type_of(self, *args):
return TypeOf(self, *args)
def merge(self, *args):
return Merge(self, *[func_wrap(arg) for arg in args])
def append(self, *args):
return Append(self, *args)
def prepend(self, *args):
return Prepend(self, *args)
def difference(self, *args):
return Difference(self, *args)
def set_insert(self, *args):
return SetInsert(self, *args)
def set_union(self, *args):
return SetUnion(self, *args)
def set_intersection(self, *args):
return SetIntersection(self, *args)
def set_difference(self, *args):
return SetDifference(self, *args)
# Operator used for get attr / nth / slice. Non-operator versions below
# in cases of ambiguity
def __getitem__(self, index):
if isinstance(index, slice):
if index.stop:
return Slice(self, index.start or 0, index.stop,
bracket_operator=True)
else:
return Slice(self, index.start or 0, -1,
right_bound='closed', bracket_operator=True)
else:
return Bracket(self, index, bracket_operator=True)
def __iter__(*args, **kwargs):
raise ReqlDriverError(
"__iter__ called on an RqlQuery object.\n"
"To iterate over the results of a query, call run first.\n"
"To iterate inside a query, use map or for_each.")
def get_field(self, *args):
return GetField(self, *args)
def nth(self, *args):
return Nth(self, *args)
def to_json(self, *args):
return ToJsonString(self, *args)
def to_json_string(self, *args):
return ToJsonString(self, *args)
def match(self, *args):
return Match(self, *args)
def split(self, *args):
return Split(self, *args)
def upcase(self, *args):
return Upcase(self, *args)
def downcase(self, *args):
return Downcase(self, *args)
def is_empty(self, *args):
return IsEmpty(self, *args)
def offsets_of(self, *args):
return OffsetsOf(self, *[func_wrap(arg) for arg in args])
def slice(self, *args, **kwargs):
return Slice(self, *args, **kwargs)
def skip(self, *args):
return Skip(self, *args)
def limit(self, *args):
return Limit(self, *args)
def reduce(self, *args):
return Reduce(self, *[func_wrap(arg) for arg in args])
def sum(self, *args):
return Sum(self, *[func_wrap(arg) for arg in args])
def avg(self, *args):
return Avg(self, *[func_wrap(arg) for arg in args])
def min(self, *args, **kwargs):
return Min(self, *[func_wrap(arg) for arg in args], **kwargs)
def max(self, *args, **kwargs):
return Max(self, *[func_wrap(arg) for arg in args], **kwargs)
def map(self, *args):
if len(args) > 0:
# `func_wrap` only the last argument
return Map(self, *(args[:-1] + (func_wrap(args[-1]), )))
else:
return Map(self)
def filter(self, *args, **kwargs):
return Filter(self, *[func_wrap(arg) for arg in args], **kwargs)
def concat_map(self, *args):
return ConcatMap(self, *[func_wrap(arg) for arg in args])
def order_by(self, *args, **kwargs):
args = [arg if isinstance(arg, (Asc, Desc)) else func_wrap(arg)
for arg in args]
return OrderBy(self, *args, **kwargs)
def between(self, *args, **kwargs):
return Between(self, *args, **kwargs)
def distinct(self, *args, **kwargs):
return Distinct(self, *args, **kwargs)
# NB: Can't overload __len__ because Python doesn't
# allow us to return a non-integer
def count(self, *args):
return Count(self, *[func_wrap(arg) for arg in args])
def union(self, *args):
return Union(self, *args)
def inner_join(self, *args):
return InnerJoin(self, *args)
def outer_join(self, *args):
return OuterJoin(self, *args)
def eq_join(self, *args, **kwargs):
return EqJoin(self, *[func_wrap(arg) for arg in args], **kwargs)
def zip(self, *args):
return Zip(self, *args)
def group(self, *args, **kwargs):
return Group(self, *[func_wrap(arg) for arg in args], **kwargs)
def branch(self, *args):
return Branch(self, *args)
def for_each(self, *args):
return ForEach(self, *[func_wrap(arg) for arg in args])
def info(self, *args):
return Info(self, *args)
# Array only operations
def insert_at(self, *args):
return InsertAt(self, *args)
def splice_at(self, *args):
return SpliceAt(self, *args)
def delete_at(self, *args):
return DeleteAt(self, *args)
def change_at(self, *args):
return ChangeAt(self, *args)
def sample(self, *args):
return Sample(self, *args)
# Time support
def to_iso8601(self, *args):
return ToISO8601(self, *args)
def to_epoch_time(self, *args):
return ToEpochTime(self, *args)
def during(self, *args, **kwargs):
return During(self, *args, **kwargs)
def date(self, *args):
return Date(self, *args)
def time_of_day(self, *args):
return TimeOfDay(self, *args)
def timezone(self, *args):
return Timezone(self, *args)
def year(self, *args):
return Year(self, *args)
def month(self, *args):
return Month(self, *args)
def day(self, *args):
return Day(self, *args)
def day_of_week(self, *args):
return DayOfWeek(self, *args)
def day_of_year(self, *args):
return DayOfYear(self, *args)
def hours(self, *args):
return Hours(self, *args)
def minutes(self, *args):
return Minutes(self, *args)
def seconds(self, *args):
return Seconds(self, *args)
def in_timezone(self, *args):
return InTimezone(self, *args)
# Geospatial support
def to_geojson(self, *args):
return ToGeoJson(self, *args)
def distance(self, *args, **kwargs):
return Distance(self, *args, **kwargs)
def intersects(self, *args):
return Intersects(self, *args)
def includes(self, *args):
return Includes(self, *args)
def fill(self, *args):
return Fill(self, *args)
def polygon_sub(self, *args):
return PolygonSub(self, *args)
# These classes define how nodes are printed by overloading `compose`
def needs_wrap(arg):
return isinstance(arg, (Datum, MakeArray, MakeObj))
class RqlBoolOperQuery(RqlQuery):
def __init__(self, *args, **optargs):
self.infix = False
RqlQuery.__init__(self, *args, **optargs)
def set_infix(self):
self.infix = True
def compose(self, args, optargs):
t_args = [T('r.expr(', args[i], ')')
if needs_wrap(self.args[i]) else args[i]
for i in xrange(len(args))]
if self.infix:
return T('(', T(*t_args, intsp=[' ', self.st_infix, ' ']), ')')
else:
return T('r.', self.st, '(', T(*t_args, intsp=', '), ')')
class RqlBiOperQuery(RqlQuery):
def compose(self, args, optargs):
t_args = [T('r.expr(', args[i], ')')
if needs_wrap(self.args[i]) else args[i]
for i in xrange(len(args))]
return T('(', T(*t_args, intsp=[' ', self.st, ' ']), ')')
class RqlBiCompareOperQuery(RqlBiOperQuery):
def __init__(self, *args, **optargs):
RqlBiOperQuery.__init__(self, *args, **optargs)
for arg in args:
try:
if arg.infix:
err = (
"Calling '%s' on result of infix bitwise operator:\n"
"%s.\n"
"This is almost always a precedence error.\n"
"Note that `a < b | b < c` <==> `a < (b | b) < c`.\n"
"If you really want this behavior, use `.or_` or "
"`.and_` instead.")
raise ReqlDriverCompileError(err %
(self.st,
QueryPrinter(self).print_query()))
except AttributeError:
pass # No infix attribute, so not possible to be an infix bool operator
class RqlTopLevelQuery(RqlQuery):
def compose(self, args, optargs):
args.extend([T(k, '=', v) for k, v in dict_items(optargs)])
return T('r.', self.st, '(', T(*(args), intsp=', '), ')')
class RqlMethodQuery(RqlQuery):
def compose(self, args, optargs):
if len(args) == 0:
return T('r.', self.st, '()')
if needs_wrap(self.args[0]):
args[0] = T('r.expr(', args[0], ')')
restargs = args[1:]
restargs.extend([T(k, '=', v) for k, v in dict_items(optargs)])
restargs = T(*restargs, intsp=', ')
return T(args[0], '.', self.st, '(', restargs, ')')
class RqlBracketQuery(RqlMethodQuery):
def __init__(self, *args, **optargs):
if 'bracket_operator' in optargs:
self.bracket_operator = optargs['bracket_operator']
del optargs['bracket_operator']
else:
self.bracket_operator = False
RqlMethodQuery.__init__(self, *args, **optargs)
def compose(self, args, optargs):
if self.bracket_operator:
if needs_wrap(self.args[0]):
args[0] = T('r.expr(', args[0], ')')
return T(args[0], '[', T(*args[1:], intsp=[',']), ']')
else:
return RqlMethodQuery.compose(self, args, optargs)
class RqlTzinfo(datetime.tzinfo):
def __init__(self, offsetstr):
hours, minutes = map(int, offsetstr.split(':'))
self.offsetstr = offsetstr
self.delta = datetime.timedelta(hours=hours, minutes=minutes)
def __getinitargs__(self):
return (self.offsetstr,)
def __copy__(self):
return RqlTzinfo(self.offsetstr)
def __deepcopy__(self, memo):
return RqlTzinfo(self.offsetstr)
def utcoffset(self, dt):
return self.delta
def tzname(self, dt):
return self.offsetstr
def dst(self, dt):
return datetime.timedelta(0)
# Python only allows immutable built-in types to be hashed, such as
# for keys in a dict This means we can't use lists or dicts as keys in
# grouped data objects, so we convert them to tuples and frozensets,
# respectively. This may make it a little harder for users to work
# with converted grouped data, unless they do a simple iteration over
# the result
def recursively_make_hashable(obj):
if isinstance(obj, list):
return tuple([recursively_make_hashable(i) for i in obj])
elif isinstance(obj, dict):
return frozenset([(k, recursively_make_hashable(v))
for k, v in dict_items(obj)])
return obj
class ReQLEncoder(py_json.JSONEncoder):
'''
Default JSONEncoder subclass to handle query conversion.
'''
def __init__(self):
py_json.JSONEncoder.__init__(self, ensure_ascii=False, allow_nan=False,
check_circular=False, separators=(',', ':'))
def default(self, obj):
if isinstance(obj, RqlQuery):
return obj.build()
return py_json.JSONEncoder.default(self, obj)
class ReQLDecoder(py_json.JSONDecoder):
'''
Default JSONDecoder subclass to handle pseudo-type conversion.
'''
def __init__(self, reql_format_opts=None):
py_json.JSONDecoder.__init__(self, object_hook=self.convert_pseudotype)
self.reql_format_opts = reql_format_opts or {}
def convert_time(self, obj):
if 'epoch_time' not in obj:
raise ReqlDriverError(('pseudo-type TIME object %s does not ' +
'have expected field "epoch_time".')
% py_json.dumps(obj))
if 'timezone' in obj:
return datetime.datetime.fromtimestamp(obj['epoch_time'],
RqlTzinfo(obj['timezone']))
else:
return datetime.datetime.utcfromtimestamp(obj['epoch_time'])
def convert_grouped_data(self, obj):
if 'data' not in obj:
raise ReqlDriverError(('pseudo-type GROUPED_DATA object' +
' %s does not have the expected field "data".')
% py_json.dumps(obj))
return dict([(recursively_make_hashable(k), v) for k, v in obj['data']])
def convert_binary(self, obj):
if 'data' not in obj:
raise ReqlDriverError(('pseudo-type BINARY object %s does not have ' +
'the expected field "data".')
% py_json.dumps(obj))
return RqlBinary(base64.b64decode(obj['data'].encode('utf-8')))
def convert_pseudotype(self, obj):
reql_type = obj.get('$reql_type$')
if reql_type is not None:
if reql_type == 'TIME':
time_format = self.reql_format_opts.get('time_format')
if time_format is None or time_format == 'native':
# Convert to native python datetime object
return self.convert_time(obj)
elif time_format != 'raw':
raise ReqlDriverError("Unknown time_format run option \"%s\"."
% time_format)
elif reql_type == 'GROUPED_DATA':
group_format = self.reql_format_opts.get('group_format')
if group_format is None or group_format == 'native':
return self.convert_grouped_data(obj)
elif group_format != 'raw':
raise ReqlDriverError("Unknown group_format run option \"%s\"."
% group_format)
elif reql_type == 'GEOMETRY':
# No special support for this. Just return the raw object
return obj
elif reql_type == 'BINARY':
binary_format = self.reql_format_opts.get('binary_format')
if binary_format is None or binary_format == 'native':
return self.convert_binary(obj)
elif binary_format != 'raw':
raise ReqlDriverError("Unknown binary_format run option \"%s\"."
% binary_format)
else:
raise ReqlDriverError("Unknown pseudo-type %s" % reql_type)
# If there was no pseudotype, or the relevant format is raw, return
# the original object
return obj
# This class handles the conversion of RQL terminal types in both directions
# Going to the server though it does not support R_ARRAY or R_OBJECT as those
# are alternately handled by the MakeArray and MakeObject nodes. Why do this?
# MakeArray and MakeObject are more flexible, allowing us to construct array
# and object expressions from nested RQL expressions. Constructing pure
# R_ARRAYs and R_OBJECTs would require verifying that at all nested levels
# our arrays and objects are composed only of basic types.
class Datum(RqlQuery):
args = []
optargs = {}
def __init__(self, val):
self.data = val
def build(self):
return self.data
def compose(self, args, optargs):
return repr(self.data)
class MakeArray(RqlQuery):
tt = pTerm.MAKE_ARRAY
def compose(self, args, optargs):
return T('[', T(*args, intsp=', '), ']')
class MakeObj(RqlQuery):
tt = pTerm.MAKE_OBJ
# We cannot inherit from RqlQuery because of potential conflicts with
# the `self` parameter. This is not a problem for other RqlQuery sub-
# classes unless we add a 'self' optional argument to one of them.
def __init__(self, obj_dict):
self.args = []
self.optargs = {}
for k, v in dict_items(obj_dict):
if not isinstance(k, (str, unicode)):
raise ReqlDriverCompileError("Object keys must be strings.")
self.optargs[k] = expr(v)
def build(self):
return self.optargs
def compose(self, args, optargs):
return T('r.expr({', T(*[T(repr(k), ': ', v)
for k, v in dict_items(optargs)],
intsp=', '), '})')
class Var(RqlQuery):
tt = pTerm.VAR
def compose(self, args, optargs):
return 'var_' + args[0]
class JavaScript(RqlTopLevelQuery):
tt = pTerm.JAVASCRIPT
st = "js"
class Http(RqlTopLevelQuery):
tt = pTerm.HTTP
st = "http"
class UserError(RqlTopLevelQuery):
tt = pTerm.ERROR
st = "error"
class Random(RqlTopLevelQuery):
tt = pTerm.RANDOM
st = "random"
class Changes(RqlMethodQuery):
tt = pTerm.CHANGES
st = "changes"
class Default(RqlMethodQuery):
tt = pTerm.DEFAULT
st = "default"
class ImplicitVar(RqlQuery):
tt = pTerm.IMPLICIT_VAR
def __call__(self, *args, **kwargs):
raise TypeError("'r.row' is not callable, use 'r.row[...]' instead")
def compose(self, args, optargs):
return 'r.row'
class Eq(RqlBiCompareOperQuery):
tt = pTerm.EQ
st = "=="
class Ne(RqlBiCompareOperQuery):
tt = pTerm.NE
st = "!="
class Lt(RqlBiCompareOperQuery):
tt = pTerm.LT
st = "<"
class Le(RqlBiCompareOperQuery):
tt = pTerm.LE
st = "<="
class Gt(RqlBiCompareOperQuery):
tt = pTerm.GT
st = ">"
class Ge(RqlBiCompareOperQuery):
tt = pTerm.GE
st = ">="
class Not(RqlQuery):
tt = pTerm.NOT
def compose(self, args, optargs):
if isinstance(self.args[0], Datum):
args[0] = T('r.expr(', args[0], ')')
return T('(~', args[0], ')')
class Add(RqlBiOperQuery):
tt = pTerm.ADD
st = "+"
class Sub(RqlBiOperQuery):
tt = pTerm.SUB
st = "-"
class Mul(RqlBiOperQuery):
tt = pTerm.MUL
st = "*"
class Div(RqlBiOperQuery):
tt = pTerm.DIV
st = "/"
class Mod(RqlBiOperQuery):
tt = pTerm.MOD
st = "%"
class Floor(RqlMethodQuery):
tt = pTerm.FLOOR
st = 'floor'
class Ceil(RqlMethodQuery):
tt = pTerm.CEIL
st = 'ceil'
class Round(RqlMethodQuery):
tt = pTerm.ROUND
st = 'round'
class Append(RqlMethodQuery):
tt = pTerm.APPEND
st = "append"
class Prepend(RqlMethodQuery):
tt = pTerm.PREPEND
st = "prepend"
class Difference(RqlMethodQuery):
tt = pTerm.DIFFERENCE
st = "difference"
class SetInsert(RqlMethodQuery):
tt = pTerm.SET_INSERT
st = "set_insert"
class SetUnion(RqlMethodQuery):
tt = pTerm.SET_UNION
st = "set_union"
class SetIntersection(RqlMethodQuery):
tt = pTerm.SET_INTERSECTION
st = "set_intersection"
class SetDifference(RqlMethodQuery):
tt = pTerm.SET_DIFFERENCE
st = "set_difference"
class Slice(RqlBracketQuery):
tt = pTerm.SLICE
st = 'slice'
# Slice has a special bracket syntax, implemented here
def compose(self, args, optargs):
if self.bracket_operator:
if needs_wrap(self.args[0]):
args[0] = T('r.expr(', args[0], ')')
return T(args[0], '[', args[1], ':', args[2], ']')
else:
return RqlBracketQuery.compose(self, args, optargs)
class Skip(RqlMethodQuery):