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

Specializing trait methods for given cases #1

Open
vigoo opened this issue Nov 1, 2024 · 2 comments
Open

Specializing trait methods for given cases #1

vigoo opened this issue Nov 1, 2024 · 2 comments

Comments

@vigoo
Copy link

vigoo commented Nov 1, 2024

Thank you for the nice crate!

I needed support for specializing some method implementations in the generated traits for each case, while having a single implementation for the rest of the trait. What I came up with is a #[when] attribute that can be used on methods within a #[trait_gen] trait, for example

#[trait_gen(DB -> sqlx::sqlite::Sqlite, sqlx::mysql::MySql, sqlx::postgres::Postgres)]
#[async_trait]
impl Repo for sqlx::Pool<DB> {
    // ...
    #[when(sqlx::sqlite::Sqlite -> update)]
    async fn update_sqlite(&self, id: u64, param: String) -> Result<(), String> {
        // SQLite specific implementation
        todo!()
    }

    #[when(sqlx::mysql::MySql -> update)]
    async fn update_mysql(&self, id: u64, param: String) -> Result<(), String> {
        // MySQL specific implementation
        todo!()
    }
   // ...

As I needed this quickly, I published it as a fork: https://github.com/vigoo/conditional_trait_gen

But if you are interested, I'm happy to open a PR with it upstream.

@blueglyph
Copy link
Owner

Glad it was useful! It started as a proof-of-concept when I fancied writing an RFC for something similar in the language, but I don't think many would find it interesting.

That's a nice feature you added. Yes, I think I'd like to merge that, at some point.

I also need to upgrade the code to support syn version 2.0 (and other dependencies), or it won't be able to parse the new Rust syntax elements. I won't do that in the next coming weeks because I'm full-time on another project. So it's as you wish, but by default, I'll grab the modification from your fork when the time comes, before tackling the 2.0 upgrade. That way, if you still want to modify your code, you won't have to bother with this repository.

I'll update this issue when the time comes.

Thanks!

@blueglyph
Copy link
Owner

I quickly went over the modifications. I'll definitely merge it on my own (and give all the due credits) because I see there's a lot of reformatting that'll make the merge a little tricky and dependencies for the tests that I won't integrate in order to keep the crate as independent as possible (tokio).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants