postgresql_embedded 0.20.2

Install and run a PostgreSQL database locally on Linux, MacOS or Windows. PostgreSQL can be bundled with your application, or downloaded on demand.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use crate::error::{Error, Result};
use postgresql_archive::VersionReq;
#[cfg(feature = "bundled")]
use postgresql_archive::{ExactVersionReq, Version};
use rand::RngExt;
use rand::distr::Alphanumeric;
use std::collections::HashMap;
use std::env;
use std::env::{current_dir, home_dir};
use std::ffi::OsString;
use std::path::PathBuf;
#[cfg(feature = "bundled")]
use std::sync::LazyLock;
use std::time::Duration;
use url::Url;

#[cfg(feature = "bundled")]
#[expect(clippy::unwrap_used)]
pub(crate) static ARCHIVE_VERSION: LazyLock<VersionReq> = LazyLock::new(|| {
    let version_string = include_str!(concat!(std::env!("OUT_DIR"), "/postgresql.version"));
    let version = Version::parse(version_string).unwrap();
    let version_req = version.exact_version_req().unwrap();
    tracing::debug!("Bundled installation archive version {version_string}");
    version_req
});

#[cfg(feature = "bundled")]
pub(crate) const ARCHIVE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/postgresql.tar.gz"));

/// `PostgreSQL` superuser
pub const BOOTSTRAP_SUPERUSER: &str = "postgres";
/// `PostgreSQL` database
pub const BOOTSTRAP_DATABASE: &str = "postgres";

/// Database settings
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
    /// URL for the releases location of the `PostgreSQL` installation archives
    pub releases_url: String,
    /// Version requirement of `PostgreSQL` to install
    pub version: VersionReq,
    /// `PostgreSQL` installation directory
    pub installation_dir: PathBuf,
    /// `PostgreSQL` password file
    pub password_file: PathBuf,
    /// `PostgreSQL` data directory
    pub data_dir: PathBuf,
    /// `PostgreSQL` host
    pub host: String,
    /// `PostgreSQL` port
    pub port: u16,
    /// `PostgreSQL` user name
    pub username: String,
    /// `PostgreSQL` password
    pub password: String,
    /// Temporary database
    pub temporary: bool,
    /// Command execution Timeout
    pub timeout: Option<Duration>,
    /// Server configuration options
    pub configuration: HashMap<String, String>,
    /// Skip installation and inferrence of the installation dir. Trust what the user provided.
    pub trust_installation_dir: bool,
    /// Unix socket directory. When set, the server will listen on a Unix socket in this directory
    /// in addition to (or instead of) TCP/IP. Unix-only; ignored on Windows.
    pub socket_dir: Option<PathBuf>,
}

/// Settings implementation
impl Settings {
    /// Create a new instance of [`Settings`]
    pub fn new() -> Self {
        let home_dir = home_dir().unwrap_or_else(|| env::current_dir().unwrap_or_default());
        let password_file_name = ".pgpass";
        let password_file = if let Ok(dir) = tempfile::tempdir() {
            dir.keep().join(password_file_name)
        } else {
            let current_dir = current_dir().unwrap_or(PathBuf::from("."));
            current_dir.join(password_file_name)
        };
        let data_dir = if let Ok(dir) = tempfile::tempdir() {
            dir.keep()
        } else {
            let temp_dir: String = rand::rng()
                .sample_iter(&Alphanumeric)
                .take(16)
                .map(char::from)
                .collect();

            let data_dir = current_dir().unwrap_or(PathBuf::from("."));
            data_dir.join(temp_dir)
        };

        let password = rand::rng()
            .sample_iter(&Alphanumeric)
            .take(16)
            .map(char::from)
            .collect();

        #[cfg(feature = "theseus")]
        let releases_url = postgresql_archive::configuration::theseus::URL.to_string();
        #[cfg(not(feature = "theseus"))]
        let releases_url = String::new();

        Self {
            releases_url,
            version: default_version(),
            installation_dir: home_dir.join(".theseus").join("postgresql"),
            password_file,
            data_dir,
            host: "localhost".to_string(),
            port: 0,
            username: BOOTSTRAP_SUPERUSER.to_string(),
            password,
            temporary: true,
            timeout: Some(Duration::from_secs(5)),
            configuration: HashMap::new(),
            trust_installation_dir: false,
            socket_dir: None,
        }
    }

