Skip to content

Commit

Permalink
Allow raw identifiers for SqlIdentifier (column-name)
Browse files Browse the repository at this point in the history
This allows using the `r#identifier` syntax for SqlIdentifier
(column-name), which is used in derive macros.
Previously the derive macros would panic when encountering such an
identifier:
    `"r#identifier"` is not a valid identifier
  • Loading branch information
z33ky committed May 20, 2024
1 parent 3c7b7c4 commit 3240f29
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
6 changes: 5 additions & 1 deletion diesel_derives/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ impl SqlIdentifier {

impl ToTokens for SqlIdentifier {
fn to_tokens(&self, tokens: &mut TokenStream) {
Ident::new(&self.field_name, self.span).to_tokens(tokens)
if self.field_name.starts_with("r#") {
Ident::new_raw(&self.field_name[2..], self.span).to_tokens(tokens)
} else {
Ident::new(&self.field_name, self.span).to_tokens(tokens)
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions diesel_derives/tests/queryable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,26 @@ fn tuple_struct() {
assert_eq!(Ok(MyStruct(1, 2)), data);
}

#[test]
fn raw_ident_struct() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable)]
struct MyStruct {
r#foo: i32,
#[diesel(column_name = bar)]
r#struct: i32,
}

let conn = &mut connection();
let data = select(sql::<(Integer, Integer)>("1, 2")).get_result(conn);
assert_eq!(
Ok(MyStruct {
foo: 1,
r#struct: 2
}),
data
);
}

#[test]
fn tuple_struct_without_column_name_annotations() {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Queryable)]
Expand Down Expand Up @@ -63,3 +83,15 @@ fn multiple_tables() {
data
);
}

#[test]
fn raw_ident_table() {
#[derive(Debug, Clone, PartialEq, Eq, Queryable)]
struct Car {
r#type: i32,
}

let conn = &mut connection();
let data = select(sql::<(diesel::sql_types::Integer,)>("0")).get_result(conn);
assert_eq!(Ok(Car { r#type: 0 }), data);
}
6 changes: 6 additions & 0 deletions diesel_derives/tests/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@ table! {
hair_color -> Nullable<Text>,
}
}

table! {
cars {
r#type -> Integer,
}
}

0 comments on commit 3240f29

Please sign in to comment.