sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

TSQL: CAST(x AS BOOLEAN) in a predicate generates invalid SQL on the first transpile pass

Open Sun-Wukhan opened this issue 2 weeks ago • 1 comments

Fully reproducible code snippet

import sqlglot

sqlglot.transpile("SELECT x FROM t WHERE CAST(y AS BOOLEAN)", read="tsql", write="tsql")
# ['SELECT x FROM t WHERE CAST(y AS BIT)']

sqlglot.transpile("SELECT x FROM t WHERE CAST(y AS BIT)", read="tsql", write="tsql")
# ['SELECT x FROM t WHERE CAST(y AS BIT) <> 0']

Expected

Transpilation should be a fixed point, and the first-pass output should be valid T-SQL. A bare CAST(y AS BIT) is not a valid SQL Server predicate, which is why the T-SQL generator normally appends <> 0 to non-boolean conditions. A direct CAST(y AS BIT) input is coerced correctly on the first pass.

Actual

The generator decides the <> 0 coercion from the AST node's type: a CAST ... AS BOOLEAN node counts as boolean, so no coercion is applied, but the cast's type prints as BIT, so the emitted SQL is a bare BIT predicate. Re-parsing yields a BIT cast (non-boolean), and the second generation does append <> 0. Also affected: HAVING, CASE WHEN, AND/NOT operands, and TRY_CAST(y AS BOOLEAN). Projection position is unaffected.

Checked against main at commit b294f7f.

Official Documentation

SQL Server bit data type (a bit value is not a boolean predicate): https://learn.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql

Found by property-based testing (a round-trip fixed-point property).

Sun-Wukhan avatar Nov 14 '26 21:11 Sun-Wukhan

I have a fix ready 🙂 Regression tests and 20 live SQL Server checks pass.

Repo´s one-open-PR limit currently prevents me from submitting it while #9106 is open. I'll open the PR once the slot is available

hector2394 avatar Nov 15 '26 11:11 hector2394