|
1 | 1 | use std::env::var;
|
2 |
| -use std::fmt::Display; |
| 2 | +use std::fmt::{Display, Write}; |
3 | 3 | use std::path::{Path, PathBuf};
|
4 | 4 |
|
5 | 5 | mod connect;
|
@@ -351,15 +351,14 @@ impl PgConnectOptions {
|
351 | 351 | V: Display,
|
352 | 352 | I: IntoIterator<Item = (K, V)>,
|
353 | 353 | {
|
354 |
| - let mut options_str = String::new(); |
| 354 | + // Do this in here so `options_str` is only set if we have an option to insert |
| 355 | + let options_str = self.options.get_or_insert_with(String::new); |
355 | 356 | for (k, v) in options {
|
356 |
| - options_str += &format!("-c {}={}", k, v); |
357 |
| - } |
358 |
| - if let Some(ref mut v) = self.options { |
359 |
| - v.push(' '); |
360 |
| - v.push_str(&options_str); |
361 |
| - } else { |
362 |
| - self.options = Some(options_str); |
| 357 | + if !options_str.is_empty() { |
| 358 | + options_str.push(' '); |
| 359 | + } |
| 360 | + |
| 361 | + write!(options_str, "-c {}={}", k, v).expect("failed to write an option to the string"); |
363 | 362 | }
|
364 | 363 | self
|
365 | 364 | }
|
@@ -399,3 +398,21 @@ fn default_host(port: u16) -> String {
|
399 | 398 | // fallback to localhost if no socket was found
|
400 | 399 | "localhost".to_owned()
|
401 | 400 | }
|
| 401 | + |
| 402 | +#[test] |
| 403 | +fn test_options_formatting() { |
| 404 | + let options = PgConnectOptions::new().options([("geqo", "off")]); |
| 405 | + assert_eq!(options.options, Some("-c geqo=off".to_string())); |
| 406 | + let options = options.options([("search_path", "sqlx")]); |
| 407 | + assert_eq!( |
| 408 | + options.options, |
| 409 | + Some("-c geqo=off -c search_path=sqlx".to_string()) |
| 410 | + ); |
| 411 | + let options = PgConnectOptions::new().options([("geqo", "off"), ("statement_timeout", "5min")]); |
| 412 | + assert_eq!( |
| 413 | + options.options, |
| 414 | + Some("-c geqo=off -c statement_timeout=5min".to_string()) |
| 415 | + ); |
| 416 | + let options = PgConnectOptions::new(); |
| 417 | + assert_eq!(options.options, None); |
| 418 | +} |
0 commit comments