Skip to content

Avoid creating subqueries for OFFSET (might also be new feature in DB2) #164

@windiana42

Description

@windiana42

This code even produces buggy subqueries:

import sqlalchemy as sa

url = "db2+ibm_db://db2inst1:password@localhost:50000/testdb"

engine = sa.create_engine(url)

with engine.connect() as conn:
    conn.execute(sa.text('CREATE TABLE IF NOT EXISTS "_tmp02" (id INT, name VARCHAR(100))'))
    conn.commit()
tbl = sa.Table("_tmp02", sa.MetaData(), autoload_with=engine).alias("_raw_tmp02")
tbl2 = tbl.alias("_other_tmp02")

id = tbl.c.id.label("id")
x = sa.func.coalesce(id.isnot(None), 0).label("id2")
query = sa.select(id, x).limit(10)
print("Query:")
print(query.compile(engine, compile_kwargs={"literal_binds": True}))
print()
print("Query with offset:")
query = query.offset(5)
print(query.compile(engine, compile_kwargs={"literal_binds": True}))
print()
print('Problem exists (see IS NOT NULL AS "Z.__db2_2"):')
print('coalesce("_raw_tmp02".id IS NOT NULL AS "Z.__db2_2",  0)' in str(query.compile(engine, compile_kwargs={"literal_binds": True})))

output:

Query:
SELECT "_raw_tmp02".id AS id, coalesce("_raw_tmp02".id IS NOT NULL, 0) AS id2 
FROM "_tmp02" AS "_raw_tmp02" LEFT OUTER JOIN "_tmp02" AS "_other_tmp02" ON "_raw_tmp02".id = "_other_tmp02".id FETCH FIRST 10 ROWS ONLY

Query with offset:
( SELECT  id, "Z.__db2_2", id2  FROM ( SELECT  id, "Z.__db2_2", id2 , ( ROW_NUMBER() OVER() ) AS "Z.__ROWNUM" FROM (  SELECT "_raw_tmp02".id AS id,  coalesce("_raw_tmp02".id IS NOT NULL AS "Z.__db2_2",  0) AS id2  
FROM "_tmp02" AS "_raw_tmp02" LEFT OUTER JOIN "_tmp02" AS "_other_tmp02" ON "_raw_tmp02".id = "_other_tmp02".id  ) AS M ) Z WHERE "Z.__ROWNUM" > 5 AND  "Z.__ROWNUM" <= 15 )

Problem exists (see IS NOT NULL AS "Z.__db2_2"):
True

This query would be ideal:

SELECT "_raw_tmp02".id AS id, coalesce("_raw_tmp02".id IS NOT NULL, 0) AS id2
FROM "_tmp02" AS "_raw_tmp02" LEFT OUTER JOIN "_tmp02" AS "_other_tmp02" ON "_raw_tmp02".id = "_other_tmp02".id
LIMIT 10 OFFSET 5

This might also be a new feature of DB2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions