According to the postgres documentation, you add a key to an hstore column as follows:
UPDATE tab SET h = h || ('c' => '3');
But it seems to only work if the hstore field is not empty. For example:
postgres=# create table htest (t text, h hstore);
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 |
(1 row)
The update was successful, yet the hstore was not updated. However:
postgres=# update htest set h = ('foo'=>'bar') where t='key';
UPDATE 1
postgres=# select * from htest;
t | h
-----+--------------
key | "foo"=>"bar"
(1 row)
postgres=# update htest set h = h || ('bar'=>'foo') where t='key';
UPDATE 1
postgres=# select * from htest;
t | h
-----+----------------------------
key | "bar"=>"foo", "foo"=>"bar"
(1 row)
Is there a way to atomically add a key to an hstore without first checking if the hstore is empty?
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:
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:This way you don’t need to recreate the table. I find that fairly gross though. Hope this helps.