Skip to content

Commit

Permalink
Process keyword fields correctly in FromRow macro
Browse files Browse the repository at this point in the history
This PR fixes the the incorrect handling of keywords fields of a struct in the FromRow macro.
Currently a struct with a field like 'r#type' will try to read values from a column with the exact same name with r# prefix. With this change this field will now map to a database column with the correct name 'type' without the r# prefix.
  • Loading branch information
sidred committed Mar 30, 2020
1 parent 670265f commit 40f11eb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlx-macros/src/derives/row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn expand_derive_from_row_struct(

let reads = fields.iter().filter_map(|field| -> Option<Stmt> {
let id = &field.ident.as_ref()?;
let id_s = id.to_string();
let id_s = id.to_string().trim_start_matches("r#").to_owned();
let ty = &field.ty;

Some(parse_quote!(
Expand Down
33 changes: 33 additions & 0 deletions tests/postgres-derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,36 @@ async fn test_from_row() -> anyhow::Result<()> {

Ok(())
}

#[cfg(feature = "macros")]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn test_from_row_with_keyword() -> anyhow::Result<()> {
use sqlx::prelude::*;

#[derive(Debug, sqlx::FromRow)]
struct AccountKeyword {
r#type: i32,
r#static: String,
r#let: Option<String>,
r#struct: Option<String>,
name: Option<String>,
}

let mut conn = new::<Postgres>().await?;

let account: AccountKeyword = sqlx::query_as(
r#"SELECT * from (VALUES (1, 'foo', 'bar', null, null)) accounts(type, static, let, struct, name)"#
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);

assert_eq!(1, account.r#type);
assert_eq!("foo", account.r#static);
assert_eq!(None, account.r#struct);
assert_eq!(Some("bar".to_owned()), account.r#let);
assert_eq!(None, account.name);

Ok(())
}

0 comments on commit 40f11eb

Please sign in to comment.