Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    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?
    Edward Mann
    @mann-ed
    @jamessewell i'm using something like this
    diesel = { version = "1.4.6", features = ["postgres", "uuidv07", "chrono", "r2d2"]}
    diesel_full_text_search = { version = "1.0.1" }
    James Sewell
    @jamessewell
    That uses libpq I think?
    rust-postgres is a pure Rust PG implementation
    I think the answer is no
    Edward Mann
    @mann-ed
    yes libpq is what it uses
    Ten0
    @Ten0_gitlab
    Hello!
    I can't find the helper_type for exists (https://docs.diesel.rs/master/diesel/dsl/fn.exists.html) (diesel master). Is it there somewhere? If not, can I PR adding it?
    2 replies
    hacktor_
    @hktr92
    Hello. I have an old project on which I'm considering usage of Rust to improve performance. The MySQL table has a column named type, so I can't use it in struct since is a reserved keyword. So the column is called kind in Rust. Is there a way to let Diesel consider kind as type? I'm unable to find anything like it in documentation nor anything..
    Georg Semmler
    @weiznich
    @hktr92 In which context?
    hacktor_
    @hktr92

    @hktr92 In which context?

    this would be a rough context:
    mysql table: foo { id: uuid, type: int, ... }
    rust struct: struct Foo { id: uuid, kind: FooType } enum FooType { A, B }

    i only want to know if i can tell diesel to hydrate type value into kind (with From implemented on FooType)

    Georg Semmler
    @weiznich
    That does not really tell me in which context you are looking for this conversion. I mean the corresponding name can appear in more than one location, like the table! macro or some struct using a diesel derive. The answer to that question differs really on the exact use case.
    hacktor_
    @hktr92

    That does not really tell me in which context you are looking for this conversion. I mean the corresponding name can appear in more than one location, like the table! macro or some struct using a diesel derive. The answer to that question differs really on the exact use case.

    thanks for the tip, i found what i was looking for in table macro here: http://docs.diesel.rs/diesel/macro.table.html

    Georg Semmler
    @weiznich
    :+1:
    Sean Klein
    @smklein:matrix.org
    [m]
    Hey all! I was struggling to find this in the docs (although I'm happy to read more) - what's the situation for CTEs ("WITH" expressions) in Diesel?
    I found diesel-rs/diesel#762 from a while back, which implies the space has been explored, but wasn't sure about best practices nowadays
    Georg Semmler
    @weiznich
    @smklein:matrix.org That is something that is not supported in the built-in dsl yet. We are open to design suggestions here. Otherwise it is always possible to implement your own dsl extension to add support for sql constructs not supported by diesel itself.
    CarlyRaeJepsenStan
    @CarlyRaeJepsenStan
    Hey there, I just tried to connect to my PostgreSQL 13 database and got the authentication method 10 not recognized
    Has anyone been able to solve this on Mac?
    I looked for the libpq DLLs and haven't found anything that could indicate it could be updated
    Furthermore, my .conf files already have the authentication method set to md5...
    My code is exactly the same as the diesel.rs getting started guide.
    Georg Semmler
    @weiznich
    @CarlyRaeJepsenStan That's not related to your code, but to your postgres configuration. In fact you will run into the same issue using your database url and psql trying to connect to the database. Checkout postgres documentation about authentication methods for details on how to fix that. In general it's really hard for someone without access to your system to give concrete instructions on such configuration issues.
    Wagner
    @mwnDK1402
    Hello! Is it possible to delete from multiple tables in one query like this? If so, how?
    DELETE T1, T2
    FROM T1
    INNER JOIN T2 ON T1.key = T2.key
    WHERE condition;
    Georg Semmler
    @weiznich
    This is not supported by the built-in dsl.
    Wagner
    @mwnDK1402
    Alright, just gotta do that in multiple queries, then. Thanks.
    Wagner
    @mwnDK1402
    Here's my use case, by the way. If you have link tables, this is very useful. I don't know how I would do this in Diesel, so I'm just writing a prepared statement instead in raw SQL. I hope you consider adding this feature, if possible.
    DELETE exhibition, exhibition_ownership
    FROM exhibition
    INNER JOIN exhibition_ownership
    ON exhibition.id = exhibition_ownership.exhibition_id
    WHERE client_id = ?;
    It seems easier to write all my queries in raw SQL. Is that less performant than using the built-in DSL?
    Georg Semmler
    @weiznich
    Feel free to open a feature request to discuss the design and a followup PR adding the implementation. I'm not opposed in having this feature, it's just that this is something that I myself did not need yet so there is no real motivation for me to add this now, especially as there are other things I consider more important for my own projects.