Rust Async Graphql Json InputObject Type - rust

I'm trying to use Async Graphql, I want to use sqlx json type in model. In normal api operations the code is running. But when I want to use the async graphql InputObject macro, I get an error. The codes I used are as follows, I couldn't find a solution for the problem.
#[derive(Serialize, Deserialize, Debug, Clone, sqlx::Type)]
#[sqlx(transparent)]
pub struct Meta(Map<String, Value>);
scalar!(Meta);
#[derive(Debug, Serialize, Deserialize, Clone, FromRow, SimpleObject)]
pub struct User {
#[serde(skip_serializing)]
#[graphql(skip)]
pub id: Uuid,
pub name: String,
pub email: String,
#[serde(skip_serializing)]
#[graphql(skip)]
pub password: String,
#[serde(skip_serializing)]
#[graphql(skip)]
pub meta: Json<Meta>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
No problem so far. But the code below gives an error.
#[derive(Debug, Deserialize, Validate, InputObject)]
pub struct RegisterInput {
#[validate(length(min = 4, max = 10))]
pub name: String,
#[validate(email)]
pub email: String,
#[validate(length(min = 6))]
pub password: String,
pub meta: Json<Meta>,
}
InputObject error.
error[E0277]: the trait bound `sqlx::types::Json<Meta>: InputType` is not satisfied
--> src/dto.rs:13:40
|
13 | #[derive(Debug, Deserialize, Validate, InputObject)]
| ^^^^^^^^^^^ the trait `InputType` is not implemented for `sqlx::types::Json<Meta>`
|
= help: the following other types implement trait `InputType`:
Arc<T>
Arc<[T]>
Arc<str>
BTreeMap<K, V>
BTreeSet<T>
Box<T>
Box<[T]>
Box<str>
and 49 others
= note: this error originates in the derive macro `InputObject` (in Nightly builds, run with -Z macro-backtrace for more info)
Can you help on the subject?

Related

How to retrieve struct with nested structs with sqlx and Rust?

I'm trying to use Rust and sqlx (v0.6.2) to retrieve from DB structs with nested structs.
I tried using the below code but I found out that there is a limit of 9 fields in tuple that I can use with FromRow.
Note:
As you can see I'm using a Box<T> for struct fields.
use sqlx::{postgres::PgRow, FromRow, QueryBuilder, Row};
#[derive(Debug, Default, sqlx::FromRow)]
pub struct PgCoach { //PgCoach has ONLY scalar values
pub team_id: String,
pub id: String,
pub created_at: Time::OffsetDateTime,
pub updated_at: Option<Time::OffsetDateTime>,
pub firstname: Option<String>,
pub lastname: Option<String>,
pub motto: Option<String>,
pub first_case: Option<String>,
pub second_case: Option<String>,
pub third_case: Option<String>,
pub birth_date: Option<Time::OffsetDateTime>,
pub sex: Option<i64>,
pub phone: Option<String>,
pub email_address: Option<String>,
pub address: Option<String>,
pub picture: Option<String>,
pub notes: Option<String>,
}
#[derive(Debug, Default)]
pub struct PgPlayer {
pub team_id: String,
pub id: String,
pub created_at: Time::OffsetDateTime,
pub updated_at: Option<Time::OffsetDateTime>,
pub score: i64,
pub birth_date: Time::OffsetDateTime,
pub code: String,
pub payed: bool,
pub coach_id: String,
pub coach: Option<Box<PgCoach>>,
pub skills: Option<Vec<PgSkill>>,
}
impl FromRow<'_, PgRow> for PgPlayer {
fn from_row(row: &PgRow) -> sqlx::Result<Self> {
let mut res = Self {
team_id: row.get("team_id"),
id: row.get("id"),
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
score: row.get("score"),
birth_date: row.get("birth_date"),
code: row.get("code"),
payed: row.get("payed"),
coach_id: row.get("coach_id"),
..Default::default()
};
if row.try_get_raw("coach").is_ok() {
res.coach = Some(Box::new(PgCoach {
id: row.try_get::<PgCoach, &str>("coach")?.1,
firstname: row.try_get::<PgCoach, &str>("coach")?.4,
lastname: row.try_get::<PgCoach, &str>("coach")?.5,
..Default::default()
}));
}
Ok(res)
}
}
The error is:
error[E0277]: the trait bound `pg::PgCoach: sqlx::Decode<'_, sqlx::Postgres>` is not satisfied
--> src\crates\project\pg.rs:656:21
|
656 | id: row.try_get::<PgCoach, &str>("coach")?.id,
| ^^^ ------- required by a bound introduced by this call
| |
| the trait `sqlx::Decode<'_, sqlx::Postgres>` is not implemented for `pg::PgCoach`
|
= help: the following other types implement trait `sqlx::Decode<'r, DB>`:
<&'r [u8] as sqlx::Decode<'r, sqlx::Postgres>>
<&'r [u8] as sqlx::Decode<'r, sqlx_core::any::database::Any>>
<&'r sqlx::types::JsonRawValue as sqlx::Decode<'r, DB>>
<&'r str as sqlx::Decode<'r, sqlx::Postgres>>
<&'r str as sqlx::Decode<'r, sqlx_core::any::database::Any>>
<() as sqlx::Decode<'r, sqlx::Postgres>>
<(T1, T2) as sqlx::Decode<'r, sqlx::Postgres>>
<(T1, T2, T3) as sqlx::Decode<'r, sqlx::Postgres>>
and 43 others
note: required by a bound in `sqlx::Row::try_get`
--> C:\Users\Fred\.cargo\registry\src\github.com-1ecc6299db9ec823\sqlx-core-0.6.2\src\row.rs:114:12
|
114 | T: Decode<'r, Self::Database> + Type<Self::Database>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `sqlx::Row::try_get`
I can use whatever SQL query the method needs.
I can return tuple from DB or single columns, I don't care. I only need a way to query with sqlx structs with nested Box<Struct> and I cannot understand how.
How can I retrieve these structs?

