sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

Bug in handling TVF with a WITH clause - TSQL

Open SALVOuankeBALDO opened this issue 5 months ago • 1 comments

Bug: CTE inside inline TVF RETURN clause is duplicated and misplaced when writing to T-SQL

SQLGlot version: 30.10.0 OS: Windows 11 Python version: 3.13.2

Code to reproduce:

print(sqlglot.transpile(
    "CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (WITH subquery AS (SELECT Id, Name FROM subtable) "
    "SELECT OtherId, Name FROM MainTable MT INNER JOIN subquery ON subquery.Id = MT.OtherId)",
    read="tsql", write="tsql")[0])

Expected result: print identity (up to irrelevant tokens)

Actual result:

WITH subquery AS (SELECT Id AS Id, Name AS Name FROM subtable)
WITH subquery AS (SELECT Id AS Id, Name AS Name FROM subtable)
CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (SELECT OtherId, Name FROM MainTable AS MT INNER JOIN subquery ON subquery.Id = MT.OtherId)

Description:

There are two issues (and I don't know if they are related):

  • the WITH clause is duplicated
  • the WITH clause is moved outside of RETURN (...) instead of staying inside it

Note: this does not happen in PostgreSQL, and it only occurs on the write path. The following calls print identity (up to irrelevant tokens):

print(sqlglot.transpile(
    "CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (WITH subquery AS (SELECT Id, Name FROM subtable) "
    "SELECT OtherId, Name FROM MainTable MT INNER JOIN subquery ON subquery.Id = MT.OtherId)",
    read="tsql", write="postgres")[0])

print(sqlglot.transpile(
    "CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (WITH subquery AS (SELECT Id, Name FROM subtable) "
    "SELECT OtherId, Name FROM MainTable MT INNER JOIN subquery ON subquery.Id = MT.OtherId)",
    read="postgres", write="postgres")[0])

While this call produces the wrong output as described above:

print(sqlglot.transpile(
    "CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (WITH subquery AS (SELECT Id, Name FROM subtable) "
    "SELECT OtherId, Name FROM MainTable MT INNER JOIN subquery ON subquery.Id = MT.OtherId)",
    read="postgres", write="tsql")[0])

SALVOuankeBALDO avatar Jun 09 '26 13:06 SALVOuankeBALDO

Addition: the issue persists if one parses as Expression (using parse or parse_one) and regenerates the tsql query

SALVOuankeBALDO avatar Jun 09 '26 13:06 SALVOuankeBALDO