sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.5k stars 443 forks source link

Statement interpolation #925

Closed wedobetter closed 2 years ago

wedobetter commented 2 years ago

(My second week learning Rust) I can't figure out why this is not being parsed:

db.query("CREATE INDEX $2_idx ON $1 ($2)", &[&"users", &"username"]) .await.unwrap();

giving me: thread 'main' panicked at 'calledResult::unwrap()on anErrvalue: Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42601), message: "syntax error at or near \"$2\"", detail: None, hint: None, position: Some(Original(14)), where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("scan.l"), line: Some(1176), routine: Some("scanner_yyerror") }) }', src/ds.rs:32:10 stack backtrace:

This doesn't work either:

db.query("CREATE INDEX $1 ON $2 ($3)", &[&"username_idx", &"users", &"username"]) .await.unwrap();

I have obviously checked if this would work fine and it does: db.query("CREATE INDEX username_idx ON users (username)", &[]) .await.unwrap();

Cargo.toml

[package]
name = "authsvc"
version = "0.1.0"
edition = "2021"

[dependencies]
deadpool-postgres = "0.10.2"
tokio = { version = "1.20.0", features = ["full"] }
tokio-postgres = "0.7.6"
sfackler commented 2 years ago

Parameters can only stand in for values in a query, not arbitrary substrings. Things like table and column names need to be directly inline in the query.

wedobetter commented 2 years ago

Right, I never used params in SQL, I thought they were interpolated before the DB query. Then in my case what I need is a format!("...{}...") instead.

Thank you!