-
Hi. I have used sqlx for several months, and I always avoid using Given the code below: create table if not exists user_ (
id serial,
name text not null unique,
full_name text,
--
primary key (id)
); pub struct CreateUserInput {
pub name: String,
pub full_name: Option<String>,
} pub async fn create(pool: &PgPool, user_input: CreateUserInput) -> anyhow::Result<User> {
let user = sqlx::query_as!(
User,
r#"insert into user_ (name, full_name) values ($1, $2) returning *"#,
&user_input.name,
&user_input.full_name,
)
.fetch_one(pool)
.await
.context("failed to perform a query to insert user")?;
Ok(user)
} I always get: 75 | &user_input.full_name,
| ^^^^^^^^^^^^^^^^^^^^^
| |
| expected `str`, found enum `std::option::Option`
| expected due to the type of this binding
|
= note: expected reference `&str`
found reference `&std::option::Option<std::string::String>` In diesel, it is handled automatically. Thanks in advance. Related issue:
Additional note: The strange thing is that it works with This works: pub struct UpdateUserInput {
pub id: i32,
pub name: String,
pub full_name: Option<String>,
}
pub async fn update(pool: &PgPool, user_input: UpdateUserInput) -> anyhow::Result<User> {
let user = sqlx::query_as!(
User,
r#"update user_ set
id = $1,
name = $2,
full_name = $3
where id = $1 returning *"#,
user_input.id,
user_input.name,
user_input.full_name,
)
.fetch_one(pool)
.await;
``` |
Beta Was this translation helpful? Give feedback.
Answered by
azzamsa
Jan 24, 2022
Replies: 1 comment
-
I find the solution, @@ -68,11 +68,17 @@ pub async fn create(pool: &PgPool, user_input: CreateUserInput) -> anyhow::Resul
bail!("a user with same `name` already exists")
}
+ let full_name = if user_input.full_name.is_some() {
+ user_input.full_name
+ } else {
+ None
+ };
+
let user = sqlx::query_as!(
User,
r#"insert into user_ (name, full_name) values ($1, $2) returning *"#,
&user_input.name,
- &user_input.full_name,
+ full_name
)
.fetch_one(pool)
.await |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
azzamsa
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I find the solution,