Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Jovons
    @Jovons

    nvm :see_no_evil: it was due to fields not being mapped properly. Had to add Option around the bool field.

    I made the same mistake yesterday

    Pearce Hayward
    @Nocturem

    Hi Everyone,

    am struggling my way through a small problem that is mostly to do with my unfamiliarity with diesel traits and dynamic dispatch,
    I have the below example table...

    table! {
        samples (id) {
            id -> Integer,
            name -> Text,
            content -> Text,
            version -> Integer,
            created -> Timestamp,
        }
    }

    and I am trying to design a dynamic filter object for it for a graphQL app to take as an input on filtering and returning sample records

    #[derive(juniper::GraphQLInputObject)]
    pub struct Filter{
        pub comparitor: Comparitor,
        pub column: Columns,
        pub value: String // probably will need to be better typed but its a placeholder for now,
    }

    I have a drafted up enum for a limited set of query types

    #[derive(juniper::GraphQLEnum)]
    pub enum Comparitor {
        Eq, // equal to
        Gt, // greater than
        Lt, // less than 
        Ge, // greater than equal to
        Le, // less than equal to
        Li, // like 
        Ne, // not equal to
        Ng, // not greater than
        Nl, // not less than 
        Nge, // not greater than equal to
        Nle, // not less than equal to
        Nl, // not like
    }

    and an enum of columns

    #[derive(juniper::GraphQLEnum)]
    enum Columns {
        id,
        name,
        content,
        version,
        created,
    }

    which is fine (maybe still have to get to its implementation) until I want to coerce from an input value to a table column with something a bit like the below

    impl Columns {
        fn as_table(self) { //type sig purposely left off since that's kind of the trouble
            match self {
                Columns::id => samlples::columns::id,
                Columns::name => samlples::columns::name,
                Columns::content => samlples::columns::content,
                Columns::version => samlples::columns::version,
                Columns::created => samlples::columns::created,
            }
        }
    }

    I don't honestly know enough about either the guts of diesel or rust's generics or dynamic dispatch so I am kinda blindly following the compilers screams on this and sadly the compiler was unable to be any more helpful in guessing what I actually am trying to do.
    Any help or hints would be greatly appreciated.

    2 replies
    Creator
    @Creator
    Hello,
    I recently switched to diesel 2.0.0 and am getting errors when using distinct_on with multiple values
    the trait diesel::sql_types::SingleValue is not implemented for (diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Integer)
    I checked all of the examples using distinct_on, and none of them use multiple values, how would I achieve that?
    Georg Semmler
    @weiznich
    @Creator First of all diesel 2.0.0 is not released yet. That means we do happily accept bug reports, but do not provide support for that version. That said this is likely the fallout of diesel-rs/diesel#2636 which fixes a more serve issue. That means it will likely not be supported anymore to have more than one value in your distinct on clause, at least if noone submits a fix for that.
    Creator
    @Creator
    @weiznich I understand
    Creator
    @Creator
    I know that the union & co clauses have not been released yet, but is it possible to perform a union on two tables with the same structure and then a join with a third table that links to both tables?
    Jovons
    @Jovons
    Hi, I followed getting-started and diesel-1.4.4\examples\mysql\getting_started_step_1, and I used Rust 2018,but it kept showing errors related with crate cannot be found. I uploaded the code (very basic) to https://github.com/Jovons/diesel_demo, could anyone please help :(
    Georg Semmler
    @weiznich
    @Jovons Your code is missing an #[macro_use] extern crate diesel;.
    @Creator Joins to unions are not implemented yet. Feel free to fill a feature request outlining a potential design.
    Jovons
    @Jovons
    I deleted #[macro_use]extern crate diesel, because I want to use Rust 2018.
    @Jovons Again: This is required and not optinal. Also this is not related to rust 2018 in any way as this compiles fine using the 2018 edition.
    Jovons
    @Jovons
    Yes, it compiles with 2018. I deleted it according to https://doc.rust-lang.org/edition-guide/rust-2018/macros/macro-changes.html
    Jovons
    @Jovons
    I added use diesel::table, and rustc expects another macro __diesel_parse_table, I guess by using #[macro_use]extern crate diesel it will bring all diesel macros into scope, that I don't have to add one by one. ;)
    Georg Semmler
    @weiznich
    That's exactly the point. Additionally those other macros are not part of our public api, so importing them can and will break in future versions.
    Jovons
    @Jovons
    Yea, I just verified it in code. learning Rust by learning Diesel. Thank you George!
    codedmart
    @codedmart:matrix.org
    [m]
    I am new to rust and diesel. I am trying to use Numeric with postgres. Seems to work fine for my migrations and schema.rs. I am seeing errors though "the trait Serialize is not implemented for diesel::sql_types::Numeric"
    I have tried BigDecimal as well and see the same errors.
    codedmart
    @codedmart:matrix.org
    [m]
    I think I am just struggling with numbers is general with diesel.
    So if I use INTEGER in postgres looks like schema.rs has Int4 so in my rust type I use i32? Is that right?
    Georg Semmler
    @weiznich
    @codedmart:matrix.org Types from diesel::sql_types are marker types that cannot hold any value. Each of them can be mapped to one or more rust types. The api documentation for those types contains a list of compatible rust types. Be sure to enable the features listed there and to use the same version of that dependency as diesel.
    codedmart
    @codedmart:matrix.org
    [m]
    @weiznich: So should I be using BigDecimal then in my rust types? I get serialize and deserialize errors for BigDecimal and i32.
    New to rust in general so trying to wrap my head around all this.
    Georg Semmler
    @weiznich
    @codedmart:matrix.org That really depends on your queries. Each query returns a set of fields with specific SQL types. Those can be mapped to matching rust types. If there is a compiler error that normally means that there is a type mismatch in that mapping.
    codedmart
    @codedmart:matrix.org
    [m]
    So do I need to have different types the api accepts to allow serialize/deserialize. Then a different type for insertable? I am trying to do something along the lines of: https://gist.github.com/codedmart/e211570b861d6e2e3ed7102a15a91585
    codedmart
    @codedmart:matrix.org
    [m]
    Basically I was my full type, a sub type that can be serializable/deserializable (without id, timestamps), then something insertable as well. Unless I am thinking about this all wong.
    eqt
    @equintessence_gitlab

    I'm trying to write a helper function to insert either a single struct or a vector of structs.
    Example: These two work.

    fn insert_food_products(connection: &PgConnection, insertable: &NewFoodProduct) -> QueryResult<usize> {
        diesel::insert_into(schema::food_products::table)
        .values(insertable)
        .execute(connection)
    }
    fn insert_food_products(connection: &PgConnection, insertable: &Vec<NewFoodProduct>) -> QueryResult<usize> {
        diesel::insert_into(schema::food_products::table)
        .values(insertable)
        .execute(connection)
    }

    But how could a more generic version look like? This does not work:

    fn insert_food_products<T: Insertable<schema::food_products::table>>(connection: &PgConnection, insertable: &T) -> QueryResult<usize> {
        diesel::insert_into(schema::food_products::table)
            .values(insertable)
            .execute(connection)
    }
    
    error[E0275]: overflow evaluating the requirement `&(_, _, _, _, _): diesel::Insertable<table>`
    Georg Semmler
    @weiznich
    @codedmart:matrix.org I cannot tell you if that code is fine or not, as this really depends on quite a few more things like how your database schema looks like, how your api endpoint looks and which queries your try to issue.
    @equintessence_gitlab That will require more trait bounds. The compiler should emit a required because of ... section that includes more information.
    codedmart
    @codedmart:matrix.org
    [m]
    @weiznich: OK thanks just fumbling through all this.
    Jack
    @Jackbaude
    Is there way to order a query? Say I want to grab all of the records in order by id or by some boolean that is true first?
    Kacper Urbaniec
    @kurbaniec
    Hi, I'm trying to create an Event in MySQL using Diesel's raw SQL function but it always results in a DataBaseError. Is there a way to fix it?
    pub fn create_post_event(conn: &MysqlConnection) {
        diesel::sql_query(
            r#"
            CREATE EVENT IF NOT EXISTS test_event_01
            ON SCHEDULE AT CURRENT_TIMESTAMP
            DO
              UPDATE posts
              SET title = 'TestRocket!!'
              WHERE id = '2';
        "#,
        )
        .execute(conn)
        .unwrap();
    }
    ... panicked at 'called `Result::unwrap()` on an `Err` value: DatabaseError(__Unknown, "This command is not supported in the prepared statement protocol yet")', src\db\posts.rs:25:6
    stack backtrace: ...
    Georg Semmler
    @weiznich
    Kacper Urbaniec
    @kurbaniec
    Works now as expected, Thanks!
    Christof Weickhardt
    @somehowchris
    Hey there. I just have spent about 8 hours of coding with rust so take what I say with a grain of salt. I love (and sometimes deeply hate) diesel and it structures but came across diesel::associations which seem ok. The thing is I have an entity which can have two relations of the same type, diesel seems to not support that as the compiler panics due to conflicting implemetations. Is there a way to have something like that?
    use diesel::prelude::*;
    use crate::database::schema::market_data;
    use crate::currency_pair::entity::CurrencyPairEntity;
    
    #[derive(Associations, Identifiable, Queryable, Debug, PartialEq)]
    #[serde(rename_all(serialize = "camelCase", deserialize = "snake_case"))]
    #[table_name = "market_data"]
    #[belongs_to(CurrencyPairEntity, foreign_key="currency_pair_id")]
    struct  MarketData {
        id: i32,
        created_at: chrono::NaiveDateTime,
        updated_at: chrono::NaiveDateTime,
        start_date: chrono::NaiveDateTime,
        high: f32,
        low: f32,
        close: f32,
        open: f32,
        interval: super::interval_enum::IntervalEnum,
        source: super::source_enum::SourceEnum,
        currency_pair_id: Option<u32>,
    }
      |
    5 | #[derive(Identifiable, Queryable, Associations, serde::Serialize, serde::Deserialize)]
      |                                   ^^^^^^^^^^^^
      |                                   |
      |                                   first implementation here
      |                                   conflicting implementation for `currency_pair::entity::CurrencyPairEntity`
      |
      = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
    2 replies
    Ryan Greenblatt
    @rgreenblatt

    Hi everyone. I am pretty new to DBs in general, so please forgive my ignorance.

    I have these types:

    #[derive(Identifiable, Queryable, PartialEq, Debug)]
    #[table_name = "users"]
    pub struct User {
      pub id: i32,
      pub login: String,
    }
    
    #[derive(Insertable, Debug)]
    #[table_name = "users"]
    pub struct NewUser<'a> {
      pub login: &'a str,
    }
    
    #[derive(Identifiable, Queryable, PartialEq, Debug)]
    #[table_name = "repos"]
    pub struct Repo {
      pub id: i32,
      pub owner: String,
      pub name: String,
    }
    
    #[derive(Insertable, Debug)]
    #[table_name = "repos"]
    pub struct NewRepo<'a> {
      pub owner: &'a str,
      pub name: &'a str,
    }
    
    #[derive(Identifiable, Queryable, Associations, PartialEq, Debug)]
    #[belongs_to(Repo)]
    #[belongs_to(User)]
    #[table_name = "contributions"]
    pub struct Contribution {
      pub id: i32,
      pub repo_id: i32,
      pub user_id: i32,
      pub num: i32,
    }

    and I would like to insert a list of events where each event consists of a repo and a user. This should (for each event):

    • add the repo to that table if it doesn't exist
    • add the user to that table if it doesn't exist
    • add a contribution entry to that table for the coresponding user and repo if it doesn't already exist
    • increment the corresponding contribution

    You can sort of think of this as the defaultdict pattern from python with num defaulting to zero and incrementing it for each event.

    I think I know roughly how I would do this as a bunch of operations, but is there a nice dieselly way to do this in a few queries?

    3 replies
    Ryan Greenblatt
    @rgreenblatt
    Related to my above question, is there a way to still get the corresponding rows when using on_conflict and do_nothing?
    1 reply
    James Sewell
    @jamessewell
    HI all
    Is there a way of creating (PostgreSQL) CREATE TABLE statements from table! macros - or is the workflow normally the other way round?
    1 reply
    codedmart
    @codedmart:matrix.org
    [m]
    Is there an example of using filter with rocket_contrib uuid? I tried .filter(clients::organization_id.eq(org_id.into_inner()))? This throws errors about trait diesel expression not implemented, NonAggregate not implemented.
    5 replies
    Plus a few other errors.
    codedmart
    @codedmart:matrix.org
    [m]
    I guess I am not sure how to go from rocket_contrib Uuid to diesel Uuid.
    sternj
    @sternj
    Hi all-- rocket question here. I have a database that I'm using to store logs, but I'm frequently getting "Database is locked" errors. Is there any way to wait until the database is available or batch writes? I am using Diesel with a sqlite3 database
    1 reply
    James Sewell
    @jamessewell
    Is there an autogen type I can use when I'm using get_results()?
    1 reply
    James Sewell
    @jamessewell
    Can I use rust-postgres from Diesel?
    2 replies
    I think I can?