functions and operator for user define type - postgresql

I have built User Define Type with function_in and function_out.
CREATE OR REPLACE FUNCTION MyOwnType_in(cstring)
RETURNS MyOwnType
AS '/home/postgres/ENCRIPTION/MyOwnType/MyOwnType.so','MyOwnType_in'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION MyOwnType_out(MyOwnType)
RETURNS cstring
AS '/home/postgres/ENCRIPTION/MyOwnType/MyOwnType.so','MyOwnType_out'
LANGUAGE C IMMUTABLE STRICT;
As you can see each function_in receives cstring and function_out returns cstring.
The thing is function overloading and operator overriding on which I don't want to waste my time.
Is there any way to declare DEFAULT TYPE for my MyOwnType type which tells postgres that functions and operators with MyOwnTypearguments can parse and rewrite it into text?

The most you can do with your type is to mark it as a string type, with:
CREATE TYPE MyOwnType(
INPUT = MyOwnType_in,
OUTPUT = MyOwnType_out,
CATEGORY = 'S'
-- ...
);
The category parameter is especially useful when adding a user-defined type to an existing built-in category, such as the numeric or string types. However, it is also possible to create new entirely-user-defined type categories. Select any ASCII character other than an upper-case letter to name such a category ...
It may require additional CASTs, as #IgorRomanchenko suggested.

You need to CREATE CAST ... AS IMPLICIT from your datatype to text. This way your type will be automatically cast to text when a function/operator requires text.
Details here: http://www.postgresql.org/docs/current/static/sql-createcast.html

Related

In PostgreSQL, which types can be cast with the type name first?

