How to represent a custom PostgreSQL domain in SQLAlchemy?

I am starting to include Alembic in my project, which already uses SQLAlchemy table definitions. Currently, my database schema is managed externally for my application, and I want to bring the whole schema to a table definition file.

In PostgreSQL, I use my own domain to store email addresses. PostgreSQL DDL:

CREATE DOMAIN email_address TEXT CHECK (value ~ ' .+@. +') 

How can I imagine creating this domain and using it as a column data type in SQLAlchemy?

+7
python orm sqlalchemy alembic sql-domain
source share
1 answer

This is most likely far from a working solution, but I think the best way to do this is to subclass sqlalchemy.schema._CreateDropBase .

 from sqlalchemy.schema import _CreateDropBase class CreateDomain(_CreateDropBase): '''Represent a CREATE DOMAIN statement.''' __visit_name__ = 'create_domain' def __init__(self, element, bind=None, **kw): super(CreateDomain, self).__init__(element, bind=bind, **kw) class DropDomain(_CreateDropBase): '''Represent a DROP BASE statement.''' __visit_name__ = 'drop_domain' def __init__(self, element, bind=None, **kw): super(DropDomain, self).__init__(element, bind=bind, **kw) @compiles(CreateDomain, 'postgresql') def visit_create_domain(element, compiler, **kw): text = '\nCREATE DOMAIN %s AS %s' % ( compiler.prepare.format_column(element.name), compiler.preparer.format_column(element.type_)) # doesn't account for arrays and such I don't think default = compiler.get_column_default_string(column) if default is not None: text += " DEFAULT %s" % default return text 

Obviously this is incomplete, but it should give you a good starting point if you want it bad enough. :)

0
source share

All Articles