Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    MaxLuchs
    @MaxLuchs
    This message was deleted

    Compiling warp-test-2 v0.1.0 (/home/xxx/rustdev/warp-test-2)
    error: could not compile warp-test-2

    To learn more, run the command again with --verbose.
    error[E0599]: no function or associated item named age found for struct table in the current scope
    --> src/graphql/graphql_schema.rs:24:56
    |
    24 | let agefilter = filter.age.map(|a| dsl::user::age.eq(a));
    | ^^^ function or associated item not found in table
    |
    ::: src/schema.rs:1:1
    |
    1 | / table! {
    2 | | user (id) {
    3 | | id -> Int4,
    4 | | name -> Varchar,
    5 | | age -> Int4,
    6 | | }
    7 | | }
    | |
    - function or associated item age not found for this

    error[E0599]: no method named eq found for struct columns::name in the current scope
    --> src/graphql/graphql_schema.rs:25:66
    |
    25 | let name_filter = filter.name.map(|n| schema::user::name.eq(n));
    | ^^ method not found in columns::name
    |
    ::: /home/mluk/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-1.4.5/src/expression_methods/global_expression_methods.rs:23:8
    |
    23 | fn eq<T: AsExpression<Self::SqlType>>(self, other: T) -> Eq<Self, T::Expression> {
    | -- the method is available for Box<columns::name> here
    |
    ::: src/schema.rs:1:1
    |
    1 | / table! {
    2 | | user (id) {
    3 | | id -> Int4,
    4 | | name -> Varchar,
    5 | | age -> Int4,
    6 | | }
    7 | | }
    | | -
    | | |
    | |_method eq not found for this
    | doesn't satisfy columns::name: std::iter::Iterator
    |
    = note: the method eq exists but the following trait bounds were not satisfied:
    columns::name: std::iter::Iterator
    which is required by &mut columns::name: std::iter::Iterator
    = help: items from traits can only be used if the trait is in scope
    = note: the following trait is implemented but not in scope; perhaps add a use for it:
    use crate::diesel::ExpressionMethods;

    [Finished running. Exit status: 101]

    Georg Semmler
    @weiznich
    = note: the method eq exists but the following trait bounds were not satisfied:
    columns::name: std::iter::Iterator
    which is required by &mut columns::name: std::iter::Iterator
    = help: items from traits can only be used if the trait is in scope
    = note: the following trait is implemented but not in scope; perhaps add a use for it:
    use crate::diesel::ExpressionMethods;
    As you are using the method on a diesel type, maybe just try to import the corresponding trait?
    MaxLuchs
    @MaxLuchs
    Thanks. That helped.
    Sorry another question. I want to build a dynamic query depending on the existence of filter values. What would be the dyn Trait for all queries in Diesel?
    I mean the dyn super trait which includes: name::eq(x) and age::eq(x)
    MaxLuchs
    @MaxLuchs
    Atm those 2 eq-checks have different incompatible types for Rust, if I return both of them in a match-statement
    MaxLuchs
    @MaxLuchs
    Found it : filter.into_boxed() Thanks
    Thibault ROBERT
    @thibaultrobertdev_gitlab

    Hi everyone 😃 i am trying to install diesel_cli on a macbook pro m1 but i'm getting this error :

    linking with 'cc' failed: exit code: 1 
    [...]
    = note: ld: library not found for -lpq clang: error: linker command failed with exit code 1 (use -v to see invocation)

    I have tried to set the link-arg with many targets in the ~/.cargo/config but maybe i'm doing it all wrong:

    [target.aarch64-apple-darwin]
    rustflags = [
      "-C", "link-arg=-undefined",
      "-C", "link-arg=dynamic_lookup",
    ]
    
    [target.stable-aarch64-apple-darwin]
    rustflags = [
      "-C", "link-arg=-undefined",
      "-C", "link-arg=dynamic_lookup",
    ]

    if you have any suggestion... 😃

    Thanks in advance!

    2 replies
    Jack
    @Jackbaude
    Why is result a Vec<ArticleModel> instead of justa single ArticleModel
        let result = articles
            .find(_id)
            .load::<ArticleModel>(&*db)
            .expect("Error loading posts");
    2 replies
    Masato Nakata
    @naughie
    Hi. I tried to link to diesel in doc, but I failed. Just created an empty library via cargo new --lib diesel-doc-test, added the dependency diesel = { version = "1.4", features = [] } to Cargo.toml, and added //! Test of documentation with [`diesel`] to src/lib.rs.
    And then I ran cargo doc --no-deps, but the link to diesel was broken. Why I couldn't link to diesel and how to fix it?
    9 replies
    Tibor Huđik
    @htunlogic

    Hello, I have troubles with the diesel_manage_updated_at I couldn't find much documentation on how to use this and I assume I'm supposed to declare it after my migration of a table, for example:

    CREATE TABLE users
    (
      id varchar(36) DEFAULT uuid_generate_v4() NOT NULL,
      "name" varchar(100) NOT NULL,
      email varchar(100) NOT NULL,
      created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      CONSTRAINT pk_user_languages_id PRIMARY KEY ( id )
    );
    
    SELECT diesel_manage_updated_at('users');

    But this does not seem to work after I do update on an existing item in the database. updated_at stays the same. Of course its not a big deal if I would have to do it manually, but I was expecting that diesel_manage_updated_at function to do it automatically.

    Georg Semmler
    @weiznich
    Can you provide a few more information here, something like which database system you are using and if there is a trigger registered for your user table.
    Tibor Huđik
    @htunlogic
    sorry, I'm using PostgreSQL 13.1, I have the first migration entry the default one where I have a CREATE OR REPLACE FUNCTION diesel_manage_updated_at statement
    The trigger set_updated_at is defined for my table
    Georg Semmler
    @weiznich
    Hmm, I've just tried to reproduce that locally in the psql console and it worked there just fine.
    I've just done the following steps:
    • Create the table
    • Create the corresponding trigger via diesel_manage_updated_at
    • Insert some dummy value
    • Issue the following update statement: update users set name = 'baz';
    • Verify that the updated_at column has changed.
    Can you double check that on your side?
    Tibor Huđik
    @htunlogic
    Ah damn, my bad. I just figured it will only do an update if I actually change something. I was running tests where I haven't actually changed anything, just sent the same values as an update method.
    Georg Semmler
    @weiznich
    Yes the trigger is not triggered in that cases. Glad to hear it works now :+1:
    c8de
    @c8de
    Hi, can anyone help me out with a diesel_ltree related question? I have the following code that throws me the error: .getresults -> the trait `FromSql<Ltree, >is not implemented forLtree`
                let results = schema::leaves::table
                    .filter(
                        schema::leaves::path.eq(diesel_ltree::text2ltree(""))
                    )
                    .get_results::<models::Leaf>(&db_conn);
    Georg Semmler
    @weiznich
    @c8de That's hard to answer without knowing more details. For example the definition of Leaf and schema::leaves and so on.
    Adrien FAURE
    @adfaure

    Hello, would it be possible to have a struct splitted in two different struct, but issued from the same table ?

    I have a table, narinfo, composed of two attributes which are the PK and a FK.
    However, I would like to be able to split into my code the struct in two different struct:

    #[belongs_to(Cache, foreign_key = "cache_name")]
    #[primary_key(narinfo_hash)]
    #[table_name = "narinfos"]
    pub struct Narinfo {
        pub narinfo_hash: String,
        pub cache_name: String,
        pub content: NarinfoContent,
    }
    
    //In this case, NarinfoContent is just a subset of the table's columns.
    #[derive(Queryable, PartialEq, Debug, Builder)]
    pub struct NarinfoContent {
        pub store_path: String,
        pub url: String,
        pub compression: Option<String>,
        pub file_hash: String,
        pub file_size: i64,
        pub nar_hash: String,
        pub nar_size: i64,
        pub refs: String,
        pub deriver: String,
        pub sig: Option<String>,
    }

    I want to do this, because, at some point, I need to work with this subset of attributes (the content). For instance, when I receive new content it does not have the information's about the FK and the PK.
    However, into the database, I don't see a reason why I should store this with two different tables (with a content belonging to the narinfo).

    The immediate solution would be to duplicate the code, to have a struct content that could transform into a narinfo when I have the missing information. But I wonder if it is direct support for this in diesel.
    I found this diesel-rs/diesel#1006 that seems related, however the asociated test case seems to use it for joining tables.

    Thanks !

    Georg Semmler
    @weiznich
    You can structure your query output in any way you want, as long as it matches the underlying select clause. For this case it means that you need something like .select((narinfo_hash, cache_name, (store_path, …)).
    Adrien FAURE
    @adfaure
    Do you suggest that I don't use the derive attributes such as Queryable etc ?
    Georg Semmler
    @weiznich
    No, you need Queryable.
    Adrien FAURE
    @adfaure
    I think I understand what you meant, thank you I'll try that out.
    Georg Semmler
    @weiznich
    If I interpreted your comment correctly you have a bit of "misunderstanding" what Queryable actually does. It does not influence your query in any way, but it's the other way around. A query can return a set of fields, all that Queryable does is providing some way to map that anonym tuple into some rust struct.
    Adrien FAURE
    @adfaure
    Ok, I understand better. Thank you for your explanation.
    Markus
    @estriv

    Here we go again:

    I want to wrap a filter which uses a join into a function an thought BoxedSelectStatement was the way to go.
    I did this:

    pub fn visible_users<'a, QS>(&self, conn: &PgConnection) -> BoxedSelectStatement<'a, diesel::sql_types::Uuid, QS, Pg>
        where
          QS: QuerySource, {
        let mut query = users::table
          .left_outer_join(organisations::table)
          .select(users::id)
          .into_boxed();
      // ... some ifs and .filter
      query
    }

    This throws me:

       |
    22 |   pub fn visible_users<'a, QS>(&self, conn: &PgConnection) -> BoxedSelectStatement<'a, diesel::sql_types::Uuid, QS, Pg>
       |                            -- this type parameter             --------------------------------------------------------- expected `diesel::query_builder::BoxedSelectStatement<'a, diesel::sql_types::Uuid, QS, Pg>` because of return type
    ...
    44 |     query
       |     ^^^^^ expected type parameter `QS`, found struct `JoinOn`
       |
       = note: expected struct `diesel::query_builder::BoxedSelectStatement<'a, _, QS, _>`
                  found struct `diesel::query_builder::BoxedSelectStatement<'_, _, JoinOn<diesel::query_source::joins::Join<schema::users::table, schema::organisations::table, LeftOuter>, diesel::expression::operators::Eq<diesel::expression::nullable::Nullable<schema::users::columns::organisation_id>, diesel::expression::nullable::Nullable<schema::organisations::columns::id>>>, _>`

    I would like to have QS infered by rust and not to explicitly declare the type. Any suggestions what to change?

    Georg Semmler
    @weiznich
    First of all: BoxedSelectStatement is not part of our public API, therefore it should probably not be used. Instead use the types from diesel::dsl, which should also make it much easier for this case to write down the actual return type.
    Other than that, I'm not aware of any way to make rustc infer that type for you.
    Markus
    @estriv
    I tried IntoBoxed and Box<BoxableExpression>. Both did not compile. The latter has the problem, that i cannot use custom traits with which I extended diesel.
    33 replies
    Do you have a hint where I can start? After a few hours of searching and trial and error I am out of ideas how to get this down.
    I think it should be possible to embedd this into a function without using macros or am I wrong?
    Adrien FAURE
    @adfaure
    I noticed, from my example that the Narinfo class needs to be insertable, Is it possible ?
    #[derive(Identifiable, Insertable, Queryable, Associations, PartialEq, Debug)]
    #[belongs_to(Cache, foreign_key = "cache_name")]
    #[primary_key(narinfo_hash)]
    #[table_name = "narinfos"]
    pub struct Narinfo {
        pub narinfo_hash: String,
        pub cache_name: String,
        pub content: NarinfoContent,
    }
    
    #[derive(Queryable, PartialEq, Debug, Builder)]
    pub struct NarinfoContent {
        pub store_path: String,
        pub url: String,
        pub compression: Option<String>,
        pub file_hash: String,
        pub file_size: i64,
        pub nar_hash: String,
        pub nar_size: i64,
        pub refs: String,
        pub deriver: String,
        pub sig: Option<String>,
    }
    Adrien FAURE
    @adfaure
    Maybe my issue come from the fact that I try to mix database code with my data structures for my application.
    Maybe I should have a clear separation between what I will actually use in my code for building my application, and what interaction I want to do with the database.
    So I'll be able to have structs that fully represent how I use the db.
    Georg Semmler
    @weiznich
    It's normally fine to mix those structs.
    Adrien FAURE
    @adfaure
    damn :D
    because Identifiable doesn't seem to support nested struct.
    Georg Semmler
    @weiznich
    Having Insertable there is also fine, you just need to derive Insertable on both structs + put #[diesel(embed)] on the content field: https://docs.diesel.rs/1.4.x/diesel/prelude/trait.Insertable.html
    Adrien FAURE
    @adfaure
    oh, awesome. Again my bad, I am terrible at reading the doc :/
    Ill scratch the doc longer next time...
    Georg Semmler
    @weiznich
    For Identifiable you don't need to do anything with the inner type, as the primary key is on the outer one.
    Adrien FAURE
    @adfaure

    Ok, this time it might be a bug:
    I have the following definitions (working great thanks to your help). We can see that the Narinfo struct belongs to the Struct (table) Cache(s).

    
    #[derive(Identifiable, Queryable, Insertable, PartialEq, Debug, Clone)]
    #[table_name = "caches"]
    #[primary_key(name)]
    pub struct Cache {
        pub name: String,
    }
    
    #[derive(Identifiable, Insertable, Queryable, Associations, PartialEq, Debug)]
    #[belongs_to(Cache, foreign_key = "cache_name")]
    #[primary_key(narinfo_hash, cache_name)]
    #[table_name = "narinfos"]
    pub struct Narinfo {
        pub narinfo_hash: String,
        pub cache_name: String,
        #[diesel(embed)]
        pub content: NarinfoContent,
    }
    
    #[derive(Queryable, Insertable, PartialEq, Debug, Builder)]
    #[table_name = "narinfos"]
    pub struct NarinfoContent {
        pub store_path: String,
        pub url: String,
        pub compression: Option<String>,
        pub file_hash: String,
        pub file_size: i64,
        pub nar_hash: String,
        pub nar_size: i64,
        pub refs: String,
        pub deriver: String,
        pub sig: Option<String>,
    }

    When I attempt to query both, as provided in the example I have:

    use crate::schema::caches::dsl::*;
    use crate::schema::narinfos::dsl::*; <-- Removing this use clearsthe error, but I am no longer able to use the narinfos table.
    
    match caches
        .find(cache_name.clone())
        .get_result::<Cache>(&*connection)
        .optional()?
    {
        Some(ref cache) => Ok((
            Some(cache.clone()),
            Narinfo::belonging_to(cache)
                .find((narinfo_filename, cache_name))
                .select((
                    narinfo_hash,
                    cache_name,
                    (
                        store_path,
                        url,
                        compression,
                        file_hash,
                        file_size,
                        nar_hash,
                        nar_size,
                        refs,
                        deriver,
                        sig,
                    ),
                ))
                .get_result::<Narinfo>(&*connection)
                .optional()?,
        )),
        None => return Ok((None, None)),
    }

    I got this error:

    error[E0271]: type mismatch resolving `<schema::caches::table as AppearsInFromClause<schema::narinfos::table>>::Count == diesel::query_source::Once`
      --> src/data_actions.rs:30:10
       |
    30 |         .get_result::<Cache>(&*connection)
       |          ^^^^^^^^^^ expected struct `Never`, found struct `diesel::query_source::Once`
       |
       = note: required because of the requirements on the impl of `AppearsOnTable<schema::caches::table>` for `schema::narinfos::columns::cache_name`
       = note: 1 redundant requirements hidden
       = note: required because of the requirements on the impl of `AppearsOnTable<schema::caches::table>` for `diesel::expression::operators::Eq<schema::caches::columns::name, schema::narinfos::columns::cache_name>`
       = note: required because of the requirements on the impl of `query_builder::where_clause::ValidWhereClause<schema::caches::table>` for `query_builder::where_clause::WhereClause<diesel::expression::operators::Eq<schema::caches::columns::name, schema::narinfos::columns::cache_name>>`
       = note: required because of the requirements on the impl of `diesel::query_builder::Query` for `diesel::query_builder::SelectStatement<schema::caches::table, query_builder::select_clause::DefaultSelectClause, query_builder::distinct_clause::NoDistinctClause, query_builder::where_clause::WhereClause<diesel::expression::operators::Eq<schema::caches::columns::name, schema::narinfos::columns::cache_name>>>`
       = note: required because of the requirements on the impl of `LoadQuery<_, models::Cache>` for `diesel::query_builder::SelectStatement<schema::caches::table, query_builder::select_clause::DefaultSelectClause, query_builder::distinct_clause::NoDistinctClause, query_builder::where_clause::WhereClause<diesel::expression::operators::Eq<schema::caches::columns::name, schema::narinfos::columns::cache_name>>>`
    
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E027
    Georg Semmler
    @weiznich
    schema::table::dsl::* is designed to be used if there is only one table in scope. Instead of using that you should use the more explicit variant here.
    So something like:
    use schema::{cahces, narinfos};
    
    // for the table itself instead of `narinfos`
    narinfos::table
    // for columns like `store_path`
    narinfos::store_path
    Adrien FAURE
    @adfaure
    It works. Thanks again.
    MaxLuchs
    @MaxLuchs
    Sorry, may I ask more questions. 1. How do you transform a QueryResult into a plain Result? 2. What is the difference between schema::table::dsl::<column_name> and schema::table::<column_name>?
    Georg Semmler
    @weiznich
    1. How do you transform a QueryResult into a plain Result?

    It's a plain result with a fixed error type: https://docs.diesel.rs/1.4.x/diesel/result/type.QueryResult.html

    1. What is the difference between schema::table::dsl::<column_name> and schema::table::<column_name>

    They are the same, one is the reexport of the other one.

    MaxLuchs
    @MaxLuchs
    Thanks :) Sorry for not using the docs properly.