Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Georg Semmler
    @weiznich
    You will probably want to mount a persistent volume somewhere to prevent that :wink:
    Peter Kolloch
    @kolloch
    Heyo, I try to use diesel(embed) with "Queryable". Is that unsupported?
    #[derive(juniper::GraphQLObject, QueryableByName, Queryable, Insertable, Debug, Clone, PartialEq)]
    #[table_name = "election_votes"]
    pub struct ElectionVoteId {
        pub choice_id: ElectionChoiceId,
        pub user_id: UserId,
    }
    
    #[derive(juniper::GraphQLObject, Identifiable, Queryable, Insertable, Debug, Clone, PartialEq)]
    #[table_name = "election_votes"]
    pub struct ElectionVote {
        #[diesel(embed)]
        pub id: ElectionVoteId,
        pub vote: i32,
    }
    
    #[derive(juniper::GraphQLScalarValue, DieselNewType, Debug, PartialEq, Hash, Eq, Copy, Clone)]
    #[graphql(transparent)]
    pub struct ElectionChoiceId(pub i32);
    
    #[derive(juniper::GraphQLScalarValue, DieselNewType, Debug, PartialEq, Hash, Eq, Copy, Clone)]
    #[graphql(transparent)]
    pub struct UserId(pub i32);
    Relevant schema excerpt:
    table! {
        election_votes (choice_id, user_id) {
            choice_id -> Int4,
            user_id -> Int4,
            vote -> Int4,
        }
    }
    error[E0277]: the trait bound `(model::ElectionVoteId, i32): diesel::Queryable<(diesel::sql_types::Integer, diesel::sql_types::Integer, diesel::sql_types::Integer), _>` is not satisfied
      |
      = help: the following implementations were found:
                <(A, B) as diesel::Queryable<(SA, SB), __DB>>
                <(A, B) as diesel::Queryable<diesel::sql_types::Record<(SA, SB)>, diesel::pg::Pg>>
                <(std::collections::Bound<T>, std::collections::Bound<T>) as diesel::Queryable<diesel::sql_types::Range<ST>, diesel::pg::Pg>>
      = note: required because of the requirements on the impl of `diesel::Queryable<(diesel::sql_types::Integer, diesel::sql_types::Integer, diesel::sql_types::Integer), _>` for `model::ElectionVote`
      = note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<_, model::ElectionVote>` for `diesel::query_builder::BoxedSelectStatement<'_, (diesel::sql_types::Integer, diesel::sql_types::Integer, diesel::sql_types::Integer), schema::election_votes::table, _>`
    Georg Semmler
    @weiznich
    No it's not supported.
    Peter Kolloch
    @kolloch
    Thank you @weiznich, so the best alternative is to implement that (model::ElectionVoteId, i32) bound?
    Georg Semmler
    @weiznich
    That won't help that much. The main question here is how would a query look like that returns exactly those information?
    Wait stop, that questions is slightly different to a similar question yesterday :see_no_evil:
    Yes you can fix that by just implementing Into<ElectionVoteId> for i32 and use #[diesel(deserialize_as = "i32)] there.
    Georg Semmler
    @weiznich
    Beside of that as you are doing juniper/graphql stuff on top of diesel you may be interested in wundergraph which simplifies a lot of things there in my opinion (obviously I'm biased here :wink:)
    Günter Zöchbauer
    @zoechi
    Is there a disadvantage for adding #[belongs_to(...)] or is it fine to add it for every foreign keys?
    similar question about joinable
    Peter Kolloch
    @kolloch

    @weiznich

    Yes you can fix that by just implementing Into<ElectionVoteId> for i32 and use #[diesel(deserialize_as = "i32)] there.

    That is not possible, I think, since it is a composite key (containing two IDs). Thanks for your suggestions anyway.

    Günter Zöchbauer
    @zoechi

    Ok, I found about joinable

    If you are using infer_schema! or diesel print-schema, an invocation of this macro will be generated for every foreign key in your database unless one of the following is true:

    but still unsure about belongs_to

    Georg Semmler
    @weiznich
    @kolloch In that case you probably need to specify the select clause explicitly. If you group together fields via a tuple they are mapped to a struct. If on of the fields is a tuple on it's own it requires that the type of the corresponding struct field is a struct implementing insertable on it's own. That means .select((some_column, some_other_colum), something)) requires a structure like following (assuming the concrete types match)
    #[derive(Queryable)]
    struct Outer {
        inner: Inner,
        foo: i32
    }
    
    #[derive(Queryable)]
    struct Inner {
       bar: i32,
       baz: i32
    }
    @zoechi Both of the will generate code behind your back, so they will have an impact of compile times. Otherwise you should be ok with just having them for all cases (beside of having multiple joinable!/#[belongs_to] between the same tables)
    Günter Zöchbauer
    @zoechi

    @weiznich thanks, good to know

    (beside of having multiple joinable!/#[belongs_to] between the same tables)

    Do you mean the cases that cause compiler errors anyway or are there cases besided that?

    Georg Semmler
    @weiznich
    Yes this cases cause compiler errors. Otherwise I'm not aware of anything that could cause an error there.
    Peter Kolloch
    @kolloch
    @kolloch In that case you probably need to specify the select clause explicitly. If you group together fields via a tuple they are mapped to a struct. If on of the fields is a tuple on it's own it requires that the type of the corresponding struct field is a struct implementing insertable on it's own. That means .select((some_column, some_other_colum), something)) requires a structure like following (assuming the concrete types match)
    That's awesome! Thank you.
    Günter Zöchbauer
    @zoechi
    @weiznich great, very helpful
    Günter Zöchbauer
    @zoechi
    Is there an example somewhere how to map an Integer (DB) to a Rust enum for Insertable and Queryable?
    Georg Semmler
    @weiznich
    There is on example specifically for integers, but we have this test case. It should be straight forward to adjust that to work with an Integer instead of a custom sql type (Basically just replace the custom sql type with Integer and implement the corresponding mapping)
    Günter Zöchbauer
    @zoechi
    I found that, but that was for a specific backend
    https://github.com/diesel-rs/diesel/blob/c1061007e8d268006f61768f2256dd281d9850a3/diesel/src/deserialize.rs#L324-L348 helped me to fix the remaining errors
    Georg Semmler
    @weiznich
    Yes code that is generic over more than one backend requires those bounds.
    Peter Kolloch
    @kolloch

    I have this query that I want to generalize with a placeholder instead of Array[1]:

    SELECT choice_id, coalesce(sum(vote), 0) as votes_sum 
                                      FROM election_votes 
                                      WHERE choice_id = ANY(Array[1])
                                      GROUP BY choice_id

    The query as written works in psql.

    Now I try to execute that with sql_query:

                    sql_query("SELECT choice_id, coalesce(sum(vote), 0) as votes_sum 
                                      FROM election_votes 
                                      WHERE choice_id = ANY( ? )
                                      GROUP BY choice_id")
                    .bind::<Array<Integer>,_>(&ids)
                    .get_results::<ElectionVoteSummary>(connection)
                    .context(WhileLoadingVoteSummaries { ids })

    and I get this error in Postgres

    23:53:38 postgres.1  | 2020-03-26 23:53:38.717 CET [127702] ERROR:  syntax error at or near ")" at character 170
    23:53:38 postgres.1  | 2020-03-26 23:53:38.717 CET [127702] STATEMENT:  SELECT choice_id, coalesce(sum(vote), 0) as votes_sum 
    23:53:38 postgres.1  |                                       FROM election_votes 
    23:53:38 postgres.1  |                                       WHERE choice_id = ANY( ? )
    23:53:38 postgres.1  |                                       GROUP BY choice_id
    Can I somehow see how the ? gets replaced? Or does it at all?
    Peter Kolloch
    @kolloch
    Oh. Found the error. For Postgres I have to use $1 as placeholder.
    IndrajitSinh Rayjada
    @indrajitsinh

    Kind of newbie question, I am getting following error while trying to check record is exist or not

    Following is the code

     let material_exist  = select(exists(materials.filter(id.eq(material_id)).filter(company_id.eq(company_uuid)))).get_result(&conn)?;
    
        match material_exist {
            Ok(isExist) => {
                if isExist {
                    Ok(isExist)
                } else {
                    Err(ApiError::NotFound("Material not found".to_string()))
                }
            },
            _ => Err(ApiError::NotFound("Material not found".to_string()))
        }

    Following is the error

    
    error[E0277]: the trait bound `std::result::Result<bool, _>: diesel::Queryable<diesel::sql_types::Bool, diesel::pg::Pg>` is not satisfied
    
       |
    67 |     let material_exist  = select(exists(materials.filter(id.eq(material_id)).filter(company_id.eq(company_uuid)))).get_result(&conn)?;
       |                                                                                                                    ^^^^^^^^^^ the trait `diesel::Queryable<diesel::sql_types::Bool, diesel::pg::Pg>` is not implemented for `std::result::Result<bool, _>`

    Any help appreciated Thanks. 😊

    Georg Semmler
    @weiznich
    @indrajitsinh get_result returns Result<U, diesel::result::Error> where U is some type that implements Queryable<SqlTypeOfTheQuery>. In your case the query returns a single boolean value. That means U needs to be some type that implements Queryable<diesel::sql_types::Bool>, which is not the case for Result<bool, _>, only for bool, structs with a single boolean field that derive Queryable and types that manually implement the right Queryable<Bool> variant.
    If you are trying to handle the case of a not existing row there you may want to look into this trait: http://docs.diesel.rs/diesel/result/trait.OptionalExtension.html#tymethod.optional
    Filippos Vasilakis
    @vasilakisfil
    is there a way to get the name of the table from a table module (like schema::users) ? I would like to get that in a string format to feed it in an sql_query that I run, in order to increase the "safety" of that sql query
    Georg Semmler
    @weiznich
    Not with the public api
    Filippos Vasilakis
    @vasilakisfil
    ok I see
    Georg Semmler
    @weiznich
    You can probably missuse diesel::debug_query for this, but I wouldn't advice that.
    Out of curiosity: What is preventing you from writing this query using the dsl?
    Filippos Vasilakis
    @vasilakisfil
    I need jsonb_set :/
    I guess I could retrieve existing record, get the jsonb column data, update the attribute I want and then update the whole column
    Georg Semmler
    @weiznich
    Is there any reason why you don't use sql_function! to just define that function?
    Filippos Vasilakis
    @vasilakisfil
    can this be used outside the select statements? Like for updating through diesel's set dsl ?
    Georg Semmler
    @weiznich
    Yes, sure
    .set() just expects a expression with the right sql type
    Filippos Vasilakis
    @vasilakisfil
    the jsonb_set is defined as jsonb_set(target jsonb, path text[], new_value jsonb [, create_missing boolean]) so I have created sql_function!(jsonb_set, JsonbSet, (x: Jsonb, y: Array<Text>, z: Jsonb) -> Jsonb);
    Georg Semmler
    @weiznich
    Which diesel version do you use?
    Filippos Vasilakis
    @vasilakisfil
    now the problem is that, in order to update a specific attribute in a jsonb column, in postgres you would run UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');. My problem is the data inside the jsonb_set, how do I denote that in diesel set ?
    I am running 1.4.3, I guess I should update to 1.4.4
    ah never mind, the impossible works, I thought it wouldn't
                    .set(
                        remote_starts::meta.eq(crate::entities::jsonb_set(
                            remote_starts::meta,
                            vec![String::from("error_info")],
                            serde_json::Value::String(String::from("hello")),
                        ),
    Georg Semmler
    @weiznich
    It does not matter which 1.4x. version, but that it's 1.4.x, because that version does support the new sql_function! syntax. That would allow you to write just
    sql_function!{
        fn json_set(target: Jsonb, path: Array<Text>, new_value: Jsonb) -> Jsonb
    }
    Yes, just using the column type there is fine, as it's a thing that implements AsExpression<SqlType = Jsonb>. (To word it otherwise: You could use whatever complex expression you want there, as long as this is true)
    Filippos Vasilakis
    @vasilakisfil
    this is simply amazing I ll try to blog post about it
    Georg Semmler
    @weiznich
    Sometimes I've the feeling it's a bit to much magic, because it's hard to understand in the first place :see_no_evil:
    Filippos Vasilakis
    @vasilakisfil
    I don't think it's too much magic once you understand how sql_function! works