How to serialize trait object with rocket::serde?

I've got the following code:
use std::fmt::Debug;
use rocket::serde::{Serialize};
#[serde(crate = "rocket::serde")]
pub trait ComponentDto: Debug + Send + Sync + Serialize {}
use rocket::serde::{Deserialize, Serialize};
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
pub struct ParagraphDto {
pub id: i32,
pub uuid: String,
pub user_id: i32,
pub project_id: i32,
pub position: i32,
pub component: Box<dyn ComponentDto>,
pub status: String,
pub created_at: String,
pub updated_at: String,
}
impl ParagraphDto {
How do I serialize trait object using rocket::serde?
Using rockett::serde as a normal struct to trait object results in the following error:
Compiling testa v0.1.0 (/mnt/repository/repository/projects/rust/testa)
error[E0038]: the trait `MyTrait` cannot be made into an object
--> src/main.rs:21:20
|
21 | fn getStruct() -> Box<dyn MyTrait> {
| ^^^^^^^^^^^^^^^^^ `MyTrait` cannot be made into an object
|
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits. html#object-safety>

Create entity with no relations

Using SeaOrm, I want to create a model that has no relations. Essentially, a DB with one table.
This seems like it should be super easy, but the documentation doesn't cover this and the DeriveEntityModel macro requires all the boilerplate for entity relations to be present.
What I want is:
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "device")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(column_name = "uuid")]
pub uuid: Uuid,
#[sea_orm(column_name = "location")]
pub location: Option<String>,
#[sea_orm(column_name = "lastHeard")]
pub lastHeard: Option<DateTime>
}
And the error I get is:
cannot find type `Relation` in this scope
help: you might have meant to use the associated type: `Self::Relation`rustc(E0412)
the trait bound `models::device::ActiveModel: sea_orm::ActiveModelBehavior` is not satisfied
the trait `sea_orm::ActiveModelBehavior` is not implemented for `models::device::ActiveModel`
I'm thinking there must be another macro to use, one that doesn't require relations, but I can't find it in the docs.
thanks for trying SeaORM. Try to define an empty Relation enum like below.
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "device")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(column_name = "uuid")]
pub uuid: Uuid,
#[sea_orm(column_name = "location")]
pub location: Option<String>,
#[sea_orm(column_name = "lastHeard")]
pub lastHeard: Option<DateTime>
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