    /// Returns the binary directory for the configured `PostgreSQL` installation.
    #[must_use]
    pub fn binary_dir(&self) -> PathBuf {
        self.installation_dir.join("bin")
    }

    /// Return the `PostgreSQL` URL for the given database name.
    ///
    /// When `socket_dir` is set, the URL will use the Unix socket path
    /// (e.g. `postgresql://user:pass@localhost:5432/db?host=%2Fpath%2Fto%2Fsocket`).
    /// When `socket_dir` is `None`, a standard TCP URL is returned.
    pub fn url<S: AsRef<str>>(&self, database_name: S) -> String {
        match &self.socket_dir {
            Some(socket_dir) => {
                let socket_str = socket_dir.to_string_lossy();
                let encoded: String =
                    url::form_urlencoded::byte_serialize(socket_str.as_bytes()).collect();
                format!(
                    "postgresql://{}:{}@{}:{}/{}?host={}",
                    self.username,
                    self.password,
                    self.host,
                    self.port,
                    database_name.as_ref(),
                    encoded
                )
            }
            None => {
                format!(
                    "postgresql://{}:{}@{}:{}/{}",
                    self.username,
                    self.password,
                    self.host,
                    self.port,
                    database_name.as_ref()
                )
            }
        }
    }

    /// Create a new instance of [`Settings`] from the given URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL is invalid.
    pub fn from_url<S: AsRef<str>>(url: S) -> Result<Self> {
        let parsed_url = match Url::parse(url.as_ref()) {
            Ok(parsed_url) => parsed_url,
            Err(error) => {
                return Err(Error::InvalidUrl {
                    url: url.as_ref().to_string(),
                    message: error.to_string(),
                });
            }
        };
        let query_parameters: HashMap<String, String> =
            parsed_url.query_pairs().into_owned().collect();
        let mut settings = Self::default();

        if let Some(releases_url) = query_parameters.get("releases_url") {
            settings.releases_url = releases_url.to_string();
        }
        if let Some(version) = query_parameters.get("version") {
            settings.version = VersionReq::parse(version)?;
        }
        if let Some(installation_dir) = query_parameters.get("installation_dir") {
            settings.installation_dir = PathBuf::from(installation_dir);
        }
        if let Some(password_file) = query_parameters.get("password_file") {
            settings.password_file = PathBuf::from(password_file);
        }
        if let Some(data_dir) = query_parameters.get("data_dir") {
            settings.data_dir = PathBuf::from(data_dir);
        }
        if let Some(host) = parsed_url.host() {
            settings.host = host.to_string();
        }
        if let Some(port) = parsed_url.port() {
            settings.port = port;
        }
        if !parsed_url.username().is_empty() {
            settings.username = parsed_url.username().to_string();
        }
        if let Some(password) = parsed_url.password() {
            settings.password = password.to_string();
        }
        if let Some(temporary) = query_parameters.get("temporary") {
            settings.temporary = temporary == "true";
        }
        if let Some(timeout) = query_parameters.get("timeout") {
            settings.timeout = match timeout.parse::<u64>() {
                Ok(timeout) => Some(Duration::from_secs(timeout)),
                Err(error) => {
                    return Err(Error::InvalidUrl {
                        url: url.as_ref().to_string(),
                        message: error.to_string(),
                    });
                }
            };
        }
        if let Some(trust_installation_dir) = query_parameters.get("trust_installation_dir") {
            settings.trust_installation_dir = trust_installation_dir == "true";
        }
        if let Some(socket_dir) = query_parameters.get("socket_dir") {
            settings.socket_dir = Some(PathBuf::from(socket_dir));
        }
        let configuration_prefix = "configuration.";
        for (key, value) in &query_parameters {
            if key.starts_with(configuration_prefix)
                && let Some(configuration_key) = key.strip_prefix(configuration_prefix)
            {
                settings
                    .configuration
                    .insert(configuration_key.to_string(), value.to_string());
            }
        }

        Ok(settings)
    }
}

