I run a small food production business and I need to manage customer orders. I have built a conceptual data model of this aspect of my business but I need some pointers on how to fully implement this in an RDMS.
As a first step, I have come up with the logical model given below. My knowledge of data modeling is limited, so there may be errors in my diagram but hopefully it conveys my intention. Note that this is merely a simplified portion of a larger schema and I'm presenting only the relevant tables for the sake of simplicity.
The data model in brief
- A customer Ordr can have one or more OrdrItems
- An OrdrItem can be either a FoodItem or a ComboItem
- A ComboItem is a logical grouping of two or more FoodItems
I have implemented the above schema in MySQL and I have written a few small programs to populate the tables with customer orders. This gets the job done but without much thought towards data integrity. I have noticed that with this implementation some data integrity rules are not enforced at the database level.
For example, FoodItem is a subtype of OrdrItem. For each row in FoodItem there must be exactly one corresponding row in OrdrItem. However, in its current implementation, I can delete a row from FoodItem thus leaving a row in OrdrItem without a corresponding row in one of the subtype tables. This should be disallowed.
Some further data constraints
- An order must have at least one associated "order item" (i.e., an order cannot be empty)
- An order item must be of exactly one associated subtype of either FoodItem or ComboItem (i.e., an OrderItem cannot be both a FoodItem and ComboItem).
- Some further constraints will probably arise in the future
I would like these data integrity rules to be baked into the database, such that I don't have to concern myself with their enforcement in every new client application, throw-away script or shoddy SQL statement that I write. I suspect that if I don't make these guarantees at the database level, I greatly increase my chances of running into data integrity issues down the road.
The question
I have only the faintest knowledge of stored procedures, triggers, and user-defined functions. I get the impression that some or all of these features can help me achieve what I want. However, if I can get the job done with check constraints, foreign keys and relatively simple features alone, I'll gladly go that route. Basically, I want to limit complexity as much as possible and not pull in every nifty database feature if it isn't warranted. Is it possible to ensure the data integrity I want without resorting to stored procedures, triggers, user-defined functions and other more esoteric database features?
I'm willing to use either MySQL or Postgresql to implement my solution as I have a basic working knowledge of both systems.
Finally, if this kind of approach towards data integrity is considered overkill, or if there is a far more pragmatic but slightly imperfect solution, I'm open to that as well.