by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Renato Hermoza Aragonés
    @renato145
    I want to retrieve something like users and last post
    Samuel Henry Kurniawan
    @ChrisMaxheart
    Hi all :)
    When using begin_test_transaction to do unit tests, somehow the rows id always increased (I use SERIAL PRIMARY KEY for id, and it seems after tests the ids is still remembered by the db; so for the next tests it still continue from previous integer; so it is always increasing over time).
    Any suggestion how to return back the id into 1? Thanks!
    3 replies
    matrixbot
    @matrixbot
    gondolyr Renato Hermoza Aragonés (Gitter) I believe the first code example in this link has most of what you are looking for: https://docs.diesel.rs/diesel/associations/index.html

    gondolyr rust let user = users.find(2).get_result::<User>(&connection)?; let users_post = Post::belonging_to(&user) .first(&connection)?; let expected = Post { id: 3, user_id: 2, title: "My first post too".into() };

    You'd have to adjust the sorting so that you get the newest post.

    Marko Mijalkovic
    @overdrivenpotato
    Does diesel support greatest-n-per-group queries? This stackoverflow post+answer documents the problem: https://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column/7745635
    2 replies
    kaminsod
    @kaminsod
    Hi, how can I specify schema name when using #table_name macro?
    If I use #[table_name="app.table"] it gives error: 'app.table' invalid identifier
    2 replies
    Elang89
    @Elang89
    Got a question. Does anybody have a way in which they handle many-to-many relationships? I know that diesel doesn't hide that from you and that you need to handle it manually through your code, but I'm not exactly sure how I should do it.
    Georg Semmler
    @weiznich
    I normally use a combination of associations API + joins, so something like JoinTable::belonging_to(&one_side_result).inner_join(other_side::table)
    7 replies
    Grégory Obanos
    @gobanos
    Hi All :) (sorry for previous message, gitter mobile interface is terrible...)
    I'm working on a UNION fragment, and more specifically in INSERT INTO ... SELECT ... UNION SELECT ... and managed to do so at the cost of exposing InsertFromSelect.
    I'd like to know if there a reason for it to not be public ? (for context, I'm already working with a fork of diesel)
    1 reply
    Aaron McLeod
    @agmcleod
    Hi there, is there a way for me to select column results from a join query, and map it to a struct that derives Queryable & Deserialize?
    1 reply
    Thomas Sieverding
    @Bajix

    I'm having a really hard time getting this to work:

    pub trait RelationLoader<Node, Params>: IntoIterator {
      fn load_grouped_data(&self, conn: &PooledConnection, params: Params) -> Result<Vec<Vec<Node>>>;
    }
    
    pub trait Taggable {
      fn variant() -> TaggingVariant;
    }
    
    impl<'a, Parent: Taggable> RelationLoader<TaggingWithTag, ()> for &'a Vec<Parent>
    where
      TaggingWithTag: BelongingToDsl<&'a Vec<Parent>>,
    {
      fn load_grouped_data(
        &self,
        conn: &PooledConnection,
        _: (),
      ) -> Result<Vec<Vec<TaggingWithTag>>> {
        use crate::schema::tags;
    
        let grouped_data = TaggingWithTag::belonging_to(self)
          .inner_join(tags::table)
          .filter(taggings::type_.eq(Parent::variant().to_string()))
          .select((taggings::id, taggings::taggableId, tags::all_columns))
          .load::<TaggingWithTag>(conn)?
          .grouped_by(self);
    
        Ok(grouped_data)
      }
    }

    I'm getting this error at the inner join:

    no method named `inner_join` found for associated type `<TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output` in the current scope
    the method `inner_join` exists but the following trait bounds were not satisfied:
    `<TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: Table`
    which is required by `<TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: diesel::QueryDsl`
    `&<TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: Table`
    which is required by `&<TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: diesel::QueryDsl`
    `&mut <TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: Table`
    which is required by `&mut <TaggingWithTag as diesel::BelongingToDsl<&'a Vec<Parent>>>::Output: diesel::QueryDsl`
    2 replies
    Grégory Obanos
    @gobanos

    Hi All :) (sorry for previous message, gitter mobile interface is terrible...)
    I'm working on a UNION fragment, and more specifically in INSERT INTO ... SELECT ... UNION SELECT ... and managed to do so at the cost of exposing InsertFromSelect.
    I'd like to know if there a reason for it to not be public ? (for context, I'm already working with a fork of diesel)

    I just saw diesel-rs/diesel#316, if there is still interest in UNION & co. support in diesel, I'd be glad to implement it !

    1 reply
    Mike Dula
    @MikeTheSapien

    Hey everyone, I'm really afraid of posting here since my background is really far from programming. I might be asking a stupid question as well, but I've been looking for ways to solve this problem of mine for naught.

    Could you guys point me to some link or article where I can get the rows inserted in a Postgresql database of the current date? I saw an example using

    use diesel::expression::dsl::now;
    let target = posts.filter(publish_at.lt(now));

    and those examples are from diesel.rs website. But I can't find examples where the current date is searched, instead of current time.

    I tried

    use diesel::expression::dsl::today;

    but it says: no today in expression::dslrustc(E0432)

    Georg Semmler
    @weiznich
    now represents the current timestamp, so time + date. today would represent the current date, but it was only added recently to diesel, therefore it is not contained in any released version yet.
    Mike Dula
    @MikeTheSapien
    @weiznich thanks for your response! So that’s why it doesn’t. I was so confused where I was wrong. I found no articles or examples about it and assumed that it might be so simple that no one bothered to make an example of it.
    Georg Semmler
    @weiznich
    No it was only added recently with diesel-rs/diesel#2502.
    Mike Dula
    @MikeTheSapien
    @weiznich What a coincidence! So you think I should just wait for a week? A month? Or maybe I should just update my version of Diesel now?
    Georg Semmler
    @weiznich
    It's only merged into the main repository yet, so no release does contain this feature yet. We do not give any ETA for future release, so noone can tell you when it's finally released.
    That written, it should be as easy as copy the implementation to your crate for actually using it now.
    Mike Dula
    @MikeTheSapien

    @weiznich I see in the Github site that you're the one who made the feature possible? Reading an open-source work similar to yours is really perplexing for me. But I do want to contribute to the open source community, it's just that I have no idea where to start.

    Perhaps I may assist you with some code testing or something tedious? In that way I can help you with your contribution, and I would also learn how to contribute. I tried reading issues, the pull requests, and other features in Gitlab or Github to assess a repository's state, but it always confuses me.

    My main background is accounting by the way. Not my choice.

    3 replies
    matrixbot
    @matrixbot

    tml So, I've just replaced all mentions of SqliteConnection in my program with a generic Connection, now I'm getting errors like:

    the trait `diesel::backend::SupportsDefaultKeyword` is not implemented for `<C as diesel::Connection>::Backend`
    the trait `diesel::sql_types::HasSqlType<diesel::sql_types::Bool>` is not implemented for `<C as diesel::Connection>::Backend`

    Which I understand is mitigable with simply specifying that C: Connection + SupportsDefaultKeyword + HasSqlType<Bool>, but then there's errors like:

    the trait `diesel::serialize::ToSql<diesel::sql_types::Timestamp, <C as diesel::Connection>::Backend>` is not implemented for `chrono::naive::datetime::NaiveDateTime`

    And I'm not entirely sure how to mitigate this. Are there any general hints how to write somewhat database-agnostic programs with diesel?

    matrixbot
    @matrixbot
    tml Or a different question rather - (how) can I write a function that takes either a SqliteConnection or a r2d2's PooledConnection<Manager<SqliteConnection>>?
    matrixbot
    @matrixbot
    tml Ah, Connection<Backend = Sqlite>, nevermind :)
    Mike Dula
    @MikeTheSapien_gitlab

    @weiznich

    Curiosity with your contribution

    not a diesel problem

    Hey there, I was just reading a bit of past messages in this gitter group chat. It seems you answer a lot of queries here, and thanks for that, may I know why? What do you think motivates you to respond to inquiries here?

    Austin Hicks
    @camlorn
    So we're adopting Diesel at work and I've encountered a problem/question. I've also left a comment on #852, but it would be nice to get a faster answer so that I know what the near-term implication is. We don't support automatically mapping sqlite INTEGER to i64 for schema inference, and the issue says that's because making the inference special case isn't ideal, but what happens if you use INTEGER AUTOINCREMENT and sqlite generates a value over the maximum value of i32? it seems to me that you can hit that case in a resaonable enough time frame that you'd run into it up front, and I really don't want to have to manually maintain the schema in 3 places.
    Plus implementing your own autoincrement and using BIGINT isn't really possible.
    Austin Hicks
    @camlorn
    Ok, looks like you can do this with --import-types and a module whose only purpose is to have type Integer = diesel::sql_types::BigInt.
    Thomas Sieverding
    @Bajix
    Ugghhh this feels impossible. All I want to do is to implement a trait for all Vec<Parent> that Child: BelongsTo<Parent>
    2 replies
    
    impl<'a, Parent> RelationLoader<TaggingWithTag, ()> for &'a Vec<Parent>
    where
      &'a Parent: HasTable + diesel::Identifiable,
      TaggingWithTag: BelongsTo<Parent>,
      <&'a Parent as diesel::Identifiable>::Id: AsExpression<<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn as Expression>::SqlType>,
      <TaggingWithTag as HasTable>::Table: FilterDsl<Eq<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn, <&'a Parent as diesel::Identifiable>::Id>>,
      <TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn: ExpressionMethods,
    {
      fn load_grouped_data(&self, conn: &PooledConnection, _: ()) -> Result<Vec<Vec<TaggingWithTag>>> {
        use crate::schema::tags;
    
        let grouped_data = <TaggingWithTag as BelongingToDsl<& Vec<Parent>>>::belonging_to(self)
          .inner_join(tags::table)
          .select((taggings::id, taggings::taggableId, tags::all_columns))
          .load::<TaggingWithTag>(conn)?
          .grouped_by(self);
    
    
        Ok(grouped_data)
      }
    }
    the trait bound `diesel::query_builder::SelectStatement<taggings::table, query_builder::select_clause::DefaultSelectClause, query_builder::distinct_clause::NoDistinctClause, query_builder::where_clause::WhereClause<In<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn, Many<<<&Parent as diesel::Identifiable>::Id as AsExpression<<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn as diesel::Expression>::SqlType>>::Expression>>>>: InternalJoinDsl<_, Inner, _>` is not satisfied
    the following implementations were found:
      <diesel::query_builder::SelectStatement<F, S, D, W, O, L, Of, G, LC> as InternalJoinDsl<Rhs, Kind, On>>
    required because of the requirements on the impl of `JoinWithImplicitOnClause<_, Inner>` for `diesel::query_builder::SelectStatement<taggings::table, query_builder::select_clause::DefaultSelectClause, query_builder::distinct_clause::NoDistinctClause, query_builder::where_clause::WhereClause<In<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn, Many<<<&Parent as diesel::Identifiable>::Id as AsExpression<<<TaggingWithTag as BelongsTo<Parent>>::ForeignKeyColumn as diesel::Expression>::SqlType>>::Expression>>>>`
    Darwin
    @darwin67

    hello! it would be great if I could get some direction for the following syntax since it seems like it's not working as expected?

            let mut sql = <some table>.into_box();
            ...some if statements...
                 sql = sql.filter(name.eq(<some value>));
            ...
    
            for field in fields.into_iter() {
                let statement = match field {
                    "name" => Some(sql.select(name)),
                    "status" => Some(sql.select(status)),
                    _ => None,
                };
    
                if let Some(stat) = statement {
                    sql = stat;
                }
            }
    90 |                 sql = stat;
       |                       ^^^^ expected tuple, found struct `diesel::sql_types::Text`
       |
       = note: expected struct `diesel::query_builder::BoxedSelectStatement<'_, (diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::Jsonb, diesel::sql_types::Jsonb, diesel::sql_types::Integer, diesel::sql_types::Text, diesel::sql_types::Text, diesel::sql_types::SmallInt, diesel::sql_types::Text, diesel::sql_types::Jsonb, diesel::sql_types::Timestamp, diesel::sql_types::Timestamp, diesel::sql_types::Nullable<diesel::sql_types::Timestamp>, diesel::sql_types::Jsonb), _, _>`
                  found struct `diesel::query_builder::BoxedSelectStatement<'_, diesel::sql_types::Text, _, _>`

    any idea why this is causing an error even though select should be able to work?

    5 replies
    dr4ds
    @dr4ds
    Hi, im trying to install diesel_cli with "cargo install diesel_cli --no-default-features --features postgres" and im getting : LINK : fatal error LNK1181: cannot open input file 'libpq.lib' but im definitely sure that libpq.lib is in my path variable. I have psql 12 and win 10
    1 reply
    0x6273
    @0x6273

    Hi. I tried following this guide: https://diesel.rs/guides/composing-applications/
    But it seems outdated, because I got a deprecation warning when I used sql_function! like it suggests. When I changed it to how it's like in the examples in the doc comment, I get this error:

    error[E0277]: the trait bound `str: diesel::Expression` is not satisfied
      --> src/models/user.rs:17:37
       |
    17 |     pub fn with_name(name: &str) -> WithName {
       |                                     ^^^^^^^^ the trait `diesel::Expression` is not implemented for `str`
       |
       = note: required because of the requirements on the impl of `diesel::Expression` for `&str`
       = note: required because of the requirements on the impl of `diesel::Expression` for `models::user::user_name::user_name<&str>`
       = note: required because of the requirements on the impl of `AsExpression<diesel::sql_types::Text>` for `models::user::user_name::user_name<&str>`
    
    error: aborting due to previous error

    This is my code:

    use uuid::Uuid;
    use crate::db::schema::users;
    
    use diesel::dsl::Eq;
    use diesel::sql_types::Text;
    sql_function!(fn user_name(x: Text) -> Text);
    type WithName<'a> = Eq<user_name::user_name<users::name>, user_name::user_name<&'a str>>;
    
    #[derive(Debug, Queryable, Identifiable)]
    pub struct User {
        pub id: i32,
        pub uuid: Uuid,
        pub name: String,
    }
    
    impl User {
        pub fn with_name(name: &str) -> WithName {
            user_name(users::name).eq(user_name(name))
        }
    }
    1 reply
    0x6273
    @0x6273
    (The code does work if I use the old sql_function! syntax and remove the duplicate user_name:: from the type alias, but I would like to get rid of the deprecation warning if possible)
    matrixbot
    @matrixbot

    huguesm Hello,
    I'm trying to use diesel postgresql backend with a pgbouncer that is configured in transaction pooling mode, sadly in this mode pgbouncer don't support PREPARE statements which diesel uses heavily.

    I didn't find any way to disable PREPARE statements globally but QueryFragment trait has a method is_safe_to_cache_prepared which could do the trick.

    How hard do you think it would be to create a partial implementation on top of postgresql backend that would only override is_safe_to_cache_prepared to always returns false?

    1 reply
    Nia Calia-Bogan
    @Alfriadox
    Is this the right place to ask about dependency issues between diesel and Uuid?
    2 replies
    I keep getting this error
    error[E0277]: the trait bound `uuid::Uuid: diesel::Expression` is not satisfied
      --> src/models/users.rs:15:10
       |
    15 | #[derive(Insertable, Queryable, Debug, Clone, Serialize, Deserialize)]
       |          ^^^^^^^^^^ the trait `diesel::Expression` is not implemented for `uuid::Uuid`
       |
       = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Uuid>` for `uuid::Uuid`
       = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
    The relavent part of my cargo looks like this:
    
    # ORM and query building (to interact with Postgres Database)
    [dependencies.diesel]
    version = "1.4.5"
    default-features = false
    features = ["uuidv07", "r2d2", "postgres", "chrono"]
    
    # GraphQL queries and API system.
    [dependencies.juniper]
    version = "0.14.2"
    default-features = false
    features = ["uuid"]
    
    # Universally unique identifier generation
    [dependencies.uuid]
    version = "0.7.4" # hold back from 0.8 because juniper doesn't support it yet
    default-features = false
    features = ["serde", "v4"]
    I am on the newest stable version of the rust compiler
    Nia Calia-Bogan
    @Alfriadox
    let me know what im doing wrong here -- im very lost.
    Nia Calia-Bogan
    @Alfriadox
    my current workaround involves manually editing the lockfile to remove uuid 0.8.1 (which diesel pulls from somewhere)
    Kayle Gishen
    @kayleg
    @Alfriadox I had a similar issue, switched to master diesel and just used the "uuid" feature flag and everything worked with latest uuid crate
    1 reply
    Matthew Dowdell
    @mattdowdell
    Hey, I was wondering if anyone knew of an implementation for Postgres SIMILAR TO (https://www.postgresql.org/docs/9.3/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP). I saw there was support for ILIKE, but searching "diesel postgres similar to" is throwing loads of false positives back"
    Georg Semmler
    @weiznich
    @mattdowdell It's not supported out of the box by diesels dsl, but it should be quite straight forward to add support for this on your own using diesel_infix_operator!.
    Matthew Dowdell
    @mattdowdell
    Thanks, I was wondering if there was a good way to implement it.
    One other thing: how does diesel handle escaping values? I assume I don't need to deal with SQL injection, but I guess I do want to escape chars that have extra effects in SIMILAR TO if I'm taking user provided values?
    Georg Semmler
    @weiznich
    @mattdowdell Diesel uses prepared statements for all user provided arguments, so there is no way to generate a sql injection that way. For escaping special tokens passed to SIMILAR TO have a look how this is handled for LIKE (and similar functions): https://docs.diesel.rs/1.4.x/diesel/expression_methods/trait.EscapeExpressionMethods.html#method.escape
    Matthew Dowdell
    @mattdowdell
    Thanks again!
    John Halbert
    @johnhalbert
    Hi all - for columns that are marked not null, if I pass an option to set on an update query, does diesel know to ignore this?
    I've got a query where sometimes we get a value and sometimes we don't, and I'm not finding a great way to conditionally update some of the columns.