sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Generate a Query in function won't build successful

Open ipconfiger opened this issue 1 year ago • 0 comments

Bug Description

i want use a function to generate a lot queries, but the code can build in main function goes wrong when move them in functions.

Minimal Reproduction

A small code snippet or a link to a Github repo or Gist, with instructions on reproducing the bug.

next code can build successfully

#[tokio::test]
async fn test_something_async() -> Result<(), sqlx::Error> {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://postgres:welcome@localhost/postgres")
        .await?;

    let mut bar = Bar{id:"asdasd".to_string(), name:"asdasd".to_string(), ts:1231312};
    let query = sqlx::query::<Postgres>("insert into testdb values ($1, $2, $3)");
    let query = query.bind(bar.id);
    let query = query.bind(bar.name);
    let query = query.bind(bar.ts);
    Ok(())
}

but i put same code in a function

fn insert_bind<'q, DB: Database>(bar: Bar) -> Query<'q, DB, <DB as HasArguments<'q>>::Arguments> {
    
    let sql = "insert into testtb values ($1, $1, $3)";
    let query = sqlx::query::<DB>(sql);
    let query = query.bind(bar.id);
    let query = query.bind(bar.name);
    let query = query.bind(bar.ts);
    query
}

it build fault:

error[E0277]: the trait bound `std::string::String: Encode<'_, DB>` is not satisfied
  --> tests/test.rs:54:28
   |
54 |     let query = query.bind(bar.id);
   |                       ---- ^^^^^^ the trait `Encode<'_, DB>` is not implemented for `std::string::String`
   |                       |
   |                       required by a bound introduced by this call
   |
note: required by a bound in `Query::<'q, DB, <DB as HasArguments<'q>>::Arguments>::bind`
  --> /Users/alex/.cargo/registry/src/rsproxy.cn-8f6827c7555bfaf8/sqlx-core-0.6.3/src/query.rs:79:32
   |
79 |     pub fn bind<T: 'q + Send + Encode<'q, DB> + Type<DB>>(mut self, value: T) -> Self {
   |                                ^^^^^^^^^^^^^^ required by this bound in `Query::<'q, DB, <DB as HasArguments<'q>>::Arguments>::bind`
help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement
   |
40 | fn insert_bind<'q, DB: Database>(bar: Bar) -> Query<'q, DB, <DB as HasArguments<'q>>::Arguments> where std::string::String: Encode<'_, DB> {
   |                                                                                                  +++++++++++++++++++++++++++++++++++++++++


#WHY?WHY?WHY?

Info

  • SQLx version: 0.7.0
  • SQLx features enabled: ["runtime-tokio-native-tls", "all-databases"]
  • Database server and version: Postgres 13
  • Operating system: MacOS 14.2.1 (23C71)
  • rustc --version: rustc 1.76.0 (07dca489a 2024-02-04)

ipconfiger avatar Feb 11 '24 12:02 ipconfiger