surrealpatch/lib/src/fnc/cast.rs

72 lines
1.6 KiB
Rust
Raw Normal View History

use crate::ctx::Context;
2021-03-29 15:43:37 +00:00
use crate::err::Error;
use crate::sql::number::Number;
use crate::sql::value::Value;
2021-03-29 15:43:37 +00:00
2022-08-17 17:10:09 +00:00
pub fn run(_: &Context, name: &str, val: Value) -> Result<Value, Error> {
match name {
2022-08-17 17:10:09 +00:00
"bool" => bool(val),
"datetime" => datetime(val),
2023-03-18 20:08:06 +00:00
"decimal" => decimal(val),
2022-08-17 17:10:09 +00:00
"duration" => duration(val),
2023-03-18 20:08:06 +00:00
"float" => float(val),
"int" => int(val),
"number" => number(val),
"string" => string(val),
2021-03-29 15:43:37 +00:00
_ => Ok(val),
}
}
2022-08-17 17:10:09 +00:00
pub fn bool(val: Value) -> Result<Value, Error> {
Ok(val.is_truthy().into())
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn datetime(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Datetime(_) => val,
_ => Value::Datetime(val.as_datetime()),
})
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn decimal(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Number(Number::Decimal(_)) => val,
_ => Value::Number(Number::Decimal(val.as_decimal())),
})
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn duration(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Duration(_) => val,
_ => Value::Duration(val.as_duration()),
})
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn float(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Number(Number::Float(_)) => val,
_ => Value::Number(Number::Float(val.as_float())),
})
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn int(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Number(Number::Int(_)) => val,
_ => Value::Number(Number::Int(val.as_int())),
})
2021-03-29 15:43:37 +00:00
}
2023-03-18 20:08:06 +00:00
pub fn number(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Number(Number::Decimal(_)) => val,
_ => Value::Number(Number::Decimal(val.as_decimal())),
})
}
2023-03-18 20:08:06 +00:00
pub fn string(val: Value) -> Result<Value, Error> {
Ok(match val {
2023-03-18 20:08:06 +00:00
Value::Strand(_) => val,
_ => Value::Strand(val.as_strand()),
})
2021-03-29 15:43:37 +00:00
}