-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathsql.py
More file actions
1540 lines (1209 loc) · 44.3 KB
/
sql.py
File metadata and controls
1540 lines (1209 loc) · 44.3 KB
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 blaze import *
>>> accounts = symbol('accounts', 'var * {name: string, amount: int}')
>>> deadbeats = accounts[accounts['amount'] < 0]['name']
>>> from sqlalchemy import Table, Column, MetaData, Integer, String
>>> t = Table('accounts', MetaData(),
... Column('name', String, primary_key = True),
... Column('amount', Integer))
>>> print(compute(deadbeats, t)) # doctest: +SKIP
SELECT accounts.name
FROM accounts
WHERE accounts.amount < :amount_1
"""
from __future__ import absolute_import, division, print_function
from copy import copy
import datetime
import itertools
from itertools import chain
from operator import and_, eq, attrgetter
import warnings
from datashape import TimeDelta, Option, int32
from datashape.predicates import iscollection, isscalar, isrecord
import numpy as np
import numbers
from odo.backends.sql import metadata_of_engine, dshape_to_alchemy
from multipledispatch import MDNotImplementedError
import sqlalchemy as sa
from sqlalchemy import sql, Table, MetaData
from sqlalchemy.engine import Engine
from sqlalchemy.sql import Selectable, Select, functions as safuncs
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.elements import ClauseElement, ColumnElement, ColumnClause
from sqlalchemy.sql.selectable import FromClause, ScalarSelect
import toolz
from toolz import unique, concat, pipe, first
from toolz.compatibility import zip
from toolz.curried import map
from .core import compute_up, compute, base
from ..compatibility import reduce, basestring, _inttypes
from ..dispatch import dispatch
from ..expr import (
BinOp,
BinaryMath,
Broadcast,
By,
Coalesce,
Coerce,
Concat,
DateTime,
DateTimeTruncate,
Distinct,
Expr,
Field,
FloorDiv,
Head,
IsIn,
Join,
Label,
Like,
Merge,
Pow,
Projection,
ReLabel,
Reduction,
Sample,
Selection,
Shift,
Slice,
Sort,
Sub,
Summary,
Tail,
UnaryOp,
UnaryStringFunction,
common_subexpression,
count,
greatest,
least,
mean,
nelements,
notnull,
nunique,
reductions,
std,
StrCat,
StrFind,
StrSlice,
var,
)
from ..expr.strings import len as str_len
from ..expr.broadcast import broadcast_collect
from ..expr.math import isnan
from ..utils import listpack
__all__ = ['sa', 'select']
def inner_columns(s):
try:
return s.inner_columns
except AttributeError:
return s.columns
@dispatch(Projection, Select)
def compute_up(expr, data, **kwargs):
d = dict((c.name, c) for c in getattr(data, 'inner_columns', data.c))
return data.with_only_columns([d[field] for field in expr.fields])
@dispatch(Projection, Selectable)
def compute_up(expr, data, **kwargs):
return compute(
expr,
sa.select([data]),
post_compute=False,
return_type='native',
)
@dispatch(Projection, sa.Column)
def compute_up(expr, data, **kwargs):
selectables = [
compute(
expr._child[field],
data,
post_compute=False,
return_type='native',
)
for field in expr.fields
]
froms = set(concat(s.froms for s in selectables))
assert 1 <= len(froms) <= 2
result = unify_froms(sa.select(first(sel.inner_columns)
for sel in selectables),
froms)
return result.where(unify_wheres(selectables))
@dispatch(Projection, Select)
def compute_up(expr, data, **kwargs):
return data.with_only_columns(
first(compute(
expr._child[field],
data,
post_compute=False,
return_type='native',
).inner_columns)
for field in expr.fields
)
@dispatch(Field, FromClause)
def compute_up(t, s, **kwargs):
return s.c[t._name]
def unify_froms(select, selectables):
return reduce(lambda x, y: x.select_from(y), selectables, select)
def unify_wheres(selectables):
clauses = list(unique((s._whereclause for s in selectables
if hasattr(s, '_whereclause')), key=str))
return reduce(and_, clauses) if clauses else None
@dispatch(Field, Select)
def compute_up(expr, data, **kwargs):
name = expr._name
try:
inner_columns = list(data.inner_columns)
names = list(c.name for c in data.inner_columns)
column = inner_columns[names.index(name)]
except (KeyError, ValueError):
single_column_select = compute(
expr,
first(data.inner_columns),
post_compute=False,
return_type='native',
)
column = first(single_column_select.inner_columns)
result = unify_froms(sa.select([column]),
data.froms + single_column_select.froms)
return result.where(unify_wheres([data, single_column_select]))
else:
return data.with_only_columns([column])
@dispatch(Field, sa.Column)
def compute_up(t, s, **kwargs):
assert len(s.foreign_keys) == 1, 'exactly one foreign key allowed'
key_col = first(s.foreign_keys).column
return sa.select([key_col.table.c[t._name]]).where(s == key_col)
@dispatch(Broadcast, Select)
def compute_up(t, s, **kwargs):
cols = list(inner_columns(s))
d = dict((t._scalars[0][c], cols[i])
for i, c in enumerate(t._scalars[0].fields))
result = compute(
t._scalar_expr,
d,
post_compute=False,
return_type='native',
).label(t._name)
s = copy(s)
s.append_column(result)
return s.with_only_columns([result])
@dispatch(Broadcast, Selectable)
def compute_up(t, s, **kwargs):
cols = list(inner_columns(s))
d = dict((t._scalars[0][c], cols[i])
for i, c in enumerate(t._scalars[0].fields))
return compute(
t._scalar_expr,
d,
post_compute=False,
return_type='native',
).label(t._name)
@dispatch(Concat, (Select, Selectable), (Select, Selectable))
def compute_up(t, lhs, rhs, **kwargs):
if t.axis != 0:
raise ValueError(
'Cannot concat along a non-zero axis in sql; perhaps you want'
" 'merge'?",
)
return select(lhs).union_all(select(rhs)).alias()
@dispatch(Broadcast, ColumnElement)
def compute_up(t, s, **kwargs):
expr = t._scalar_expr
return compute(
expr,
s,
post_compute=False,
return_type='native',
).label(expr._name)
def _binop(type_, f):
@dispatch(type_, ColumnElement)
def compute_up(t, data, **kwargs):
if isinstance(t.lhs, Expr):
return t.op(data, t.rhs)
else:
return f(t, t.lhs, data)
@dispatch(type_, Select)
def compute_up(t, data, **kwargs):
assert len(data.c) == 1, (
'Select cannot have more than a single column when doing'
' arithmetic'
)
column = first(data.inner_columns)
if isinstance(t.lhs, Expr):
return f(t, column, t.rhs)
else:
return f(t, t.lhs, column)
@compute_up.register(type_,
(Select, ColumnElement, base),
(Select, ColumnElement))
@compute_up.register(type_,
(Select, ColumnElement),
base)
def binop_sql(t, lhs, rhs, **kwargs):
if isinstance(lhs, Select):
assert len(lhs.c) == 1, (
'Select cannot have more than a single column when doing'
' arithmetic, got %r' % lhs
)
lhs = first(lhs.inner_columns)
if isinstance(rhs, Select):
assert len(rhs.c) == 1, (
'Select cannot have more than a single column when doing'
' arithmetic, got %r' % rhs
)
rhs = first(rhs.inner_columns)
return f(t, lhs, rhs)
_binop(BinOp, lambda expr, lhs, rhs: expr.op(lhs, rhs))
_binop(
(greatest, least),
lambda expr, lhs, rhs: getattr(sa.func, type(expr).__name__)(lhs, rhs),
)
@dispatch(Pow, ColumnElement)
def compute_up(t, data, **kwargs):
if isinstance(t.lhs, Expr):
return sa.func.pow(data, t.rhs)
else:
return sa.func.pow(t.lhs, data)
@dispatch(Pow, Select)
def compute_up(t, data, **kwargs):
assert len(data.c) == 1, (
'Select cannot have more than a single column when doing'
' arithmetic, got %r' % data
)
column = first(data.inner_columns)
if isinstance(t.lhs, Expr):
return sa.func.pow(column, t.rhs)
else:
return sa.func.pow(t.lhs, column)
@compute_up.register(Pow, (ColumnElement, base), ColumnElement)
@compute_up.register(Pow, ColumnElement, base)
def binop_sql_pow(t, lhs, rhs, **kwargs):
return sa.func.pow(lhs, rhs)
@dispatch(BinaryMath, ColumnElement)
def compute_up(t, data, **kwargs):
op = getattr(sa.func, type(t).__name__)
if isinstance(t.lhs, Expr):
return op(data, t.rhs)
else:
return op(t.lhs, data)
@dispatch(BinaryMath, Select)
def compute_up(t, data, **kwargs):
assert len(data.c) == 1, (
'Select cannot have more than a single column when doing'
' arithmetic, got %r' % data
)
column = first(data.inner_columns)
op = getattr(sa.func, type(t).__name__)
if isinstance(t.lhs, Expr):
return op(column, t.rhs)
else:
return op(t.lhs, column)
@compute_up.register(BinaryMath, (ColumnElement, base), ColumnElement)
@compute_up.register(BinaryMath, ColumnElement, base)
def binary_math_sql(t, lhs, rhs, **kwargs):
return getattr(sa.func, type(t).__name__)(lhs, rhs)
@compute_up.register(BinaryMath, Select, base)
def binary_math_sql_select(t, lhs, rhs, **kwargs):
left, right = first(lhs.inner_columns), rhs
result = getattr(sa.func, type(t).__name__)(left, right)
return reconstruct_select([result], lhs)
@compute_up.register(BinaryMath, base, Select)
def binary_math_sql_select(t, lhs, rhs, **kwargs):
left, right = lhs, first(rhs.inner_columns)
result = getattr(sa.func, type(t).__name__)(left, right)
return reconstruct_select([result], rhs)
@compute_up.register(BinaryMath, Select, Select)
def binary_math_sql_select(t, lhs, rhs, **kwargs):
left, right = first(lhs.inner_columns), first(rhs.inner_columns)
result = getattr(sa.func, type(t).__name__)(left, right)
assert lhs.table == rhs.table
return reconstruct_select([result], lhs.table)
@dispatch(FloorDiv, ColumnElement)
def compute_up(t, data, **kwargs):
if isinstance(t.lhs, Expr):
return sa.func.floor(data / t.rhs)
else:
return sa.func.floor(t.rhs / data)
@compute_up.register(FloorDiv, (ColumnElement, base), ColumnElement)
@compute_up.register(FloorDiv, ColumnElement, base)
def binop_sql(t, lhs, rhs, **kwargs):
return sa.func.floor(lhs / rhs)
@dispatch(isnan, ColumnElement)
def compute_up(t, s, **kwargs):
return s == float('nan')
@dispatch(UnaryOp, ColumnElement)
def compute_up(t, s, **kwargs):
sym = t.symbol
return getattr(t, 'op', getattr(safuncs, sym, getattr(sa.func, sym)))(s)
@dispatch(Selection, sa.sql.ColumnElement)
def compute_up(expr, data, scope=None, **kwargs):
predicate = compute(
expr.predicate,
data,
post_compute=False,
return_type='native',
)
return compute(
expr,
{expr._child: data, expr.predicate: predicate},
return_type='native',
**kwargs
)
@dispatch(Selection, sa.sql.ColumnElement, ColumnElement)
def compute_up(expr, col, predicate, **kwargs):
return sa.select([col]).where(predicate)
@dispatch(Selection, Selectable)
def compute_up(expr, sel, scope=None, **kwargs):
return compute(
expr,
{
expr._child: sel,
expr.predicate: compute(
expr.predicate,
toolz.merge(
{
expr._child[col.name]: col
for col in getattr(sel, 'inner_columns', sel.columns)
},
scope,
),
optimize=False,
post_compute=False,
),
},
return_type='native',
**kwargs
)
@dispatch(Selection, Selectable, ColumnElement)
def compute_up(expr, tbl, predicate, scope=None, **kwargs):
try:
return tbl.where(predicate)
except AttributeError:
return select([tbl]).where(predicate)
@dispatch(Selection, Selectable, Selectable)
def compute_up(expr, tbl, predicate, **kwargs):
col, = inner_columns(predicate)
return reconstruct_select(
inner_columns(tbl),
tbl,
whereclause=unify_wheres((tbl, predicate)),
).where(col)
def select(s):
""" Permissive SQL select
Idempotent sa.select
Wraps input in list if neccessary
"""
if not isinstance(s, sa.sql.Select):
if not isinstance(s, (tuple, list)):
s = [s]
s = sa.select(s)
return s
table_names = ('table_%d' % i for i in itertools.count(1))
def name(sel):
""" Name of a selectable """
if hasattr(sel, 'name'):
return sel.name
if hasattr(sel, 'froms'):
if len(sel.froms) == 1:
return name(sel.froms[0])
return next(table_names)
@dispatch(Select, Select)
def _join_selectables(a, b, condition=None, **kwargs):
return a.join(b, condition, **kwargs)
@dispatch(Select, ClauseElement)
def _join_selectables(a, b, condition=None, **kwargs):
if len(a.froms) > 1:
raise MDNotImplementedError()
return a.replace_selectable(a.froms[0],
a.froms[0].join(b, condition, **kwargs))
@dispatch(ClauseElement, Select)
def _join_selectables(a, b, condition=None, **kwargs):
if len(b.froms) > 1:
raise MDNotImplementedError()
return b.replace_selectable(b.froms[0],
a.join(b.froms[0], condition, **kwargs))
@dispatch(ClauseElement, ClauseElement)
def _join_selectables(a, b, condition=None, **kwargs):
return a.join(b, condition, **kwargs)
_getname = attrgetter('name')
def _clean_join_name(opposite_side_colnames, suffix, c):
if c.name not in opposite_side_colnames:
return c
else:
return c.label(c.name + suffix)
@dispatch(Join, ClauseElement, ClauseElement)
def compute_up(t, lhs, rhs, **kwargs):
if isinstance(lhs, ColumnElement):
lhs = select(lhs)
if isinstance(rhs, ColumnElement):
rhs = select(rhs)
if name(lhs) == name(rhs):
left_suffix, right_suffix = t.suffixes
lhs = lhs.alias('%s%s' % (name(lhs), left_suffix))
rhs = rhs.alias('%s%s' % (name(rhs), right_suffix))
lhs = alias_it(lhs)
rhs = alias_it(rhs)
if isinstance(lhs, Select):
lhs = lhs.alias(next(aliases))
left_conds = [lhs.c.get(c) for c in listpack(t.on_left)]
else:
ldict = dict((c.name, c) for c in inner_columns(lhs))
left_conds = [ldict.get(c) for c in listpack(t.on_left)]
if isinstance(rhs, Select):
rhs = rhs.alias(next(aliases))
right_conds = [rhs.c.get(c) for c in listpack(t.on_right)]
else:
rdict = dict((c.name, c) for c in inner_columns(rhs))
right_conds = [rdict.get(c) for c in listpack(t.on_right)]
condition = reduce(and_, map(eq, left_conds, right_conds))
# Perform join
if t.how == 'inner':
join = _join_selectables(lhs, rhs, condition=condition)
main = lhs
elif t.how == 'left':
main, other = lhs, rhs
join = _join_selectables(lhs, rhs, condition=condition, isouter=True)
elif t.how == 'right':
join = _join_selectables(rhs, lhs, condition=condition, isouter=True)
main = rhs
else:
# http://stackoverflow.com/questions/20361017/sqlalchemy-full-outer-join
raise ValueError("SQLAlchemy doesn't support full outer Join")
"""
We now need to arrange the columns in the join to match the columns in
the expression. We care about order and don't want repeats
"""
if isinstance(join, Select):
def cols(x):
if isinstance(x, Select):
return list(x.inner_columns)
else:
return list(x.columns)
else:
cols = lambda x: list(x.columns)
main_cols = cols(main)
left_cols = cols(lhs)
left_names = set(map(_getname, left_cols))
right_cols = cols(rhs)
right_names = set(map(_getname, right_cols))
left_suffix, right_suffix = t.suffixes
fields = [
f.replace(left_suffix, '').replace(right_suffix, '') for f in t.fields
]
columns = [c for c in main_cols if c.name in t._on_left]
columns += [_clean_join_name(right_names, left_suffix, c)
for c in left_cols
if c.name in fields and c.name not in t._on_left]
columns += [_clean_join_name(left_names, right_suffix, c)
for c in right_cols
if c.name in fields and c.name not in t._on_right]
if isinstance(join, Select):
return join.with_only_columns(columns)
else:
return sa.select(columns, from_obj=join)
names = {
mean: 'avg'
}
def reconstruct_select(columns, original, **kwargs):
return sa.select(columns,
from_obj=kwargs.pop('from_obj', None),
whereclause=kwargs.pop('whereclause',
getattr(original,
'_whereclause', None)),
bind=kwargs.pop('bind', original.bind),
distinct=kwargs.pop('distinct',
getattr(original,
'_distinct', False)),
group_by=kwargs.pop('group_by',
getattr(original,
'_group_by_clause', None)),
having=kwargs.pop('having',
getattr(original, '_having', None)),
limit=kwargs.pop('limit',
getattr(original, '_limit', None)),
offset=kwargs.pop('offset',
getattr(original, '_offset', None)),
order_by=kwargs.pop('order_by',
getattr(original,
'_order_by_clause', None)),
**kwargs)
@dispatch((nunique, Reduction), Select)
def compute_up(expr, data, **kwargs):
if expr.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
data = data.alias(name=next(aliases))
cols = list(inner_columns(data))
d = dict((expr._child[c], cols[i])
for i, c in enumerate(expr._child.fields))
return select([
compute(expr, d, post_compute=False, return_type='native')
])
@dispatch(Distinct, ColumnElement)
def compute_up(t, s, **kwargs):
return s.distinct(*t.on).label(t._name)
@dispatch(Distinct, Select)
def compute_up(t, s, **kwargs):
return s.distinct(*t.on)
@dispatch(Distinct, Selectable)
def compute_up(t, s, **kwargs):
return select(s).distinct(*t.on)
@dispatch(Reduction, ClauseElement)
def compute_up(t, s, **kwargs):
if t.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
try:
op = getattr(sa.sql.functions, t.symbol)
except AttributeError:
op = getattr(sa.sql.func, names.get(type(t), t.symbol))
return op(s).label(t._name)
prefixes = {
std: 'stddev',
var: 'var'
}
@dispatch((std, var), sql.elements.ColumnElement)
def compute_up(t, s, **kwargs):
measure = t.schema.measure
is_timedelta = isinstance(getattr(measure, 'ty', measure), TimeDelta)
if is_timedelta:
# part 1 of 2 to work around the fact that postgres does not have
# timedelta var or std: cast to a double which is seconds
s = sa.extract('epoch', s)
if t.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
funcname = 'samp' if t.unbiased else 'pop'
full_funcname = '%s_%s' % (prefixes[type(t)], funcname)
ret = getattr(sa.func, full_funcname)(s)
if is_timedelta:
# part 2 of 2 to work around the fact that postgres does not have
# timedelta var or std: cast back from seconds by
# multiplying by a 1 second timedelta
ret = ret * datetime.timedelta(seconds=1)
return ret.label(t._name)
@dispatch(count, Selectable)
def compute_up(t, s, **kwargs):
return s.count()
@dispatch(count, sa.Table)
def compute_up(t, s, **kwargs):
if t.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
try:
c = list(s.primary_key)[0]
except IndexError:
c = list(s.columns)[0]
return sa.func.count(c)
@dispatch(nelements, (Select, ClauseElement))
def compute_up(t, s, **kwargs):
return compute_up(t._child.count(), s)
@dispatch(count, Select)
def compute_up(t, s, **kwargs):
if t.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
al = next(aliases)
try:
s2 = s.alias(al)
col = list(s2.primary_key)[0]
except (KeyError, IndexError):
s2 = s.alias(al)
col = list(s2.columns)[0]
result = sa.func.count(col)
return select([list(inner_columns(result))[0].label(t._name)])
@dispatch(nunique, (sa.sql.elements.Label, sa.Column))
def compute_up(t, s, **kwargs):
if t.axis != (0,):
raise ValueError('axis not equal to 0 not defined for SQL reductions')
return sa.func.count(s.distinct())
@dispatch(nunique, Selectable)
def compute_up(expr, data, **kwargs):
return select(data).distinct().alias(next(aliases)).count()
@dispatch(By, sa.Column)
def compute_up(expr, data, scope=None, **kwargs):
data = lower_column(data)
grouper = compute(
expr.grouper,
scope,
post_compute=False,
return_type='native',
**kwargs
)
app = expr.apply
reductions = [
compute(
val,
data,
post_compute=None,
return_type='native',
).label(name)
for val, name in zip(app.values, app.fields)
]
froms = list(unique(chain(get_all_froms(grouper),
concat(map(get_all_froms, reductions)))))
inner_cols = list(getattr(grouper, 'inner_columns', [grouper]))
grouper_cols = inner_cols[:]
inner_cols.extend(concat(
getattr(getattr(r, 'element', None), 'inner_columns', [r])
for r in reductions
))
wheres = unify_wheres([grouper] + reductions)
sel = unify_froms(sa.select(inner_cols, whereclause=wheres), froms)
return sel.group_by(*grouper_cols)
@dispatch(By, ClauseElement)
def compute_up(expr, data, **kwargs):
if not valid_grouper(expr.grouper):
raise TypeError("Grouper must have a non-nested record or one "
"dimensional collection datashape, "
"got %s of type %r with dshape %s" %
(expr.grouper, type(expr.grouper).__name__,
expr.grouper.dshape))
grouper = get_inner_columns(
compute(
expr.grouper,
data,
post_compute=False,
return_type='native',
),
)
app = expr.apply
reductions = [
compute(
val,
data,
post_compute=False,
return_type='native',
).label(name)
for val, name in zip(app.values, app.fields)
]
return sa.select(grouper + reductions).group_by(*grouper)
def lower_column(col):
""" Return column from lower level tables if possible
>>> metadata = sa.MetaData()
>>> s = sa.Table('accounts', metadata,
... sa.Column('name', sa.String),
... sa.Column('amount', sa.Integer),
... sa.Column('id', sa.Integer, primary_key=True),
... )
>>> s2 = select([s])
>>> s2.c.amount is s.c.amount
False
>>> lower_column(s2.c.amount) is s.c.amount
True
>>> lower_column(s2.c.amount)
Column('amount', Integer(), table=<accounts>)
"""
old = None
while col is not None and col is not old:
old = col
if not hasattr(col, 'table') or not hasattr(col.table, 'froms'):
return col
for f in col.table.froms:
if f.corresponding_column(col) is not None:
col = f.corresponding_column(col)
return old
aliases = ('alias_%d' % i for i in itertools.count(1))
@toolz.memoize
def alias_it(s):
""" Alias a Selectable if it has a group by clause """
if (hasattr(s, '_group_by_clause') and
s._group_by_clause is not None and
len(s._group_by_clause)):
return s.alias(next(aliases))
else:
return s
def is_nested_record(measure):
"""Predicate for checking whether `measure` is a nested ``Record`` dshape
Examples
--------
>>> from datashape import dshape
>>> is_nested_record(dshape('{a: int32, b: int32}').measure)
False
>>> is_nested_record(dshape('{a: var * ?float64, b: ?string}').measure)
True
"""
if not isrecord(measure):
raise TypeError('Input must be a Record type got %s of type %r' %
(measure, type(measure).__name__))
return not all(isscalar(getattr(t, 'key', t)) for t in measure.types)
def valid_grouper(expr):
ds = expr.dshape
measure = ds.measure
return (iscollection(ds) and
(isscalar(getattr(measure, 'key', measure)) or
(isrecord(measure) and not is_nested_record(measure))))
def valid_reducer(expr):
ds = expr.dshape
measure = ds.measure
return (not iscollection(ds) and
(isscalar(measure) or
(isrecord(measure) and not is_nested_record(measure))))
@dispatch(By, Select)
def compute_up(expr, data, **kwargs):
if not valid_grouper(expr.grouper):
raise TypeError("Grouper must have a non-nested record or one "
"dimensional collection datashape, "
"got %s of type %r with dshape %s" %
(expr.grouper, type(expr.grouper).__name__,
expr.grouper.dshape))
s = alias_it(data)
if valid_reducer(expr.apply):
reduction = compute(
expr.apply,
s,
post_compute=False, return_type='native',
)
else:
raise TypeError('apply must be a Summary expression')
grouper = get_inner_columns(compute(
expr.grouper,
s,
post_compute=False,
return_type='native',
))
reduction_columns = pipe(reduction.inner_columns,
map(get_inner_columns),
concat)
columns = list(unique(chain(grouper, reduction_columns)))
if (not isinstance(s, sa.sql.selectable.Alias) or
(hasattr(s, 'froms') and isinstance(s.froms[0],
sa.sql.selectable.Join))):
assert len(s.froms) == 1, 'only a single FROM clause supported for now'
from_obj, = s.froms
else:
from_obj = None
return reconstruct_select(columns,
getattr(s, 'element', s),
from_obj=from_obj,
group_by=grouper)
@dispatch(Sort, (Selectable, Select))
def compute_up(t, s, **kwargs):
s = select(s.alias())
direction = sa.asc if t.ascending else sa.desc
cols = [direction(lower_column(s.c[c])) for c in listpack(t.key)]
return s.order_by(*cols)
@dispatch(Sort, (sa.Table, ColumnElement))
def compute_up(t, s, **kwargs):
s = select(s)
direction = sa.asc if t.ascending else sa.desc
cols = [direction(lower_column(s.c[c])) for c in listpack(t.key)]
return s.order_by(*cols)
def _samp_compute_up(t, s, **kwargs):
if t.n is not None:
limit = t.n
else:
limit = sa.select([safuncs.count() * t.frac],
from_obj=s.alias()).as_scalar()
return s.order_by(safuncs.random()).limit(limit)
@dispatch(Sample, sa.Table)
def compute_up(t, s, **kwargs):
return _samp_compute_up(t, select(s), **kwargs)
@dispatch(Sample, ColumnElement)
def compute_up(t, s, **kwargs):
return _samp_compute_up(t, sa.select([s]), **kwargs)
@dispatch(Sample, FromClause)
def compute_up(t, s, **kwargs):
return _samp_compute_up(t, s, **kwargs)
@dispatch(Head, FromClause)
def compute_up(t, s, **kwargs):
if s._limit is not None and s._limit <= t.n:
return s
return s.limit(t.n)