Re: jsonb_set() strictness considered harmful to data

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Christoph Moench-Tegeder <cmt(at)burggraben(dot)net>
Cc: Ariadne Conill <ariadne(at)dereferenced(dot)org>, "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>, feld(at)freebsd(dot)org
Subject: Re: jsonb_set() strictness considered harmful to data
Date: 2019-10-18 22:00:50
Message-ID: CAKFQuwZ2w5D1yJ9vaexiR8kbqOyxbzKwo2hsbi74ruVfFiNe-g@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

On Fri, Oct 18, 2019 at 2:50 PM Christoph Moench-Tegeder <cmt(at)burggraben(dot)net>
wrote:

> ## Ariadne Conill (ariadne(at)dereferenced(dot)org):
>
> > update users set info=jsonb_set(info, '{bar}', info->'foo');
> >
> > Typically, this works nicely, except for cases where evaluating
> > info->'foo' results in an SQL null being returned. When that happens,
> > jsonb_set() returns an SQL null, which then results in data loss.[3]
>
> So why don't you use the facilities of SQL to make sure to only
> touch the rows which match the prerequisites?
>
> UPDATE users SET info = jsonb_set(info, '{bar}', info->'foo')
> WHERE info->'foo' IS NOT NULL;
>
>
There are many ways to add code to queries to make working with this
function safer - though using them presupposes one remembers at the time of
writing the query that there is danger and caveats in using this function.
I agree that we should have (and now) provided sane defined behavior when
one of the inputs to the function is null instead blowing off the issue and
defining the function as being strict. Whether that is "ignore and return
the original object" or "add the key with a json null scalar value" is
debatable but either is considerably more useful than returning SQL NULL.

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ariadne Conill 2019-10-18 22:05:02 Re: jsonb_set() strictness considered harmful to data
Previous Message Edilmar Alves 2019-10-18 21:54:34 Replication of Replication

Browse pgsql-hackers by date

  From Date Subject
Next Message Ariadne Conill 2019-10-18 22:05:02 Re: jsonb_set() strictness considered harmful to data
Previous Message Christoph Moench-Tegeder 2019-10-18 21:50:18 Re: jsonb_set() strictness considered harmful to data