sqlx_postgres/options/mod.rs
1use std::borrow::Cow;
2use std::env::var;
3use std::fmt::{self, Display, Write};
4use std::net::IpAddr;
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, OnceLock};
7
8use sqlx_core::net::tls::TlsConnector;
9use sqlx_core::net::UrlHost;
10pub use ssl_mode::PgSslMode;
11
12use crate::{connection::LogSettings, net::tls::CertificateInput};
13
14mod connect;
15mod parse;
16mod pgpass;
17mod ssl_mode;
18
19#[doc = include_str!("doc.md")]
20#[derive(Debug, Clone)]
21pub struct PgConnectOptions {
22 pub(crate) host: UrlHost,
23 pub(crate) port: u16,
24 pub(crate) hostaddr: Option<IpAddr>,
25 pub(crate) socket: Option<PathBuf>,
26 pub(crate) username: String,
27 pub(crate) password: Option<String>,
28 pub(crate) database: Option<String>,
29 pub(crate) ssl_options: SslOptions,
30 pub(crate) statement_cache_capacity: usize,
31 pub(crate) application_name: Option<String>,
32 pub(crate) log_settings: LogSettings,
33 pub(crate) extra_float_digits: Option<Cow<'static, str>>,
34 pub(crate) options: Option<String>,
35}
36
37impl Default for PgConnectOptions {
38 fn default() -> Self {
39 Self::new_without_pgpass().apply_pgpass()
40 }
41}
42
43#[derive(Debug, Clone)]
44pub(crate) struct SslOptions {
45 pub(crate) ssl_mode: PgSslMode,
46 pub(crate) ssl_root_cert: Option<CertificateInput>,
47 pub(crate) ssl_client_cert: Option<CertificateInput>,
48 pub(crate) ssl_client_key: Option<CertificateInput>,
49 pub(crate) cached_connector: Arc<OnceLock<TlsConnector>>,
50}
51
52impl PgConnectOptions {
53 /// Create a default set of connection options populated from the current environment.
54 ///
55 /// This behaves as if parsed from the connection string `postgres://`
56 ///
57 /// See the type-level documentation for details.
58 pub fn new() -> Self {
59 Self::new_without_pgpass().apply_pgpass()
60 }
61
62 /// Create a default set of connection options _without_ reading from `passfile`.
63 ///
64 /// Equivalent to [`PgConnectOptions::new()`] but `passfile` is ignored.
65 ///
66 /// See the type-level documentation for details.
67 pub fn new_without_pgpass() -> Self {
68 let port = var("PGPORT")
69 .ok()
70 .and_then(|v| v.parse().ok())
71 .unwrap_or(5432);
72
73 let host = var("PGHOST").ok().unwrap_or_else(|| default_host(port));
74
75 let username = if let Ok(username) = var("PGUSER") {
76 username
77 } else if let Ok(username) = whoami::username() {
78 username
79 } else {
80 // keep the same fallback as previous version
81 "unknown".to_string()
82 };
83
84 let database = var("PGDATABASE").ok();
85
86 PgConnectOptions {
87 port,
88 host: host.into(),
89 hostaddr: var("PGHOSTADDR")
90 .ok()
91 .and_then(|hostaddr| hostaddr.parse().ok()),
92 socket: None,
93 username,
94 password: var("PGPASSWORD").ok(),
95 database,
96 ssl_options: SslOptions {
97 ssl_root_cert: var("PGSSLROOTCERT").ok().map(CertificateInput::from),
98 ssl_client_cert: var("PGSSLCERT").ok().map(CertificateInput::from),
99 // As of writing, the implementation of `From<String>` only looks for
100 // `-----BEGIN CERTIFICATE-----` and so will not attempt to parse
101 // a PEM-encoded private key.
102 ssl_client_key: var("PGSSLKEY").ok().map(CertificateInput::from),
103 ssl_mode: var("PGSSLMODE")
104 .ok()
105 .and_then(|v| v.parse().ok())
106 .unwrap_or_default(),
107 cached_connector: Arc::new(OnceLock::new()),
108 },
109 statement_cache_capacity: 100,
110 application_name: var("PGAPPNAME").ok(),
111 extra_float_digits: Some("2".into()),
112 log_settings: Default::default(),
113 options: var("PGOPTIONS").ok(),
114 }
115 }
116
117 pub(crate) fn apply_pgpass(mut self) -> Self {
118 if self.password.is_none() {
119 self.password = pgpass::load_password(
120 self.host.original(),
121 self.port,
122 &self.username,
123 self.database.as_deref(),
124 );
125 }
126
127 self
128 }
129
130 /// Sets the name of the host to connect to.
131 ///
132 /// If a host name begins with a slash, it specifies
133 /// Unix-domain communication rather than TCP/IP communication; the value is the name of
134 /// the directory in which the socket file is stored.
135 ///
136 /// The default behavior when host is not specified, or is empty,
137 /// is to connect to a Unix-domain socket
138 ///
139 /// # Example
140 ///
141 /// ```rust
142 /// # use sqlx_postgres::PgConnectOptions;
143 /// let options = PgConnectOptions::new()
144 /// .host("localhost");
145 /// ```
146 pub fn host(mut self, host: &str) -> Self {
147 self.host.set(host);
148 self
149 }
150
151 /// Sets the port to connect to at the server host.
152 ///
153 /// The default port for PostgreSQL is `5432`.
154 ///
155 /// # Example
156 ///
157 /// ```rust
158 /// # use sqlx_postgres::PgConnectOptions;
159 /// let options = PgConnectOptions::new()
160 /// .port(5432);
161 /// ```
162 pub fn port(mut self, port: u16) -> Self {
163 self.port = port;
164 self
165 }
166
167 /// Override hostname resolution with a preset IP address.
168 ///
169 /// [`Self::host()`] is still used for TLS server name identification (SNI) if
170 /// [`Self::ssl_mode()`] is [`PgSslMode::VerifyFull`].
171 ///
172 /// This avoids DNS lookup overhead if the server IP is already known,
173 /// allows connecting to a host through a proxy,
174 /// or allows using SNI when connecting to a host that is not listed in DNS.
175 ///
176 /// Defaults to `None`.
177 ///
178 /// Has no effect if [`Self::socket()`] is set.
179 pub fn hostaddr(mut self, hostaddr: impl Into<IpAddr>) -> Self {
180 self.hostaddr = Some(hostaddr.into());
181 self
182 }
183
184 /// Sets a custom path to a directory containing a unix domain socket,
185 /// switching the connection method from TCP to the corresponding socket.
186 ///
187 /// By default set to `None`.
188 pub fn socket(mut self, path: impl AsRef<Path>) -> Self {
189 self.socket = Some(path.as_ref().to_path_buf());
190 self
191 }
192
193 /// Sets the username to connect as.
194 ///
195 /// Defaults to be the same as the operating system name of
196 /// the user running the application.
197 ///
198 /// # Example
199 ///
200 /// ```rust
201 /// # use sqlx_postgres::PgConnectOptions;
202 /// let options = PgConnectOptions::new()
203 /// .username("postgres");
204 /// ```
205 pub fn username(mut self, username: &str) -> Self {
206 username.clone_into(&mut self.username);
207 self
208 }
209
210 /// Sets the password to use if the server demands password authentication.
211 ///
212 /// # Example
213 ///
214 /// ```rust
215 /// # use sqlx_postgres::PgConnectOptions;
216 /// let options = PgConnectOptions::new()
217 /// .username("root")
218 /// .password("safe-and-secure");
219 /// ```
220 pub fn password(mut self, password: &str) -> Self {
221 self.password = Some(password.to_owned());
222 self
223 }
224
225 /// Sets the database name. Defaults to be the same as the user name.
226 ///
227 /// # Example
228 ///
229 /// ```rust
230 /// # use sqlx_postgres::PgConnectOptions;
231 /// let options = PgConnectOptions::new()
232 /// .database("postgres");
233 /// ```
234 pub fn database(mut self, database: &str) -> Self {
235 self.database = Some(database.to_owned());
236 self
237 }
238
239 fn ssl_options_mut(&mut self) -> &mut SslOptions {
240 Arc::make_mut(&mut self.ssl_options.cached_connector).take();
241 &mut self.ssl_options
242 }
243
244 /// Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated
245 /// with the server.
246 ///
247 /// By default, the SSL mode is [`Prefer`](PgSslMode::Prefer), and the client will
248 /// first attempt an SSL connection but fallback to a non-SSL connection on failure.
249 ///
250 /// Ignored for Unix domain socket communication.
251 ///
252 /// # Example
253 ///
254 /// ```rust
255 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
256 /// let options = PgConnectOptions::new()
257 /// .ssl_mode(PgSslMode::Require);
258 /// ```
259 pub fn ssl_mode(mut self, mode: PgSslMode) -> Self {
260 self.ssl_options_mut().ssl_mode = mode;
261 self
262 }
263
264 /// Sets the name of a file containing SSL certificate authority (CA) certificate(s).
265 /// If the file exists, the server's certificate will be verified to be signed by
266 /// one of these authorities.
267 ///
268 /// # Example
269 ///
270 /// ```rust
271 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
272 /// let options = PgConnectOptions::new()
273 /// // Providing a CA certificate with less than VerifyCa is pointless
274 /// .ssl_mode(PgSslMode::VerifyCa)
275 /// .ssl_root_cert("./ca-certificate.crt");
276 /// ```
277 pub fn ssl_root_cert(mut self, cert: impl AsRef<Path>) -> Self {
278 self.ssl_options_mut().ssl_root_cert =
279 Some(CertificateInput::File(cert.as_ref().to_path_buf()));
280 self
281 }
282
283 /// Sets the name of a file containing SSL client certificate.
284 ///
285 /// # Example
286 ///
287 /// ```rust
288 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
289 /// let options = PgConnectOptions::new()
290 /// // Providing a CA certificate with less than VerifyCa is pointless
291 /// .ssl_mode(PgSslMode::VerifyCa)
292 /// .ssl_client_cert("./client.crt");
293 /// ```
294 pub fn ssl_client_cert(mut self, cert: impl AsRef<Path>) -> Self {
295 self.ssl_options_mut().ssl_client_cert =
296 Some(CertificateInput::File(cert.as_ref().to_path_buf()));
297 self
298 }
299
300 /// Sets the SSL client certificate as a PEM-encoded byte slice.
301 ///
302 /// This should be an ASCII-encoded blob that starts with `-----BEGIN CERTIFICATE-----`.
303 ///
304 /// # Example
305 /// Note: embedding SSL certificates and keys in the binary is not advised.
306 /// This is for illustration purposes only.
307 ///
308 /// ```rust
309 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
310 ///
311 /// const CERT: &[u8] = b"\
312 /// -----BEGIN CERTIFICATE-----
313 /// <Certificate data here.>
314 /// -----END CERTIFICATE-----";
315 ///
316 /// let options = PgConnectOptions::new()
317 /// // Providing a CA certificate with less than VerifyCa is pointless
318 /// .ssl_mode(PgSslMode::VerifyCa)
319 /// .ssl_client_cert_from_pem(CERT);
320 /// ```
321 pub fn ssl_client_cert_from_pem(mut self, cert: impl AsRef<[u8]>) -> Self {
322 self.ssl_options_mut().ssl_client_cert =
323 Some(CertificateInput::Inline(cert.as_ref().to_vec()));
324 self
325 }
326
327 /// Sets the name of a file containing SSL client key.
328 ///
329 /// # Example
330 ///
331 /// ```rust
332 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
333 /// let options = PgConnectOptions::new()
334 /// // Providing a CA certificate with less than VerifyCa is pointless
335 /// .ssl_mode(PgSslMode::VerifyCa)
336 /// .ssl_client_key("./client.key");
337 /// ```
338 pub fn ssl_client_key(mut self, key: impl AsRef<Path>) -> Self {
339 self.ssl_options_mut().ssl_client_key =
340 Some(CertificateInput::File(key.as_ref().to_path_buf()));
341 self
342 }
343
344 /// Sets the SSL client key as a PEM-encoded byte slice.
345 ///
346 /// This should be an ASCII-encoded blob that starts with `-----BEGIN PRIVATE KEY-----`.
347 ///
348 /// # Example
349 /// Note: embedding SSL certificates and keys in the binary is not advised.
350 /// This is for illustration purposes only.
351 ///
352 /// ```rust
353 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
354 ///
355 /// const KEY: &[u8] = b"\
356 /// -----BEGIN PRIVATE KEY-----
357 /// <Private key data here.>
358 /// -----END PRIVATE KEY-----";
359 ///
360 /// let options = PgConnectOptions::new()
361 /// // Providing a CA certificate with less than VerifyCa is pointless
362 /// .ssl_mode(PgSslMode::VerifyCa)
363 /// .ssl_client_key_from_pem(KEY);
364 /// ```
365 pub fn ssl_client_key_from_pem(mut self, key: impl AsRef<[u8]>) -> Self {
366 self.ssl_options_mut().ssl_client_key =
367 Some(CertificateInput::Inline(key.as_ref().to_vec()));
368 self
369 }
370
371 /// Sets PEM encoded trusted SSL Certificate Authorities (CA).
372 ///
373 /// # Example
374 ///
375 /// ```rust
376 /// # use sqlx_postgres::{PgSslMode, PgConnectOptions};
377 /// let options = PgConnectOptions::new()
378 /// // Providing a CA certificate with less than VerifyCa is pointless
379 /// .ssl_mode(PgSslMode::VerifyCa)
380 /// .ssl_root_cert_from_pem(vec![]);
381 /// ```
382 pub fn ssl_root_cert_from_pem(mut self, pem_certificate: Vec<u8>) -> Self {
383 self.ssl_options_mut().ssl_root_cert = Some(CertificateInput::Inline(pem_certificate));
384 self
385 }
386
387 /// Sets the capacity of the connection's statement cache in a number of stored
388 /// distinct statements. Caching is handled using LRU, meaning when the
389 /// amount of queries hits the defined limit, the oldest statement will get
390 /// dropped.
391 ///
392 /// The default cache capacity is 100 statements.
393 pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
394 self.statement_cache_capacity = capacity;
395 self
396 }
397
398 /// Sets the application name. Defaults to None
399 ///
400 /// # Example
401 ///
402 /// ```rust
403 /// # use sqlx_postgres::PgConnectOptions;
404 /// let options = PgConnectOptions::new()
405 /// .application_name("my-app");
406 /// ```
407 pub fn application_name(mut self, application_name: &str) -> Self {
408 self.application_name = Some(application_name.to_owned());
409 self
410 }
411
412 /// Sets or removes the `extra_float_digits` connection option.
413 ///
414 /// This changes the default precision of floating-point values returned in text mode (when
415 /// not using prepared statements such as calling methods of [`Executor`] directly).
416 ///
417 /// Historically, Postgres would by default round floating-point values to 6 and 15 digits
418 /// for `float4`/`REAL` (`f32`) and `float8`/`DOUBLE` (`f64`), respectively, which would mean
419 /// that the returned value may not be exactly the same as its representation in Postgres.
420 ///
421 /// The nominal range for this value is `-15` to `3`, where negative values for this option
422 /// cause floating-points to be rounded to that many fewer digits than normal (`-1` causes
423 /// `float4` to be rounded to 5 digits instead of six, or 14 instead of 15 for `float8`),
424 /// positive values cause Postgres to emit that many extra digits of precision over default
425 /// (or simply use maximum precision in Postgres 12 and later),
426 /// and 0 means keep the default behavior (or the "old" behavior described above
427 /// as of Postgres 12).
428 ///
429 /// SQLx sets this value to 3 by default, which tells Postgres to return floating-point values
430 /// at their maximum precision in the hope that the parsed value will be identical to its
431 /// counterpart in Postgres. This is also the default in Postgres 12 and later anyway.
432 ///
433 /// However, older versions of Postgres and alternative implementations that talk the Postgres
434 /// protocol may not support this option, or the full range of values.
435 ///
436 /// If you get an error like "unknown option `extra_float_digits`" when connecting, try
437 /// setting this to `None` or consult the manual of your database for the allowed range
438 /// of values.
439 ///
440 /// For more information, see:
441 /// * [Postgres manual, 20.11.2: Client Connection Defaults; Locale and Formatting][20.11.2]
442 /// * [Postgres manual, 8.1.3: Numeric Types; Floating-point Types][8.1.3]
443 ///
444 /// [`Executor`]: crate::executor::Executor
445 /// [20.11.2]: https://www.postgresql.org/docs/current/runtime-config-client.html#RUNTIME-CONFIG-CLIENT-FORMAT
446 /// [8.1.3]: https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-FLOAT
447 ///
448 /// ### Examples
449 /// ```rust
450 /// # use sqlx_postgres::PgConnectOptions;
451 ///
452 /// let mut options = PgConnectOptions::new()
453 /// // for Redshift and Postgres 10
454 /// .extra_float_digits(2);
455 ///
456 /// let mut options = PgConnectOptions::new()
457 /// // don't send the option at all (Postgres 9 and older)
458 /// .extra_float_digits(None);
459 /// ```
460 pub fn extra_float_digits(mut self, extra_float_digits: impl Into<Option<i8>>) -> Self {
461 self.extra_float_digits = extra_float_digits.into().map(|it| it.to_string().into());
462 self
463 }
464
465 /// Set additional startup options for the connection as a list of key-value pairs.
466 ///
467 /// Escapes the options’ backslash and space characters as per
468 /// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
469 ///
470 /// # Example
471 ///
472 /// ```rust
473 /// # use sqlx_postgres::PgConnectOptions;
474 /// let options = PgConnectOptions::new()
475 /// .options([("geqo", "off"), ("statement_timeout", "5min")]);
476 /// ```
477 pub fn options<K, V, I>(mut self, options: I) -> Self
478 where
479 K: Display,
480 V: Display,
481 I: IntoIterator<Item = (K, V)>,
482 {
483 // Do this in here so `options_str` is only set if we have an option to insert
484 let options_str = self.options.get_or_insert_with(String::new);
485 for (k, v) in options {
486 if !options_str.is_empty() {
487 options_str.push(' ');
488 }
489
490 options_str.push_str("-c ");
491 write!(PgOptionsWriteEscaped(options_str), "{k}={v}").ok();
492 }
493 self
494 }
495
496 /// We try using a socket if hostname starts with `/` or if socket parameter
497 /// is specified.
498 pub(crate) fn make_socket_path(&self) -> Option<String> {
499 match self.socket {
500 Some(ref socket) => {
501 let full_path = format!("{}/.s.PGSQL.{}", socket.display(), self.port);
502 Some(full_path)
503 }
504 None if self.host.original().starts_with('/') => {
505 let full_path = format!("{}/.s.PGSQL.{}", self.host.original(), self.port);
506 Some(full_path)
507 }
508 _ => None,
509 }
510 }
511}
512
513impl PgConnectOptions {
514 /// Get the current host.
515 ///
516 /// # Example
517 ///
518 /// ```rust
519 /// # use sqlx_postgres::PgConnectOptions;
520 /// let options = PgConnectOptions::new()
521 /// .host("127.0.0.1");
522 /// assert_eq!(options.get_host(), "127.0.0.1");
523 /// ```
524 pub fn get_host(&self) -> &str {
525 self.host.original()
526 }
527
528 /// Get the server's port.
529 ///
530 /// # Example
531 ///
532 /// ```rust
533 /// # use sqlx_postgres::PgConnectOptions;
534 /// let options = PgConnectOptions::new()
535 /// .port(6543);
536 /// assert_eq!(options.get_port(), 6543);
537 /// ```
538 pub fn get_port(&self) -> u16 {
539 self.port
540 }
541
542 /// Get the socket path.
543 ///
544 /// # Example
545 ///
546 /// ```rust
547 /// # use sqlx_postgres::PgConnectOptions;
548 /// let options = PgConnectOptions::new()
549 /// .socket("/tmp");
550 /// assert!(options.get_socket().is_some());
551 /// ```
552 pub fn get_socket(&self) -> Option<&PathBuf> {
553 self.socket.as_ref()
554 }
555
556 /// Get the server's port.
557 ///
558 /// # Example
559 ///
560 /// ```rust
561 /// # use sqlx_postgres::PgConnectOptions;
562 /// let options = PgConnectOptions::new()
563 /// .username("foo");
564 /// assert_eq!(options.get_username(), "foo");
565 /// ```
566 pub fn get_username(&self) -> &str {
567 &self.username
568 }
569
570 /// Get the current database name.
571 ///
572 /// # Example
573 ///
574 /// ```rust
575 /// # use sqlx_postgres::PgConnectOptions;
576 /// let options = PgConnectOptions::new()
577 /// .database("postgres");
578 /// assert!(options.get_database().is_some());
579 /// ```
580 pub fn get_database(&self) -> Option<&str> {
581 self.database.as_deref()
582 }
583
584 /// Get the SSL mode.
585 ///
586 /// # Example
587 ///
588 /// ```rust
589 /// # use sqlx_postgres::{PgConnectOptions, PgSslMode};
590 /// let options = PgConnectOptions::new();
591 /// assert!(matches!(options.get_ssl_mode(), PgSslMode::Prefer));
592 /// ```
593 pub fn get_ssl_mode(&self) -> PgSslMode {
594 self.ssl_options.ssl_mode
595 }
596
597 /// Get the application name.
598 ///
599 /// # Example
600 ///
601 /// ```rust
602 /// # use sqlx_postgres::PgConnectOptions;
603 /// let options = PgConnectOptions::new()
604 /// .application_name("service");
605 /// assert!(options.get_application_name().is_some());
606 /// ```
607 pub fn get_application_name(&self) -> Option<&str> {
608 self.application_name.as_deref()
609 }
610
611 /// Get the options.
612 ///
613 /// # Example
614 ///
615 /// ```rust
616 /// # use sqlx_postgres::PgConnectOptions;
617 /// let options = PgConnectOptions::new()
618 /// .options([("foo", "bar")]);
619 /// assert!(options.get_options().is_some());
620 /// ```
621 pub fn get_options(&self) -> Option<&str> {
622 self.options.as_deref()
623 }
624}
625
626fn default_host(port: u16) -> String {
627 // try to check for the existence of a unix socket and uses that
628 let socket = format!(".s.PGSQL.{port}");
629 let candidates = [
630 "/var/run/postgresql", // Debian
631 "/private/tmp", // OSX (homebrew)
632 "/tmp", // Default
633 ];
634
635 for candidate in &candidates {
636 if Path::new(candidate).join(&socket).exists() {
637 return candidate.to_string();
638 }
639 }
640
641 // fallback to localhost if no socket was found
642 "localhost".to_owned()
643}
644
645/// Writer that escapes passed-in PostgreSQL options.
646///
647/// Escapes backslashes and spaces with an additional backslash according to
648/// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
649#[derive(Debug)]
650struct PgOptionsWriteEscaped<'a>(&'a mut String);
651
652impl Write for PgOptionsWriteEscaped<'_> {
653 fn write_str(&mut self, s: &str) -> fmt::Result {
654 let mut span_start = 0;
655
656 for (span_end, matched) in s.match_indices([' ', '\\']) {
657 write!(self.0, r"{}\{matched}", &s[span_start..span_end])?;
658 span_start = span_end + matched.len();
659 }
660
661 // Write the rest of the string after the last match, or all of it if no matches
662 self.0.push_str(&s[span_start..]);
663
664 Ok(())
665 }
666
667 fn write_char(&mut self, ch: char) -> fmt::Result {
668 if matches!(ch, ' ' | '\\') {
669 self.0.push('\\');
670 }
671
672 self.0.push(ch);
673
674 Ok(())
675 }
676}
677
678#[test]
679fn test_options_formatting() {
680 let options = PgConnectOptions::new().options([("geqo", "off")]);
681 assert_eq!(options.options, Some("-c geqo=off".to_string()));
682 let options = options.options([("search_path", "sqlx")]);
683 assert_eq!(
684 options.options,
685 Some("-c geqo=off -c search_path=sqlx".to_string())
686 );
687 let options = PgConnectOptions::new().options([("geqo", "off"), ("statement_timeout", "5min")]);
688 assert_eq!(
689 options.options,
690 Some("-c geqo=off -c statement_timeout=5min".to_string())
691 );
692 // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
693 let options =
694 PgConnectOptions::new().options([("application_name", r"/back\slash/ and\ spaces")]);
695 assert_eq!(
696 options.options,
697 Some(r"-c application_name=/back\\slash/\ and\\\ spaces".to_string())
698 );
699 let options = PgConnectOptions::new();
700 assert_eq!(options.options, None);
701}
702
703#[test]
704fn test_pg_write_escaped() {
705 let mut buf = String::new();
706 let mut x = PgOptionsWriteEscaped(&mut buf);
707 x.write_str("x").unwrap();
708 x.write_str("").unwrap();
709 x.write_char('\\').unwrap();
710 x.write_str("y \\").unwrap();
711 x.write_char(' ').unwrap();
712 x.write_char('z').unwrap();
713 assert_eq!(buf, r"x\\y\ \\\ z");
714}