footing 0.5.3

Feature-gated foundations for Rust backend services
Documentation
use uuid::Uuid;

use super::TestkitError;

#[must_use]
/// Reads the test database URL from `DATABASE_URL`.
pub fn database_url_from_env() -> Option<String> {
    std::env::var("DATABASE_URL")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

#[must_use]
/// Generates a unique database name within PostgreSQL's default 63-byte limit.
/// The prefix is truncated on a UTF-8 boundary, preserving the full UUID suffix.
pub fn unique_database_name(prefix: &str) -> String {
    let prefix = prefix.trim().trim_matches('_');
    let prefix = if prefix.is_empty() { "test" } else { prefix };
    let prefix = &prefix[..prefix.floor_char_boundary(30)];
    format!("{prefix}_{}", Uuid::now_v7().simple())
}

/// Replaces the database name in a PostgreSQL URL.
/// Preserves connection options and encodes ordinary names as one path segment.
/// Dot-only names and opaque URLs such as `postgres:app` use `dbname`. Existing
/// `dbname` options are replaced so they cannot select the original database.
/// Invalid URLs or names return an error instead of the original address.
/// Names must contain non-whitespace text, have no control characters, and fit
/// PostgreSQL's default 63-byte identifier limit.
///
/// ```rust
/// use footing::testkit::postgres::database_url_with_name;
///
/// let url = database_url_with_name("postgres:production", "isolated_test")?;
/// assert_eq!(footing::db::postgres::database_name(&url).as_deref(), Some("isolated_test"));
/// # Ok::<(), footing::testkit::TestkitError>(())
/// ```
pub fn database_url_with_name(base_url: &str, database_name: &str) -> Result<String, TestkitError> {
    if database_name.trim().is_empty()
        || database_name.len() > 63
        || database_name.chars().any(char::is_control)
    {
        return Err(TestkitError::InvalidDatabaseName);
    }
    let mut url = url::Url::parse(base_url).map_err(|_| TestkitError::InvalidPostgresUrl)?;
    if !matches!(url.scheme(), "postgres" | "postgresql") {
        return Err(TestkitError::InvalidPostgresUrl);
    }
    let path_replaced = if let Ok(mut segments) = url.path_segments_mut() {
        segments.clear().push(database_name);
        true
    } else {
        false
    };
    if !path_replaced
        || matches!(database_name, "." | "..")
        || url.query_pairs().any(|(key, _)| key == "dbname")
    {
        let options = url
            .query_pairs()
            .filter(|(key, _)| key != "dbname")
            .map(|(key, value)| (key.into_owned(), value.into_owned()))
            .collect::<Vec<_>>();
        url.query_pairs_mut()
            .clear()
            .extend_pairs(options)
            .append_pair("dbname", database_name);
    }
    // Apply the connection URL safety boundary even when the caller passes the
    // result directly to SQLx instead of Footing's connection helpers.
    if crate::db::postgres::database_name(url.as_str()).as_deref() != Some(database_name) {
        return Err(TestkitError::InvalidPostgresUrl);
    }
    Ok(url.into())
}

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

    #[test]
    fn generated_database_names_preserve_uuid_with_long_unicode_prefixes() {
        for prefix in [
            "postgres_schema_migration_integration_test",
            "postgres_schema_migration_integration_test_with_a_prefix_exceeding_sixty_three_bytes",
            "数据库测试数据库测试数据库测试",
            "测试🦀test🦀test🦀test🦀test🦀",
            "",
        ] {
            let name = unique_database_name(prefix);
            assert!(name.len() <= 63);
            let (prefix, suffix) = name.rsplit_once('_').unwrap();
            assert!(!prefix.is_empty());
            assert_eq!(suffix.len(), 32);
            assert_eq!(Uuid::parse_str(suffix).unwrap().get_version_num(), 7);
            assert_ne!(name, unique_database_name(prefix));
        }
    }
}