title: Update or create nested jsonb value using single update command
body: <p>Let us say I have [in Postgres <strong>9.6</strong>] a JSONB column named <code>xyz</code>. In an update, I want to set the <code>.foo.bar</code> key of this column to <code>{"done":true}</code>.</p>
  
  <p>But the update must tolerate that the pre-update value for <code>xyz</code> is anything from <code>{}</code> to</p>
  
  <pre><code>{ 
      "abc": "Hello"
  }
  </code></pre>
  
  <p>or maybe </p>
  
  <pre><code>{ 
      "foo": {
          "baz": { "done": false }
      },
      "abc": "Hello"
  }
  </code></pre>
  
  <p>So I cannot use <code>jsonb_set</code> straight away, because it fails if <code>xyz-&gt;foo</code> is undefined. In that case I could use <code>jsonb_insert</code>, but that fails if <code>xyz-&gt;foo</code> <strong>is</strong> already defined.</p>
  
  <p>So I try to use concatenation, with something like</p>
  
  <pre><code>jsonb_set( 
      jsonb_set(xyz, '{foo}', '{}'::jsonb || xyz-&gt;'foo', true),
      '{foo, bar}', '{"done":true}', true
  )
  </code></pre>
  
  <p>...which also fails when <code>foo</code> is undefined since <code>xyz-&gt;'foo'</code> is <code>null</code> which overrides <code>{}</code> in the concatenation.</p>
  
  <p>Obviously I could write a function that uses an <code>if</code> to get around this, but I really feel I should be able to do it in a single update.</p>