Warning
This post was published 38 days ago. The information described in this article may have changed.
I want to write a base trait for to work with DB objects and implement the default methods . My trait look like
trait Model {
type Entity: FromRow<'static, PgRow> + Send + Unpin + Debug;
fn table_name() -> &'static str;
async fn get_by(
column: &str,
value: impl sqlx::Encode<'_, Postgres> + sqlx::Type<Postgres> + Send + Debug,
) -> Result<Option<Self::Entity>, Error> {
let sql = format!(
"SELECT * FROM {} WHERE {} = $1 LIMIT 1",
Self::table_name(),
column
);
let query = query_as::<Postgres, Self::Entity>(&sql).bind(value);
let row: Option<Self::Entity> = query.fetch_optional(pool()).await?;
Ok(row)
}
}
I get error:
error[E0599]: no method named `fetch_optional` found for struct `QueryAs<'_, Postgres, <Self as Model>::Entity, PgArguments>` in the current scope
--> src/db/db.rs:33:47
|
33 | let row: Option<Self::Entity> = query.fetch_optional(pool()).await?;
| ^^^^^^^^^^^^^^ method not found in `QueryAs<'_, Postgres, <Self as Model>::Entity, PgArguments>`
|
= note: the method was found for
- `QueryAs<'q, DB, O, A>`
I thought that depends on with imports, but I'v imported all I need.
use sqlx::{
Error, FromRow, Postgres,
postgres::{PgArguments, PgPool, PgRow},
prelude::*,
query::QueryAs,
query_as,
};
use std::fmt::Debug;
Can you help me to understand, why query doesn't have fetch_* methods?
P.S pool() returns &'static PgPool
1 post - 1 participant
🏷️ rust_feed