You can do this with jsonb
, at least with Postgres 9.5.2.
Given the following table:
CREATE TABLE users (id INT, counters JSONB NOT NULL DEFAULT '{}');
With sample data:
INSERT INTO users (id, counters) VALUES (1, '{"bar": 0}');
SELECT * FROM users;
id | counters
----+------------
1 | {"bar": 0}
You can increment "bar" key in JSON atomically:
UPDATE users SET counters = counters || CONCAT('{"bar":', COALESCE(counters->>'bar','0')::int + 1, '}')::jsonb WHERE id = 1;
SELECT * FROM users;
id | counters
----+------------
1 | {"bar": 1}
It's not beautiful but it works.
Here it is broken down in steps:
You can set a key in jsonb
to an explicit value by ||
'ing the jsonb objects:
UPDATE users SET counters = counters || '{"bar": 314}'::jsonb WHERE id = 1;
SELECT * FROM users;
id | counters
----+--------------
1 | {"bar": 314}
From the documentation:
jsonb || jsonb → jsonb
Concatenates two jsonb values. Concatenating two objects generates an
object containing the union of their keys, taking the second object's
value when there are duplicate keys.
Now all that's left to do is build the string dynamically with the help of CONCAT(), at the same time demonstrating incrementing (by 27) an undefined key (defaulting initial value with help of COALESCE() ):
UPDATE users SET counters = counters || CONCAT('{"foo":', COALESCE(counters->>'foo','0')::int + 27, '}')::jsonb WHERE id = 1;
SELECT * FROM users;
id | counters
----+-------------------------
1 | {"bar": 314, "foo": 27}
Bob's your uncle. :)