StackOverflowNewbie
StackOverflowNewbie

Reputation: 40653

DB Design: how to enforce integrity

Assume I want to log certain things in an activity log in my database. In some cases, these activities are associated with a user (e.g. a user created something). In some cases, these activities are automatically done by the application (e.g. the system updated some record for some reason). I want to be able to keep track of who did what in the system. Keeping track of what users do seems simple:

TABLE: user
- user_id (PK)

TABLE: activity_log
- activity_log_id (PK)
- user_id (FK)

The above design allows me to associate each activity to a particular user (and, thus, enforce referential integrity). However, what if it's the system that took action? It doesn't have a user_id I can insert in the activity_log.

Should I:

Suggestions?

Upvotes: 2

Views: 85

Answers (2)

One of the problems of enforcing referential integrity in logging and auditing applications is that you can't delete a user. (Or whatever thing you're auditing.) You can make a good argument for both cases,

  • live with that restriction, or
  • drop that referential constraint.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434745

You could allow your activity_log.user_id to contain NULLs, then a NULL would indicate that no user performed the action and "no user" means "the system did it".

If you don't want to use NULL to indicate that "the system did it", then you could add a user to your users table and use that user as a placeholder for the "the system did it".

Upvotes: 1

Related Questions