sqltrail-cli 0.1.0

Reusable PostgreSQL schema migration CLI and library: diff declared schema against a live database, generate versioned SQL, apply with a checksum-protected history
Documentation
//! 数据库连接:sqltrail-cli 是唯一允许连接本地 PostgreSQL 的组件。

use anyhow::anyhow;
use tokio_postgres::{Client, NoTls};

/// 建立 PostgreSQL 连接并启动后台接收连接事件。
///
/// # 参数
/// - `database_url`:形如 `postgres://user:password@host:5432/dbname` 的连接串。
pub async fn connect(database_url: &str) -> anyhow::Result<Client> {
    let (client, connection) = tokio_postgres::connect(database_url, NoTls)
        .await
        .map_err(|e| {
            anyhow!(
                "无法连接 PostgreSQL({}):{e}",
                mask_password(database_url)
            )
        })?;

    // 连接事件必须持续被驱动,否则连接会被关闭
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("PostgreSQL 连接异常: {e}");
        }
    });
    Ok(client)
}

/// 脱敏连接串,避免在错误信息中泄露密码。
/// `postgres://user:pass@host:5432/db` → `postgres://user:***@host:5432/db`
fn mask_password(url: &str) -> String {
    let Some(scheme_end) = url.find("://") else {
        return url.to_string();
    };
    let rest = &url[scheme_end + 3..];
    let Some(at) = rest.rfind('@') else {
        return url.to_string();
    };
    let userinfo = &rest[..at];
    let Some(colon) = userinfo.rfind(':') else {
        return url.to_string();
    };
    format!(
        "{}://{}:***@{}",
        &url[..scheme_end],
        &userinfo[..colon],
        &rest[at + 1..]
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn 密码脱敏() {
        assert_eq!(
            mask_password("postgres://alice:s3cret@db.local:5432/cip"),
            "postgres://alice:***@db.local:5432/cip"
        );
        assert_eq!(
            mask_password("postgres://alice@db.local/cip"),
            "postgres://alice@db.local/cip"
        );
    }
}