Re: Cast jsonb to numeric, int, float, bool - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Cast jsonb to numeric, int, float, bool
Date
Msg-id 8775.1520873000@sss.pgh.pa.us
Whole thread Raw
In response to Re: Cast jsonb to numeric, int, float, bool  (Darafei "Komяpa" Praliaskouski <me@komzpa.net>)
Responses Re: Cast jsonb to numeric, int, float, bool  (Michael Paquier <michael@paquier.xyz>)
List pgsql-hackers
=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net> writes:
> But what would be the scenario of failure if we have an implicit cast from
> jsonb datatype (that likely already parsed the number internally, or knows
> it holds non-numeric value) to numeric, that returns an error if it's
> unable to perform the conversion?

One fundamental problem is this: what's special about a cast to numeric?
There's no reason to assume that a jsonb field is more likely to be
numeric than anything else.  But basically you only get to have one of
these.  If we put this in, and then somebody else comes along and proposes
an implicit cast to text, or an implicit cast to timestamp, then
everything is broken, because the parser will no longer be able to
resolve max(jsonb) --- it won't know which implicit cast to apply.

Another fundamental problem is that implicit casts mask mistakes.
If there's an implicit cast to numeric, that applies everywhere not
only where it was what you meant.  For some context on this you might
go back to the archives around the time of 8.3, where we actually
removed a bunch of implicit casts because they led to too many
surprising behaviors.  Restricting implicit casts to the same type
category is a rule-of-thumb for reducing the potential surprise factor.

The cast notation is important here because it lets/makes the user
specify which semantics she wants for the converted value.  I think
it's about equally likely for people to be converting JSON fields to text,
or (some form of) numeric, or datetime, so I don't think it's appropriate
to privilege one of those over all others.

> What would be other options, if not implicit cast?

Explicit casts, ie (jsonvar->'fieldname')::numeric.  Yeah, you have
to write a bit more, but you don't get surprised by the way the
parser interpreted your query.

The other thing you can potentially do is use a variant operator
name, as we did for text output with ->>.  But that doesn't scale
to very many result types, because it's impossible to choose
readily mnemonic operator names.  So I'd stick with the casts.

            regards, tom lane


pgsql-hackers by date:

Previous
From: Alvaro Herrera
Date:
Subject: Re: pgsql: Allow UNIQUE indexes on partitioned tables
Next
From: Tom Lane
Date:
Subject: Re: Ambigous Plan - Larger Table on Hash Side