Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add embed support for AsChangeSet #4209

Merged
merged 4 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Increasing the minimal supported Rust version will always be coupled at least wi

### Added

* Added embedded struct support for `AsChangeset` via `#[diesel(embed)]`
* Support for libsqlite3-sys 0.30.0
* Add support for built-in PostgreSQL range operators and functions
* Support for postgres multirange type
Expand Down
7 changes: 7 additions & 0 deletions diesel_compile_tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ table! {
}
}

#[derive(Insertable)]
#[derive(Insertable, AsChangeset)]
#[diesel(table_name = users)]
struct NameAndHairColor<'a> {
name: &'a str,
Expand All @@ -24,4 +24,13 @@ struct User<'a> {
name_and_hair_color: NameAndHairColor<'a>,
}

#[derive(AsChangeset)]
#[diesel(table_name = users)]
struct UserChangeSet<'a> {
id: i32,
#[diesel(embed, serialize_as = SomeType)]
// to test the compile error, this type doesn't need to exist
name_and_hair_color: NameAndHairColor<'a>,
}

fn main() {}
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@ error: `#[diesel(embed)]` cannot be combined with `#[diesel(serialize_as)]`
|
22 | #[diesel(embed, serialize_as = SomeType)]
| ^^^^^^

error: `#[diesel(embed)]` cannot be combined with `#[diesel(serialize_as)]`
--> tests/fail/derive/embed_and_serialize_as_cannot_be_mixed.rs:31:7
|
31 | #[diesel(embed, serialize_as = SomeType)]
| ^^^^^^
38 changes: 34 additions & 4 deletions diesel_derives/src/as_changeset.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use proc_macro2::TokenStream;
use quote::quote;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;
use syn::{parse_quote, DeriveInput, Expr, Path, Result, Type};

Expand Down Expand Up @@ -49,6 +49,13 @@ pub fn derive(item: DeriveInput) -> Result<TokenStream> {
// Use field-level attr. with fallback to the struct-level one.
let treat_none_as_null = match &field.treat_none_as_null {
Some(attr) => {
if let Some(embed) = &field.embed {
return Err(syn::Error::new(
embed.attribute_span,
"`embed` and `treat_none_as_default_value` are mutually exclusive",
));
}

if !is_option_ty(&field.ty) {
return Err(syn::Error::new(
field.ty.span(),
Expand All @@ -61,8 +68,8 @@ pub fn derive(item: DeriveInput) -> Result<TokenStream> {
None => treat_none_as_null,
};

match field.serialize_as.as_ref() {
Some(AttributeSpanWrapper { item: ty, .. }) => {
match (field.serialize_as.as_ref(), field.embed()) {
(Some(AttributeSpanWrapper { item: ty, .. }), false) => {
direct_field_ty.push(field_changeset_ty_serialize_as(
field,
table_name,
Expand All @@ -78,7 +85,19 @@ pub fn derive(item: DeriveInput) -> Result<TokenStream> {

generate_borrowed_changeset = false; // as soon as we hit one field with #[diesel(serialize_as)] there is no point in generating the impl of AsChangeset for borrowed structs
}
None => {
(Some(AttributeSpanWrapper { attribute_span, .. }), true) => {
return Err(syn::Error::new(
*attribute_span,
"`#[diesel(embed)]` cannot be combined with `#[diesel(serialize_as)]`",
));
}
(None, true) => {
direct_field_ty.push(field_changeset_ty_embed(field, None));
direct_field_assign.push(field_changeset_expr_embed(field, None));
ref_field_ty.push(field_changeset_ty_embed(field, Some(quote!(&'update))));
ref_field_assign.push(field_changeset_expr_embed(field, Some(quote!(&))));
}
(None, false) => {
direct_field_ty.push(field_changeset_ty(
field,
table_name,
Expand Down Expand Up @@ -151,6 +170,17 @@ pub fn derive(item: DeriveInput) -> Result<TokenStream> {
)))
}

fn field_changeset_ty_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
let field_ty = &field.ty;
let span = field.span;
quote_spanned!(span=> #lifetime #field_ty)
}

fn field_changeset_expr_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
let field_name = &field.name;
quote!(#lifetime self.#field_name)
}

fn field_changeset_ty(
field: &Field,
table_name: &Path,
Expand Down
7 changes: 7 additions & 0 deletions diesel_derives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ mod valid_grouping;
/// from the name of the corresponding column, you can annotate the field with
/// `#[diesel(column_name = some_column_name)]`.
///
/// Your struct can also contain fields which implement `AsChangeset`. This is
/// useful when you want to have one field map to more than one column (for
/// example, an enum that maps to a label and a value column). Add
/// `#[diesel(embed)]` to any such fields.
///
/// To provide custom serialization behavior for a field, you can use
/// `#[diesel(serialize_as = SomeType)]`. If this attribute is present, Diesel
/// will call `.into` on the corresponding field and serialize the instance of `SomeType`,
Expand Down Expand Up @@ -98,6 +103,8 @@ mod valid_grouping;
/// * `#[diesel(column_name = some_column_name)]`, overrides the column name
/// of the current field to `some_column_name`. By default, the field
/// name is used as column name.
/// * `#[diesel(embed)]`, specifies that the current field maps not only
/// to a single database field, but is a struct that implements `AsChangeset`.
/// * `#[diesel(serialize_as = SomeType)]`, instead of serializing the actual
/// field type, Diesel will convert the field into `SomeType` using `.into` and
/// serialize that instead. By default, this derive will serialize directly using
Expand Down
48 changes: 48 additions & 0 deletions diesel_derives/tests/as_changeset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -843,3 +843,51 @@ fn option_fields_are_correctly_detected() {
// Causes a compile error if the field is not detected as `Option<T>`
define!((((Option<String>))));
}

#[test]
fn embedded_struct() {
#[derive(AsChangeset)]
#[diesel(table_name = users)]
struct UserAttributes<'a> {
hair_color: &'a str,
r#type: &'a str,
}

#[derive(AsChangeset)]
#[diesel(table_name = users)]
struct UserForm<'a> {
name: &'a str,
#[diesel(embed)]
attribute: UserAttributes<'a>,
}

let connection = &mut connection_with_sean_and_tess_in_users_table();

update(users::table.find(1))
.set(&UserForm {
name: "Jim",
attribute: UserAttributes {
hair_color: "blue",
r#type: "super",
},
})
.execute(connection)
.unwrap();

let expected = vec![
(
1,
String::from("Jim"),
Some(String::from("blue")),
Some(String::from("super")),
),
(
2,
String::from("Tess"),
Some(String::from("brown")),
Some(String::from("admin")),
),
];
let actual = users::table.order(users::id).load(connection);
assert_eq!(Ok(expected), actual);
}
Loading