File size: 2,235 Bytes
7856e60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use std::env;

pub fn clean_database_url(url: &str) -> String {
    let mut cleaned = url.trim().to_string();

    // 1. Strip 'psql ' command prefix if accidentally included
    if cleaned.to_lowercase().starts_with("psql ") {
        cleaned = cleaned[5..].trim().to_string();
    }

    // 2. Strip surrounding quotes (common in shell envs)
    cleaned = cleaned.trim_matches(|c| c == '\'' || c == '"').to_string();

    // 3. Ensure it starts with the correct scheme
    if !cleaned.starts_with("postgres://") && !cleaned.starts_with("postgresql://") {
        tracing::debug!(
            "Database URL scheme missing or malformed, but attempting to clean further..."
        );
    }

    cleaned
}

pub fn database_schema() -> String {
    let schema = env::var("RTIX_DB_SCHEMA")
        .or_else(|_| env::var("INVESA_DB_SCHEMA"))
        .unwrap_or_else(|_| "rtix_app".to_string());
    let is_valid = schema.chars().enumerate().all(|(idx, ch): (usize, char)| {
        ch == '_' || ch.is_ascii_alphanumeric() && (idx > 0 || ch.is_ascii_alphabetic())
    });

    if !is_valid {
        panic!("INVALID_DATABASE_SCHEMA: use only letters, numbers, and underscores, starting with a letter or underscore.");
    }

    schema
}

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

    #[test]
    fn test_clean_database_url() {
        // Standard URL
        assert_eq!(
            clean_database_url("postgresql://user:pass@host/db"),
            "postgresql://user:pass@host/db"
        );

        // Wrapped in psql command
        assert_eq!(
            clean_database_url("psql 'postgresql://user:pass@host/db'"),
            "postgresql://user:pass@host/db"
        );

        // Double quotes
        assert_eq!(
            clean_database_url("psql \"postgresql://user:pass@host/db\""),
            "postgresql://user:pass@host/db"
        );

        // Whitespace and weirdness
        assert_eq!(
            clean_database_url("  psql   'postgresql://user:pass@host/db'  "),
            "postgresql://user:pass@host/db"
        );

        // Naked quotes without psql
        assert_eq!(
            clean_database_url("'postgresql://user:pass@host/db'"),
            "postgresql://user:pass@host/db"
        );
    }
}