Skip to content

Commit 906bb65

Browse files
zzzeekGerrit Code Review
authored andcommitted
Merge "Correctly apply self_group in type_coerce element."
2 parents a2e8e77 + d163088 commit 906bb65

3 files changed

Lines changed: 25 additions & 6 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.. change::
2+
:tags: bug, sql
3+
:tickets: 5344
4+
5+
Correctly apply self_group in type_coerce element.
6+
7+
The type coerce element did not correctly apply grouping rules when using
8+
in an expression

lib/sqlalchemy/sql/elements.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2823,14 +2823,11 @@ def __init__(self, expression, type_):
28232823
renders SQL that labels the expression, but otherwise does not
28242824
modify its value on the SQL side::
28252825
2826-
SELECT date_string AS anon_1 FROM log
2826+
SELECT date_string AS date_string FROM log
28272827
2828-
When result rows are fetched, the ``StringDateTime`` type
2828+
When result rows are fetched, the ``StringDateTime`` type processor
28292829
will be applied to result rows on behalf of the ``date_string`` column.
2830-
The rationale for the "anon_1" label is so that the type-coerced
2831-
column remains separate in the list of result columns vs. other
2832-
type-coerced or direct values of the target column. In order to
2833-
provide a named label for the expression, use
2830+
In order to provide a named label for the expression, use
28342831
:meth:`_expression.ColumnElement.label`::
28352832
28362833
stmt = select([
@@ -2893,6 +2890,13 @@ def typed_expression(self):
28932890
def wrapped_column_expression(self):
28942891
return self.clause
28952892

2893+
def self_group(self, against=None):
2894+
grouped = self.clause.self_group(against=against)
2895+
if grouped is not self.clause:
2896+
return TypeCoerce(grouped, self.type)
2897+
else:
2898+
return self
2899+
28962900

28972901
class Extract(ColumnElement):
28982902
"""Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""

test/sql/test_selectable.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,13 @@ class MyType(TypeDecorator):
439439
assert isinstance(stmt2.selected_columns.foo.type, MyType)
440440
assert isinstance(subq2.c.foo.type, MyType)
441441

442+
def test_type_coerce_selfgroup(self):
443+
no_group = column("a") / type_coerce(column("x"), Integer)
444+
group = column("b") / type_coerce(column("y") * column("w"), Integer)
445+
446+
self.assert_compile(no_group, "a / x")
447+
self.assert_compile(group, "b / (y * w)")
448+
442449
def test_subquery_on_table(self):
443450
sel = select([table1, table2], use_labels=True).subquery()
444451

0 commit comments

Comments
 (0)