My app is creating sqlalchemy.Tables from a MySQL database and as it use tinyint(1) as boolean after select.select_from.all i am getting values with int instead of boolean. After that i am using json.dumps to pass it to a js receiver and that is the problem because js can’t distinguish int from bool as they has the same type.
so my question is how can i cast tinyint to bool in moment of execution .all() function in the simplest and most pythonic way?
i have tables with columns which datatype is tinyint. when i am executing select().select_from().all() it returns values with ints, not with bools
2
Answers
By using a cast:
SELECT cast(tiny_int_value as signed) FROM table
If you want to transparently convert the
TINYINT
s to booleans (and the reverse), there are a couple of approaches you could take, depending on how you are reflecting the tables.Let’s assume we have this table:
If you are not reflecting, you can just define the table in the Python layer with the right type:
If you are reflecting the tables via
autoload_with
, you can override the column type when you load the table.If you are reflecting multiple tables at once, via
metadata.reflect
, you can use a listener to automatically change the column type using the reflection process: