简体   繁体   English

RDBMS中的多行表约束

[英]Multi-row Table Constraint in an RDBMS

Say there is a business level constraint where a given object can have no more than N children objects. 假设存在一个业务级别约束,其中给定对象的子对象不能超过N个。 If you are creating children objects, how can you ensure that you will never create more than N children objects for that given object? 如果要创建子对象,则如何确保为该给定对象创建的子对象绝不超过N个?

If you do a READ to get the number of existing children objects, validate that there are less than N, then do an INSERT in the table, there is time between the READ and INSERT where another INSERT could have gotten in. 如果执行READ获取现有子对象的数量,请验证是否少于N,然后在表中执行INSERT,则在READ和INSERT之间会有一段时间可能会插入另一个INSERT。

You don't want to lock the table since this can adversely affect other queries. 您不想锁定表,因为这可能会对其他查询产生不利影响。

A more concrete example is if you have a Resident object and a Home object. 一个更具体的示例是,如果您有一个Resident对象和Home对象。 In the Resident table, there is something like id, resident_name, home_id. 在“居民”表中,有诸如id,resident_name,home_id之类的内容。 How do you ensure that no more than 4 residents have the same home_id? 您如何确保不超过4位居民拥有相同的home_id?

Relational DB constraints aren't designed to implement business rules -- they're designed to protect data integrity at a technical level, and a lot of modern developers don't like them at all, preferring to view the DB as a simple persistence mechanism. 关系数据库的约束并不是为了实现业务规则而设计的,而是旨在在技术层面上保护数据完整性的,并且许多现代开发人员根本不喜欢它们,而是倾向于将数据库视为一种简单的持久性机制。 。 Though, having said that, in some databases you can achieve what you want though the use of stored procs and triggers. 尽管如此,在某些数据库中,您可以通过使用存储的proc和触发器来实现所需的功能。

If you want to ensure that this rule can 'never' be violated then the DB must become a private data store for a service that is the only method of accessing the database, and all access to it must go via that service. 如果要确保“从不”违反此规则,则数据库必须成为服务的私有数据存储,这是访问数据库的唯一方法,并且对数据库的所有访问都必须通过该服务进行。 This service could then implement this, and other business rules, in a clear and consistent way. 然后,该服务可以以清晰一致的方式实施此规则以及其他业务规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM