Subject: Re: Custom type's modifiers

From: "David G. Johnston" <[email-masked]>
Date: Thu, 27 Jun 2024 09:12:25 -0700

On Thu, Jun 27, 2024 at 8:49 AM Marthin Laubscher <[email-masked]>
wrote:

>
> I suppose when a cast is involved it goes via the external format as well,
> right?
>

A cast between two types is going to accept a concrete instance of the
input type, in memory, as its argument and then produces a concrete
instance of the output type, in memory, as output.  If the input data is
serialized the constructor for the input type will handle deserialization.

See: create cast

https://www.postgresql.org/docs/current/sql-createcast.html

In particular the phrasing: identical to or binary-coercible to

David J.

---

From: Marthin Laubscher <[email-masked]>
Date: Thu, 27 Jun 2024 19:01:10 +0200

On 2024/06/27, 18:13, "David G. Johnston" <mailto:[email-masked]> wrote:
> A cast between two types is going to accept a concrete instance of the input type, in memory, as its argument and then produces a concrete instance of the output type, in memory, as output.  If the input data is serialized the constructor for the input type will handle deserialization.

I confess to some uncertainty whether the PostgreSQL specific x::y notation and the standards based CAST(x AS y) would both be addressed by creating a cast. What you’re saying means both forms engage the same code and defining a cast would cover the :: syntax as well. Thanks for that.

If my understanding is accurate, it means that even when both values are of MyType the CAST function would still be invoked so the type logic can determine how to handle (or reject) the cast. Cast would (obviously) require the target type modifiers as well, and the good news is that it’s already there as the second parameter of the function. So that’s the other function that receives the type modifier that I was missing. It’s starting to make plenty sense. 

To summarise:
- The type modifiers, encoded by the TYPMOD_IN function are passed directly as parameters to:- 
  -  the type's input function (parameter 3), and
  - any "with function" cast where the target type has type modifiers.
- Regardless of the syntax used to invoke the cast, the same function will be called.
- Depending on what casts are defined, converting from the external string format to a value of MyType will be handled either by the input function or a cast function. By default (without any casts) only values recognised by input can be converted to MyType values.

     -- Thanks for your time – Marthin Laubscher