Rust Diesel过滤查询报错:trait bound不满足及类型匹配问题
Rust Diesel过滤查询编译错误修复
核心问题分析
编译报错分为两类:
bool: diesel::Expressiontrait未实现:filter条件误用本地字符串变量而非数据库表字段,导致生成普通布尔值而非Diesel可识别的查询表达式。- 查询结果与
BriefUrlModel类型不兼容:模型结构与数据库表的字段数量、类型不匹配。
相关代码片段
main.rs
use std::io::Write; use BriefURL::establish_connection; use BriefURL::insert_brief_url; use BriefURL::schema::BriefUrl::dsl::BriefUrl; use BriefURL::models::BriefUrlModel; use diesel::prelude::*; #[cfg(test)] use diesel::debug_query; fn main() { let connection = &mut establish_connection(); let user_name = "Anish"; let url = "https://8gwifi.org"; let short_url = "tessbrown"; let long_url = "tessbrown"; if let Err(e) = insert_brief_url(connection, &user_name, &url, &short_url, &long_url) { writeln!(&mut std::io::stderr(), "Error: {}", e).unwrap(); std::process::exit(1); } let _results = BriefUrl .filter(user_name.eq("Anish")) .limit(5) .load::<BriefUrlModel>(connection) .expect("Error loading posts"); }
schema.rs
use diesel::prelude::*; diesel::table! { BriefUrl (id) { id -> Nullable<Integer>, user_name -> Text, url -> Text, short_url -> Nullable<Text>, long_url -> Nullable<Text>, clicks -> Integer, click_date -> Nullable<Timestamp>, active -> Integer, date_accessed -> Nullable<Timestamp>, date_created -> Timestamp, } }
models.rs
use diesel::prelude::*; #[derive(Queryable, PartialEq, Debug)] pub struct BriefUrlModel { pub id: i32, pub user_name: String, pub url: String, pub short_url: Option<String>, pub long_url: Option<String>, pub active: i32, pub clicks: i32, pub click_date: Option<String>, pub date_accessed: Option<String>, }
完整编译报错
❯ cargo build warning: unused import: `diesel::prelude::*` --> src/schema.rs:2:5 | 2 | use diesel::prelude::*; | ^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default warning: unused import: `models::BriefUrlModel` --> src/lib.rs:12:5 | 12 | use models::BriefUrlModel; | ^^^^^^^^^^^^^^^^^^^^^ warning: crate `BriefURL` should have a snake case name | = help: convert the identifier to snake case: `brief_url` = note: `#[warn(non_snake_case)]` on by default warning: module `BriefUrl` should have a snake case name --> src/schema.rs:4:5 | 4 | BriefUrl (id) { | ^^^^^^^^ help: convert the identifier to snake case: `brief_url` warning: `BriefURL` (lib) generated 4 warnings Compiling BriefURL v0.1.0 (/Users/anish/IdeaProjects/BriefURL) error[E0277]: the trait bound `bool: diesel::Expression` is not satisfied --> src/main.rs:22:17 | 22 | .filter(user_name.eq("ANISH")) | ------ ^^^^^^^^^^^^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `bool` | | | required by a bound introduced by this call | = help: the following other types implement trait `diesel::Expression`: &'a T (T0, T1) (T0, T1, T2) (T0, T1, T2, T3) (T0, T1, T2, T3, T4) (T0, T1, T2, T3, T4, T5) (T0, T1, T2, T3, T4, T5, T6) (T0, T1, T2, T3, T4, T5, T6, T7) and 88 others = note: required for `SelectStatement<FromClause<table>>` to implement `FilterDsl<bool>` = note: 1 redundant requirement hidden = note: required for `table` to implement `FilterDsl<bool>` note: required by a bound in `diesel::QueryDsl::filter` --> /Users/anish/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-2.0.3/src/query_dsl/mod.rs:619:15 | 619 | Self: methods::FilterDsl<Predicate>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::QueryDsl::filter` error[E0277]: the trait bound `bool: ValidGrouping<()>` is not satisfied --> src/main.rs:22:10 | 22 | .filter(user_name.eq("ANISH")) | ^^^^^^ the trait `ValidGrouping<()>` is not implemented for `bool` | = help: the following other types implement trait `ValidGrouping<GroupByClause>`: <&'a T as ValidGrouping<GB>> <(T0, T1) as ValidGrouping<__GroupByClause>> <(T0, T1, T2) as ValidGrouping<__GroupByClause>> <(T0, T1, T2, T3) as ValidGrouping<__GroupByClause>> <(T0, T1, T2, T3, T4) as ValidGrouping<__GroupByClause>> <(T0, T1, T2, T3, T4, T5) as ValidGrouping<__GroupByClause>> <(T0, T1, T2, T3, T4, T5, T6) as ValidGrouping<__GroupByClause>> <(T0, T1, T2, T3, T4, T5, T6, T7) as ValidGrouping<__GroupByClause>> and 100 others = note: required for `bool` to implement `NonAggregate` = note: required for `SelectStatement<FromClause<table>>` to implement `FilterDsl<bool>` error[E0277]: the trait bound `(Nullable<diesel::sql_types::Integer>, diesel::sql_types::Text, diesel::sql_types::Text, Nullable<diesel::sql_types::Text>, Nullable<diesel::sql_types::Text>, diesel::sql_types::Integer, Nullable<Timestamp>, diesel::sql_types::Integer, Nullable<Timestamp>, Timestamp): load_dsl::private::CompatibleType<BriefUrlModel, Sqlite>` is not satisfied --> src/main.rs:24:32 | 24 | .load::<BriefUrlModel>(connection) | ---- ^^^^^^^^^^ the trait `load_dsl::private::CompatibleType<BriefUrlModel, Sqlite>` is not implemented for `(Nullable<diesel::sql_types::Integer>, diesel::sql_types::Text, diesel::sql_types::Text, Nullable<diesel::sql_types::Text>, Nullable<diesel::sql_types::Text>, diesel::sql_types::Integer, Nullable<Timestamp>, diesel::sql_types::Integer, Nullable<Timestamp>, Timestamp)` | | | required by a bound introduced by this call | = help: the following other types implement trait `load_dsl::private::CompatibleType<U, DB>`: (ST0, ST1) (ST0, ST1, ST2) (ST0, ST1, ST2, ST3) (ST0, ST1, ST2, ST3, ST4) (ST0, ST1, ST2, ST3, ST4, ST5) (ST0, ST1, ST2, ST3, ST4, ST5, ST6) (ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7) (ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, ST8) and 24 others = note: required for `SelectStatement<FromClause<table>, ..., ..., ..., ..., ...>` to implement `LoadQuery<'_, _, BriefUrlModel>` = note: the full type name has been written to '/Users/anish/IdeaProjects/BriefURL/target/debug/deps/BriefURL-88f99135e88d0a5a.long-type-5193104054952781216.txt' note: required by a bound in `diesel::RunQueryDsl::load` --> /Users/anish/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-2.0.3/src/query_dsl/mod.rs:1499:15 | 1499 | Self: LoadQuery<'query, Conn, U>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::RunQueryDsl::load` Some errors have detailed explanations: E0271, E0277. For more information about an error, try `rustc --explain E0271`. error: could not compile `BriefURL` due to 7 previous errors
修复方案
1. 修正filter条件的字段引用
main.rs中,user_name是本地字符串变量,需替换为Diesel生成的表字段:
// 新增导入schema中的user_name字段 use BriefURL::schema::BriefUrl::dsl::user_name; // 修改查询逻辑 let _results = BriefUrl .filter(user_name.eq("Anish")) // 使用schema字段而非本地变量 .limit(5) .load::<BriefUrlModel>(connection) .expect("Error loading posts");
2. 对齐模型与数据库表的字段
models.rs中的BriefUrlModel缺少date_created字段,且时间类型需与数据库Timestamp匹配:
use diesel::prelude::*; #[derive(Queryable, PartialEq, Debug)] pub struct BriefUrlModel { pub id: i32, pub user_name: String, pub url: String, pub short_url: Option<String>, pub long_url: Option<String>, pub active: i32, pub clicks: i32, pub click_date: Option<chrono::NaiveDateTime>, // 替换为NaiveDateTime pub date_accessed: Option<chrono::NaiveDateTime>, // 替换为NaiveDateTime pub date_created: chrono::NaiveDateTime, // 新增缺失字段 }
同时在Cargo.toml中添加chrono依赖:
[dependencies] chrono = { version = "0.4", features = ["diesel"] }
3. 可选:修正命名规范警告
按照Rust命名规范,将crate名改为brief_url,schema表名改为brief_url,消除编译警告。
内容的提问来源于stack exchange,提问作者anish
相关产品推荐
相关产品推荐

