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
    Again: Please include the necessary information in your question, not in some image. I cannot see an error message in your question.
    Wagner
    @mwnDK1402
    the trait bound `query_builder::sql_query::UncheckedBind<SqlQuery, u32, diesel::sql_types::Unsigned<diesel::sql_types::Integer>>: LoadQuery<_, Exhibitions>` is not satisfied
    the following implementations were found:
      <query_builder::sql_query::UncheckedBind<Query, Value, ST> as LoadQuery<Conn, T>>
    Georg Semmler
    @weiznich
    That says that there is some type missmatch somewhere in your query. I cannot tell you where as I don't know your code.
    Wagner
    @mwnDK1402
    #[derive(QueryableByName)]
    struct Exhibitions {
        #[sql_type = "String"]
        exhibitions: String,
    }
    
    #[post("/sqlconnect/readExhibitions.php", data = "<form>")]
    pub fn get_handler(
        form: Form<GetHandlerForm>,
        conn: Database,
    ) -> Result<JsonValue, Custom<String>> {
        Ok(
            match sql_query(include_str!("select_exhibitions.sql"))
                .bind::<Unsigned<Integer>, _>(form.cid)
                .load::<Exhibitions>(&*conn)
                .map_err(|e| Custom(Status::InternalServerError, e.to_string()))?
                .pop()
                .map(|w| w.exhibitions)
            {
                Some(json) => serde_json::to_value(json)
                    .map_err(|e| {
                        Custom(
                            Status::InternalServerError,
                            format!("Failed to serialize Exhibitions: {}", e.to_string()),
                        )
                    })?
                    .into(),
                None => json!({
                    "exhibitions": []
                }),
            },
        )
    }
    It's at the call to load. Since Exhibitions derives from QueryableByName, I thought I could load it from the query, but something is wrong.
    Also, the exhibitions member of the struct refers to the exhibitions column in the table returned by my custom query. And that's a big JSON_OBJECT.
    Georg Semmler
    @weiznich
    #[sql_type="…"] expects a sql type not a rust type. Normally that should be a type from diesel::sql_types or a custom defined sql type.
    Wagner
    @mwnDK1402
    #[sql_type = "sql_types::Longtext"]
    exhibitions: String,
    Thank you so much!
    joonnna
    @joonnna

    Is it possible to conditionally perform update on conflicts with multiple values? (I'm using postrgres)

    Something like this:

    #[derive(Insertable)]
    struct InsertPost {
        id: i64,
        date: NaiveDate,
    }
    
    let insert_vec = vec![Test{id: 1, date: "2014.05.05"}, Test{id: 2, date: "2013.03.05"}];
    
    diesel::insert_into(tests)
      .values(&insert_vec)
      .on_conflict(id)
      .do_update()
      .filter(date.ge(excluded(date)))
      .set(date.eq(excluded(date)));

    I want to insert multiple values and only update the rows that meet a certain criteria, is there any way to acheive this?
    The example above does not compile as the type IncompleteDoUpdate type does not contain a filter method.

    Georg Semmler
    @weiznich
    @joonnna That's not possible as far as I'm aware of.
    joonnna
    @joonnna
    Thanks for the clarification!
    Diógenes Falcão
    @diogenes

    Hello folks,

    I'm trying to do a simple sum in a Postgres BIGINT (NOT NULL) column:

    orders.select(sum(units))
                    .filter(user_id.eq(&p_user_id))
                    .first(&connection).unwrap()

    (Where orders is the table, units is the BIGINT column and user_id is just a filter.)

    When I try to assign it to an i64 variable it throws:

    60 |             .first(&connection).unwrap();
       |              ^^^^^ the trait `diesel::deserialize::FromSql<diesel::sql_types::Nullable<diesel::sql_types::Numeric>, diesel::pg::Pg>` is not implemented for `i64`
       |
       = help: the following implementations were found:
                 <i64 as diesel::deserialize::FromSql<diesel::sql_types::BigInt, DB>>

    When I try to assign to a BigInt variable it throws:

    .first(&connection).unwrap();
       |              ^^^^^ the trait `diesel::Queryable<diesel::sql_types::Nullable<diesel::sql_types::Numeric>, diesel::pg::Pg>` is not implemented for `diesel::sql_types::BigInt`
       |
       = note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<diesel::PgConnection, diesel::sql_types::BigInt>`

    Similar errors happen when I try to wrap the type using an Option (Option<i64> or Option<BigInt> var).

    Could you please help me to identify what's wrong here?

    Georg Semmler
    @weiznich
    A sum over a column of the type BigInt returns a Numeric that can by null. Therefore you need to use a compatible rust type like BigDecimal.
    Diógenes Falcão
    @diogenes
    Hum, ok. I will give it a try. Thanks for that!
    Jack
    @Jackbaude

    Hi, I have a question about many to many realtions. I have the follwing tables

    CREATE TABLE articles
    (
        id          SERIAL       NOT NULL UNIQUE PRIMARY KEY,
        urn_title   VARCHAR(50)  NOT NULL UNIQUE,
        title       VARCHAR(50)  NOT NULL UNIQUE,
        tags        TEXT[]       NOT NULL,
        description VARCHAR(200) NOT NULL,
        authors     TEXT[]        NOT NULL,
        edit_count  INTEGER      NOT NULL DEFAULT 0,
        last_edited TIMESTAMP             DEFAULT current_timestamp NOT NULL,
        status      BOOLEAN      NOT NULL DEFAULT true,
        publicized  BOOLEAN      NOT NULL DEFAULT false,
        featured    BOOLEAN      NOT NULL DEFAULT false
    );
    
    CREATE TABLE users
    (
        id            TEXT    NOT NULL PRIMARY KEY,
        username      TEXT    NOT NULL,
        discriminator TEXT    NOT NULL,
        avatar        TEXT    NOT NULL,
        rank          INTEGER NOT NULL DEFAULT 1,
        contributed_articles      INT[]
    );
    
    CREATE TABLE user_articles
    (
        author_id  TEXT REFERENCES users,
        article_id INT REFERENCES articles,
        PRIMARY KEY (article_id, author_id)
    );

    The following code returns an empty array

    #[derive(Queryable, Associations, Identifiable)]
    #[belongs_to(ArticleModel, foreign_key = "article_id")]
    #[belongs_to(UserModel, foreign_key = "author_id")]
    #[primary_key(article_id, author_id)]
    pub struct UserArticle {
        author_id: String,
        article_id: i32,
    }
    
    impl UserArticle {
        pub fn find_user_articles(user: &UserModel, conn: &PgConnection) -> Result<Vec<ArticleModel>, diesel::result::Error>{
            UserArticle::belonging_to(user)
                .inner_join(articles::table)
                .select(ARTICLE_COLUMNS)
                .load::<ArticleModel>(conn)
        }
    }

    I was wondering if I need to insert anything into user_articlesin order to be able to do many to many realtions. In this scenario, a user can have many articles and a articles can have many users (contributers). I have trired reading up on many to many and have read the stackoverflow question on many to many in diesel but I am still confused. Thank you for any help!

    2 replies
    Jack
    @Jackbaude
    no...
    I just wanna know how to do many to many relationships :(
    dasheightmate [any]
    @dasheightmate:chapo.chat
    [m]
    You know what they say - many to many relationships are as good as sex
    Jack
    @Jackbaude
    right now only thing on my mind is how to find all of a user's articles
    dasheightmate [any]
    @dasheightmate:chapo.chat
    [m]
    This guy is trying to pm me now. Are there any mods on this channel?
    1 reply
    Jovons
    @Jovons
    Hi, this is a new comer. Is it true, that with MySQL, I can only get an inserted/updated data, with a query? Like first insert/update it, and then query it. Since get_result is not available for MySQL
    Georg Semmler
    @weiznich
    @Jovons That's true. MySQL does just not provide the necessary SQL constructs (like returning clauses) to solve this in a generic way.
    Jovons
    @Jovons
    @weiznich Thank you George.
    suyash1993
    @suyash1993
    Hi Team, I am using bind method in diesel for parameterized sql. But i have few dynamic column names which needs to be escaped to avoid sql injection
    Bascially i am looking functionality like this (Actually in other ORM/query builder we can specify ? for value & ?? for column name/table name)
    https://github.com/mysqljs/mysql#escaping-query-identifiers
    Is there any way in diesel to do this or maybe some sort of escape method to avoid sql injection?
    Georg Semmler
    @weiznich
    @suyash1993 That's nothing we support yet.
    Thibault ROBERT
    @thibaultrobertdev_gitlab

    Hello 😀 I'm trying to do a diesel setup on my MacBook Pro M1 and I'm having this error:

    dyld: lazy symbol binding failed: Symbol not found: _PQconnectdb
     Referenced from: /Users/thibaultrobert/.cargo/bin/diesel
     Expected in: flat namespace
    
    dyld: Symbol not found: _PQconnectdb
     Referenced from: /Users/thibaultrobert/.cargo/bin/diesel
     Expected in: flat namespace
    
    [1]  33071 abort   diesel setup

    Postgresql is installed and it works I can access the DB with the psql command

    If anyone has any clue 😀
    Thanks in advance

    Georg Semmler
    @weiznich
    That sounds like the linker is unable to find some required symbols. Its nearly impossible to tell you what is exactly wrong without having access to your system or at least some similar system ( I do not own a macbook)
    Thibault ROBERT
    @thibaultrobertdev_gitlab
    ok I think it's the postgresql installation on ARM architecture ... thank you for your answer I will continue to search in this direction 🙂
    Felix Henninger
    @FelixHenninger

    Hi everyone! I'd like to add support for RETURNING in SQLite to the library, as per recent community discussions. To get things started, I made the relevant changes to the diesel code in a fork. However, this fails CI in a way I hadn't expected, apparently calling for another feature in SQLite:

    error[E0277]: the trait bound `Sqlite: SupportsDefaultKeyword` is not satisfied
    Error:   --> diesel_tests/tests/insert.rs:76:10
       |
    76 |         .get_results::<User>(&connection)
       |          ^^^^^^^^^^^ the trait `SupportsDefaultKeyword` is not implemented for `Sqlite`
       |
       = note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<Sqlite>` for `BatchInsert<'_, schema::NewUser, schema::users::table>`
       = note: 1 redundant requirements hidden
       = note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<Sqlite>` for `InsertStatement<schema::users::table, BatchInsert<'_, schema::NewUser, schema::users::table>, diesel::query_builder::insert_statement::Insert, diesel::query_builder::returning_clause::ReturningClause<(schema::users::columns::id, schema::users::columns::name, schema::users::columns::hair_color)>>`
       = note: required because of the requirements on the impl of `LoadQuery<diesel::SqliteConnection, schema::User>` for `InsertStatement<schema::users::table, BatchInsert<'_, schema::NewUser, schema::users::table>>`

    I'm confused by this because the batch insert does work, using nearly identical code in related tests. This particular error has been reported and discussed a couple of times already in this channel, too, but the solutions that have previously been suggested (i.e. using the correct Connection type) don't seem to apply here. Can you see what's going on? Any hints or clues are massively appreciated (I'm learning Rust, so apologies in advance if this is something trivial -- I'm happy to read up on things if you could give me a starting point). Thanks!

    4 replies
    Thomas Sieverding
    @Bajix
    I'm having issues with my raw query. I'm using SELECT "connectedProfiles"."mutualCount" AS "mutualCount" and my struct is annotated with #[column_name = "mutualCount"] but I'm getting the error: Column mutualCount was not present in query
    1 reply
    Thomas Sieverding
    @Bajix
    It looks like the column_name annotations are being ignored. If I rewrite to use snake_case so that I don't need the column name annotations it works
    Thomas Sieverding
    @Bajix
    From what I can tell using [diesel(embed)] with sql_query ignores the column_name annotations of the embedded type
    1 reply
    Ana Trakhtman
    @ana-altonotch_gitlab
    Hey guys, I'm getting this error the trait bound ```bool: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Bool>, Pg>``` is not satisfied. Is there something I'm missing in the imports?
    nvm :see_no_evil: it was due to fields not being mapped properly. Had to add Option around the bool field.
    Jack
    @Jackbaude
    Is there a way to update a column on a row to IS NOT. for example I have a boolean, and I just want to flip it?
    2 replies
    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