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.
Code
-- 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
FAQ
- Which tables or CTEs does it reference?
- `pg_input_error_info` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.