sea-query icon indicating copy to clipboard operation
sea-query copied to clipboard

Macro for generating the Iden from a given Struct

Open chikko80 opened this issue 2 years ago • 6 comments

Motivation

Hi,

I am primarily using SQLx at the moment, but I did take a look at SeaQuery and would like to try it in a few places. However, for me, it produces some unnecessary boilerplate with the Iden when I am already using structs as my models. I understand that Iden is not really a replacement, but maintaining both an enum and a struct is not very efficient for me.

Is there any macro we can use to automatically generate the Iden enum definition for the struct? I'd prefer to use SeaQuery optionally in a few places where it's perfectly fine to have a "CompanyIden" enum or something similar. I could also submit a pull request if this is a use case that benefits more people than just me. I've not really worked with macros so far, but could probably make it work

Proposed Solutions

Example struct with "IdenGen" derive:

#[derive(Clone, Debug, Object, FromRow, IdenGen)]
struct Company {
    id: i32,
    name: String,
    street: String,
    zip: i32,
}

Generated Iden:

    #[derive(Iden)]
    pub enum CompanyIden {
        Table,
        Id,
        Name,
        Street,
        Zip,
    }

chikko80 avatar Oct 23 '23 09:10 chikko80

Hi there. Thank you for your suggestion. It may not be well-advertised, but do you think https://github.com/SeaQL/sea-query/blob/master/sea-query-attr/tests/pass/default.rs serves the need?

one more example: https://github.com/SeaQL/sea-query#iden

tyt2y3 avatar Oct 23 '23 11:10 tyt2y3

@tyt2y3 Definitely, totally my bad! Awesome that this feature already is implemented, totally missed that while I was checking the docs. Thanks!

chikko80 avatar Oct 23 '23 11:10 chikko80

I was about to say, the original contributor thinks it's more appropriate to make it an attribute macro instead of a derive macro, since it generates structs instead of implementing traits.

So a possible improvement might be to make it work as a derive macro as well. This could possibly make the user code looks cleaner.

tyt2y3 avatar Oct 23 '23 11:10 tyt2y3

Ahh, I see, then let's reopen the issue. I would also probably prefer a derive macro, i'll take a look at it when I have some time

chikko80 avatar Oct 23 '23 11:10 chikko80

@tyt2y3

Upon a first look, i found additional functionality for Prefixing and Suffixing.

Wouldn't we loose this in case of a raw derive macro? Wouldn't we have to keep the attribute macro anyway in order to preserve the prefix/suffix functionality?

chikko80 avatar Oct 23 '23 14:10 chikko80

Derive macros also support extra derive attributes. I think it's just a stylistic preference to the user. But yes, we'd still want to keep the attribute macros. So there will be two ways to invoke the macro.

tyt2y3 avatar Oct 23 '23 14:10 tyt2y3