gluesql / gluesql

GlueSQL is quite sticky. It attaches to anywhere.

Home Page:https://gluesql.org/docs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

impl `TryFrom<Value>` for common `Option<T>` types

gitmalong opened this issue · comments

This works:

let fee: Decimal = fee.try_into().unwrap();

this doesn't

let fee: Option<Decimal> = fee.try_into().unwrap();
the trait bound `std::option::Option<rust_decimal::Decimal>: std::convert::From<gluesql_core::data::Value>` is not satisfied

Workaround

let fee: Option<Decimal> = match !fee.is_null() {
      true => Some(Decimal::try_from(fee).unwrap()),
      false => None,
};

The current implementation of try_from in Value looks like this

https://github.com/gluesql/gluesql/blob/81a4d9e8b8dedcf947e744afbb36c09753867989/core/src/data/value/convert.rs

  1. Returns ImpossibleCast error for Null variant
  2. returns an ImpossibleCast error if the data cannot be automatically cast (dynamic type)

If your definition is,

  1. If NULL, return Option::None.
  2. returns a type of T if the data can be cast.

Currently, you can use it as follows
https://docs.rs/gluesql/latest/gluesql/core/data/enum.Value.html#method.is_null
Use try_from after checking Value::is_null separately.