Skip to content

Instantly share code, notes, and snippets.

@rintaun
Last active December 14, 2015 22:19
Show Gist options
  • Save rintaun/5157422 to your computer and use it in GitHub Desktop.
Save rintaun/5157422 to your computer and use it in GitHub Desktop.
+---------------+
| organizations |
+---------------+
+------>| id(PK) |<---------+
| +---------------+ |
| |
| +--------+ +----------+ |
| | groups | | profiles | |
| +--------+ +----------+ |
+---| org_id | | org_id |---+
+-->| id(PK) | | id(PK) |<--+
| +--------+ +----------+ |
| |
| +----------------+ |
| | group_profiles | |
| +----------------+ |
+-------| group_id | |
| profile_id |---------+
+----------------+
@rintaun
Copy link
Author

rintaun commented Mar 13, 2013

In the file without_org_id_fk, entries in group_profiles cannot guarantee that the referenced group and profile will be owned by the same organization.

In order to guarantee this, group_profiles must have an org_id attribute as well, and reference it in its relationships with both groups and profiles.

Currently, this requires an additional constraint -- UNIQUE (id, org_id) -- on both groups and profiles; without it PG complains:

there is no unique constraint matching given keys for referenced table

However, a set of attributes is necessarily unique if one or more of the attributes contained in that set is unique. Which is to say, the uniqueness of the keys is implied as the id attribute in each case is a PK.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment