-
Notifications
You must be signed in to change notification settings - Fork 19
/
algebra.py
1583 lines (1141 loc) · 46.9 KB
/
algebra.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
from raco import expression
from raco import scheme
from raco.utility import Printable, real_str
from abc import ABCMeta, abstractmethod
import copy
import operator
import math
from raco.expression import StateVar
from functools import reduce
# BEGIN Code to generate variables names
var_id = 0
def reset():
global var_id
var_id = 0
def gensym():
global var_id
var_id += 1
return "V%s" % var_id
# END Code to generate variables names
# Global constants
DEFAULT_CARDINALITY = 10000
class RecursionError(ValueError):
pass
class SchemaError(Exception):
pass
class Operator(Printable):
"""Operator base class"""
__metaclass__ = ABCMeta
def __init__(self):
self.bound = None
# Extra code to emit to cleanup
self.cleanup = ""
self.alias = self
self._trace = []
@abstractmethod
def apply(self, f):
""" apply function f to its children. """
@abstractmethod
def children(self):
"""Return all the children of this operator."""
@abstractmethod
def scheme(self):
"""Return the scheme of the tuples output by this operator."""
def walk(self):
"""Return an iterator over the tree of operators."""
yield self
for c in self.children():
for x in c.walk():
yield x
@abstractmethod
def num_tuples(self):
"""Return the expected number of tuples output by this operator."""
def postorder(self, f):
"""Postorder traversal, applying a function to each operator. The
function returns an iterator"""
for c in self.children():
for x in c.postorder(f):
yield x
for x in f(self):
yield x
def preorder(self, f):
"""Preorder traversal, applying a function to each operator. The
function returns an iterator"""
for x in f(self):
yield x
for c in self.children():
for x in c.postorder(f):
yield x
def collectParents(self, parent_map=None):
"""Construct a dict mapping children to parents. Used in
optimization"""
if parent_map is None:
parent_map = {}
for c in self.children():
parent_map.setdefault(c, []).append(self)
c.collectParents(parent_map)
def __copy__(self):
raise RuntimeError("Shallow copy not supported for operators")
def __eq__(self, other):
return self.__class__ == other.__class__
def __str__(self):
if len(self.children()) > 0:
return "%s%s" % (self.shortStr(), real_str(self.children()))
return self.shortStr()
def __hash__(self):
h = str(self.__class__).__hash__()
for i, c in enumerate(self.children()):
h ^= (c.__hash__() << i)
return h
def copy(self, other):
self._trace = [pair for pair in other.gettrace()]
self.bound = None
def trace(self, key, val):
self._trace.append((key, val))
def gettrace(self):
"""Return a list of trace messages"""
return self._trace
def set_alias(self, alias):
"""Set a user-defined identifier for this operator. Used in
optimization and transformation of plans"""
self.alias = alias
@abstractmethod
def shortStr(self):
"""Returns a short string describing the current operator and its
arguments, but not its children. Consider:
query = "A(x) :- R(x,3)."
logicalplan = dlog.fromDatalog(query)
(label, root_op) = logicalplan[0]
str(root_op) returns "Project($0)[Select($1 = 3)[Scan(R)]]"
shortStr(root_op) should return "Project($0)" """
def collectGraph(self, graph=None):
"""Collects the operator graph for a given query. Input parameter graph
has the format {'nodes': list(), 'edges': list()}, initialized to empty
lists by default. An input graph will be mutated."""
# Initialize graph if necessary
if graph is None:
graph = {'nodes': list(), 'edges': list()}
# Cycle detection - continue, but don't re-add this node to the graph
if id(self) in [id(n) for n in graph['nodes']]:
return graph
# Add this node to the graph
graph['nodes'].append(self)
# Add all edges
graph['edges'].extend([(x, self) for x in self.children()])
for x in self.children():
# Recursively add children and edges to the graph. This mutates
# graph
x.collectGraph(graph)
# Return the graph
return graph
def resolveAttribute(self, ref):
"""Return a tuple of (column_name, type) for a given AttributeRef."""
assert isinstance(ref, expression.AttributeRef), ref
return self.scheme().resolve(ref)
class ZeroaryOperator(Operator):
"""Operator with no arguments"""
def __init__(self):
Operator.__init__(self)
def __eq__(self, other):
return self.__class__ == other.__class__
def children(self):
return []
def apply(self, f):
"""Apply a function to your children"""
return self
def copy(self, other):
"""Deep copy"""
Operator.copy(self, other)
def compileme(self, resultsym):
"""Compile this operator, storing its result in resultsym"""
raise NotImplementedError("{op}.compileme".format(op=type(self)))
def __repr__(self):
return "{op}()".format(op=self.opname())
class UnaryOperator(Operator):
"""Operator with one argument"""
def __init__(self, input):
self.input = input
Operator.__init__(self)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.input == other.input
def children(self):
return [self.input]
def scheme(self):
"""Default scheme is the same as the input. Usually overriden"""
return self.input.scheme()
def apply(self, f):
"""Apply a function to your children"""
self.input = f(self.input)
return self
def copy(self, other):
"""deep copy"""
self.input = other.input
Operator.copy(self, other)
def compileme(self, inputsym):
"""Compile this operator with specified input and output symbol
names"""
raise NotImplementedError("{op}.compileme".format(op=type(self)))
def __repr__(self):
return "{op}({inp!r})".format(op=self.opname(), inp=self.input)
class BinaryOperator(Operator):
"""Operator with two arguments"""
def __init__(self, left, right):
self.left = left
self.right = right
Operator.__init__(self)
def __eq__(self, other):
return (self.__class__ == other.__class__
and self.left == other.left
and self.right == other.right)
def children(self):
return [self.left, self.right]
def apply(self, f):
"""Apply a function to your children"""
self.left = f(self.left)
self.right = f(self.right)
return self
def copy(self, other):
"""deep copy"""
self.left = other.left
self.right = other.right
Operator.copy(self, other)
def compileme(self, leftsym, rightsym):
"""Compile this operator with specified left, right, and output symbol
names"""
raise NotImplementedError("{op}.compileme".format(op=type(self)))
def __repr__(self):
return "{op}({l!r}, {r!r})".format(op=self.opname(), l=self.left,
r=self.right)
class NaryOperator(Operator):
"""Operator with N arguments. e.g., multi-way joins in one step."""
def __init__(self, args=None):
Operator.__init__(self)
if args is None:
self.args = []
else:
self.args = args
def add(self, op):
"""Add a child operator to the end of the child argument list."""
self.args.append(op)
def children(self):
return self.args
def copy(self, other):
"""deep copy"""
self.args = [a for a in other.args]
Operator.copy(self, other)
def apply(self, f):
"""Apply a function to your children"""
self.args = [f(arg) for arg in self.args]
return self
def compileme(self, resultsym, argsyms):
"""Compile this operator with specified children and output symbol
names"""
raise NotImplementedError("{op}.compileme".format(op=type(self)))
def __repr__(self):
return "{op}({ch!r})".format(op=self.opname(), ch=self.args)
class NaryJoin(NaryOperator):
"""Logical Nary Join operator"""
def __init__(self, children=None, conditions=None, output_columns=None):
# TODO: conditions is not actually an expression, it's a list of
# pairs of UnnamedAttributeRefs that represent equijoins. This is
# wrong -- it should be a single expression like in Join.
#
# Should be able to:
# assert isinstance(condition, racoExpression).
self.conditions = conditions
self.output_columns = output_columns
NaryOperator.__init__(self, children)
def __eq__(self, other):
return (NaryOperator.__eq__(self, other)
and self.conditions == other.conditions)
def num_tuples(self):
# TODO: use AGM bound (P10 in http://arxiv.org/pdf/1310.3314v2.pdf)
return DEFAULT_CARDINALITY
def scheme(self):
combined = reduce(operator.add, [c.scheme() for c in self.children()])
# do projection
if self.output_columns:
combined = [combined[attr.get_position(combined)]
for attr in self.output_columns]
return scheme.Scheme(combined)
def copy(self, other):
"""deep copy"""
self.conditions = other.conditions
self.output_columns = other.output_columns
NaryOperator.copy(self, other)
def shortStr(self):
return "%s(%s)" % (self.opname(), real_str(self.conditions,
skip_out=True))
"""Logical Relational Algebra"""
class Union(BinaryOperator):
"""Set union."""
def __init__(self, left=None, right=None):
BinaryOperator.__init__(self, left, right)
def num_tuples(self):
# a heuristic
return int((self.left.num_tuples() + self.right.num_tuples()) / 2)
def scheme(self):
"""Same semantics as SQL: Assume first schema "wins" and throw an
error if they don't match during evaluation"""
return self.left.scheme()
def shortStr(self):
return self.opname()
class UnionAll(BinaryOperator):
"""Bag union."""
def __init__(self, left=None, right=None):
BinaryOperator.__init__(self, left, right)
def num_tuples(self):
return self.left.num_tuples() + self.right.num_tuples()
def copy(self, other):
"""deep copy"""
BinaryOperator.copy(self, other)
def scheme(self):
return self.left.scheme()
def shortStr(self):
return self.opname()
class Intersection(BinaryOperator):
"""Set intersection."""
def __init__(self, left=None, right=None):
BinaryOperator.__init__(self, left, right)
def num_tuples(self):
return min(self.left.num_tuples(), self.right.num_tuples())
def scheme(self):
return self.left.scheme()
def shortStr(self):
return self.opname()
class Difference(BinaryOperator):
"""Set difference"""
def __init__(self, left=None, right=None):
BinaryOperator.__init__(self, left, right)
def num_tuples(self):
left_num = self.left.num_tuples()
right_num = self.right.num_tuples()
return left_num - math.floor(min(right_num, left_num * 0.5))
def scheme(self):
return self.left.scheme()
def shortStr(self):
return self.opname()
class CompositeBinaryOperator(BinaryOperator):
"""Join-like operations whose output schema combines its input schemas."""
@abstractmethod
def add_equijoin_condition(self, col0, col1):
"""Attempt to add a selection filter to this operation.
Returns a (possibly modified) operator or None if the columns do not
refer to different children of the join/cross-product.
"""
@staticmethod
def get_equijoin_condition(col0, col1):
"""Return a boolean expression representing an equijoin."""
return expression.EQ(expression.UnnamedAttributeRef(col0),
expression.UnnamedAttributeRef(col1))
class CrossProduct(CompositeBinaryOperator):
"""Logical Cross Product operator"""
def __init__(self, left=None, right=None):
BinaryOperator.__init__(self, left, right)
def num_tuples(self):
return self.left.num_tuples() * self.right.num_tuples()
def copy(self, other):
"""deep copy"""
BinaryOperator.copy(self, other)
def shortStr(self):
return self.opname()
def scheme(self):
"""Return the scheme of the result."""
return self.left.scheme() + self.right.scheme()
def add_equijoin_condition(self, col0, col1):
"""Convert the cross-product into a join whenever possible."""
condition = self.get_equijoin_condition(col0, col1)
return Join(condition, self.left, self.right)
class Join(CompositeBinaryOperator):
"""Logical Join operator"""
def __init__(self, condition=None, left=None, right=None):
self.condition = condition
BinaryOperator.__init__(self, left, right)
def __eq__(self, other):
return (BinaryOperator.__eq__(self, other)
and self.condition == other.condition)
def num_tuples(self):
# this is black magic
return int(self.left.num_tuples() * self.right.num_tuples() / 10)
def copy(self, other):
"""deep copy"""
self.condition = other.condition
BinaryOperator.copy(self, other)
def shortStr(self):
return "%s(%s)" % (self.opname(), self.condition)
def scheme(self):
"""Return the scheme of the result."""
return self.left.scheme() + self.right.scheme()
def add_equijoin_condition(self, col0, col1):
condition = self.get_equijoin_condition(col0, col1)
self.condition = expression.AND(self.condition, condition)
return self
def __repr__(self):
return "{op}({cond!r}, {l!r}, {r!r})".format(op=self.opname(),
cond=self.condition,
l=self.left,
r=self.right)
def resolve_attribute_name(user_name, scheme, sexpr, index):
"""Resolve an attribute/column into a name.
:param user_name: A user-provided string name. Can be None.
:type user_name: string
:param scheme: The schema of the operator's input.
:type scheme: raco.Scheme
:param sexpr: The scalar expression describing the column's contents.
:type sexpr: raco.expression.Expression
:param index: The numeric index of the column
:type index: int
:returns: A string representing the column name
"""
# We always give preference to a user-provided name
if user_name:
return user_name
# If the column contains a simple attribute reference, infer the column
# name from the input schema. However, do not pass along an auto-gen
# column name.
elif isinstance(sexpr, expression.AttributeRef):
inferred_name = scheme.resolve(sexpr)[0]
if not inferred_name.startswith('_COLUMN'):
return inferred_name
# Otherwise, just concoct a column name based on the column index.
return '_COLUMN%d_' % index
class Apply(UnaryOperator):
def __init__(self, emitters=None, input=None):
"""Create new attributes from expressions with optional rename.
:param emitters: list of tuples of the form:
(column_name, raco.expression.Expression).
column_name can be None, in which case the system will infer a
name based on the expression
:type emitters: list of tuples
"""
if emitters is not None:
in_scheme = input.scheme()
self.emitters = \
[(resolve_attribute_name(name, in_scheme, sexpr, index), sexpr)
for index, (name, sexpr) in enumerate(emitters)]
UnaryOperator.__init__(self, input)
def __eq__(self, other):
return (UnaryOperator.__eq__(self, other) and
self.emitters == other.emitters)
def num_tuples(self):
return self.input.num_tuples()
def copy(self, other):
"""deep copy"""
self.emitters = other.emitters
UnaryOperator.copy(self, other)
def scheme(self):
"""scheme of the result."""
input_scheme = self.input.scheme()
new_attrs = [(name, expr.typeof(input_scheme, None))
for (name, expr) in self.emitters]
return scheme.Scheme(new_attrs)
def shortStr(self):
estrs = ",".join(["%s=%s" % (name, str(ex))
for name, ex in self.emitters])
return "%s(%s)" % (self.opname(), estrs)
def get_names(self):
"""Get the names of the columns emitted by this Apply."""
return [e[0] for e in self.emitters]
def get_unnamed_emit_exprs(self):
"""Get the emit expressions for this Apply after ensuring that all
attribute references are UnnamedAttributeRefs."""
emits = [e[1] for e in self.emitters]
return expression.ensure_unnamed(emits, self.input)
def __repr__(self):
return "{op}({emt!r}, {inp!r})".format(op=self.opname(),
emt=self.emitters,
inp=self.input)
class StatefulApply(UnaryOperator):
inits = None
updaters = None
state_scheme = None
emitters = None
def __init__(self, emitters=None, state_modifiers=None, input=None):
"""Create new attributes from expressions with additional state passed
from tuple to tuple.
:param emitters: list of tuples of the form:
(column_name, raco.expression.Expression).
column_name can be None, in which case the system will infer a
name based on the expression
:type emitters: list of tuples
:param state_modifiers: State variables maintained by the StatefulApply
operator.
:type state_modifiers: list of StateVar tuples
"""
if state_modifiers is not None:
self.inits = [(x.name, x.init_expr) for x in state_modifiers]
self.updaters = [(x.name, x.update_expr) for x in state_modifiers]
self.state_scheme = scheme.Scheme()
for (name, expr) in self.inits:
self.state_scheme.addAttribute(name, expr.typeof(None, None))
if emitters is not None:
in_scheme = input.scheme()
self.emitters = \
[(resolve_attribute_name(name, in_scheme, sexpr, index), sexpr)
for index, (name, sexpr) in enumerate(emitters)]
UnaryOperator.__init__(self, input)
def __eq__(self, other):
return (super(StatefulApply, self).__eq__(self, other) and
self.emitters == other.emitters and
self.updaters == other.updaters and
self.inits == other.inits)
def __repr__(self):
# the next line is because of the refactoring that we do in __init__
state_mods = [StateVar(a, b, d)
for ((a, b), (c, d)) in zip(self.inits, self.updaters)]
return "{op}({emt!r}, {sm!r}, {inp!r})".format(op=self.opname(),
emt=self.emitters,
sm=state_mods,
inp=self.input)
def num_tuples(self):
return self.input.num_tuples()
def copy(self, other):
"""deep copy"""
self.emitters = other.emitters
self.updaters = other.updaters
self.inits = other.inits
self.state_scheme = other.state_scheme
UnaryOperator.copy(self, other)
def scheme(self):
"""scheme of the result."""
input_scheme = self.input.scheme()
new_attrs = [(name, expr.typeof(input_scheme, self.state_scheme))
for (name, expr) in self.emitters]
return scheme.Scheme(new_attrs)
def shortStr(self):
estrs = ",".join(["%s=%s" % (name, str(ex))
for name, ex in self.emitters])
return "%s(%s)" % (self.opname(), estrs)
# TODO: Non-scheme-mutating operators
class Distinct(UnaryOperator):
"""Remove duplicates from the child operator"""
def __init__(self, input=None):
UnaryOperator.__init__(self, input)
def num_tuples(self):
# TODO: better heuristics?
return self.input.num_tuples()
def scheme(self):
"""scheme of the result"""
return self.input.scheme()
def shortStr(self):
return self.opname()
class Limit(UnaryOperator):
def __init__(self, count=None, input=None):
UnaryOperator.__init__(self, input)
self.count = count
def __eq__(self, other):
return UnaryOperator.__eq__(self, other) and self.count == other.count
def __repr__(self):
return "{op}({cnt!r}, {inp!r})".format(op=self.opname(),
cnt=self.count,
inp=self.input)
def num_tuples(self):
return self.count
def copy(self, other):
self.count = other.count
UnaryOperator.copy(self, other)
def scheme(self):
return self.input.scheme()
def shortStr(self):
return "%s(%s)" % (self.opname(), self.count)
class Select(UnaryOperator):
"""Logical selection operator"""
def __init__(self, condition=None, input=None):
self.condition = condition
UnaryOperator.__init__(self, input)
def __eq__(self, other):
return (UnaryOperator.__eq__(self, other)
and self.condition == other.condition)
def num_tuples(self):
return int(self.input.num_tuples() * 0.5)
def shortStr(self):
if isinstance(self.condition, dict):
cond = self.condition["condition"]
else:
cond = self.condition
return "%s(%s)" % (self.opname(), cond)
def __repr__(self):
return "{op}({cond!r}, {inp!r})".format(op=self.opname(),
cond=self.condition,
inp=self.input)
def copy(self, other):
"""deep copy"""
self.condition = other.condition
UnaryOperator.copy(self, other)
def scheme(self):
"""scheme of the result."""
return self.input.scheme()
def get_unnamed_condition(self):
"""Get the filter condition for this Select after ensuring that all
attribute references are UnnamedAttributeRefs."""
return expression.ensure_unnamed(self.condition, self.input)
class Project(UnaryOperator):
"""Logical projection operator"""
def __init__(self, columnlist=None, input=None):
self.columnlist = columnlist
UnaryOperator.__init__(self, input)
def __eq__(self, other):
return (UnaryOperator.__eq__(self, other)
and self.columnlist == other.columnlist)
def num_tuples(self):
return self.input.num_tuples()
def shortStr(self):
return "%s(%s)" % (self.opname(), real_str(self.columnlist,
skip_out=True))
def __repr__(self):
return "{op}({col!r}, {inp!r})".format(op=self.opname(),
col=self.columnlist,
inp=self.input)
def copy(self, other):
"""deep copy"""
self.columnlist = other.columnlist
UnaryOperator.copy(self, other)
def scheme(self):
"""scheme of the result. Raises a TypeError if a name in the project
list is not in the source schema"""
attrs = [self.input.resolveAttribute(attref)
for attref in self.columnlist]
return scheme.Scheme(attrs)
def get_unnamed_column_list(self):
"""Get the column list for this Project after ensuring that all
attribute references are UnnamedAttributeRefs."""
return expression.ensure_unnamed(self.columnlist, self.input)
class GroupBy(UnaryOperator):
"""Logical GroupBy operator
:param grouping_list: A list of expressions in a "group by" clause
:param aggregate_list: A list of aggregate expressions (e.g., MIN, MAX)
:param input: The input operator
:param state_modifiers: A list of StateVar tuples associated with the
user-defined aggregates.
"""
def __init__(self, grouping_list=None, aggregate_list=None, input=None,
state_modifiers=None):
self.grouping_list = grouping_list or []
self.aggregate_list = aggregate_list or []
if state_modifiers is not None:
self.inits = [(x.name, x.init_expr) for x in state_modifiers]
self.updaters = [(x.name, x.update_expr) for x in state_modifiers]
self.state_scheme = scheme.Scheme()
for name, expr in self.inits:
self.state_scheme.addAttribute(name, expr.typeof(None, None))
else:
self.inits = []
self.updaters = []
self.state_scheme = scheme.Scheme()
UnaryOperator.__init__(self, input)
def num_tuples(self):
if not self.grouping_list:
return 1
return self.input.num_tuples()
def shortStr(self):
return "%s(%s; %s)" % (self.opname(),
real_str(self.grouping_list, skip_out=True),
real_str(self.aggregate_list, skip_out=True))
def __repr__(self):
# the next line is because of the refactoring that we do in __init__
state_mods = [StateVar(a, b, d)
for ((a, b), (c, d)) in zip(self.inits, self.updaters)]
return "{op}({gl!r}, {al!r}, {inp!r}, {sm!r})".format(
op=self.opname(), gl=self.grouping_list, al=self.aggregate_list,
inp=self.input, sm=state_mods)
def copy(self, other):
"""deep copy"""
self.grouping_list = other.grouping_list
self.aggregate_list = other.aggregate_list
self.updaters = other.updaters
self.inits = other.inits
self.state_scheme = other.state_scheme
UnaryOperator.copy(self, other)
def column_list(self):
return self.grouping_list + self.aggregate_list
def get_unnamed_grouping_list(self):
"""Get the grouping list for this GroupBy after ensuring that all
attribute references are UnnamedAttributeRefs."""
return expression.ensure_unnamed(self.grouping_list, self.input)
def get_unnamed_aggregate_list(self):
"""Get the aggregate list for this GroupBy after ensuring that all
attribute references are UnnamedAttributeRefs."""
return expression.ensure_unnamed(self.aggregate_list, self.input)
def get_unnamed_update_exprs(self):
"""Get the update list for this GroupBy after ensuring that all
attribute references are UnnamedAttributeRefs."""
ups = [expr for _, expr in self.updaters]
return expression.ensure_unnamed(ups, self.input)
def scheme(self):
"""scheme of the result."""
in_scheme = self.input.scheme()
# Note: user-provided column names are supplied by a subsequent Apply
# invocation; see raco/myrial/groupby.py
schema = scheme.Scheme()
for index, sexpr in enumerate(self.column_list()):
name = resolve_attribute_name(None, in_scheme, sexpr, index)
_type = sexpr.typeof(in_scheme, self.state_scheme)
schema.addAttribute(name, _type)
return schema
class OrderBy(UnaryOperator):
""" Logical Sort operator
"""
def __init__(self, input=None, sort_columns=None, ascending=None):
UnaryOperator.__init__(self, input)
self.sort_columns = sort_columns
self.ascending = ascending
def num_tuples(self):
return self.input.num_tuples()
def shortStr(self):
ascend_string = ['+' if a else '-' for a in self.ascending]
sort_string = ','.join('{col}{asc}'.format(col=c, asc=a)
for c, a in zip(self.sort_columns,
ascend_string))
return "%s(%s)" % (self.opname(), sort_string)
def copy(self, other):
"""deep copy"""
self.sort_columns = other.sort_columns
self.ascending = other.ascending
UnaryOperator.copy(self, other)
def scheme(self):
return self.input.scheme()
class ProjectingJoin(Join):
"""Logical Projecting Join operator"""
def __init__(self, condition=None, left=None, right=None,
output_columns=None):
self.output_columns = output_columns
Join.__init__(self, condition, left, right)
def __eq__(self, other):
return (Join.__eq__(self, other)
and self.output_columns == other.output_columns)
def shortStr(self):
if self.output_columns is None:
return Join.shortStr(self)
return "%s(%s; %s)" % (self.opname(), self.condition,
real_str(self.output_columns, skip_out=True))
def __repr__(self):
return "{op}({cond!r}, {l!r}, {r!r}, {oc!r})"\
.format(op=self.opname(), cond=self.condition,
l=self.left, r=self.right, oc=self.output_columns)
def copy(self, other):
"""deep copy"""
self.output_columns = other.output_columns
Join.copy(self, other)
def scheme(self):
"""Return the scheme of the result."""
if self.output_columns is None:
return Join.scheme(self)
def get_col(pos, left_sch, right_sch):
if pos < len(left_sch):
return left_sch.getName(pos), left_sch.getType(pos)
else:
pos -= len(left_sch)
assert pos < len(right_sch)
return right_sch.getName(pos), right_sch.getType(pos)
left_sch = self.left.scheme()
right_sch = self.right.scheme()
combined = left_sch + right_sch
return scheme.Scheme([get_col(p.get_position(combined),
left_sch, right_sch)
for p in self.output_columns])
def add_equijoin_condition(self, col0, col1):