athena_rs 0.82.2

Database gateway API
Documentation
//! Retrieves the `X-JDBC-URL` header for direct Postgres connection.
//!
//! When present, the gateway can connect directly to a database instead of using
//! a pre-configured `X-Athena-Client`. Accepts JDBC-style URLs
//! (`jdbc:postgresql://...`) and converts them to the `postgres://` format used by sqlx.

use actix_web::HttpRequest;

/// Extracts the JDBC URL from the request, if present.
/// Supports both `X-JDBC-URL` and `x-jdbc-url` (case-insensitive).
pub fn x_jdbc_url(req: &HttpRequest) -> Option<String> {
    req.headers()
        .get("X-JDBC-URL")
        .or_else(|| req.headers().get("x-jdbc-url"))
        .and_then(|h| h.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// Converts a JDBC PostgreSQL URL to the postgres:// format expected by sqlx.
///
/// Handles:
/// - `jdbc:postgresql://host:port/database` → `postgres://host:port/database`
/// - `jdbc:postgresql://user:pass@host:port/database` → `postgres://user:pass@host:port/database`
/// - Query parameters (user, password, sslmode, etc.) are preserved.
pub fn jdbc_to_postgres_url(jdbc_url: &str) -> Option<String> {
    let trimmed = jdbc_url.trim();
    if trimmed.starts_with("jdbc:postgresql://") {
        Some(trimmed.replacen("jdbc:postgresql://", "postgres://", 1))
    } else if trimmed.starts_with("postgres://") || trimmed.starts_with("postgresql://") {
        Some(trimmed.to_string())
    } else {
        None
    }
}

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

    #[test]
    fn test_jdbc_to_postgres_url() {
        assert_eq!(
            jdbc_to_postgres_url("jdbc:postgresql://localhost:5432/mydb"),
            Some("postgres://localhost:5432/mydb".to_string())
        );
        assert_eq!(
            jdbc_to_postgres_url("jdbc:postgresql://user:pass@host/db"),
            Some("postgres://user:pass@host/db".to_string())
        );
        assert_eq!(
            jdbc_to_postgres_url("postgres://localhost/db"),
            Some("postgres://localhost/db".to_string())
        );
        assert_eq!(jdbc_to_postgres_url("jdbc:mysql://localhost/db"), None);
    }
}