pg_input_is_valid Probes Cast Safety

PG16 adds pg_input_is_valid to test whether a string converts cleanly to a type without raising, and pg_input_error_info to fetch the failure detail.

SqlData Integrity

Code

snippet
-- ETL 先探后转:pg_input_is_valid 测试字符串能否干净地 cast 成目标类型
SELECT
    pg_input_is_valid('42', 'integer')      AS ok_int,
    pg_input_is_valid('4.2', 'integer')     AS bad_int,     -- false,不抛错
    pg_input_is_valid('2026-06-21', 'date') AS ok_date,
    pg_input_is_valid('not-a-date', 'date') AS bad_date;    -- false

-- 对非法输入追问细节:pg_input_error_info 返回错误消息与光标位置
SELECT * FROM pg_input_error_info('4.2', 'integer');

-- 管道用法:非法值清洗成 NULL,合法值正常转换
SELECT v,
       CASE WHEN pg_input_is_valid(v, 'integer')
            THEN v::integer END AS cleaned
FROM (VALUES ('42'), ('x7'), ('17')) AS t(v);

What this snippet does

SELECT statements share the script, touching pg_input_error_info.

Applying it

Run the statement against the pg_input_error_info table.

Statements that matter

SELECT
    pg_input_is_valid('42', 'integer')      AS ok_int,
    pg_input_is_valid('4.2', 'integer')     AS bad_int,     -- false,不抛错
    pg_input_is_valid('2026-06-21', 'date') AS ok_date,
    pg_input_is_valid('not-a-date', 'date') AS bad_date;    -- false
SELECT v,
       CASE WHEN pg_input_is_valid(v, 'integer')
            THEN v::integer END AS cleaned
FROM (VALUES ('42'), ('x7'), ('17')) AS t(v);
SELECT * FROM pg_input_error_info('4.2', 'integer');

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`pg_input_error_info` — referenced directly, no join needed.