/// Implement the [`Settings`] trait for [`Settings`]
impl postgresql_commands::Settings for Settings {
    fn get_binary_dir(&self) -> PathBuf {
        self.binary_dir().clone()
    }

    fn get_host(&self) -> OsString {
        self.host.parse().expect("host")
    }

    fn get_port(&self) -> u16 {
        self.port
    }

    fn get_username(&self) -> OsString {
        self.username.parse().expect("username")
    }

    fn get_password(&self) -> OsString {
        self.password.parse().expect("password")
    }

    fn get_socket_dir(&self) -> Option<PathBuf> {
        self.socket_dir.clone()
    }
}

/// Default implementation for [`Settings`]
impl Default for Settings {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for constructing [`Settings`] with a fluent API.
///
/// # Examples
///
/// ```no_run
/// use postgresql_embedded::SettingsBuilder;
///
/// let settings = SettingsBuilder::new()
///     .host("127.0.0.1")
///     .port(5433)
///     .username("admin")
///     .password("secret")
///     .temporary(false)
///     .build();
/// ```
///
/// To configure a Unix socket:
///
/// ```no_run
/// use postgresql_embedded::SettingsBuilder;
/// use std::path::PathBuf;
///
/// let settings = SettingsBuilder::new()
///     .socket_dir(PathBuf::from("/tmp/pg_socket"))
///     .build();
/// ```
#[derive(Clone, Debug)]
pub struct SettingsBuilder {
    settings: Settings,
}

impl SettingsBuilder {
    /// Create a new [`SettingsBuilder`] starting from the default [`Settings`].
    #[must_use]
    pub fn new() -> Self {
        Self {
            settings: Settings::new(),
        }
    }

    /// Set the releases URL for downloading PostgreSQL archives.
    #[must_use]
    pub fn releases_url<S: Into<String>>(mut self, releases_url: S) -> Self {
        self.settings.releases_url = releases_url.into();
        self
    }

    /// Set the PostgreSQL version requirement.
    #[must_use]
    pub fn version(mut self, version: VersionReq) -> Self {
        self.settings.version = version;
        self
    }

    /// Set the installation directory.
    #[must_use]
    pub fn installation_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.settings.installation_dir = dir.into();
        self
    }

    /// Set the password file path.
    #[must_use]
    pub fn password_file<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.settings.password_file = path.into();
        self
    }

    /// Set the data directory.
    #[must_use]
    pub fn data_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.settings.data_dir = dir.into();
        self
    }

    /// Set the host name or IP address.
    #[must_use]
    pub fn host<S: Into<String>>(mut self, host: S) -> Self {
        self.settings.host = host.into();
        self
    }

    /// Set the TCP port number.
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.settings.port = port;
        self
    }

    /// Set the database username.
    #[must_use]
    pub fn username<S: Into<String>>(mut self, username: S) -> Self {
        self.settings.username = username.into();
        self
    }

    /// Set the database password.
    #[must_use]
    pub fn password<S: Into<String>>(mut self, password: S) -> Self {
        self.settings.password = password.into();
        self
    }

    /// Set whether the database is temporary (cleaned up on drop).
    #[must_use]
    pub fn temporary(mut self, temporary: bool) -> Self {
        self.settings.temporary = temporary;
        self
    }

    /// Set the command execution timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
        self.settings.timeout = timeout;
        self
    }

    /// Set server configuration options.
    #[must_use]
    pub fn configuration(mut self, configuration: HashMap<String, String>) -> Self {
        self.settings.configuration = configuration;
        self
    }

    /// Add a single server configuration option.
    #[must_use]
    pub fn config<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
        self.settings.configuration.insert(key.into(), value.into());
        self
    }

    /// Set whether to trust the installation directory as-is.
    #[must_use]
    pub fn trust_installation_dir(mut self, trust: bool) -> Self {
        self.settings.trust_installation_dir = trust;
        self
    }

    /// Set the Unix socket directory. When set, the server will listen on a Unix socket in this directory. This is only
    /// supported on Unix platforms.
    #[must_use]
    pub fn socket_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.settings.socket_dir = Some(dir.into());
        self
    }

    /// Consume the builder and return the configured [`Settings`].
    #[must_use]
    pub fn build(self) -> Settings {
        self.settings
    }
}

