Кажется, что единственный способ - перехватить исключение, но вы можете сделать это с помощью удобной функции, подобной этой:
create or replace function oid_or_null(text)
returns oid language plpgsql immutable as $$
begin
return $1::oid;
exception when invalid_text_representation then
return null;
end $$;
select oid_or_null('123'), oid_or_null('abc');
oid_or_null | oid_or_null
-------------+-------------
123 |
(1 row)
Вы можете создать более общую логическую функцию:
create or replace function is_valid_cast(text, text)
returns boolean language plpgsql immutable as $$
begin
execute format('select %L::%I', $1, $2);
return true;
exception when others then
return false;
end $$;
select
is_valid_cast('123', 'oid') as oid, is_valid_cast('abc', 'oid') as not_oid,
is_valid_cast('2018-10-10', 'date') as date, is_valid_cast('2018-20-20', 'date') as not_date;
oid | not_oid | date | not_date
-----+---------+------+----------
t | f | t | f
(1 row)