Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic TEXT/CLOB data type for cross-database SQLAlchemy application

I am working on Python web application that uses MySQL as a database backend on the development environment and Oracle 11g on the production environment. Is there a specific way to unify the SQLAlchemy text fields, so that they work both on MySQL and Oracle database? For the Oracle backend in the models I use sqlalchemy.CLOB and for MySQL sqlalchemy.TEXT.

like image 949
Jordan Jambazov Avatar asked Jan 22 '26 11:01

Jordan Jambazov


2 Answers

According to @agronholm on #sqlalchemy one is supposed to use generic SQLAlchemy type Text (which TEXT is specialization of):

A variably sized string type.

In SQL, usually corresponds to CLOB or TEXT. Can also take Python unicode objects and encode to the database’s encoding in bind params (and the reverse for result sets.) In general, TEXT objects do not have a length; while some databases will accept a length argument here, it will be rejected by others.

like image 102
Piotr Dobrogost Avatar answered Jan 25 '26 01:01

Piotr Dobrogost


I think that using this official documentation trick should do the trick: Overiding Type Compilation. In this case i would keep CLOB as original because it is used in production, and would apply a compilation for mysql:

from sqlalchemy.ext.compiler import compiles
from sqlalchemy.types import CLOB

@compiles(CLOB, "mysql")
def compile_binary_mysql(type_, compiler, **kw):
    return "TEXT"
    # @note: this will handle other parameter such as `length`
    # return compiler.visit_TEXT(type_, **kw)

Note that it is strongly advised to use the same RDBMS for production/test/development to avoid these and other issues.

like image 26
van Avatar answered Jan 24 '26 23:01

van



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!