select * from users where binary name = 'AdMin';
select * from users where binary name = 'admin';
from sqlalchemy import func
User.query.filter(User.name == func.binary('AdMin')).count()
User.query.filter(User.name == func.binary('admin')).count()
how to force a filter() to match exact cases (case sensitivity) in sqlalchemy?
-
03-06-2023 - |
Вопрос
I am using sqlalchemy with mysql database. When I am using following query on User object :
session.query(User).filter(User.name == 'admin').all()
I get all the results which have usename as 'Admin', 'admin', 'ADMIN' (basically all case-insensitive 'admin'). I would like to know how can I force a filter() to filter exact matches (without ignoring cases)?
Update : Actually I just came to know that mysql does not allow case-sensitive columns for varchar() datatype. So the simplest solution would be to force a column to be case-sensitive while declaring in mysql, as :
`name` VARCHAR(255) BINARY NULL UNIQUE,
But I would still love to know how can I force a filter to match the results exactly (not ignoring cases). Is there anyway using some inbuilt (or custom, if possible) sqlalchemy func?
Нет правильного решения
Другие советы
Generally, what SQLAlchemy does is construct a SQL string query out of the expressions. Typing freely your above expression would yield something like this:
SELECT user.* FROM user WHERE user.name = 'admin'
Of course, user.*
would replaced by an explicity enumeration of all user
columns.
The thing is that it depends what this query returns: If it compares case-insensitively, there is not much SQLAlchemy can do. From what I gather looking around, you can explicitly construct a query using WHERE BINARY user.name = 'admin'
. However, I am not aware of a SQLAlchemy equivalent, so you might be stuck with building a literal string here.
Anyways, I would suggest that you ask on the SQLAlchemy list for the particular solution (especially, I think it would be interesting to know a way of intergrating the BINARY
into a WHERE
query).