use clap::{Parser, Subcommand};
use env_logger::Env;
use pgmq::install::Version;
use pgmq::PgmqError;
use sqlx::PgPool;
use url::Url;
#[derive(Debug, Parser)]
#[clap(author, version, about = "PGMQ CLI tool for installing and managing PostgreSQL message queues", long_about = None)]
struct Arguments {
#[clap(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
Install(InstallArgs),
}
#[derive(Debug, Parser)]
struct InstallArgs {
#[clap(short = 'd')]
database_url: Option<Url>,
#[command(subcommand)]
command: InstallCommands,
}
#[derive(Debug, Subcommand)]
enum InstallCommands {
InitMigrationsTable(InitMigrationsTableArgs),
InstalledVersion,
InstallFromGithub(InstallFromGithubArgs),
InstallFromEmbedded,
}
#[derive(Debug, Parser)]
struct InitMigrationsTableArgs {
#[clap(short = 'v')]
version: Version,
}
#[derive(Debug, Parser)]
struct InstallFromGithubArgs {
#[clap(short = 'v')]
version: Option<String>,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), PgmqError> {
let log_env = Env::default().filter_or("RUST_LOG", "info");
env_logger::init_from_env(log_env);
let args = Arguments::parse();
match args.command {
Commands::Install(args) => {
let db_url = args.database_url.unwrap_or_else(|| {
Url::parse(
&std::env::var("DATABASE_URL")
.expect("Unable to read DATABASE_URL environment variable"),
)
.expect("Unable to parse DATABASE_URL environment variable")
});
let pool = PgPool::connect(db_url.as_str())
.await
.expect("Failed to connect to database");
match args.command {
InstallCommands::InitMigrationsTable(args) => {
pgmq::install::init_migrations_table(&pool, args.version).await?;
}
InstallCommands::InstalledVersion => {
let version = pgmq::install::installed_version(&pool).await?;
if let Some(version) = version {
log::info!("Installed version: {version}");
} else {
log::info!("PGMQ is not currently installed, or was not installed using a versioned SQL-only installation method.");
}
}
InstallCommands::InstallFromGithub(args) => {
pgmq::install::install_sql_from_github(&pool, args.version.as_deref()).await?;
}
InstallCommands::InstallFromEmbedded => {
pgmq::install::install_sql_from_embedded(&pool).await?;
}
}
}
}
Ok(())
}