I would like to create a function that attempts to cast a group of values into a user-specified type (with a default of text). A very simple function would look like so:
CREATE OR REPLACE FUNCTION cast_to(variable jsonb, key text, target_type anyelement DEFAULT 'TEXT'::regtype) RETURNS anyelement as $$
begin
RETURN CAST(variable->>key AS target_type);
end
$$
language plpgsql;
I have tried the following:
SELECT CAST('foo' AS 'text');
: Gives syntax errorSELECT CAST('foo' AS 'text'::regtype);
: Same error as 1SELECT CAST('foo' AS pg_typeof(null::text));
says thattype pg_typeof does not exist
The last attempt was a thought that I could pass in a variable with the target type instead of a text representation. Using the function would then look like SELECT cast_to('text', NULL::text);
.
How to accomplish this or similar functionality?
Edit: As suggested in the comments, I tried to use dynamic SQL. I am not having much luck. I created a very basic case that doesn't use any variables:
CREATE OR REPLACE FUNCTION audit.cast_to() RETURNS text as $$
DECLARE
_sql TEXT := 'SELECT CAST($1 AS $2)';
out TEXT;
begin
EXECUTE _sql
USING 'foo', 'TEXT'
INTO out;
return out;
end
$$
language plpgsql;
That however throws the error:
syntax error at or near "$2"