Re: How to return argument data type from sql function

Andrus <kobruleht2@hot.ee>

From: Andrus <kobruleht2@hot.ee>
To: Tom Lane <tgl@sss.pgh.pa.us>, Adrian Klaver <adrian.klaver@aklaver.com>
Cc: pgsql-general <pgsql-general@postgresql.org>
Date: 2022-10-14T20:59:52Z
Lists: pgsql-general
Hi!

Making separate functions for text and bpchar works for me.
> regression=# select pg_typeof(torus(f1)) from char_tbl;
>   pg_typeof
> -----------
>   character

I tried

create or replace FUNCTION torus(eevarus bpchar) returns bpchar 
immutable AS $f$
select translate( $1, U&'\00f8\00e9', U&'\0451\0439' );
$f$ LANGUAGE SQL ;

create temp table test (
charcol char(10) );
insert into test values ('test');
select torus(charcol)
FROM Test

but it still returns result without trailing spaces. So it is not working.

> Another possibility is to have just one function declared
> to take and return anyelement.  You'd get failures at
> execution if the actual argument type isn't coercible
> to and from text (since translate() deals in text) but
> that might be fine.

I tried

create or replace FUNCTION torus(eevarus anylement ) returns anylement 
immutable AS $f$
select translate( $1, U&'\00f8\00e9', U&'\0451\0439' );
$f$ LANGUAGE SQL ;

but got error

type anyelement does not exists.

Finally I tried

create or replace FUNCTION torus(eevarus text ) returns text immutable 
AS $f$
select translate( $1, U&'\00f8\00e9', U&'\0451\0439' );
$f$ LANGUAGE SQL ;

create or replace function public.ColWidth(p_namespace text, p_table 
text, p_field text)
     returns int as $f$
select atttypmod-4 from pg_namespace n, pg_class c, pg_attribute a
          where n.nspname = p_namespace and
              c.relnamespace = n.oid and
              c.relname = p_table and
              a.attrelid = c.oid and
              a.attname = p_field;
$f$ LANGUAGE SQL ;

create table public.test ( charcol char(10) );
insert into test values ('test');
select rpad ( torus(charcol),  colwidth('public', 'test', 'charcol') )
FROM Test

as Adrian Klaver recommends in

https://stackoverflow.com/questions/74061290/how-to-return-argument-datatype-from-sql-function#comment130780708_74061290

at this worked. In this best solution?

How to remove p_namespace  parameter from colwidth()? ColWidth() should 
return column width in first search_path table just like select ... from 
test finds table test.

Andrus.