Using a domain
Hello,
I'm trying to use a domain to define a data type constraint, let's say
an hypothetical uk_post_code with pattern LNNLL. I'd enforce no
whitespaces, all uppercase.
I would also need a way to normalize before validate: given an input
such as "w3 6bq", normalize it to W36BQ before trying to apply the
check. It would be great if I could give this function the same name
of the domain, so that uk_post_code('w3 6bq') would return W36BQ cast
to the domain.
Unfortunately it seems a domain implicitly defines a function, and
this function only perform the cast: the above is thus equivalent to
'w3 6bq'::uk_post_code, which would fail as the constraint doesn't
match. IIRC from when I've played with type definitions in C, for a
type there is no such automatic definition: a function converting text
to the type must be explicitly provided. \df doesn't show such
function for the domain (nor DROP FUNCTION seems knowing it), and if I
create one, it is not invoked (the cast takes precedence).
Is there any way to define a conversion in a function call
uk_post_code(text), or the only way to provide a normalization
function is to give it a different name (such as to_uk_post_code - I'd
like to know if there is a convention in how to name this function).
Is there any documentation about domains apart from the
CREATE/ALTER/DELETE commands? Haven't found any in the docs.
Thanks.
-- Daniele
Daniele Varrazzo <daniele.varrazzo@gmail.com> writes:
I'm trying to use a domain to define a data type constraint, let's say
an hypothetical uk_post_code with pattern LNNLL. I'd enforce no
whitespaces, all uppercase.
I would also need a way to normalize before validate: given an input
such as "w3 6bq", normalize it to W36BQ before trying to apply the
check. It would be great if I could give this function the same name
of the domain, so that uk_post_code('w3 6bq') would return W36BQ cast
to the domain.
That particular case isn't going to work unless you choose a different
function name --- as you've found out, the parser prefers the
interpretation that this means the same as 'w3 6bq'::uk_post_code,
which is not a cast but just a literal of the named type.
If you were willing to write something like uk_post_code('w3 6bq'::text)
and define your function as taking text (or varchar if that turns you on),
it should work. Likewise anytime the argument is a variable/expression
of known type text. But with a bare untyped literal, no.
regards, tom lane