Reading the PostgreSQL docs, I see that you can cast a longish bit of text to xml like this:
SELECT xml '<long>long text, may span many lines</long>'
SELECT xml '...'
Curious, I found that I could do the same with JSON:
SELECT json '{"arg1":"val1", <more args spanning many lines>}'
(I couldn't find an official reference for this one. It just works!)
By contrast, this does not work:
SELECT float8 3.14159
I like this alternate syntax from a readability perspective. Now I'm looking for a reference listing which types may be specified up front like this. but I haven't found it yet.
Any pointers?
The documentation says:
A constant of an arbitrary type can be entered using any one of the following notations:
type 'string'
'string'::type
CAST ( 'string' AS type )
The string constant's text is passed to the input conversion routine for the type called type. The result is a constant of the indicated type. The explicit type cast can be omitted if there is no ambiguity as to the type the constant must be (for example, when it is assigned directly to a table column), in which case it is automatically coerced.
The form you are asking about is the first one.
So this can be used for all PostgreSQL types.
Note that the data must be specified as a string literal (in single or dollar quotes) when you use that syntax.

Postgres: How to overload functions having single record type input parameter

I have a user defined type:
create type match_input as (
_values text[],
_name text,
_norm_fn text,
_operator text
);
and I use this as the input parameter for a function:
get_matches(mi match_input)
I want to be able to call the same function, but passing a single text value for _values. So I defined a new type:
create type match_input_simple as (
_values text,
_name text,
_norm_fn text,
_operator text
);
If I try and overload the function with the following:
create or replace function get_matches(_mis match_input_simple)
returns setof contact_index
as $func$
select get_matches((array[_mis._values], _mis._name,
_mis._norm_fn, _mis._operator)::match_input);
$func$
language sql strict;
The function compiles without complaining, but when I run the function I get this error:
ERROR: function get_matches(record) is not unique
HINT: Could not choose a best candidate function. You might need to add explicit type casts.
So it looks like postgres can't tell the difference between my two different record types when its trying to decide which function to run.
I don't want the user to have to explicitly type cast the record each time the function is called, since that kind of defeats the purpose of trying to make the interface simple.
It is getting confused over type on the similar functions. Explicit type cast might help. Like
SELECT get_matches(val::match_input_simple)
Or
SELECT get_matches(val::match_input )
Depending upon the type of val
It can't be done without casting.
Remember that you can have multiple types with the exactly same content and create a overload for each one of them. How would the database choose the right type and function?

PostgreSQL syntax error in parameterized query on "date $1"

Trying to parameterize my SQL queries (using libpq function PQexecParams), I was stuck on a syntax error:
SELECT date $1
The error is:
ERROR: syntax error at or near "$1"
Prepared statements
The explanation for this can be found in the chapter Constants of Other Types of the manual:
The ::, CAST(), and function-call syntaxes can also be used to specify
run-time type conversions of arbitrary expressions, as discussed in
Section 4.2.9. To avoid syntactic ambiguity, the type 'string' syntax
can only be used to specify the type of a simple literal constant.
Another restriction on the type 'string' syntax is that it does not
work for array types; use :: or CAST() to specify the type of an array
constant.
Bold emphasis mine.
Parameters for prepared statements are not actually sting literals but typed values, so you cannot use the form type 'string'. Use one of the other two forms to cast the value to a different type, like you found yourself already.
Example:
PREPARE foo AS SELECT $1::date;
EXECUTE foo('2005-1-1');
Similar for PQexecParams in the libpq C library
The documentation:
... In the SQL command text, attach an explicit cast to the parameter
symbol to show what data type you will send. For example:
SELECT * FROM mytable WHERE x = $1::bigint;
This forces parameter $1 to be treated as bigint, whereas by default
it would be assigned the same type as x. Forcing the parameter type
decision, either this way or by specifying a numeric type OID, is
strongly recommended. ...
The alternative, as mentioned in the quote above, is to pass the OIDs of respective data types with paramTypes[] - if you actually need the cast. In most cases it should work just fine to let Postgres derive data types from the query context.
paramTypes[]
Specifies, by OID, the data types to be assigned to the parameter
symbols. If paramTypes is NULL, or any particular element in the array
is zero, the server infers a data type for the parameter symbol in the
same way it would do for an untyped literal string.
You can get the OID of data types from the system catalog pg_type:
SELECT oid FROM pg_type WHERE typname = 'date';
You must use the correct internal type name. For instance: int4 for integer.
Or with a convenience cast to regtype:
SELECT 'date'::regtype::oid;
This is more flexible as known aliases for the type name are accepted as well. For instance: int4, int or integer for integer.
The solution is to use a type cast instead of date:
SELECT $1::date

Can one create a custom type in postgres without writing functions in C?

I'm trying to create a type to store color hexes preferably in byte form. I followed all the instructions in postgres docs here: http://www.postgresql.org/docs/9.3/static/sql-createtype.html
and found the part where it says CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ; a bit... unsettling. What goes in the ellipses? Turns out that was justified as I cannot find any example of creating a simple data type without custom PG functions written in C.
My best attempt was this:
CREATE TYPE color;
CREATE FUNCTION color_in(cstring) RETURNS color AS $$
BEGIN
RETURN decode($1::text, 'hex')::color;
END;
$$ LANGUAGE PLPGSQL IMMUTABLE RETURNS NULL ON NULL INPUT;
CREATE FUNCTION color_out(color) RETURNS cstring AS $$
BEGIN
RETURN encode($1::bytea, 'hex')::text;
END;
$$ LANGUAGE PLPGSQL IMMUTABLE RETURNS NULL ON NULL INPUT;
CREATE TYPE color (
INTERNALLENGTH = 3,
LIKE = bytea,
INPUT = color_in,
OUTPUT = color_out
);
This yields the error:
NOTICE: return type color is only a shell
ERROR: PL/pgSQL functions cannot return type color
Similar error if I use Language SQL or default to SPL.
The example in-out functions are listed here: http://www.postgresql.org/docs/9.3/static/xtypes.html. The only example functions are written in C. Am I correct in assuming this is the only way to write a UDT in postgres? Is there another way? My goal is to have the colors stored as bytes but have their native text form be hexadecimal (for the purposes of dumping, restoring, and casting from raw).
From http://www.postgresql.org/docs/9.4/interactive/datatype-pseudo.html
Functions coded in procedural languages can use pseudo-types only as
allowed by their implementation languages. At present the procedural
languages all forbid use of a pseudo-type as argument type, and allow
only void and record as a result type (plus trigger when the function
is used as a trigger). Some also support polymorphic functions using
the types anyelement, anyarray, anynonarray, anyenum, and anyrange.
And from the docs for create type
http://www.postgresql.org/docs/9.4/interactive/sql-createtype.html
The input function can be declared as taking one argument of type
cstring, or as taking three arguments of types cstring, oid, integer.
The output function must return type cstring.
Given the above:
Base data type input and output functions use cstring.
Procedural languages can not use cstring.
Base data type functions can't be written in procedural language.
Defining a base data type can't be done purely in procedural languages.
You can use pre-existing input and output functions, but I don't think
that any of them will directly get you a hex string. The closest
is probably the \x hex escaped bytea, but you'd have a \x at the beginning of your text representation. If you're willing to cast to and from text, I think you could create a type using bytea_in and bytea_out and writing custom casts to and from text. You'd have to explicitly cast to avoid the \x though.

Is there a way to disable function overloading in Postgres

My users and I do not use function overloading in PL/pgSQL. We always have one function per (schema, name) tuple. As such, we'd like to drop a function by name only, change its signature without having to drop it first, etc. Consider for example, the following function:
CREATE OR REPLACE FUNCTION myfunc(day_number SMALLINT)
RETURNS TABLE(a INT)
AS
$BODY$
BEGIN
RETURN QUERY (SELECT 1 AS a);
END;
$BODY$
LANGUAGE plpgsql;
To save time, we would like to invoke it as follows, without qualifying 1 with ::SMALLINT, because there is only one function named myfunc, and it has exactly one parameter named day_number:
SELECT * FROM myfunc(day_number := 1)
There is no ambiguity, and the value 1 is consistent with SMALLINT type, yet PostgreSQL complains:
SELECT * FROM myfunc(day_number := 1);
ERROR: function myfunc(day_number := integer) does not exist
LINE 12: SELECT * FROM myfunc(day_number := 1);
^
HINT: No function matches the given name and argument types.
You might need to add explicit type casts.
When we invoke such functions from Python, we use a wrapper that looks up functions' signatures and qualifies parameters with types. This approach works, but there seems to be a potential for improvement.
Is there a way to turn off function overloading altogether?
Erwin sent a correct reply. My next reply is related to possibility to disable overloading.
It is not possible to disable overloading - this is a base feature of PostgreSQL function API system - and cannot be disabled. We know so there are some side effects like strong function signature rigidity - but it is protection against some unpleasant side effects when function is used in Views, table definitions, .. So you cannot to disable it.
You can simply check if you have or have not overloaded functions:
postgres=# select count(*), proname
from pg_proc
where pronamespace <> 11
group by proname
having count(*) > 1;
count | proname
-------+---------
(0 rows)
This is actually not directly a matter of function overloading (which would be impossible to "turn off"). It's a matter of function type resolution. (Of course, that algorithm could be more permissive without overloaded functions.)
All of these would just work:
SELECT * FROM myfunc(day_number := '1');
SELECT * FROM myfunc('1'); -- note the quotes
SELECT * FROM myfunc(1::smallint);
SELECT * FROM myfunc('1'::smallint);
Why?
The last two are rather obvious, you mentioned that in your question already.
The first two are more interesting, the explanation is buried in the Function Type Resolution:
unknown literals are assumed to be convertible to anything for this purpose.
And that should be the simple solution for you: use string literals.
An untyped literal '1' (with quotes) or "string literal" as defined in the SQL standard is different in nature from a typed literal (or constant).
A numeric constant 1 (without quotes) is cast to a numeric type immediately. The manual:
A numeric constant that contains neither a decimal point nor an
exponent is initially presumed to be type integer if its value fits in
type integer (32 bits); otherwise it is presumed to be type bigint if
its value fits in type bigint (64 bits); otherwise it is taken to be
type numeric. Constants that contain decimal points and/or exponents
are always initially presumed to be type numeric.
The initially assigned data type of a numeric constant is just a
starting point for the type resolution algorithms. In most cases the
constant will be automatically coerced to the most appropriate type
depending on context. When necessary, you can force a numeric value to
be interpreted as a specific data type by casting it.
Bold emphasis mine.
The assignment in the function call (day_number := 1) is a special case, the data type of day_number is unknown at this point. Postgres cannot derive a data type from this assignment and defaults to integer.
Consequently, Postgres looks for a function taking an integer first. Then for functions taking a type only an implicit cast away from integer, in other words:
SELECT casttarget::regtype
FROM pg_cast
WHERE castsource = 'int'::regtype
AND castcontext = 'i';
All of these would be found - and conflict if there were more than one function. That would be function overloading, and you would get a different error message. With two candidate functions like this:
SELECT * FROM myfunc(1);
ERROR: function myfunc(integer) is not unique
Note the "integer" in the message: the numeric constant has been cast to integer.
However, the cast from integer to smallint is "only" an assignment cast. And that's where the journey ends:
No function matches the given name and argument types.
SQL Fiddle.
More detailed explanation in these related answers:
PostgreSQL ERROR: function to_tsvector(character varying, unknown) does not exist
Generate series of dates - using date type as input
Dirty fix
You could fix this by "upgrading" the cast from integer to smallint to an implicit cast:
UPDATE pg_cast
SET castcontext = 'i'
WHERE castsource = 'int'::regtype
AND casttarget = 'int2'::regtype;
But I would strongly discourage tampering with the default casting system. Only consider this if you know exactly what you are doing. You'll find related discussions in the Postgres lists. It can have all kinds of side effects, starting with function type resolution, but not ending there.
Aside
Function type resolution is completely independent from the used language. An SQL function would compete with PL/perl or PL/pgSQL or "internal" functions just the same. The function signature is essential. Built-in functions only come first, because pg_catalog comes first in the default search_path.
There are plenty of in built functions that are overloaded, so it simply would not work if you turned off function overloading.