I am doing a count query using rust 1.59.0
diesel diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono"] }
following this document, this is my code looks like right now:
use diesel::{ExpressionMethods, QueryDsl, QueryResult, RunQueryDsl};
use diesel::dsl::count;
use rocket::serde::json::Json;
use rust_wheel::config::db::config;
pub fn channel_fav_count(req_channel_id: &i64) -> i32 {
use crate::model::diesel::dolphin::dolphin_schema::article_favorites::dsl::*;
let connection = config::establish_connection();
let query = article_favorites
.filter(channel_id.eq(req_channel_id));
let query_result = query.select(count(id)).first(&connection);
return query_result.unwrap_or(0);
}
when I compile the code, shows error like this:
error[E0277]: the trait bound `i32: FromSql<BigInt, Pg>` is not satisfied
--> src/service/app/cruise/article/article_fav_service.rs:11:48
|
11 | let query_result = query.select(count(id)).first(&connection);
| ^^^^^ the trait `FromSql<BigInt, Pg>` is not implemented for `i32`
why did this happen? what should I do to fix this problem?
first thing you must know it's query count return i64 not i32, so you must convert i64 to i32 by your self
maybe like this
let query_result = query.select(count(id)).first(&connection).map(|x| x as i32);
also you can get count by filter query like below
users
.filter(user_id.eq(_user_id))
.count()
.get_result(conn) // Result<i64, Error>
for your code it's like this
article_favorites
.filter(channel_id.eq(req_channel_id))
.count()
.get_result(&connection)