Question

When I construct an hstore

CREATE EXTENSION hstore;
SELECT hstore(null::my_type);
                     hstore                     
------------------------------------------------
 "name"=>NULL, "street"=>NULL, "location"=>NULL
(1 row)

While the jsonb method,

SELECT to_jsonb(null::my_type);
 to_jsonb 
----------

(1 row)

This creates a surprising effect too when you try to merge (||) another like type,

SELECT hstore(null::my_type) || hstore('name', 'Evan');
                     ?column?                     
--------------------------------------------------
 "name"=>"Evan", "street"=>NULL, "location"=>NULL
(1 row)

SELECT to_jsonb(null::my_type) || jsonb_build_object('name', 'Evan');
 ?column? 
----------

(1 row)
Was it helpful?

Solution

The workaround here is to construct the jsonb by proxy of jsonb_populate_record

SELECT jsonb_populate_record(
  null::my_type,
  '{}'
);

Or, in the event you're just trying to update the record type, you can do it directly with the one call.

SELECT jsonb_populate_record(
  null::my_type,
  jsonb_build_object('name', 'Evan')
);
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top