Returning structure in Substrate RPC

We're trying to return structure in RPC, but as far as I understand it should be serializable:
error[E0277]: the trait bound `pallet_spaces::Space<T>: serde::de::Deserialize<'_>` is not satisfied
--> pallets/spaces/rpc/src/lib.rs:15:1
|
15 | #[rpc]
| ^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `pallet_spaces::Space<T>`
|
= note: required because of the requirements on the impl of `for<'de> serde::de::Deserialize<'de>` for `std::vec::Vec<pallet_spaces::Space<T>>`
= note: required because of the requirements on the impl of `serde::de::DeserializeOwned` for `std::vec::Vec<pallet_spaces::Space<T>>`
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
The problem is that we use T::Moment from pallet_timestamp and it's not serializable, so we stuck at this point:
error[E0277]: the trait bound `<T as pallet_timestamp::Trait>::Moment: _::_serde::Serialize` is not satisfied
--> pallets/spaces/src/lib.rs:25:5
|
25 | pub created: WhoAndWhen<T>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `_::_serde::Serialize` is not implemented for `<T as pallet_timestamp::Trait>::Moment`
|
= note: required because of the requirements on the impl of `_::_serde::Serialize` for `pallet_utils::WhoAndWhen<T>`
= note: required by `_::_serde::ser::SerializeStruct::serialize_field`
What can you suggest to easily return a structure like this?
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, Serialize, Deserialize)]
pub struct Space<T: Trait> {
pub id: SpaceId,
pub created: WhoAndWhen<T>,
pub updated: Option<WhoAndWhen<T>>,
pub owner: T::AccountId,
// Can be updated by the owner:
pub parent_id: Option<SpaceId>,
pub handle: Option<Vec<u8>>,
pub content: Content,
pub hidden: bool,
pub posts_count: u32,
pub hidden_posts_count: u32,
pub followers_count: u32,
pub score: i32,
/// Allows to override the default permissions for this space.
pub permissions: Option<SpacePermissions>,
}
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, Serialize, Deserialize)]
pub struct WhoAndWhen<T: Trait> {
pub account: T::AccountId,
pub block: T::BlockNumber,
pub time: T::Moment,
}
Your main problem is that you are mixing std and no-std here. Substrate only depends on serde in std mode, as you can learn about in literally any Cargo.toml file in the project.
Start by fixing this: You only derive serde::* when you are in std mode.
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)]
pub struct Space<T: Trait> {
// snip..
}

Using Option<T> with Diesel's Insertable trait

I have the following model:
use diesel::prelude::*;
use crate::schema::category;
#[derive(Debug, Identifiable, Queryable)]
#[table_name = "category"]
pub struct Category {
pub id: i64,
pub name: String,
pub description: String,
pub parent_id: Option<i64>,
}
#[derive(Debug, Insertable)]
#[table_name = "category"]
pub struct NewCategory<'a> {
pub name: &'a str,
pub description: &'a str,
pub parent_id: &'a Option<i64>,
}
and schema.rs:
table! {
category (id) {
id -> Integer,
name -> Text,
description -> Text,
parent_id -> Nullable<Integer>,
}
}
However, when I try to compile this code, I get the following errors:
error[E0277]: the trait bound `std::option::Option<i64>: diesel::Expression` is not satisfied
--> src/models/categories.rs:15:17
|
15 | #[derive(Debug, Insertable)]
| ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `std::option::Option<i64>`
|
= note: required because of the requirements on the impl of `diesel::Expression` for `&std::option::Option<i64>`
error[E0277]: the trait bound `std::option::Option<i64>: diesel::Expression` is not satisfied
--> src/models/categories.rs:15:17
|
15 | #[derive(Debug, Insertable)]
| ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `std::option::Option<i64>`
|
= note: required because of the requirements on the impl of `diesel::Expression` for `&'a std::option::Option<i64>`
What do I need to get this to work? I've looked around, but the only similar issue that I've found is when someone had more than 16 columns in their table, which is not the case here.
Modify pub parent_id: &'a Option<i64> to place the &'a inside of the Option: pub parent_id: Option<&'a i64>.

Resources