A safe, extensible ORM and Query Builder for Rust – For feature requests and longer questions also see https://github.com/diesel-rs/diesel/discussions/categories/q-a
sql_query
requires always a custom struct that implements QueryableByName
. Instead of using sql_query
you could define your version function via sql_function!
and use the typed query builder (so diesel::select(version())
which allows you to select directly into a String
.sql_query
.
QueryableByName
. That seems so be what's in the example, at least.
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>>
#[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.
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
.
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.
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?
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_articles
in 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!