How to properly use UUID with sqlx? #1548
-
I have a query that returns single UUID value, but it looks like there is need from some special handling for converting UUID from Row. sqlx = { version = "0.5", features = [
"runtime-tokio-rustls",
"postgres",
"chrono",
"uuid",
] }
let id = sqlx::query_as::<_, Uuid>(
"INSERT INTO users (name, password, email) VALUES ($1, $2, $3) RETURNING id",
)
.bind(name)
.bind(password)
.bind(email)
.fetch_one(&self.pool)
error[E0277]: the trait bound `for<'r> Uuid: FromRow<'r, _>` is not satisfied
--> src/pg_store.rs:23:18
|
23 | let id = sqlx::query_as::<_, Uuid>(
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `for<'r> FromRow<'r, _>` is not implemented for `Uuid`
| |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
@jplatte Answered in discord: let (id,) = sqlx::query_as::<_, (Uuid,)>(
"INSERT INTO users (name, password, email) VALUES ($1, $2, $3) RETURNING id",
)
.bind(...)
.fetch_one(&self.pool)
.await?; |
Beta Was this translation helpful? Give feedback.
-
To extend @marknefedov answer: Scalar: let id = sqlx::query_scalar::<_, Uuid>(
"INSERT INTO users (name, password, email) VALUES ($1, $2, $3) RETURNING id",
)
.bind(...)
.fetch_one(&pool)
.await?; Tuple: let (id,) = sqlx::query_as::<_, (Uuid,)>(
"INSERT INTO users (name, password, email) VALUES ($1, $2, $3) RETURNING id",
)
.bind(...)
.fetch_one(&pool)
.await?; |
Beta Was this translation helpful? Give feedback.
@jplatte Answered in discord:
query_as is for getting a type that implements FromRow, not Type
What you need if you just want the single column of the output is query_scalar
You could also use a one-tuple, but that's kind of ugly which is why there is query_scalar