JSON foreign keys in PostgreSQL

后端 未结 3 2006
星月不相逢
星月不相逢 2021-02-12 13:15

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 User         


        
相关标签:
3条回答
  • 2021-02-12 13:32

    The foreign key parameter must be a column name:

    http://www.postgresql.org/docs/current/static/sql-createtable.html

    You will have to normalize

    create table user_data (
        id int not null primary key,
        user_id int not null,
        somedata text,
        constraint fk_users_data foreign key (user_id) references Users(Id)
    );
    
    0 讨论(0)
  • 2021-02-12 13:43

    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.

    0 讨论(0)
  • 2021-02-12 13:49

    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.

    0 讨论(0)
提交回复
热议问题