How would I quote the type name to protect against SQL Injection. For example, take this
SELECT FORMAT('SELECT CAST(%L AS %s);', '5.42', 'int');
^ Quote this
That works fine, but if 'int' is instead ''int); DROP DATABASE foo;SELECT (' you'll have some problems,
SELECT FORMAT('SELECT CAST(%L AS %s);', '5.42', 'int); DROP DATABASE foo;SELECT (');
format
----------------------------------------------------------
SELECT CAST('5.42' AS int); DROP DATABASE foo;SELECT ();
(1 row)
How would I go about casting to a type provided in run time safely with Dynamic SQL? If I use %I instead of %s I get an identifier (safe-quoting with ", but type-names are not identifiers and do not work with double-quotes).
Inspired by this answer to "PostgreSQL alternative to SQL Server’s try_cast function" provided by Jasen