forked from sqlalchemy/sqlalchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_selectable.py
More file actions
4065 lines (3419 loc) · 130 KB
/
test_selectable.py
File metadata and controls
4065 lines (3419 loc) · 130 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
"""Test various algorithmic properties of selectables."""
from itertools import zip_longest
import random
import threading
import time
from sqlalchemy import and_
from sqlalchemy import bindparam
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import Column
from sqlalchemy import delete
from sqlalchemy import exc
from sqlalchemy import exists
from sqlalchemy import false
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import insert
from sqlalchemy import Integer
from sqlalchemy import join
from sqlalchemy import literal_column
from sqlalchemy import MetaData
from sqlalchemy import not_
from sqlalchemy import null
from sqlalchemy import or_
from sqlalchemy import outerjoin
from sqlalchemy import select
from sqlalchemy import Sequence
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import true
from sqlalchemy import type_coerce
from sqlalchemy import TypeDecorator
from sqlalchemy import union
from sqlalchemy import update
from sqlalchemy import util
from sqlalchemy.sql import Alias
from sqlalchemy.sql import annotation
from sqlalchemy.sql import base
from sqlalchemy.sql import column
from sqlalchemy.sql import elements
from sqlalchemy.sql import LABEL_STYLE_DISAMBIGUATE_ONLY
from sqlalchemy.sql import LABEL_STYLE_TABLENAME_PLUS_COL
from sqlalchemy.sql import operators
from sqlalchemy.sql import sqltypes
from sqlalchemy.sql import table
from sqlalchemy.sql import util as sql_util
from sqlalchemy.sql import visitors
from sqlalchemy.sql.dml import Insert
from sqlalchemy.sql.selectable import LABEL_STYLE_NONE
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import config
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import in_
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_not
from sqlalchemy.testing import ne_
from sqlalchemy.testing.assertions import expect_raises_message
from sqlalchemy.testing.provision import normalize_sequence
metadata = MetaData()
table1 = Table(
"table1",
metadata,
Column("col1", Integer, primary_key=True),
Column("col2", String(20)),
Column("col3", Integer),
Column("colx", Integer),
)
table2 = Table(
"table2",
metadata,
Column("col1", Integer, primary_key=True),
Column("col2", Integer, ForeignKey("table1.col1")),
Column("col3", String(20)),
Column("coly", Integer),
)
keyed = Table(
"keyed",
metadata,
Column("x", Integer, key="colx"),
Column("y", Integer, key="coly"),
Column("z", Integer),
)
class SelectableTest(
fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL
):
__dialect__ = "default"
@testing.combinations(
(
(table1.c.col1, table1.c.col2),
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
],
),
(
(table1,),
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
{
"name": "col3",
"type": table1.c.col3.type,
"expr": table1.c.col3,
},
{
"name": "colx",
"type": table1.c.colx.type,
"expr": table1.c.colx,
},
],
),
(
(func.count(table1.c.col1),),
[
{
"name": "count",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
}
],
),
(
(func.count(table1.c.col1), func.count(table1.c.col2)),
[
{
"name": "count",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
},
{
"name": "count_1",
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col2)
),
},
],
),
)
def test_core_column_descriptions(self, cols, expected):
stmt = select(*cols)
# reverse eq_ is so eq_clause_element works
eq_(expected, stmt.column_descriptions)
@testing.combinations(insert, update, delete, argnames="dml_construct")
@testing.combinations(
(
table1,
(table1.c.col1, table1.c.col2),
{"name": "table1", "table": table1},
[
{
"name": "col1",
"type": table1.c.col1.type,
"expr": table1.c.col1,
},
{
"name": "col2",
"type": table1.c.col2.type,
"expr": table1.c.col2,
},
],
),
(
table1,
(func.count(table1.c.col1),),
{"name": "table1", "table": table1},
[
{
"name": None,
"type": testing.eq_type_affinity(Integer),
"expr": testing.eq_clause_element(
func.count(table1.c.col1)
),
},
],
),
(
table1,
None,
{"name": "table1", "table": table1},
[],
),
(
table1.alias("some_alias"),
None,
{
"name": "some_alias",
"table": testing.eq_clause_element(table1.alias("some_alias")),
},
[],
),
(
table1.join(table2),
None,
{
"name": None,
"table": testing.eq_clause_element(table1.join(table2)),
},
[],
),
argnames="entity, cols, expected_entity, expected_returning",
)
def test_dml_descriptions(
self, dml_construct, entity, cols, expected_entity, expected_returning
):
stmt = dml_construct(entity)
if cols:
stmt = stmt.returning(*cols)
eq_(stmt.entity_description, expected_entity)
eq_(expected_returning, stmt.returning_column_descriptions)
def test_indirect_correspondence_on_labels(self):
# this test depends upon 'distance' to
# get the right result
# same column three times
s = select(
table1.c.col1.label("c2"),
table1.c.col1,
table1.c.col1.label("c1"),
).subquery()
# this tests the same thing as
# test_direct_correspondence_on_labels below -
# that the presence of label() affects the 'distance'
assert s.corresponding_column(table1.c.col1) is s.c.col1
assert s.corresponding_column(s.c.col1) is s.c.col1
assert s.corresponding_column(s.c.c1) is s.c.c1
def test_labeled_select_twice(self):
scalar_select = select(table1.c.col1).label("foo")
s1 = select(scalar_select)
s2 = select(scalar_select, scalar_select)
eq_(
s1.selected_columns.foo.proxy_set,
{s1.selected_columns.foo, scalar_select, scalar_select.element},
)
eq_(
s2.selected_columns.foo.proxy_set,
{s2.selected_columns.foo, scalar_select, scalar_select.element},
)
assert (
s1.corresponding_column(scalar_select) is s1.selected_columns.foo
)
assert (
s2.corresponding_column(scalar_select) is s2.selected_columns.foo
)
def test_labeled_subquery_twice(self):
scalar_select = select(table1.c.col1).label("foo")
s1 = select(scalar_select).subquery()
s2 = select(scalar_select, scalar_select).subquery()
eq_(
s1.c.foo.proxy_set,
{s1.c.foo, scalar_select, scalar_select.element},
)
eq_(
s2.c.foo.proxy_set,
{s2.c.foo, scalar_select, scalar_select.element},
)
assert s1.corresponding_column(scalar_select) is s1.c.foo
assert s2.corresponding_column(scalar_select) is s2.c.foo
def test_labels_name_w_separate_key(self):
label = select(table1.c.col1).label("foo")
label.key = "bar"
s1 = select(label)
assert s1.corresponding_column(label) is s1.selected_columns.bar
# renders as foo
self.assert_compile(
s1, "SELECT (SELECT table1.col1 FROM table1) AS foo"
)
@testing.combinations(("cte",), ("subquery",), argnames="type_")
@testing.combinations(
("onelevel",), ("twolevel",), ("middle",), argnames="path"
)
@testing.combinations((True,), (False,), argnames="require_embedded")
def test_subquery_cte_correspondence(self, type_, require_embedded, path):
stmt = select(table1)
if type_ == "cte":
cte1 = stmt.cte()
elif type_ == "subquery":
cte1 = stmt.subquery()
if path == "onelevel":
is_(
cte1.corresponding_column(
table1.c.col1, require_embedded=require_embedded
),
cte1.c.col1,
)
elif path == "twolevel":
cte2 = cte1.alias()
is_(
cte2.corresponding_column(
table1.c.col1, require_embedded=require_embedded
),
cte2.c.col1,
)
elif path == "middle":
cte2 = cte1.alias()
is_(
cte2.corresponding_column(
cte1.c.col1, require_embedded=require_embedded
),
cte2.c.col1,
)
def test_labels_anon_w_separate_key(self):
label = select(table1.c.col1).label(None)
label.key = "bar"
s1 = select(label)
# .bar is there
assert s1.corresponding_column(label) is s1.selected_columns.bar
# renders as anon_1
self.assert_compile(
s1, "SELECT (SELECT table1.col1 FROM table1) AS anon_1"
)
def test_labels_anon_w_separate_key_subquery(self):
label = select(table1.c.col1).label(None)
label.key = label._tq_key_label = "bar"
s1 = select(label)
subq = s1.subquery()
s2 = select(subq).where(subq.c.bar > 5)
self.assert_compile(
s2,
"SELECT anon_2.anon_1 FROM (SELECT (SELECT table1.col1 "
"FROM table1) AS anon_1) AS anon_2 "
"WHERE anon_2.anon_1 > :param_1",
checkparams={"param_1": 5},
)
def test_labels_anon_generate_binds_subquery(self):
label = select(table1.c.col1).label(None)
label.key = label._tq_key_label = "bar"
s1 = select(label)
subq = s1.subquery()
s2 = select(subq).where(subq.c[0] > 5)
self.assert_compile(
s2,
"SELECT anon_2.anon_1 FROM (SELECT (SELECT table1.col1 "
"FROM table1) AS anon_1) AS anon_2 "
"WHERE anon_2.anon_1 > :param_1",
checkparams={"param_1": 5},
)
@testing.combinations((True,), (False,))
def test_broken_select_same_named_explicit_cols(self, use_anon):
"""test for #6090. the query is "wrong" and we dont know how
# to render this right now.
"""
stmt = select(
table1.c.col1,
table1.c.col2,
literal_column("col2").label(None if use_anon else "col2"),
).select_from(table1)
if use_anon:
self.assert_compile(
select(stmt.subquery()),
"SELECT anon_1.col1, anon_1.col2, anon_1.col2_1 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2, "
"col2 AS col2_1 FROM table1) AS anon_1",
)
else:
# the keys here are not critical as they are not what was
# requested anyway, maybe should raise here also.
eq_(stmt.selected_columns.keys(), ["col1", "col2", "col2_1"])
with expect_raises_message(
exc.InvalidRequestError,
"Label name col2 is being renamed to an anonymous "
"label due to "
"disambiguation which is not supported right now. Please use "
"unique names for explicit labels.",
):
select(stmt.subquery()).compile()
def test_same_anon_named_explicit_cols(self):
"""test for #8569. This adjusts the change in #6090 to not apply
to anonymous labels.
"""
lc = literal_column("col2").label(None)
subq1 = select(lc).subquery()
stmt2 = select(subq1, lc).subquery()
self.assert_compile(
select(stmt2),
"SELECT anon_1.col2_1, anon_1.col2_1_1 FROM "
"(SELECT anon_2.col2_1 AS col2_1, col2 AS col2_1 FROM "
"(SELECT col2 AS col2_1) AS anon_2) AS anon_1",
)
def test_correlate_none_arg_error(self):
stmt = select(table1)
with expect_raises_message(
exc.ArgumentError,
"additional FROM objects not accepted when passing "
"None/False to correlate",
):
stmt.correlate(None, table2)
def test_correlate_except_none_arg_error(self):
stmt = select(table1)
with expect_raises_message(
exc.ArgumentError,
"additional FROM objects not accepted when passing "
"None/False to correlate_except",
):
stmt.correlate_except(None, table2)
def test_select_label_grouped_still_corresponds(self):
label = select(table1.c.col1).label("foo")
label2 = label.self_group()
s1 = select(label)
s2 = select(label2)
assert s1.corresponding_column(label) is s1.selected_columns.foo
assert s2.corresponding_column(label) is s2.selected_columns.foo
def test_subquery_label_grouped_still_corresponds(self):
label = select(table1.c.col1).label("foo")
label2 = label.self_group()
s1 = select(label).subquery()
s2 = select(label2).subquery()
assert s1.corresponding_column(label) is s1.c.foo
assert s2.corresponding_column(label) is s2.c.foo
def test_direct_correspondence_on_labels(self):
# this test depends on labels being part
# of the proxy set to get the right result
l1, l2 = table1.c.col1.label("foo"), table1.c.col1.label("bar")
sel = select(l1, l2)
sel2 = sel.alias()
assert sel2.corresponding_column(l1) is sel2.c.foo
assert sel2.corresponding_column(l2) is sel2.c.bar
sel2 = select(table1.c.col1.label("foo"), table1.c.col2.label("bar"))
sel3 = sel.union(sel2).alias()
assert sel3.corresponding_column(l1) is sel3.c.foo
assert sel3.corresponding_column(l2) is sel3.c.bar
def test_keyed_gen(self):
s = select(keyed)
eq_(s.selected_columns.colx.key, "colx")
eq_(s.selected_columns.colx.name, "x")
assert (
s.selected_columns.corresponding_column(keyed.c.colx)
is s.selected_columns.colx
)
assert (
s.selected_columns.corresponding_column(keyed.c.coly)
is s.selected_columns.coly
)
assert (
s.selected_columns.corresponding_column(keyed.c.z)
is s.selected_columns.z
)
sel2 = s.alias()
assert sel2.corresponding_column(keyed.c.colx) is sel2.c.colx
assert sel2.corresponding_column(keyed.c.coly) is sel2.c.coly
assert sel2.corresponding_column(keyed.c.z) is sel2.c.z
def test_keyed_label_gen(self):
s = select(keyed).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
assert (
s.selected_columns.corresponding_column(keyed.c.colx)
is s.selected_columns.keyed_colx
)
assert (
s.selected_columns.corresponding_column(keyed.c.coly)
is s.selected_columns.keyed_coly
)
assert (
s.selected_columns.corresponding_column(keyed.c.z)
is s.selected_columns.keyed_z
)
sel2 = s.alias()
assert sel2.corresponding_column(keyed.c.colx) is sel2.c.keyed_colx
assert sel2.corresponding_column(keyed.c.coly) is sel2.c.keyed_coly
assert sel2.corresponding_column(keyed.c.z) is sel2.c.keyed_z
def test_keyed_c_collection_upper(self):
c = Column("foo", Integer, key="bar")
t = Table("t", MetaData(), c)
is_(t.c.bar, c)
def test_keyed_c_collection_lower(self):
c = column("foo")
c.key = "bar"
t = table("t", c)
is_(t.c.bar, c)
def test_clone_c_proxy_key_upper(self):
c = Column("foo", Integer, key="bar")
t = Table("t", MetaData(), c)
s = select(t)._clone()
assert c in s.selected_columns.bar.proxy_set
s = select(t).subquery()._clone()
assert c in s.c.bar.proxy_set
def test_clone_c_proxy_key_lower(self):
c = column("foo")
c.key = "bar"
t = table("t", c)
s = select(t)._clone()
assert c in s.selected_columns.bar.proxy_set
s = select(t).subquery()._clone()
assert c in s.c.bar.proxy_set
def test_no_error_on_unsupported_expr_key(self):
from sqlalchemy.sql.expression import BinaryExpression
def myop(x, y):
pass
t = table("t", column("x"), column("y"))
expr = BinaryExpression(t.c.x, t.c.y, myop)
s = select(t, expr)
# anon_label, e.g. a truncated_label, is used here because
# the expr has no name, no key, and myop() can't create a
# string, so this is the last resort
eq_(s.selected_columns.keys(), ["x", "y", "_no_label"])
s = select(t, expr).subquery()
eq_(s.c.keys(), ["x", "y", "_no_label"])
def test_cloned_intersection(self):
t1 = table("t1", column("x"))
t2 = table("t2", column("x"))
s1 = t1.select()
s2 = t2.select()
s3 = t1.select()
s1c1 = s1._clone()
s1c2 = s1._clone()
s2c1 = s2._clone()
s3c1 = s3._clone()
eq_(base._cloned_intersection([s1c1, s3c1], [s2c1, s1c2]), {s1c1})
def test_cloned_difference(self):
t1 = table("t1", column("x"))
t2 = table("t2", column("x"))
s1 = t1.select()
s2 = t2.select()
s3 = t1.select()
s1c1 = s1._clone()
s1c2 = s1._clone()
s2c1 = s2._clone()
s3c1 = s3._clone()
eq_(
base._cloned_difference([s1c1, s2c1, s3c1], [s2c1, s1c2]),
{s3c1},
)
def test_distance_on_aliases(self):
a1 = table1.alias("a1")
for s in (
select(a1, table1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery(),
select(table1, a1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery(),
):
assert s.corresponding_column(table1.c.col1) is s.c.table1_col1
assert s.corresponding_column(a1.c.col1) is s.c.a1_col1
def test_join_against_self(self):
jj = select(table1.c.col1.label("bar_col1")).subquery()
jjj = join(table1, jj, table1.c.col1 == jj.c.bar_col1)
# test column directly against itself
# joins necessarily have to prefix column names with the name
# of the selectable, else the same-named columns will overwrite
# one another. In this case, we unfortunately have this
# unfriendly "anonymous" name, whereas before when select() could
# be a FROM the "bar_col1" label would be directly in the join()
# object. However this was a useless join() object because PG and
# MySQL don't accept unnamed subqueries in joins in any case.
name = "%s_bar_col1" % (jj.name,)
assert jjj.corresponding_column(jjj.c.table1_col1) is jjj.c.table1_col1
assert jjj.corresponding_column(jj.c.bar_col1) is jjj.c[name]
# test alias of the join
j2 = (
jjj.select()
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery("foo")
)
assert j2.corresponding_column(table1.c.col1) is j2.c.table1_col1
def test_clone_append_column(self):
sel = select(literal_column("1").label("a"))
eq_(list(sel.selected_columns.keys()), ["a"])
cloned = visitors.ReplacingCloningVisitor().traverse(sel)
cloned.add_columns.non_generative(
cloned, literal_column("2").label("b")
)
cloned.add_columns.non_generative(cloned, func.foo())
eq_(list(cloned.selected_columns.keys()), ["a", "b", "foo"])
def test_clone_col_list_changes_then_proxy(self):
t = table("t", column("q"), column("p"))
stmt = select(t.c.q).subquery()
def add_column(stmt):
stmt.add_columns.non_generative(stmt, t.c.p)
stmt2 = visitors.cloned_traverse(stmt, {}, {"select": add_column})
eq_(list(stmt.c.keys()), ["q"])
eq_(list(stmt2.c.keys()), ["q", "p"])
def test_clone_col_list_changes_then_schema_proxy(self):
t = Table("t", MetaData(), Column("q", Integer), Column("p", Integer))
stmt = select(t.c.q).subquery()
def add_column(stmt):
stmt.add_columns.non_generative(stmt, t.c.p)
stmt2 = visitors.cloned_traverse(stmt, {}, {"select": add_column})
eq_(list(stmt.c.keys()), ["q"])
eq_(list(stmt2.c.keys()), ["q", "p"])
@testing.combinations(
func.now(), null(), true(), false(), literal_column("10"), column("x")
)
def test_const_object_correspondence(self, c):
"""test #7154"""
stmt = select(c).subquery()
stmt2 = select(stmt)
is_(
stmt2.selected_columns.corresponding_column(c),
stmt2.selected_columns[0],
)
def test_append_column_after_visitor_replace(self):
# test for a supported idiom that matches the deprecated / removed
# replace_selectable method
basesel = select(literal_column("1").label("a"))
tojoin = select(
literal_column("1").label("a"), literal_column("2").label("b")
)
basefrom = basesel.alias("basefrom")
joinfrom = tojoin.alias("joinfrom")
sel = select(basefrom.c.a)
replace_from = basefrom.join(joinfrom, basefrom.c.a == joinfrom.c.a)
def replace(elem):
if elem is basefrom:
return replace_from
replaced = visitors.replacement_traverse(sel, {}, replace)
self.assert_compile(
replaced,
"SELECT basefrom.a FROM (SELECT 1 AS a) AS basefrom "
"JOIN (SELECT 1 AS a, 2 AS b) AS joinfrom "
"ON basefrom.a = joinfrom.a",
)
replaced.selected_columns
replaced.add_columns.non_generative(replaced, joinfrom.c.b)
self.assert_compile(
replaced,
"SELECT basefrom.a, joinfrom.b FROM (SELECT 1 AS a) AS basefrom "
"JOIN (SELECT 1 AS a, 2 AS b) AS joinfrom "
"ON basefrom.a = joinfrom.a",
)
@testing.combinations(
("_internal_subquery",),
("selected_columns",),
("_all_selected_columns"),
)
def test_append_column_after_legacy_subq(self, attr):
"""test :ticket:`6261`"""
t1 = table("t1", column("a"), column("b"))
s1 = select(t1.c.a)
if attr == "selected_columns":
s1.selected_columns
elif attr == "_internal_subuqery":
with testing.expect_deprecated("The SelectBase.c"):
s1.c
elif attr == "_all_selected_columns":
s1._all_selected_columns
s1.add_columns.non_generative(s1, t1.c.b)
self.assert_compile(s1, "SELECT t1.a, t1.b FROM t1")
def test_against_cloned_non_table(self):
# test that corresponding column digs across
# clone boundaries with anonymous labeled elements
col = func.count().label("foo")
sel = select(col).subquery()
sel2 = visitors.ReplacingCloningVisitor().traverse(sel)
assert sel2.corresponding_column(col) is sel2.c.foo
sel3 = visitors.ReplacingCloningVisitor().traverse(sel2)
assert sel3.corresponding_column(col) is sel3.c.foo
def test_with_only_generative(self):
s1 = table1.select().scalar_subquery()
self.assert_compile(
s1.with_only_columns(s1),
"SELECT (SELECT table1.col1, table1.col2, "
"table1.col3, table1.colx FROM table1) AS anon_1",
)
def test_reduce_cols_odd_expressions(self):
"""test util.reduce_columns() works with text, non-col expressions
in a SELECT.
found_during_type_annotation
"""
stmt = select(
table1.c.col1,
table1.c.col3 * 5,
text("some_expr"),
table2.c.col2,
func.foo(),
).join(table2)
self.assert_compile(
stmt.reduce_columns(only_synonyms=False),
"SELECT table1.col1, table1.col3 * :col3_1 AS anon_1, "
"some_expr, foo() AS foo_1 FROM table1 JOIN table2 "
"ON table1.col1 = table2.col2",
)
def test_with_only_generative_no_list(self):
s1 = table1.select().scalar_subquery()
with testing.expect_raises_message(
exc.ArgumentError,
r"The \"entities\" argument to "
r"Select.with_only_columns\(\), when referring "
"to a sequence of items, is now passed",
):
s1.with_only_columns([s1])
@testing.combinations(
(
[table1.c.col1],
[table1.join(table2)],
[table1.join(table2)],
[table1],
),
([table1], [table2], [table2, table1], [table1]),
(
[table1.c.col1, table2.c.col1],
[],
[table1, table2],
[table1, table2],
),
)
def test_froms_accessors(
self, cols_expr, select_from, exp_final_froms, exp_cc_froms
):
"""tests for #6808"""
s1 = select(*cols_expr).select_from(*select_from)
for ff, efp in zip_longest(s1.get_final_froms(), exp_final_froms):
assert ff.compare(efp)
eq_(s1.columns_clause_froms, exp_cc_froms)
def test_scalar_subquery_from_subq_same_source(self):
s1 = select(table1.c.col1)
for i in range(2):
stmt = s1.subquery().select().scalar_subquery()
self.assert_compile(
stmt,
"(SELECT anon_1.col1 FROM "
"(SELECT table1.col1 AS col1 FROM table1) AS anon_1)",
)
def test_type_coerce_preserve_subq(self):
class MyType(TypeDecorator):
impl = Integer
cache_ok = True
stmt = select(type_coerce(column("x"), MyType).label("foo"))
subq = stmt.subquery()
stmt2 = subq.select()
subq2 = stmt2.subquery()
assert isinstance(stmt._raw_columns[0].type, MyType)
assert isinstance(subq.c.foo.type, MyType)
assert isinstance(stmt2.selected_columns.foo.type, MyType)
assert isinstance(subq2.c.foo.type, MyType)
def test_type_coerce_selfgroup(self):
no_group = column("a") // type_coerce(column("x"), Integer)
group = column("b") // type_coerce(column("y") * column("w"), Integer)
self.assert_compile(no_group, "a / x")
self.assert_compile(group, "b / (y * w)")
def test_subquery_on_table(self):
sel = (
select(table1, table2)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
assert sel.corresponding_column(table1.c.col1) is sel.c.table1_col1
assert (
sel.corresponding_column(table1.c.col1, require_embedded=True)
is sel.c.table1_col1
)
assert table1.corresponding_column(sel.c.table1_col1) is table1.c.col1
assert (
table1.corresponding_column(
sel.c.table1_col1, require_embedded=True
)
is None
)
def test_join_against_join(self):
j = outerjoin(table1, table2, table1.c.col1 == table2.c.col2)
jj = (
select(table1.c.col1.label("bar_col1"))
.select_from(j)
.alias(name="foo")
)
jjj = join(table1, jj, table1.c.col1 == jj.c.bar_col1)
assert jjj.corresponding_column(jjj.c.table1_col1) is jjj.c.table1_col1
j2 = jjj._anonymous_fromclause("foo")
assert j2.corresponding_column(jjj.c.table1_col1) is j2.c.table1_col1
assert jjj.corresponding_column(jj.c.bar_col1) is jj.c.bar_col1
def test_table_alias(self):
a = table1.alias("a")
j = join(a, table2)
criterion = a.c.col1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_join_doesnt_derive_from_onclause(self):
# test issue #4621. the hide froms from the join comes from
# Join._from_obj(), which should not include tables in the ON clause
t1 = table("t1", column("a"))
t2 = table("t2", column("b"))
t3 = table("t3", column("c"))
t4 = table("t4", column("d"))
j = t1.join(t2, onclause=t1.c.a == t3.c.c)
j2 = t4.join(j, onclause=t4.c.d == t2.c.b)
stmt = select(t1, t2, t3, t4).select_from(j2)
self.assert_compile(
stmt,
"SELECT t1.a, t2.b, t3.c, t4.d FROM "
"t4 JOIN (t1 JOIN t2 ON t1.a = t3.c) ON t4.d = t2.b, t3",
)
stmt = select(t1).select_from(t3).select_from(j2)
self.assert_compile(
stmt,
"SELECT t1.a FROM t3, t4 JOIN (t1 JOIN t2 ON t1.a = t3.c) "
"ON t4.d = t2.b",
)
@testing.fails("not supported with rework, need a new approach")
def test_alias_handles_column_context(self):
# not quite a use case yet but this is expected to become
# prominent w/ PostgreSQL's tuple functions
stmt = select(table1.c.col1, table1.c.col2)
a = stmt.alias("a")
# TODO: this case is crazy, sending SELECT or FROMCLAUSE has to
# be figured out - is it a scalar row query? what kinds of
# statements go into functions in PG. seems likely select statement,
# but not alias, subquery or other FROM object
self.assert_compile(
select(func.foo(a)),
"SELECT foo(SELECT table1.col1, table1.col2 FROM table1) "
"AS foo_1 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2 FROM table1) "
"AS a",
)
def test_union_correspondence(self):
# tests that we can correspond a column in a Select statement
# with a certain Table, against a column in a Union where one of
# its underlying Selects matches to that same Table
u = select(
table1.c.col1,
table1.c.col2,
table1.c.col3,
table1.c.colx,
null().label("coly"),
).union(
select(
table2.c.col1,
table2.c.col2,
table2.c.col3,
null().label("colx"),
table2.c.coly,
)
)