I want to do a page query using rust diesel, I am using this code to do a unit test in rust:
#[cfg(test)]
mod test {
use std::env;
use diesel::{Connection, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl};
use rust_wheel::common::query::pagination::PaginateForQuerySource;
use crate::model::diesel::rhythm::rhythm_schema::favorites::dsl::favorites;
use crate::model::diesel::rhythm::rhythm_schema::favorites::like_status;
use crate::models::Favorites;
#[test]
fn page_test(){
use crate::model::diesel::rhythm::rhythm_schema::favorites::dsl::*;
use rust_wheel::common::query::pagination::{PaginateForQueryFragment, PaginateForQuerySource};
let conn = establish_music_connection();
let query = favorites
.filter(like_status.eq(1))
.paginate(1)
.per_page(10)
.load::<Favorites>(&conn)
.expect("query fav failed");
println!("{:?}", 1);
}
pub fn establish_music_connection() -> PgConnection {
let database_url = std::env::var("MUSIC_DATABASE_URL").expect("MUSIC_DATABASE_URL must be set");
PgConnection::establish(&database_url).expect(&format!("Error connecting to {}", database_url))
}
}
shows error like this:
error: cannot find attribute `table_name` in this scope
--> src/models.rs:15:3
|
15 | #[table_name = "favorites"]
| ^^^^^^^^^^
this is my models.rs define, this two models are store in different database:
use rocket::serde::Serialize;
use serde::Deserialize;
use crate::model::diesel::dolphin::dolphin_schema::dashboard;
use crate::model::diesel::rhythm::rhythm_schema::favorites;
#[derive(Insertable, Serialize, Queryable, Deserialize,Default)]
#[table_name = "dashboard"]
pub struct Dashboard {
pub id: i32,
pub app_count: i32,
pub user_count: i32
}
#[derive(Serialize, Queryable, Deserialize,Default)]
#[table_name = "favorites"]
pub struct Favorites {
pub id: i64,
pub song_id: String,
pub created_time: i64
}
why did this happen? what should I do to fix it?
Only the Insertable derive macro handles the #[table_name = ...] attribute. So it should not be included if you're not using it.
Related
I have the following:
struct Health {
health: f32,
}
struct Position {
position: Vec2,
}
struct Collections {
healths: Vec<Health>,
positions: Vec<Position>,
}
I would like to generate the Collections struct automatically; I am thinking using a macro?
I thought perhaps I could mark each struct I want to include with a custom attribute and then have a macro which builds the Collections struct.
How could I do this?
To be able to do something like custom attributes you need to write a proc_macro, that can do almost anything you need with your code.
For a simpler solution you may try with a normal macro_rules. For that you will need to enclose your type definitions into a macro that does the parsing, and emits back the type definition plus the extra code you need, in your case the Container class.
Something like this:
macro_rules! collectables {
(
$(
#[collection=$fname:ident]
$(#[$attr:meta])?
$vis:vis struct $name:ident $def:tt
)*
) => {
// The struct definitions
$(
$(#[$attr])?
$vis struct $name $def
)*
// The container
#[derive(Default, Debug)]
pub struct Collections {
$(
$fname: Vec<$name>,
)*
}
};
}
Now you can use the macro to build your original code (playground):
collectables!{
#[collection=healths]
#[derive(Debug)]
struct Health {
health: f32,
}
#[collection=positions]
#[derive(Debug)]
struct Position {
position: (f32, f32),
}
}
Note that as written the #[collection=xxx] attribute is mandatory and must be the first in every struct definition.
So I managed to solve this problem using a proc_macro. Each struct which is to be included in the final Storage struct is marked with the Component derive attribute. The Storage struct is then built with the storage!() macro.
use lazy_static::lazy_static;
use proc_macro::TokenStream;
use quote::quote;
use std::sync::Mutex;
use syn::{parse_macro_input, parse_str, DeriveInput, ExprType};
lazy_static! {
static ref COMPONENTS: Mutex<Vec<String>> = Mutex::new(Vec::new());
}
#[proc_macro_derive(Component)]
pub fn component(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput); ‣DeriveInput
let ident = input.ident; ‣Ident
COMPONENTS.lock().unwrap().push(ident.to_string());
let expanded = quote! { ‣TokenStream
impl component::Component for #ident {}
};
TokenStream::from(expanded)
}
#[proc_macro]
pub fn storage(_input: TokenStream) -> TokenStream {
println!("Building Storage with: {:?}", COMPONENTS.lock().unwrap());
let mut fields = Vec::new(); ‣Vec<ExprType>
for type_name in COMPONENTS.lock().unwrap().iter() { ‣&String
let field = parse_str::<ExprType>( ‣ExprType
format!("{}s: Vec<{}>", type_name.to_lowercase(), type_name).as_str(),
) ‣Result<ExprType, Error>
.expect("Could not parse component field type");
fields.push(field);
}
let expanded = quote! { ‣TokenStream
#[derive(Serialize, Deserialize, Debug, Default)]
struct Storage {
#(#fields),*
}
};
TokenStream::from(expanded)
}
#[derive(Debug, Serialize, Deserialize, Component)]
struct Health {
health: f32,
}
#[derive(Debug, Serialize, Deserialize, Component)]
pub struct Age {
pub age: u64,
}
storage!();
In my rust project, I'm trying to make a db like implementation that can store the state of a user from different integrations that all implement same functions through a trait, and can be written to a file later using serde with this code:
#[derive(Serialize, Deserialize, Debug)]
pub struct State {
pub current: HashMap<Bytes, Box<dyn UserState>>
pub changes: HashMap<u64, Vec<UserStateChange>>
}
pub trait UserState {
fn id(&self) -> Bytes;
fn apply_change(&mut self, change: UserStateChange);
}
#[derive(Serialize, Deserialize, Debug)]
pub enum UserStateChange {
Foo(FooChange),
Bar(BarChange)
}
#[derive(Serialize, Deserialize, Debug)]
pub struct FooState {
id: Bytes,
count: u64,
start: u64
}
#[derive(Serialize, Deserialize, Debug)]
pub struct FooChange {
count_delta: i64
}
impl UserState for FooState {
fn id(&self) -> Bytes {self.id.clone()}
fb apply_change(&mut self, change: UserStateChange) {
let UserStateChange::Foo(change) = change;
todo!();
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BarState {
id: Bytes,
attempts: u64
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BarChange {
attempt_delta: i64
}
impl UserState for BarState {
fn id(&self) -> Bytes {self.id.clone()}
fb apply_change(&mut self, change: UserStateChange) {
let UserStateChange::Bar(change) = change;
// apply logic
}
}
How can I make it so that it can store and serialize the dynamic trait, while ensuring that it supports the apply_change function, and can use its own structure for storing changes with relevant fields?
I am using rust rocket as the http server side. On the server side, I define a rust struct like this to receive the data from client side:
#[derive(Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct PlayRecordRequest {
pub id: i64,
pub title: String,
pub url: String,
pub mvId: i64,
pub album: MusicAlbum,
pub artist: Vec<Artist>,
}
and recieve in the http controller like this:
#[post("/user/v1/save-play-record", data = "<record>")]
pub fn save_play_record<'r>(
record: Json<PlayRecordRequest>,
) -> content::Json<String> {
info!("save play record,title:{}",record.title);
save_play_record_impl(record);
let res = ApiResponse {
result: "ok".to_string(),
..Default::default()
};
let result_json = serde_json::to_string(&res).unwrap();
return content::Json(result_json);
}
the problem is that when the client side did not have some fields, the code run into error. is it possible to auto fit the field for Deserialize, if the client have the field, Deserialize it normally, if the client did not contains some fields, just ignore it and do not run into error. I read the official document of serde and find the skip annotation. But the annotation just use to mark the field should be ignored, what I want is that the struct could auto fit all field exists or not. is it possible to do like this?
There are two ways to handle this.
First is with options. Options imply that the data may or may not exist. If the data is null or missing it convert to an Option::none value. You can preserve the lack of data on serialization if you add #[serde(skip_serializing_if = "Option::is_none")]
Second option is to apply defaults to the value if the data is missing. Although from your use case this doesn't seem to be ideal.
Here is a code snippet of the two cases that you can run on https://play.rust-lang.org/:
use::serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug)]
#[allow(non_snake_case)]
pub struct Foo {
#[serde(skip_serializing_if = "Option::is_none")]
pub bar: Option<i64>,
#[serde(default = "default_baz")]
pub baz: i64,
}
fn default_baz()-> i64{
3
}
fn main(){
let data = r#"{"bar": null, "baz": 1}"#;
let v: Foo = serde_json::from_str(data).unwrap();
println!("{:#?}", v);
let s = serde_json::to_string(&v).unwrap();
println!("Don't serialize None values: {:#?}", s);
let data = r#"{"missing_bar": null}"#;
let v: Foo = serde_json::from_str(data).unwrap();
println!("{:#?}", v)
}
I have struct from which I want to extract the data.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunResult {
pub runs: Vec<RunDetails>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunDetails {
pub details: String,
pub name: String,
pub id: String,
pub type: String,
}
I am getting the data which got inserted in above struct in the variable result which I am iterating below
let my_result:RunResult = result
.runs
.into_iter()
.filter(|line| line.details.contains(&"foo"))
.collect();
I am getting the error as
value of type `RunResult` cannot be built from `std::iter::Iterator<Item=RunDetails>`
I want to get the record where type=OK, details contains foo with highest id.
How can I achieve this?
Check out the documentation for collect here.
Your struct RunResult should implement FromIterator<RunDetails>.
Try adding this (untested by me):
impl FromIterator<RunDetails> for RunResult {
fn from_iter<I: IntoIterator<Item=RunDetails>>(iter: I) -> Self {
Self {
runs: Vec::from_iter(iter);
}
}
}
The relevant bits of my model:
table! {
server_website {
id -> Integer,
server_database_id -> Nullable<Integer>,
server_id -> Integer,
}
}
table! {
server_database {
id -> Integer,
server_id -> Integer,
}
}
table! {
server {
id -> Integer,
}
}
joinable!(server_website -> server_database (server_database_id));
allow_tables_to_appear_in_same_query!(server_website, server_database);
#[derive(Queryable, Debug, Clone, PartialEq, Eq)]
pub struct Server {
pub id: i32,
}
#[derive(Queryable, Debug, Clone, PartialEq, Eq)]
pub struct ServerWebsite {
pub id: i32,
pub server_database_id: Option<i32>,
pub server_id: i32,
}
#[derive(Queryable, Debug, Clone, PartialEq, Eq)]
pub struct ServerDatabase {
pub id: i32,
pub server_id: i32,
}
I'm trying to express the following working SQLite query with Diesel:
select * from server_website where server_database_id in (
select id from server_database where server_id = 83
);
And here is my diesel query code:
use projectpadsql::schema::server::dsl as srv;
use projectpadsql::schema::server_database::dsl as db;
use projectpadsql::schema::server_website::dsl as srvw;
let database_ids_from_server = db::server_database
.filter(db::server_id.eq(83))
.select(db::id);
let used_websites = srvw::server_website
.filter(srvw::server_database_id.eq_any(database_ids_from_server))
.load::<ServerWebsite>(sql_conn)
.unwrap();
This fails with the error:
error[E0277]: the trait bound `diesel::query_builder::SelectStatement<projectpadsql::schema::server_database::table, diesel::query_builder::select_clause::SelectClause<projectpadsql::schema::server_database::columns::id>, diesel::query_builder::distinct_clause::NoDistinctClause, diesel::query_builder::where_clause::WhereClause<diesel::expression::operators::Eq<projectpadsql::schema::server_database::columns::server_id, diesel::expression::bound::Bound<diesel::sql_types::Integer, i32>>>>: diesel::expression::array_comparison::AsInExpression<diesel::sql_types::Nullable<diesel::sql_types::Integer>>` is not satisfied
I see that the compiler would like the inner query to have the type AsInExpression<Nullable<Integer>> which looks good to me (besides the nullable).
The inner query has more or less the type SelectStatement<server_database, SelectClause<server_database::id>>, which looks good to me since the id is Integer just like the outer query wants.
I have the feeling I'm quite close, but I can't put my finger on what the issue is.
I needed to use nullable() to get the types matching. Notice the db::id.nullable():
let database_ids_from_server = db::server_database
.filter(db::server_id.eq(server_id))
.select(db::id.nullable());
let used_websites = srvw::server_website
.filter(srvw::server_database_id.eq_any(database_ids_from_server))
.load::<ServerWebsite>(sql_conn)
.unwrap();
Georg Semmler - #weiznich on the Diesel Gitter channel answered this question.