impl Default for SettingsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Get the default version used if not otherwise specified
#[must_use]
fn default_version() -> VersionReq {
    #[cfg(feature = "bundled")]
    {
        ARCHIVE_VERSION.clone()
    }

    #[cfg(not(feature = "bundled"))]
    {
        VersionReq::STAR
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_log::test;

    #[test]
    #[cfg(feature = "bundled")]
    fn test_archive_version() {
        assert!(!super::ARCHIVE_VERSION.to_string().is_empty());
    }

    #[test]
    fn test_settings_new() {
        let settings = Settings::new();
        assert!(
            !settings
                .installation_dir
                .to_str()
                .unwrap_or_default()
                .is_empty()
        );
        assert!(settings.password_file.ends_with(".pgpass"));
        assert!(!settings.data_dir.to_str().unwrap_or_default().is_empty());
        assert_eq!(0, settings.port);
        assert_eq!(BOOTSTRAP_SUPERUSER, settings.username);
        assert!(!settings.password.is_empty());
        assert_ne!("password", settings.password);
        assert!(settings.binary_dir().ends_with("bin"));
        assert_eq!(
            "postgresql://postgres:password@localhost:0/test",
            settings
                .url("test")
                .replace(settings.password.as_str(), "password")
        );
        assert_eq!(Some(Duration::from_secs(5)), settings.timeout);
        assert!(settings.configuration.is_empty());
        assert!(settings.socket_dir.is_none());
    }

    #[test]
    fn test_settings_url_with_socket_dir() {
        let mut settings = Settings::new();
        settings.username = "user".to_string();
        settings.password = "pass".to_string();
        settings.host = "localhost".to_string();
        settings.port = 5432;
        settings.socket_dir = Some(PathBuf::from("/tmp/pg_socket"));

        assert_eq!(
            "postgresql://user:pass@localhost:5432/test?host=%2Ftmp%2Fpg_socket",
            settings.url("test")
        );
    }

    #[test]
    fn test_settings_from_url() -> Result<()> {
        let base_url = "postgresql://postgres:password@localhost:5432/test";
        let releases_url = "releases_url=https%3A%2F%2Fgithub.com";
        let version = "version=%3D16.4.0";
        let installation_dir = "installation_dir=/tmp/postgresql";
        let password_file = "password_file=/tmp/.pgpass";
        let data_dir = "data_dir=/tmp/data";
        let temporary = "temporary=false";
        let trust_installation_dir = "trust_installation_dir=true";
        let timeout = "timeout=10";
        let configuration = "configuration.max_connections=42";
        let url = format!(
            "{base_url}?{releases_url}&{version}&{installation_dir}&{password_file}&{data_dir}&{temporary}&{trust_installation_dir}&{timeout}&{configuration}"
        );

        let settings = Settings::from_url(url)?;

        assert_eq!("https://github.com", settings.releases_url);
        assert_eq!(VersionReq::parse("=16.4.0")?, settings.version);
        assert_eq!(PathBuf::from("/tmp/postgresql"), settings.installation_dir);
        assert_eq!(PathBuf::from("/tmp/.pgpass"), settings.password_file);
        assert_eq!(PathBuf::from("/tmp/data"), settings.data_dir);
        assert_eq!("localhost", settings.host);
        assert_eq!(5432, settings.port);
        assert_eq!(BOOTSTRAP_SUPERUSER, settings.username);
        assert_eq!("password", settings.password);
        assert!(!settings.temporary);
        assert!(settings.trust_installation_dir);
        assert_eq!(Some(Duration::from_secs(10)), settings.timeout);
        let configuration = HashMap::from([("max_connections".to_string(), "42".to_string())]);
        assert_eq!(configuration, settings.configuration);
        assert!(settings.socket_dir.is_none());
        assert_eq!(base_url, settings.url("test"));

        Ok(())
    }

    #[test]
    fn test_settings_from_url_with_socket_dir() -> Result<()> {
        let url =
            "postgresql://postgres:password@localhost:5432/test?socket_dir=%2Ftmp%2Fpg_socket";
        let settings = Settings::from_url(url)?;

        assert_eq!(Some(PathBuf::from("/tmp/pg_socket")), settings.socket_dir);
        assert_eq!("localhost", settings.host);
        assert_eq!(5432, settings.port);
        assert_eq!(
            "postgresql://postgres:password@localhost:5432/test?host=%2Ftmp%2Fpg_socket",
            settings.url("test")
        );

        Ok(())
    }

    #[test]
    fn test_settings_from_url_invalid_url() {
        assert!(Settings::from_url("^`~").is_err());
    }

    #[test]
    fn test_settings_from_url_invalid_version() {
        assert!(Settings::from_url("postgresql://?version=foo").is_err());
    }

    #[test]
    fn test_settings_from_url_invalid_timeout() {
        assert!(Settings::from_url("postgresql://?timeout=foo").is_err());
    }

    #[test]
    fn test_settings_builder_defaults() {
        let settings = SettingsBuilder::new().build();
        assert_eq!("localhost", settings.host);
        assert_eq!(0, settings.port);
        assert_eq!(BOOTSTRAP_SUPERUSER, settings.username);
        assert!(settings.temporary);
        assert!(settings.socket_dir.is_none());
        assert_eq!(Some(Duration::from_secs(5)), settings.timeout);
    }

    #[test]
    fn test_settings_builder_all_fields() {
        let configuration = HashMap::from([("max_connections".to_string(), "100".to_string())]);
        let settings = SettingsBuilder::new()
            .releases_url("https://example.com")
            .version(VersionReq::STAR)
            .installation_dir("/tmp/install")
            .password_file("/tmp/.pgpass")
            .data_dir("/tmp/data")
            .host("127.0.0.1")
            .port(5433)
            .username("admin")
            .password("secret")
            .temporary(false)
            .timeout(Some(Duration::from_secs(30)))
            .configuration(configuration.clone())
            .trust_installation_dir(true)
            .socket_dir(PathBuf::from("/tmp/pg_socket"))
            .build();

        assert_eq!("https://example.com", settings.releases_url);
        assert_eq!(PathBuf::from("/tmp/install"), settings.installation_dir);
        assert_eq!(PathBuf::from("/tmp/.pgpass"), settings.password_file);
        assert_eq!(PathBuf::from("/tmp/data"), settings.data_dir);
        assert_eq!("127.0.0.1", settings.host);
        assert_eq!(5433, settings.port);
        assert_eq!("admin", settings.username);
        assert_eq!("secret", settings.password);
        assert!(!settings.temporary);
        assert_eq!(Some(Duration::from_secs(30)), settings.timeout);
        assert_eq!(configuration, settings.configuration);
        assert!(settings.trust_installation_dir);
        assert_eq!(Some(PathBuf::from("/tmp/pg_socket")), settings.socket_dir);
    }

    #[test]
    fn test_settings_builder_config_method() {
        let settings = SettingsBuilder::new()
            .config("max_connections", "42")
            .config("shared_buffers", "128MB")
            .build();

        assert_eq!(
            Some(&"42".to_string()),
            settings.configuration.get("max_connections")
        );
        assert_eq!(
            Some(&"128MB".to_string()),
            settings.configuration.get("shared_buffers")
        );
    }

    #[test]
    fn test_settings_builder_socket_dir() {
        let settings = SettingsBuilder::new()
            .socket_dir(PathBuf::from("/tmp/pg_socket"))
            .build();

        assert_eq!(Some(PathBuf::from("/tmp/pg_socket")), settings.socket_dir);
    }

    #[test]
    fn test_settings_builder_default() {
        let builder = SettingsBuilder::default();
        let settings = builder.build();
        assert_eq!("localhost", settings.host);
        assert_eq!(0, settings.port);
    }
}