当我知道列由于过滤器而不能为空时,如何删除列上的“可为空”包装器?

Ros*_*ers 3 rust rust-diesel

如果我有schema.rs

table! {
    Foo (id) {
        id -> Integer,
        label -> Nullable<Text>,
    }
}
Run Code Online (Sandbox Code Playgroud)

我过滤如下:

let result: String = foo_dsl::Foo
    .select(foo_dsl::label)
    .filter(foo_dsl::label.is_not_null())
    .first(&conn)
    .unwrap();
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

error[E0277]: the trait bound `*const str: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, Mysql>` is not satisfied
    --> src/main.rs:21:10
     |
21   |         .first(&conn)
     |          ^^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, Mysql>` is not implemented for `*const str`
     |
     = help: the following other types implement trait `FromSql<A, DB>`:
               <*const str as FromSql<diesel::sql_types::Text, DB>>
               <std::string::String as FromSql<ST, DB>>
     = note: required because of the requirements on the impl of `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, Mysql>` for `std::string::String`
     = note: required because of the requirements on the impl of `Queryable<diesel::sql_types::Nullable<diesel::sql_types::Text>, Mysql>` for `std::string::String`
     = note: required because of the requirements on the impl of `LoadQuery<MysqlConnection, std::string::String>` for `diesel::query_builder::SelectStatement<table, query_builder::select_clause::SelectClause<columns::label>, query_builder::distinct_clause::NoDistinctClause, query_builder::where_clause::WhereClause<IsNotNull<columns::label>>, query_builder::order_clause::NoOrderClause, query_builder::limit_clause::LimitClause<diesel::expression::bound::Bound<BigInt, i64>>>`
note: required by a bound in `first`
    --> /home/kmdreko/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-1.4.8/src/query_dsl/mod.rs:1343:22
     |
1343 |         Limit<Self>: LoadQuery<Conn, U>,
     |                      ^^^^^^^^^^^^^^^^^^ required by this bound in `first`
Run Code Online (Sandbox Code Playgroud)

这是有道理的;该字段被指定为Nullable并且如果我使用则将起作用Option<String>。但对于这个查询,我知道该值存在,因为我按 进行过滤.is_not_null()。是否可以剥离Nullable列包装器,或者我是否需要在查询结果后手动解开包装器?

wei*_*ich 5

您有多种选择:

  • .unwrap()对结果使用或类似的方法
  • 使用显式 select 子句 + .assume_not_null(). (请注意,此方法仅适用于柴油 2.0,因为您的问题缺少有关柴油版本的信息,很难判断您是否可以直接使用此方法,或者是否需要自己实现类似的操作)。