具有函数的复合UniqueConstraint [英] Compound UniqueConstraint with a function

查看:165
本文介绍了具有函数的复合UniqueConstraint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个快速SQLAlchemy问题...



我有一个类Document,属性为Number和Date。我需要确保同一年没有重复的数字,是
有一个方法可以在数字+年(日期)有一个UniqueConstraint?我应该使用唯一的索引吗?我如何声明函数部分?



(SQLAlchemy 0.5.5,PostgreSQL 8.3.4)




解决方案

您应该使用功能唯一索引来应用此约束。不幸的是,SQLAlchemy中的数据库通用数据库独立模式定义机制尚未抽象函数索引。您必须使用DDL结构注册自定义模式定义子句。如果您使用声明方法声明您的模式,在类定义之后添加以下内容:

  DDL(
CREATE UNIQUE INDEX doc_year_num_uniq ON%(fullname)s
(EXTRACT(YEAR FROM date),number)
).execute_at('after-create',Document .__ table__)

这种方法非常有效,但在v0.7中引发了SADeprecation警告
我成功使用的语法:

 来自sqlalchemy import event 

event.listen(ModelObject .__ table__,
' after_create',
DDL(CREATE UNIQUE INDEX term_year ON%(fullname)s
(EXTRACT(YEAR FROM start_date),term),
on ='postgresql'



A quick SQLAlchemy question...

I have a class "Document" with attributes "Number" and "Date". I need to ensure that there's no duplicated number for the same year, is there a way to have a UniqueConstraint on "Number + year(Date)"? Should I use a unique Index instead? How would I declare the functional part?

(SQLAlchemy 0.5.5, PostgreSQL 8.3.4)

Thanks in advance!

解决方案

You should use a functional unique index to apply this constraint. Unfortunately the database generic database independent schema definition machinery in SQLAlchemy doesn't abstract functional indexes yet. You'll have to use the DDL construct to register custom schema definition clauses. If you are using the declarative approach to declaring your schema add the following after your class definition:

DDL(
    "CREATE UNIQUE INDEX doc_year_num_uniq ON %(fullname)s "
    "(EXTRACT(YEAR FROM date), number)"
).execute_at('after-create', Document.__table__)

This method works very nicely but throws a SADeprecation warning in v0.7 The syntax that I've used successfully:

from sqlalchemy import event

event.listen(ModelObject.__table__,
         'after_create',
          DDL("CREATE UNIQUE INDEX term_year ON %(fullname)s "
              "(EXTRACT(YEAR FROM start_date), term)",
              on = 'postgresql'
              )
         )

这篇关于具有函数的复合UniqueConstraint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