rust - 使用 Diesel 将 bool 值插入 PostgreSQL 数据库时出错

标签 rust rust-diesel

let _ = diesel::insert_into(like::table)
       .values(&like)
       .load::<Like>(&db.connection)
       .unwrap();

关于&db.connection我收到以下错误

the trait bound bool: FromSql<Integer, _> is not satisfied
the trait FromSql<diesel::sql_types::Bool, Pg> is implemented for bool
required for bool to implement Queryable<Integer, _>

我尝试使用CustomBool来实现这种方法,但无论如何我得到了同样的错误,但对于 CustomBool

#[derive(Debug, Clone, Copy, PartialEq, FromSqlRow)]
pub struct CustomBool(bool);

impl FromSql<SqlBool, Pg> for CustomBool {
    fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
        match bytes {
            Some(bytes) => Ok(CustomBool(bytes[0] != 0)),
            None => Ok(CustomBool(false)),
        }
    }
}

impl ToSql<SqlBool, Pg> for CustomBool {
    fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
        ToSql::<diesel::sql_types::Integer, Pg>::to_sql(&(self.0 as i32), out)
    }
}

#[derive(Queryable, Identifiable, Associations, Debug)]
#[belongs_to(User, Post)]
#[table_name="like"]
pub struct Like {
    pub id: i32,
    pub reaction: CustomBool,
    pub post_id: i32,
    pub user_id: i32
}

我的架构

diesel::table! {
    like (id) {
        id -> Int4,
        user_id -> Int4,
        post_id -> Int4,
        reaction -> Bool,
    }
}

我遇到了这个问题,非常感谢您的帮助

最佳答案

此问题的根本原因是架构和模型属性之间的顺序不匹配。就我而言,reaction 应该是最后一项

pub struct Like {
    pub id: i32,
    pub post_id: i32,
    pub user_id: i32,
    pub reaction: bool,
}

关于rust - 使用 Diesel 将 bool 值插入 PostgreSQL 数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76756829/

相关文章:

string - 拆分字符串并跳过空子字符串

rust - 如何使用 byteorder crate 读取 usize?

mysql - 使用 Diesel、r2d2 和 r2d2-diesel 查询数据库时出错

mysql - 我无法在 MariaDB 上使用 Diesel 进行绑定(bind)

rust/柴油 : How to query and insert into postgres tables which have uuid

rust - 感叹号在特征实现中意味着什么?

rust - 复制模式匹配中的值而不拥有它

rust - 如何在 Diesel 中针对 Postgres 数据库执行带有子查询的删除?

rust - Diesel "get_results"给出特征绑定(bind)错误

c++ - Rust与C++ : Returning objects from functions