I'm using postgres and I'm trying to obtain this raw query using SQLAlchemy expression, but I'm not able to:
SELECT foo.id FROM foo WHERE NOT foo.id = ANY('{1,2,3}'::int[]);
I tested it with the following table definition:
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class foo(Base):
__tablename__ = 'foo'
id = Column(Integer(), primary_key=True)
name = Column(String(80), unique=True)
and by running the followings in IPython:
In [57]: from sqlalchemy.sql.expression import any_, not_
In [58]: from sqlalchemy.dialects import postgresql
In [59]: def compile_(where):
...: statement = select([foo.id, foo.name]).where(where)
...: return str(statement.compile(dialect=postgresql.dialect()))
...:
In [60]: where1 = not_(foo.id == any_([1,2,3]))
In [61]: compile_(where1)
Out[61]: 'SELECT foo.id, foo.name \nFROM foo \nWHERE foo.id != ANY (%(param_1)s)'
As you can see, instead of obtaining WHERE NOT foo.id != ANY(...) I get WHERE foo.id != ANY(...).
NOTES:
I'm aware of IN and NOT IN, but I cannot use them due to the length of other which is > 32767 and this causes an InterfaceError due to the number of bind arguments.
Seems SQLAlchemy tries to be too smart. You can outsmart it not using NOT:
where1 = foo.id != all_([1,2,3]))