How to represent a custom PostgreSQL domain in SQLAlchemy?

这一生的挚爱 提交于 2019-11-29 14:22:30

问题


I'm beginning to incorporate Alembic into my project which already uses SQLAlchemy table definitions. At present my DB schema is managed external to my application, and I want to bring the entire schema into my table definitions file.

In PostgreSQL I use a custom domain for storing email addresses. The PostgreSQL DDL is:

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

How do I represent the creation of this domain, and the usage of it as a column data type, in SQLAlchemy?


回答1:


This likely far from a working solution, but I think the best way to do this would be 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 this badly enough. :)



来源:https://stackoverflow.com/questions/18662846/how-to-represent-a-custom-postgresql-domain-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!