Skip to main content

parse

Function parse 

Source
pub fn parse(input: &str) -> Result<DSN, ParseError>
Expand description

Parse a DSN string into a structured DSN object

This function parses a Data Source Name (DSN) string and extracts all components including driver, credentials, protocol, address, database name, and parameters.

§Arguments

  • input - A DSN string in the format: driver://username:password@protocol(address)/database?param=value

§Returns

Returns a Result containing the parsed DSN struct on success, or a ParseError if the DSN string is malformed.

§Errors

Returns ParseError in the following cases:

  • InvalidDriver - Missing or invalid driver name
  • InvalidProtocol - Missing or invalid protocol
  • InvalidSocket - Unix socket path doesn’t start with /
  • InvalidPath - File path is not absolute
  • InvalidPort - Port number is invalid or out of range (0-65535)
  • MissingAddress - Address is missing after protocol
  • MissingHost - Host is missing in TCP/UDP address
  • InvalidParams - Query parameters are malformed
  • Utf8Error - Percent-encoded credentials contain invalid UTF-8

§Examples

Basic TCP connection:

use dsn::parse;

let dsn = parse(r#"mysql://user:o%3Ao@tcp(localhost:3306)/database?charset=utf8"#).unwrap();
assert_eq!(dsn.driver, "mysql");
assert_eq!(dsn.username.unwrap(), "user");
assert_eq!(dsn.password.unwrap(), "o:o");
assert_eq!(dsn.protocol, "tcp");
assert_eq!(dsn.address, "localhost:3306");
assert_eq!(dsn.host.unwrap(), "localhost");
assert_eq!(dsn.port.unwrap(), 3306);
assert_eq!(dsn.database.unwrap(), "database");
assert_eq!(dsn.socket, None);
assert!(!dsn.params.is_empty());
assert_eq!(dsn.params.get("charset").unwrap(), "utf8");

Unix socket connection:

use dsn::parse;

let dsn = parse(r"mysql://user@unix(/var/run/mysql.sock)/mydb").unwrap();
assert_eq!(dsn.protocol, "unix");
assert_eq!(dsn.socket.unwrap(), "/var/run/mysql.sock");
Examples found in repository?
examples/postgres_ssl.rs (line 53)
7fn main() {
8    println!("=== PostgreSQL SSL Mode Examples ===\n");
9
10    // Building DSNs with different SSL modes
11    println!("1. Building PostgreSQL DSNs:\n");
12
13    let ssl_require = DSNBuilder::postgres()
14        .username("app")
15        .password("secret")
16        .host("prod.postgres.com")
17        .database("app_db")
18        .param("sslmode", "require")
19        .build();
20    println!("   Production (SSL required):");
21    println!("   {ssl_require}\n");
22
23    let ssl_prefer = DSNBuilder::postgres()
24        .username("app")
25        .password("secret")
26        .host("staging.postgres.com")
27        .database("app_db")
28        .param("sslmode", "prefer")
29        .build();
30    println!("   Staging (SSL preferred):");
31    println!("   {ssl_prefer}\n");
32
33    let ssl_disable = DSNBuilder::postgres()
34        .username("dev")
35        .password("dev123")
36        .host("localhost")
37        .database("dev_db")
38        .param("sslmode", "disable")
39        .build();
40    println!("   Development (SSL disabled):");
41    println!("   {ssl_disable}\n");
42
43    // Parsing and checking SSL mode
44    println!("2. Parsing PostgreSQL DSN and checking SSL mode:\n");
45
46    let examples = [
47        "postgres://user:pass@tcp(localhost:5432)/mydb?sslmode=disable",
48        "postgres://user:pass@tcp(prod.db.com:5432)/mydb?sslmode=require",
49        "postgres://user:pass@tcp(stage.db.com:5432)/mydb?sslmode=prefer&connect_timeout=10",
50    ];
51
52    for dsn_str in examples {
53        match parse(dsn_str) {
54            Ok(dsn) => {
55                println!("   DSN: {dsn_str}");
56                println!("   Host: {}", dsn.host.as_ref().unwrap());
57                println!("   Database: {}", dsn.database.as_ref().unwrap());
58
59                if let Some(sslmode) = dsn.params.get("sslmode") {
60                    println!("   SSL Mode: {sslmode}");
61
62                    match sslmode.as_str() {
63                        "disable" => {
64                            println!(
65                                "   [WARNING] SSL is disabled - not recommended for production!"
66                            );
67                        }
68                        "require" => println!("   [OK] SSL is required - secure connection"),
69                        "prefer" => println!("   [INFO] SSL is preferred - will use if available"),
70                        "verify-ca" => println!("   [SECURE] SSL with CA verification"),
71                        "verify-full" => println!("   [SECURE] SSL with full verification"),
72                        _ => println!("   [UNKNOWN] Unknown SSL mode: {sslmode}"),
73                    }
74                } else {
75                    println!("   [INFO] No SSL mode specified (will use PostgreSQL default)");
76                }
77
78                // Check for other connection parameters
79                if let Some(timeout) = dsn.params.get("connect_timeout") {
80                    println!("   Connection timeout: {timeout}s");
81                }
82
83                println!();
84            }
85            Err(e) => {
86                eprintln!("   [ERROR] Failed to parse: {e}");
87            }
88        }
89    }
90
91    // Practical usage example
92    println!("3. Practical usage - connection string selection:\n");
93
94    let environment = std::env::var("ENVIRONMENT").unwrap_or_else(|_| "development".to_string());
95
96    let dsn = match environment.as_str() {
97        "production" => DSNBuilder::postgres()
98            .username("prod_user")
99            .password("prod_pass")
100            .host("prod.postgres.com")
101            .database("prod_db")
102            .param("sslmode", "require")
103            .param("connect_timeout", "30")
104            .build(),
105
106        "staging" => DSNBuilder::postgres()
107            .username("stage_user")
108            .password("stage_pass")
109            .host("staging.postgres.com")
110            .database("stage_db")
111            .param("sslmode", "prefer")
112            .param("connect_timeout", "10")
113            .build(),
114
115        _ => DSNBuilder::postgres()
116            .username("dev")
117            .password("dev")
118            .host("localhost")
119            .database("dev_db")
120            .param("sslmode", "disable")
121            .build(),
122    };
123
124    println!("   Environment: {environment}");
125    println!("   Connection string: {dsn}");
126}