Adding a key to an empty hstore column

后端 未结 4 1067
礼貌的吻别
礼貌的吻别 2021-02-02 13:30

According to the postgres documentation, you add a key to an hstore column as follows:

UPDATE tab SET h = h || (\'c\' => \'3\');

But it seem

4条回答
  •  半阙折子戏
    2021-02-02 13:36

    I think the problem here is that the hstore you have is null, and null OR some hstore is null.

    The best solution I have, which is probably not the best solution, is to make the table with a default empty hstore rather than allowing null. Then your examples work as you would like:

    postgres=# create table htest (t text, h hstore default hstore(array[]::varchar[]));
    CREATE TABLE
    postgres=# insert into htest (t) values ('key');
    INSERT 0 1
    postgres=# update htest set h = h || ('foo'=>'bar') where t='key';
    UPDATE 1
    postgres=# select * from htest;
      t  |      h       
    -----+--------------
     key | "foo"=>"bar"
    (1 row)
    

    I unfortunately do not see a cleaner way to create an empty hstore than hstore(array[]::varchar[]) but that doesn't mean there isn't a better way. You could incorporate this into your hstore update from before like so:

    update htest set h = coalesce(h, hstore(array[]::varchar[])) || ('foo'=>'bar') where t='key';
    

    This way you don't need to recreate the table. I find that fairly gross though. Hope this helps.

提交回复
热议问题