Skip to content
Advertisement

Postgresql unique constraint for colums of multiple related tables

I have the following tables:

server (server_id as PK)

server_groups
Each server can have multiple server groups, every group name within a server must be unique.

group_tags
Each group can have multiple tags, a tag can be connected to multiple groups. Each tag name must be unique.

group_tag_relations

Problem:

I need group tag names and server group names to be unique within one server. So a tag can be connected to multiple groups, but only to one group per server. Or the tag "foo" cannot be connected to the group "bar" of server z because server z already has a group "foo". The same goes for the other way around, so if the group "foo" had the tag "hey" you shouldn’t be able to add a group "hey" to the same server.

Basically names should not appear multiple times on a server, no matter if tag or group name.

How would I implement such a Constraint?

EDIT

So basically I’m trying to convert this JSON format into SQL tables:

The id’s 5578921 and 3251623 should just represent Discord server id’s, so every id is for one server my bot is on. The Json file is all the information of my bot for each server, but it’s not as reliable and scalable as a database, so I wanted to convert it.

So the upper tables are what I came up with:

A One-To-Many relation between server and server_groups and a Many-To-Many relation between server_groups and group_tags (so instead of storing duplicate tags I can just assign them to different groups).

I just want to make sure there are no duplicate names on one server and asking how to do so for my current tables.

Advertisement

Answer

After hours of suffering I finally got what I wanted:

Get all Tags of a server

Get all Groups of a server

Get a Group by Name (Calling both Functions above)

Update Trigger for server_groups table, checking wether the name is already taken on a server

Insert Trigger for server_groups table, checking wether the name is already taken on a server

Insert Trigger for group_tag_relation table, checking wether the tag is already taken on a server (as the tags wont get updated there’s no need for an update trigger)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement