tokio-postgres-mapper icon indicating copy to clipboard operation
tokio-postgres-mapper copied to clipboard

Allow raw identifiers as column names

Open ygunayer opened this issue 3 years ago • 1 comments

In Rust, we can use the r# prefix to define fields with names that match built-in keywords like type, e.g.:

pub struct Foo {
  pub r#type: i64
}

Currently, when we derive the FromTokioPostgresRow trait using #[derive(PostgresMapper)] on a struct with fields that have the r# prefix, queries against the said fields with an error such as the following:

Failed to map database entities: UnknownTokioPG("invalid column `r#type`")

This happens because when we build queries, we pass the identifier name as-is, without removing this prefix, and the term r#type ends up in the query sent to Postgres. By using the unraw() method in the IdentExt trait of the syn package, however, we can remove the prefix from the identifier and make sure that we don't end up with invalid queries.

Note that it's safe to call unraw() regardless of the fact that fields are prefixed or not, because it has no effect regular identifier names.

This PR updates the usages of identifiers by calling unraw() to make sure they're not prefixed with r#.

ygunayer avatar Jul 20 '22 21:07 ygunayer

Hi @Dowwie! Could you please merge this PR? I have this problem and it would be cool if you could fix it.

sinitcin avatar Mar 16 '23 14:03 sinitcin