Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: How to conditionally choose type for column by depending on its backend

I want to use HSTORE type for a column if it uses PostgreSQL as its backend, or PickleType otherwise. The problem is that we cannot determine which backend will be used when schema is being defined (in Python). How can I determine this and conditionally choose the data type when the table actually is created on the backend database?

like image 354
minhee Avatar asked Mar 01 '13 16:03

minhee


1 Answers

You can accomplish something like this with TypeEngine.with_variant:

from sqlalchemy.types import PickleType
from sqlalchemy.dialects import postgresql

HybridType = PickleType()

HybridType = HybridType.with_variant(postgresql.HSTORE(), 'postgresql')

This creates a new type, HybridType, which you can use like any other type, with the caveat that it will produce an HSTORE column on Postgres and a PickleType everywhere else.

like image 109
Kurt Raschke Avatar answered Oct 13 '22 02:10

Kurt Raschke