Skip to content

Build a migration-cli without DATABASE_URL #3024

@dumindu

Description

@dumindu

Description

I am trying to use own config.rs on migration CLI with following data to match with API configs which has more DB configurations like max_connections, connect_timeout, etc.

Steps to Reproduce

Project structure

└── src
    ├── config.rs
    ├── lib.rs
    ├── m20260301_205220_create_initial_tables.rs
    └── main.rs

main.rs

use sea_orm_migration::prelude::*;

mod config;

#[tokio::main]
async fn main() {
    let conf = config::DbConf::init();
    let connect_options = sea_orm::ConnectOptions::new(conf.to_database_url()).to_owned();

    cli::run_cli_with_connection(migrator::Migrator, |_connect_options| async {
        let db = sea_orm::Database::connect(connect_options).await?;
        Ok(db)
    })
    .await;
}

config.rs

use envconfig::Envconfig;

#[derive(Envconfig)]
pub struct DbConf {
    #[envconfig(from = "DB_PROTOCOL")]
    pub protocol: String,
    #[envconfig(from = "DB_HOST")]
    pub host: String,
    #[envconfig(from = "DB_PORT")]
    pub port: u16,
    #[envconfig(from = "DB_USER")]
    pub user: String,
    #[envconfig(from = "DB_PASS")]
    pub password: String,
    #[envconfig(from = "DB_NAME")]
    pub db_name: String,
}

impl DbConf {
    pub fn init() -> Self {
        Self::init_from_env().expect("Failed to load configuration! Check the .env file.")
    }

    pub fn to_database_url(&self) -> String {
        format!(
            "{}://{}:{}@{}:{}/{}",
            self.protocol, self.user, self.password, self.host, self.port, self.db_name
        )
    }
}

When I run cli with DATABASE_URL it works but when I try without it + own env vars, it panics

Environment variable 'DATABASE_URL' not set

Image

Do I need to register db inside the closure?

Expected Behavior

url should get from connect_options

Actual Behavior

Panic with Environment variable 'DATABASE_URL' not set

Reproduces How Often

Workarounds

Versions

sea-orm-migration = { version = "2.0.0-rc", features = ["runtime-tokio-rustls", "sqlx-postgres"] }

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions