I'm writing up a scheduling application for my wife, and I ran into the following question.
I have a schema that can be described in ActiveRecord terms as such:
- Each resource has and belongs to many events
- Each event has and belongs to many resources, and has many timespans
- Each timespan belongs to an event, and has three attributes: day, start-time, and end-time.
I want to put the following constraints on my data:
A. For each timespan, timespan.start-time ≤ timespan.end-time
B. For each event, for each t_a, t_b ∈ TIMESPANS(event),
either t_a = t_b
or t_a.day ≠ t_b.day
or t_a.end-time ≤ t_b.start-time
or t_a.start-time ≥ t_b.end-time
C. For each resource, for each e_a, e_b ∈ EVENTS(resource),
either e_a = e_b
or for each t_a ∈ TIMESPANS(e_a) and t_b ∈ TIMESPANS(e_b),
either t_a.day ≠ t_b.day
or t_a.end-time ≤ t_b.start-time
or t_a.start-time ≥ t_b.end-time
(A) makes sure timespans are well-formed, (B) makes sure events don't self-conflict, and (C) makes sure resources aren't over-scheduled.
Currently I'm enforcing these constraints at the application layer, but, in the interest of self-learning, I was wondering if I can put these constraints in the database layer.
Is there any way I can express these constraints in SQL?
EDIT:
So I found that what I wanted was SQL's CREATE ASSERTION statement (at least, for the ones that couldn't be covered by a simple CHECK), but it doesn't seem like any RDBMS that supports it (at least, as of 2005)