Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON foreign keys in PostgreSQL

Tags:

Is it possible to assign a foreign key to a json property in PostgreSQL? Here is an example what I would like to achieve, but it doesn't work:

CREATE TABLE Users (Id int NOT NULL PRIMARY KEY);  CREATE TABLE Data (     Id int NOT NULL PRIMARY KEY,     JsonData json NOT NULL, -- [{Id: 1, somedata: null},{Id: 2, somedata: null}, ...]     CONSTRAINT FK_Users_Data FOREIGN KEY (JsonData->Id) REFERENCES Users(Id) -- this constraint will fail ); 
like image 785
user1613797 Avatar asked Jun 30 '14 11:06

user1613797


People also ask

What is foreign key in PostgreSQL?

The PostgreSQL FOREIGN KEY is a combination of columns with values based on the primary key values from another table. A foreign key constraint, also known as Referential integrity Constraint, specifies that the values of the foreign key correspond to actual values of the primary key in the other table.

Should you use JSON in Postgres?

Follow these guidelines when you consider using JSON in PostgreSQL: Don't use JSON for data that can easily be stored in database tables. Avoid large JSON objects if you want to modify individual attributes. Don't use JSON if you want to use attributes in complicated WHERE conditions.


Video Answer


2 Answers

It is not possible, and may not ever be possible, to assign a foreign key to a json property. It'd be a major and quite complicated change to PostgreSQL's foreign key enforcement. I don't think it's impossible to do, but would face similar issues to those experienced by the foreign-keys-to-arrays patch.

With 9.4 it'll be possible to make a whole json object a foreign key as jsonb supports equality tests. In 9.3 you can't even do that.

like image 69
Craig Ringer Avatar answered Oct 19 '22 18:10

Craig Ringer


Here's a little SPI function have_ids which I use for an integrity constraint on a one-to-many relationship with a jsonb column

CREATE TABLE foo (   id INTEGER NOT NULL )  CREATE TABLE bar (   foo_ids pg_catalog.jsonb DEFAULT '[]'::jsonb NOT NULL,   CONSTRAINT bar_fooids_chk CHECK (have_ids ('foo', foo_ids)) ) 

With a couple of triggers on foo it's almost as good as a foreign key.

like image 23
ArtemGr Avatar answered Oct 19 '22 16:10

ArtemGr