加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在SQLAlchemy中表示自定义PostgreSQL域?

发布时间:2020-12-13 16:17:19 所属栏目:百科 来源:网络整理
导读:我开始将Alembic合并到我已经使用SQLAlchemy表定义的项目中.目前我的数据库架构是在我的应用程序外部管理的,我想将整个架构带入我的表定义文件中. 在PostgreSQL中,我使用自定义域来存储电子邮件地址. PostgreSQL DDL是: CREATE DOMAIN email_address TEXT C
我开始将Alembic合并到我已经使用SQLAlchemy表定义的项目中.目前我的数据库架构是在我的应用程序外部管理的,我想将整个架构带入我的表定义文件中.

在PostgreSQL中,我使用自定义域来存储电子邮件地址. PostgreSQL DDL是:

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

如何在SQLAlchemy中表示此域的创建及其作为列数据类型的用法?

这可能远不是一个有效的解决方案,但我认为最好的方法是子类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,**kw):
        super(DropDomain,**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

显然,这是不完整的,但如果你想要这么做的话,它应该给你一个很好的起点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读