Skip to content

Commit dfd9cf5

Browse files
liushuyuabonander
andauthored
fix(postgres): fix option passing logic (#1731)
Co-authored-by: Austin Bonander <[email protected]> Co-authored-by: Austin Bonander <[email protected]>
1 parent 5b85a03 commit dfd9cf5

File tree

1 file changed

+26
-9
lines changed
  • sqlx-core/src/postgres/options

1 file changed

+26
-9
lines changed

sqlx-core/src/postgres/options/mod.rs

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::env::var;
2-
use std::fmt::Display;
2+
use std::fmt::{Display, Write};
33
use std::path::{Path, PathBuf};
44

55
mod connect;
@@ -351,15 +351,14 @@ impl PgConnectOptions {
351351
V: Display,
352352
I: IntoIterator<Item = (K, V)>,
353353
{
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);
355356
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");
363362
}
364363
self
365364
}
@@ -399,3 +398,21 @@ fn default_host(port: u16) -> String {
399398
// fallback to localhost if no socket was found
400399
"localhost".to_owned()
401400
}
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

Comments
 (0)