Skip to content

Commit ad54ef4

Browse files
fix: fix mssql syntax in subqueries
1 parent 15ff868 commit ad54ef4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

ibis/backends/sql/compilers/mssql.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,20 @@ def rewrite_rows_range_order_by_window(_, **kwargs):
6161
return _.copy(order_by=(_.func.arg,))
6262

6363

64+
from ibis.expr.datatypes import dt
65+
from ibis.expr.operations import IfElse
66+
67+
# wrap any boolean-valued SELECT column in IIF(..) CAST BIT (Gil tip)
68+
@replace(p.Select)
69+
def cast_boolean_in_select(_, **kwargs):
70+
new_selections: dict[str, Any] = {}
71+
for name, expr in _.selections.items():
72+
if expr.dtype.is_boolean():
73+
new_selections[name] = IfElse(expr, 1, 0).cast(dt.boolean)
74+
else:
75+
new_selections[name] = expr
76+
return _.copy(selections=new_selections)
77+
6478
class MSSQLCompiler(SQLGlotCompiler):
6579
__slots__ = ()
6680

@@ -69,6 +83,7 @@ class MSSQLCompiler(SQLGlotCompiler):
6983
dialect = MSSQL
7084
type_mapper = MSSQLType
7185
rewrites = (
86+
cast_boolean_in_select,
7287
exclude_unsupported_window_frame_from_ops,
7388
exclude_unsupported_window_frame_from_row_number,
7489
exclude_unsupported_window_frame_from_rank,
@@ -553,5 +568,13 @@ def visit_RPad(self, op, *, arg, length, pad):
553568
),
554569
)
555570

571+
def visit_IfElse(self, op, *, bool_expr, true_expr, false_null_expr):
572+
iif_expr = super().visit_IfElse(
573+
op,
574+
bool_expr=bool_expr,
575+
true_expr=true_expr,
576+
false_null_expr=false_null_expr,
577+
)
578+
return self.cast(iif_expr, dt.boolean)
556579

557580
compiler = MSSQLCompiler()

0 commit comments

Comments
 (0)