pub fn cast_value(
value: CastValue,
target: CastTarget,
) -> Result<Option<CastValue>, CastError>Expand description
The value PostgreSQL 18’s explicit cast value::target produces, None for NULL, or the
error it raises.
A value of a character type is read by the target’s input function, as pg_cast’s I/O
coercion does, and a value cast to a character type is printed by its type’s output function,
boolean as true or false. Between the other types the cast is the function pg_cast
names, int4_bool, bool_int4, the integer narrowings, int*_numeric, numeric_int*,
date_timestamp, timestamp_date, jsonb_bool, jsonb_numeric and jsonb_int*, the last
three followed by numeric_int*. A jsonb null cast to boolean, numeric or an integer
type is NULL, the one cast giving NULL. The length coercion of the target’s modifier
follows, and a pair pg_cast has no cast for raises CastError::CannotCast.
§Errors
The CastError PostgreSQL raises, or CastError::Unsupported for a cast whose answer
the session’s TimeZone decides, or a text the target’s input function is not modelled for.
use sql_values::postgres::{
CastError, CastTarget, CastValue, JsonbKind, PgJsonb, PgNumeric, PgType, cast_value,
};
let cast = |value, target| {
cast_value(value, target).map(|value| value.map(|value| value.to_string()))
};
let some = |text: &str| Ok(Some(text.to_owned()));
assert_eq!(cast(CastValue::Integer(1), CastTarget::Boolean), some("t"));
assert_eq!(
cast(CastValue::Bigint(1), CastTarget::Boolean),
Err(CastError::CannotCast { from: PgType::Bigint, to: PgType::Boolean }),
);
assert_eq!(cast(CastValue::Boolean(true), CastTarget::Text), some("true"));
let half = PgNumeric::parse("-2.5").unwrap();
assert_eq!(cast(CastValue::Numeric(half), CastTarget::Smallint), some("-3"));
assert_eq!(
cast(CastValue::Numeric(PgNumeric::NAN), CastTarget::Integer),
Err(CastError::CannotConvertNaN(PgType::Integer)),
);
assert_eq!(
cast(CastValue::Integer(40_000), CastTarget::Smallint),
Err(CastError::OutOfRange(PgType::Smallint)),
);
assert_eq!(
cast(CastValue::Text("x".into()), CastTarget::Boolean),
Err(CastError::InvalidInputSyntax(PgType::Boolean)),
);
let jsonb = |text| CastValue::Jsonb(PgJsonb::parse(text).unwrap());
assert_eq!(cast(jsonb("1.5"), CastTarget::Integer), some("2"));
assert_eq!(cast(jsonb("null"), CastTarget::Integer), Ok(None));
assert_eq!(
cast(jsonb("[1]"), CastTarget::Numeric(None)),
Err(CastError::CannotCastJsonb { from: JsonbKind::Array, to: PgType::Numeric }),
);