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

编程入门 行业动态 更新时间:2024-10-27 18:31:58
本文介绍了如何在SQLAlchemy中表示自定义PostgreSQL域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我开始将Alembic合并到我的已经使用SQLAlchemy表定义的项目中.目前,我的数据库模式是在应用程序外部进行管理的,我希望将整个模式带入表定义文件中.

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.

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

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

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

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

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

推荐答案

这可能与可行的解决方案相去甚远,但我认为做到这一点的最佳方法是子类.

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. :)

更多推荐

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

本文发布于:2023-10-20 03:43:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509740.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   如何在   SQLAlchemy   PostgreSQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!