Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database-Independent to_char Function in SQLAlchemy

I am using SQLAlchemy to make database-independent querys.

I am facing one issue with to_char function.

Consider the simple query like:

select to_char(id,'999') from xyz 

It's working on Postgres but MySQL doesn't support it.

How can I make this query database-independent using SQLAlchemy?

like image 610
asb Avatar asked Feb 02 '26 13:02

asb


1 Answers

use the CAST function for simple type conversions. it is SQL standard and SQLAlchemy supports it directly via the cast() function: http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/expressions.html?highlight=cast#sqlalchemy.sql.expression.cast .

for date values, SQLA has an extract() function that produces the SQL EXTRACT function - a translation layer translates common fieldnames like "month", "day", "minute", etc. into the appropriate keyword for the backend in use.

like image 128
zzzeek Avatar answered Feb 04 '26 03:02

zzzeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!