SeaQL / sea-orm

🐚 An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
7.3k stars 513 forks source link

Use `file!` in migration files #705

Closed tyt2y3 closed 2 years ago

tyt2y3 commented 2 years ago

https://github.com/SeaQL/sea-orm/blob/cdc70f4fd97e520d2b7a3b3052cc868532eca4d1/examples/actix_example/migration/src/m20220120_000001_create_post_table.rs#L6-L10

Can we use https://doc.rust-lang.org/std/macro.file.html instead of manually copying the name?

We'd probably want to change the migration template too

smonv commented 2 years ago

I did some testing and found out file!() return full filename with extension. So in order to use, we need extra step to remove the extension part too.

So I'm not sure it worth the effort to change for template, the string already generated by cli.

tyt2y3 commented 2 years ago

I imagine we can use a compile time const fn to split out the file name. I think this will reduce confusion when files got renamed.

billy1624 commented 2 years ago

This is doable. I guess we can introduce a derive for Migration struct.

pub struct Migration;

impl MigrationName for Migration {
    fn name(&self) -> &str {
        std::path::Path::new(file!())
            .file_stem()
            .map(|f| f.to_str().unwrap())
            .unwrap()
    }
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    ...
}
lpotthast commented 2 years ago

I usually do the following:

In all migration files, include:

crate::migration_file!();

I defined the macro like this:

#[macro_export]
macro_rules! migration_file {
    () => {
        pub struct Migration;
        impl MigrationName for Migration {
            fn name(&self) -> &str {
                std::path::Path::new(file!())
                    .file_name()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .split(".")
                    .next()
                    .unwrap()
            }
        }
    };
}
tyt2y3 commented 2 years ago

Thanks. This is quite neat!