'SQLAlchemy: filtering for string/number queries result in "?" in SQL

I'm having trouble with a basic join query in SQLAlchemy.

SQLAlchemy Query

with Session.begin() as session:
    fs = session.query(Plan.CoveragePlanId, Plan.ClientId).\
        join(
            History, 
            and_(
                History.ClientCoveragePlanId == Plan.ClientCoveragePlanId, 
                History.RecordDeleted.contains('N')
            ),
            isouter = True
        ).\
            filter(
                and_(
                    Plan.CoveragePlanId == 17436,
                    Plan.RecordDeleted == 'N',
                    Plan.ClientId != 1092374
                )
            )

And here's the SQL output from the engine.

SELECT 
  [ClientCoveragePlans].[CoveragePlanId] AS [ClientCoveragePlans_CoveragePlanId], 
  [ClientCoveragePlans].[ClientId] AS [ClientCoveragePlans_ClientId] 
FROM 
  [ClientCoveragePlans] 
  LEFT OUTER JOIN [ClientCoverageHistory] ON [ClientCoverageHistory].[ClientCoveragePlanId] = [ClientCoveragePlans].[ClientCoveragePlanId] 
  AND (
    [ClientCoverageHistory].[RecordDeleted] LIKE '%' + ? + '%'
  ) 
WHERE 
  [ClientCoveragePlans].[CoveragePlanId] = ? 
  AND [ClientCoveragePlans].[RecordDeleted] = ? 
  AND [ClientCoveragePlans].[ClientId] != ?

I've tried removing the quotes around numbers, same result. As you can see above, I tried column == 'n' and column.containers('n') with the same results. What stupid thing am I overlooking?



Solution 1:[1]

@snakecharmerb and @PaddyAlton sent me down the right path. The '%' symbol does represent a variable pre-rendering.

You can also print the raw SQL of a SQL Server query using the method below:

from sqlalchemy.dialects import mssql
from somewhere import Session

with Session.begin() as session:
    myquery = db.session.query(Model).all()
    print(myquery.statement.compile(
        session, 
        dialect=mssql.dialect(), 
        compile_kwargs={"literal_binds": True}
        )
    )

Thanks for the help!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ishazel