1

I'm looking to bind data through my SQL string:

#[derive(Debug, sqlx::FromRow)]
struct CurrencyExchangeRateBdd {
    currency_exchange_rate_id: i64,
    from_currency: String,
    to_currency: String,
    rate_date: Date,
    rate: f64,
    creation_date: OffsetDateTime,
    rate_down: Option<f64>,
    rate_up: Option<f64>,
}

async fn get_data(date: &String) -> Result<Vec<CurrencyExchangeRateBdd>, sqlx::Error> {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres")
        .await?;

    let row = sqlx::query_as!(
        CurrencyExchangeRateBdd,
        "SELECT * FROM currency_exchange_rate WHERE rate_date = ?"
    )
    .bind(date)
    .fetch_all(&pool)
    .await;

    row
}

I get this error:

error: error returned from database: syntax error at end of input
  --> src/main.rs:50:15
   |
50 |     let row = sqlx::query_as!(CurrencyExchangeRateBdd,"SELECT * FROM currency_exchange_rate WHERE rate_date = ?")
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

I have tried:

let row = sqlx::query_as!(CurrencyExchangeRateBdd, "SELECT * FROM currency_exchange_rate WHERE rate_date = ?", date)

Or with a $ or @ rather than ?. I have the same as the documentation.

How I can fix this error?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Raphael M
  • 109
  • 1
  • 9
  • 2
    Have you tried `$1` rather than just `?` or `$`? That is the syntax for parameters in Postgres prepared statements. https://www.postgresql.org/docs/current/sql-prepare.html#SQL-PREPARE-EXAMPLES – justinas Jul 13 '21 at 14:29
  • @justinas Thanks man it's work, the documentation look not up-to-date :D – Raphael M Jul 13 '21 at 14:34

1 Answers1

4

The correct syntax is:

let row = sqlx::query_as!(
    CurrencyExchangeRateBdd,
    "SELECT * FROM currency_exchange_rate WHERE rate_date = $1"
)

Postgres uses identifiers $1, $2, etc. to indicate parameters in a prepared statement. See documentation.

The very first example in sqlx's README also shows proper usage of parameters with Postgres.

justinas
  • 6,287
  • 3
  • 26
  • 36