简体   繁体   中英

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. If you are creating children objects, how can you ensure that you will never create more than N children objects for that given object?

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.

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. In the Resident table, there is something like id, resident_name, home_id. How do you ensure that no more than 4 residents have the same 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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