I need some suggestions to implement a business rule - whether to keep it in DB (using TRIGGERs) or in App code.
--- Table structure:---
# ORG - Master table for Organizations
# USER - Master table for Users (each user belongs to an Org so there's a field OrgId which is FK ro ORG)
# SITE - Master table for Sites
# ORGSITE - {OrgId, SiteId} links Site(s) with Org(s)
# USERSITE - {UserId, SiteId} links Site(s) with User(s)
The constraint is that : "A site is accessible to a User ONLY if its accessible to his Organization."
Now, it happens in the app that on day1 we relate Site1 to Org1 and then we're able to relate Site1 to User1 (User1 belongs to Org1). On day2 I delete the relationship between Site1 & Org1 from ORGSITE (this requires that I also delete the corresponding User1 & Site1 relationship from the USERSITE table).
This is handled from within the app code. So, now my question is where shud I keep the above constraint handling -
APPROACH#1:
Deploy TRIGGERs on the ORGSITE table and USER table which will handle the activity for:
On after delete for ORGSITE (delete corresponding USERSITE records)
Onafter update for USER (if User's Org is changed then delete all his records from USERSITE)
APPROACH#2:
Handle everything from within the code - tap the events which trigger those DB actions and delete records from USERSITE (as and when necessary). Need to manage via a Transaction.
APPROACH#3:
Simply, add a new field OrgSiteId in the USERSITE table which is an FK ref to an 'Auto Increment PK: Id' of ORGSITE. Next, I'll deploy the cascaded delete for the USERSITE.OrgSiteId FK. This will handle most of the things and make it implicit!
Hope I explaind well. Is APPROACH#3 really gonna work? If not - what is your preference and why?
Thank you for your time.