I am using rust diesel diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono","serde_json"] } to do the group by query follow the docs like this:
fpub fn get_bill_book_account_sum(){
use crate::diesel::GroupByDsl;
use diesel::dsl::max;
use crate::model::diesel::dict::dict_schema::test as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::id)
.select((max(bill_record_table::tags),bill_record_table::id))
.filter(bill_record_table::dsl::tags.eq(9));
}
then compile this code, shows error like this:
error[E0277]: the trait bound `aggregate_ordering::max::max<BigInt, columns::tags>: NonAggregate` is not satisfied
--> src/main.rs:19:17
|
19 | .select((max(bill_record_table::tags),bill_record_table::id))
| ------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `NonAggregate` is not implemented for `aggregate_ordering::max::max<BigInt, columns::tags>`
| |
| required by a bound introduced by this call
|
= note: required because of the requirements on the impl of `diesel::Expression` for `(aggregate_ordering::max::max<BigInt, columns::tags>, columns::id)`
note: required by a bound in `diesel::QueryDsl::select`
--> /Users/xiaoqiangjiang/.cargo/registry/src/mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd/diesel-1.4.8/src/query_dsl/mod.rs:291:20
|
291 | Selection: Expression,
| ^^^^^^^^^^ required by this bound in `diesel::QueryDsl::select`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `rust-learn` due to previous error
where am I doing wrong? what should I do to fixed this problem? this is the schema define(I have removed all the columns just using 2 columns to make a minimal reproduce example):
table! {
test (id) {
id -> Int8,
tags -> Int8,
}
}
and this is the model define:
// Generated by diesel_ext
#![allow(unused)]
#![allow(clippy::all)]
use std::io::Write;
use diesel::deserialize::FromSql;
use diesel::pg::Pg;
use diesel::serialize::{Output, ToSql};
use diesel::sql_types::Jsonb;
use rocket::serde::Serialize;
use serde::Deserialize;
use crate::model::diesel::dict::dict_schema::*;
#[derive(Queryable,Debug,Serialize,Deserialize,Default)]
pub struct Test {
pub id: i64,
pub tags: i64,
}
this is the minimal main.rs entrypoint:
#[macro_use]
extern crate diesel;
mod model;
use diesel::{ ExpressionMethods, QueryDsl};
fn main() {
get_bill_book_account_sum();
}
pub fn get_bill_book_account_sum(){
use crate::diesel::GroupByDsl;
use diesel::dsl::max;
use crate::model::diesel::dict::dict_schema::test as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::id)
.select((max(bill_record_table::tags),bill_record_table::id))
.filter(bill_record_table::dsl::tags.eq(9));
}
change the aggregate query like this fixed this problem:
pub fn get_bill_book_account_sum(request: &BillAccountRequest) -> Result<Vec<(i64, i32)>, diesel::result::Error>{
use crate::diesel::GroupByDsl;
use crate::model::diesel::fortune::fortune_schema::bill_record as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::account_id)
.select((diesel::dsl::sql::<diesel::sql_types::BigInt>("SUM(CAST(amount AS Integer))"),bill_record_table::account_id))
.filter(bill_record_table::dsl::bill_book_id.eq(request.bill_book_id));
let result = source_query.load::<(i64,i32)>(&get_connection());
return result;
}
the solution come from this issue. This is the answer come from the maintainer that shows diesel 1.x did not support group by official.
Related
I am relatively new to rust and have really enjoyed playing around with it. However I am stuck on an error for my CRUD application using Diesel and Rocket. I have a main.rs, model.rs and schema.rs.
I get an error with my POST method that uses the User struct i created.
I am using a postgres DB i have running in the background on docker, Diesel and rocket for routing.
My models.rs
use super::schema::users;
use diesel::{prelude::*, table, Queryable, Insertable, RunQueryDsl};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Queryable, Debug, Insertable)]
#[table_name= "users"]
pub struct User {
pub id: i32,
pub first_name: String,
pub last_name: String,
pub user_name: String,
pub email_address: String,
}
My main.rs (included everything for detail but really question is about the Post method - create_user
#[macro_use] extern crate rocket;
mod models;
mod schema;
use rocket_sync_db_pools::{database};
use models::{User};
use rocket::{serde::json::Json};
use diesel::{RunQueryDsl};
use schema::users;
#[database("my_db")]
pub struct Db(rocket_sync_db_pools::diesel::PgConnection);
#[get("/")]
fn index() -> &'static str {
"Hello World"
}
#[get("/<id>")]
fn get_user(id: i32) -> Json<User> {
Json(User {
id: id,
first_name: "A Fist Name".to_string(),
last_name: "A Last Name".to_string(),
user_name: "A User Name".to_string(),
email_address: "AnEmail#email.com".to_string(),
})
}
#[post("/", data = "<user>")]
async fn create_user(connection: Db, user: Json<User>) -> Json<User> {
connection.run(move |c| {
diesel::insert_into(users::table)
.values(&user.into_inner())
.get_result(c)
})
.await
.map(Json)
.expect("There was an error saving the user")
}
#[launch]
fn rocket() -> _ {
let rocket = rocket::build();
rocket
.attach(Db::fairing())
.mount("/", routes![index])
.mount("/users", routes![get_user, create_user])
}
Dependencies from Cargo.toml
[dependencies]
diesel = "2.0.2"
diesel_cli = { version = "1.4.1", default-features = false, features = ["postgres"] }
rocket = { version = "0.5.0-rc.2", features = ["json"] }
rocket_sync_db_pools = { version = "0.1.0-rc.2", features = ["diesel_postgres_pool"] }
serde = "1.0.140"
The error message
--> src/main.rs:66:6
|
66 | .get_result(c)
| ^^^^^^^^^^
|
= help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`with_auth_rust_rocket_diesel_binary`)
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: 123 redundant requirements hidden
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: required because of the requirements on the impl of `diesel::insertable::InsertValues<table, _>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: 3 redundant requirements hidden
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `diesel::query_builder::InsertStatement<table, diesel::query_builder::insert_statement::ValuesClause<(DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::first_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::last_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::user_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::email_address, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>), table>, diesel::query_builder::insert_statement::private::Insert, diesel::query_builder::returning_clause::ReturningClause<(columns::id, columns::first_name, columns::last_name, columns::user_name, columns::email_address)>>`
= note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<'_, _, _>` for `diesel::query_builder::InsertStatement<table, diesel::query_builder::insert_statement::ValuesClause<(DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::first_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::last_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::user_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::email_address, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>), table>>`
note: required by a bound in `diesel::RunQueryDsl::get_result`
--> /Users/me/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-2.0.2/src/query_dsl/mod.rs:1679:15
|
1679 | Self: LoadQuery<'query, Conn, U>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::RunQueryDsl::get_result`
I have reviewed both Diesel, Rocket and Rust documentation and worked worked through other examples for what I can find online however still do not quite get what i am doing incorrectly. Thanks in advance for any help.
I tried to create a post method that uses Diesel to take a Json version of my User object and insert it into my database.
This is a mismatch between the diesel version used by your project (2.0.2) and the diesel version provided by rocket_sync_db_pools (1.4.8). This means the c in connection.run(move |c| { is just a completely different type than expected by get_result, even if the types share the same name.
I currently trying to implement abstract function which will update a few meta fields for any table in the database, but getting problems with Identifiable.
I have a database where every table has meta-fields:
....
pub updu: Option<Uuid>, // ID of a user who changed it
pub updt: Option<NaiveDateTime>, //updated with current date/time on every change
pub ver: Option<i32>, //Version increases on every change
.....
I want to implement a function which would make update for every entity. Currently I have this implementation:
pub fn update<Model>(
conn: &PgConnection,
old_model: Model,
mut updated_model: Model,
user_id: Uuid,
) -> Result<Model, diesel::result::Error>
where
Model: MetaFields + AsChangeset<Target = <Model as HasTable>::Table> + IntoUpdateTarget,
Update<Model, Model>: LoadQuery<PgConnection, Model>
{
updated_model.update_fields(user_id);
Ok(
diesel::update(old_model)
.set(updated_model)
.get_result(conn).unwrap()
)
When I am trying to call it it shows this error:
error[E0277]: the trait bound `Marking: Identifiable` is not satisfied
--> src/service/marking_service.rs:116:24
|
116 | web::block(move || common::dao::update(&conn2, real_marking1[0].clone(), marking2_to_update, jwt_token.user_id))
| ^^^^^^^^^^^^^^^^^^^ the trait `Identifiable` is not implemented for `Marking`
|
= help: the following implementations were found:
<&'ident Marking as Identifiable>
= note: required because of the requirements on the impl of `IntoUpdateTarget` for `Marking`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `testapi` due to previous error
An entity which I am trying to update in this example is:
use chrono::{NaiveDateTime, Utc};
use common::model::MetaFields;
use common::utils::constants::DEL_MARK_AVAILABLE;
use serde::{Deserialize, Serialize};
use serde_json;
use uuid::Uuid;
use crate::schema::marking;
#[derive(
Clone,
Serialize,
Deserialize,
Debug,
Queryable,
Insertable,
AsChangeset,
Identifiable,
QueryableByName,
Default,
)]
#[primary_key(uuid)]
#[table_name = "marking"]
pub struct Marking {
pub uuid: Uuid,
pub updt: Option<NaiveDateTime>,
pub ver: Option<i32>,
pub updu: Option<Uuid>,
pub comment: Option<String>,
pub status: Option<String>,
}
impl MetaFields for Marking {
fn update_fields(&mut self, user_id: Uuid) {
self.updu = Option::from(user_id);
self.ver = Option::from(self.ver.unwrap() + 1);
self.updt = Option::from(Utc::now().naive_local());
}
}
As you can see Identifiable is defined for this entity, but for some reason update cannot see it. Could someone suggest what I am missing here?
Update, schema:
table! {
marking (uuid) {
uuid -> Uuid,
updt -> Nullable<Timestamp>,
ver -> Nullable<Int4>,
updu -> Nullable<Uuid>,
comment -> Nullable<Varchar>,
status -> Nullable<Varchar>,
}
}
diesel = { version = "1.4.6", features = ["postgres", "uuid", "chrono", "uuidv07", "serde_json"] }
r2d2 = "0.8"
r2d2-diesel = "1.0.0"
diesel_json = "0.1.0"
Your code is almost correct. The error message already mentions the issue:
#[derive(Identifiable)] does generate basically the following impl: impl<'a> Identifiable for &'a struct {}, which means that trait is only implemented for a reference to self. Depending on your other trait setup you can try the following things:
Pass a reference as old_model common::dao::update
Change the definition of common::dao::update to take a reference as second argument. Then you can separate the trait bounds for Model so that you bound IntoUpdateTarget on &Model instead.
(It's hard to guess which one will be the better solution as your question is missing a lot of important context. Please try to provide a complete minimal example in the future.)
I'm loosely following Diesel's getting started guide trying to set up a relational database, but getting the following error on compile:
error[E0433]: failed to resolve: use of undeclared type or module `birds`
--> src/models.rs:9:12
|
9 | pub struct Bird {
| ^^^^ use of undeclared type or module `birds`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0433`.
error: Could not compile `prrr_gql`.
Here's the binary:
extern crate prrr_gql;
extern crate diesel;
use self::prrr_gql::*;
use self::models::*;
use self::diesel::prelude::*;
fn main() {
use prrr_gql::schema::cats::dsl::*;
use prrr_gql::schema::birds::dsl::*;
let connection = establish_connection();
let results = cats.load::<Cat>(&connection)
.expect("Error hearding cats");
for cat in results {
println!("{}", cat.name);
}
}
and lib.rs (imported as prrr_gql)
#[macro_use]
extern crate diesel;
extern crate dotenv;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;
pub mod schema;
pub mod models;
pub fn establish_connection() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url))
}
models.rs
#[derive(Queryable, Debug)]
pub struct Cat {
pub id: i32,
pub name: String,
}
#[derive(Queryable, Associations, Debug)]
#[belongs_to(Cat)]
pub struct Bird {
pub id: i32,
pub cat_id: i32,
pub species: String,
pub colors: String
}
and the schema.rs generated by Diesel
table! {
birds (id) {
id -> Int4,
species -> Varchar,
colors -> Varchar,
cat_id -> Nullable<Int4>,
}
}
table! {
cats (id) {
id -> Int4,
name -> Varchar,
}
}
joinable!(birds -> cats (cat_id));
allow_tables_to_appear_in_same_query!(
birds,
cats,
);
The only issue I could find related to this says I need to have birds in scope and references the table! macro that I have provided, so I'm not sure what's missing.
When I comment out everything related to the birds database, everything runs as expected.
Full project with Cargo.toml for reference: https://github.com/crashspringfield/prrr_gql/tree/diesel-error
As the error mentions, birds is not in scope. The table! macro creates a public module (birds), which you then need to bring into scope to be able to derive Associations (in models.rs):
use super::schema::birds;
See diesel::associations for an example, where it shows that one needs to use the schema for derive.
I'm trying to use Diesel and diesel_geography to read from a PostGIS database using Rust.
Here's the error I'm getting:
error[E0277]: the trait bound `diesel_geography::types::GeogPoint: serde::Serialize` is not satisfied
--> src/models.rs:11:5
|
11 | pub coordinates: GeogPoint,
| ^^^ the trait `serde::Serialize` is not implemented for `diesel_geography::types::GeogPoint`
|
= note: required by `serde::ser::SerializeStruct::serialize_field`
error[E0277]: the trait bound `diesel_geography::types::GeogPoint: serde::Deserialize<'_>` is not satisfied
--> src/models.rs:11:5
|
11 | pub coordinates: GeogPoint,
| ^^^ the trait `serde::Deserialize<'_>` is not implemented for `diesel_geography::types::GeogPoint`
|
= note: required by `serde::de::SeqAccess::next_element`
error[E0277]: the trait bound `diesel_geography::types::GeogPoint: serde::Deserialize<'_>` is not satisfied
--> src/models.rs:11:5
|
11 | pub coordinates: GeogPoint,
| ^^^ the trait `serde::Deserialize<'_>` is not implemented for `diesel_geography::types::GeogPoint`
|
= note: required by `serde::de::MapAccess::next_value`
Looking around, I found that a similar error happens when there are several versions of serde used as dependency, this can be checked using cargo tree -d. I've tried and serde does not appear as a duplicate dependency.
This is my code so far:
Cargo.toml
[package]
name = "123"
version = "0.1.0"
authors = ["ASD"]
edition = "2018"
[dependencies]
diesel = { version = "1.4.2", features = ["postgres"] }
serde = { version = "1.0", features = ["derive"] }
serde_json="1.0"
dotenv = "0.14.1"
diesel-geography = "0.2.0"
schema.rs
table! {
use diesel::sql_types::*;
use diesel_geography::sql_types::*;
users (email) {
email -> Varchar,
password -> Varchar,
coordinates -> Geography
}
}
models.rs
use diesel_geography::types::*;
use crate::schema::users;
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]
#[table_name = "users"]
pub struct User {
pub email: String,
pub password: String,
pub coordinates: GeogPoint
}
main.rs
extern crate serde;
extern crate dotenv;
#[macro_use] extern crate diesel;
//#[macro_use] extern crate serde_derive;
mod models;
mod schema;
use diesel::PgConnection;
use dotenv::dotenv;
use std::env;
use diesel::prelude::*;
fn main() {
dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let connection = PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url));
use crate::schema::users::dsl::*;
use crate::models::User;
let results = users
.limit(5)
.load::<User>(&connection)
.expect("Error loading users");
println!("Displaying {} users", results.len());
for user in results {
println!("{}", user.email);
println!("----------\n");
println!("{}", user.password);
}
}
Serde is an optional dependency of diesel-geography. You need to enable the feature:
[dependencies]
diesel-geography = { version = "0.2.0", features = ["serde"] }
I'm trying to serialize the following Result object, however I'm getting an error because while it workings for some of the properties, it doesn't seem to work on path, even though all of the elements involved have implementations provided by Serde.
#[macro_use]
extern crate serde;
extern crate rocket;
use rocket_contrib::json::Json;
use std::rc::Rc;
#[derive(Serialize)]
struct Result {
success: bool,
path: Vec<Rc<GraphNode>>,
visited_count: u32,
}
struct GraphNode {
value: u32,
parent: Option<Rc<GraphNode>>,
}
fn main(){}
fn index() -> Json<Result> {
Json(Result {
success: true,
path: vec![],
visited_count: 1,
})
}
Playground, although I can't get it to pull in the Rocket crate, it must not be one of the 100 most popular.
error[E0277]: the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `std::rc::Rc<GraphNode>`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
From my understanding, #[derive(Serialize)] should automatically create a serialize method which serde can then use. However I would expect it to work for the properties too. Do I need to create structs for all the types and then derive Serialize for all of those structs?
Do I need to do something to enable it?
The following crates are in use:
rocket = "*"
serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "*"
the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
This means that Rc does not implement Serialize. See How do I serialize or deserialize an Arc<T> in Serde?. TL;DR:
serde = { version = "1.0", features = ["derive", "rc"] }
Once adding that, the error message changes to:
error[E0277]: the trait bound `GraphNode: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `GraphNode`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::rc::Rc<GraphNode>`
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
That's because every type that needs to be serialized must implement Serialize:
#[derive(Serialize)]
struct GraphNode {