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