safecast
safecast · Pure-SQL helper functions that return NULL for some invalid text-to-number casts.
Overview
| ID | Extension | Package | Version | Category | License | Language |
|---|---|---|---|---|---|---|
| 100281 | safecast | safecast | 0.0.1 | FUNC | Apache-2.0 | SQL |
Usage
Sources:
safecast supplies small SQL functions that return NULL for some text values that do not match a numeric-looking regular expression before casting. Despite its name, version 0.0.1 does not catch cast exceptions and is not safe for arbitrary untrusted input.
Core Workflow
The second call returns NULL; accepted strings are passed to PostgreSQL’s normal cast implementation.
Functions and Accepted Shapes
to_integer(text): accepts only one or more ASCII digits, then casts tointeger.to_bigint(text): accepts only one or more ASCII digits, then casts tobigint.to_float(text): accepts any nonempty combination of-, digits, and., then casts tofloat(double precision).to_double_precision(text): accepts only one or more ASCII digits, then casts todouble precision.
Caveats
Range overflow still raises an error. The to_float regular expression is permissive enough to accept malformed values such as . or --1, which then raise cast errors. The integer functions reject leading signs, whitespace, decimal points, and exponent notation; to_double_precision rejects signs, fractions, and exponents as well. Locale-specific numbers and NaN/Infinity are not accepted.
The functions are not declared STRICT or with volatility/parallel attributes, and the abandoned project has a very small test surface. Use explicit validation or an exception-catching function when failure must reliably become NULL. The extension is SQL-only and needs no preload or restart.