sqlalchemyexiststurbogears

SqlAlchemy: proper way to do a bare exists query


I've the following construct which seems to produce the desired SQL:

>>> print session.query(exists('1').where(MyTable.name=='x'))
SELECT EXISTS (SELECT 1 
FROM my_table
WHERE my_table.name = :name_1) AS anon_1

However, when I try to execute it with .scalar() or .all() it returns the error:

*** UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session

How can I bind it for this simple query? I don't want to do bool(MyTable.query.filter(MyTable.name=='x').first()) as that wastefully pulls back the entire row from the table.


Update:

I've also tried:

>>> session.connection(mapper=MyTable).execute(
        exists('1').where(MyTable.name=='x'))
StatementError: Not an executable clause 'EXISTS \
  (SELECT 1 \nFROM my_table \nWHERE my_table.name = %(name_1)s)' []

Solution

  • Got it I think:

    >>> session.connection(mapper=MyTable).execute(
          select([exists('1').where(MyTable.name=='x')]))