Problem description
I have a situation where I want to enforce that a relationship can only be defined once and I want to solve it on database (Postgres) level.
The following situation I consider invalid, because the relationship is defined twice.
user_id | friend_id
---------+-----------
1 | 35
35 | 1
I've tried adding CHECK
constraints [1] but I can't come up with condition that will render this situation invalid. I'm not sure about other ways of handling this, without starting to think of a lot less transparant features (like procedures).
The current table structure:
Table "public.friends"
Column | Type | Modifiers
-----------+---------+-----------
user_id | integer | not null
friend_id | integer | not null
Indexes:
"friends_pkey" PRIMARY KEY, btree (user_id, friend_id)
Check constraints:
"no_schizophrenia" CHECK (friend_id <> user_id)
Foreign-key constraints:
"friends_id_key" FOREIGN KEY (friend_id) REFERENCES users(id)
"user_id_key" FOREIGN KEY (user_id) REFERENCES users(id)
Desired situation
Data:
user_id | friend_id
---------+-----------
1 | 35
Query:
insert into friends (user_id, friend_id) values (35, 1) \g
Result:
ERROR: new row for relation "friends" violates check constraint "duplicate_relation"
DETAIL: Failing row contains (35, 1).
[1] - https://www.postgresql.org/docs/current/static/ddl-constraints.html