pgdb 0.10.1

Creates and runs Postgres databases through Rust in temporary directories, cleaned up on drop
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
#![doc = include_str!("../README.md")]

pub mod config;
mod db_instance;
mod error;
pub mod state;

use std::{
    borrow::Cow,
    env, fs, io,
    net::TcpListener,
    path, process, thread,
    time::{Duration, Instant},
};

pub use db_instance::{DbInstance, db_fixture};
pub use error::{Error, ExternalUrlError};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
#[cfg(target_os = "linux")]
use process_guard::CommandExt;
use process_guard::{DEFAULT_FORCE_TIME, ProcessGuard, ShutdownPolicy, Signal};
use url::Url;

use crate::state::{Credentials, State};

/// Default PostgreSQL port and Unix socket suffix.
const DEFAULT_POSTGRES_PORT: u16 = 5432;

/// Returns the connection host represented by a PostgreSQL URL.
pub fn connection_host(url: &Url) -> Option<Cow<'_, str>> {
    if let Some((_, host)) = url.query_pairs().find(|(key, _)| key == "host") {
        return Some(host);
    }

    url.host_str()
        .map(|host| percent_decode_str(host).decode_utf8_lossy())
}

/// Returns the connection port represented by a PostgreSQL URL.
pub fn connection_port(url: &Url) -> Option<u16> {
    url.query_pairs()
        .find(|(key, _)| key == "port")
        .and_then(|(_, port)| port.parse().ok())
        .or_else(|| url.port())
}

/// Executes SQL using psql with the given connection parameters.
pub fn run_psql_command(superuser_url: &Url, database: &str, sql: &str) -> Result<(), Error> {
    // TODO: Do not use which, allow passing in.
    let psql_binary = which::which("psql").unwrap_or_else(|_| "psql".into());
    let username = superuser_url.username();
    let password = superuser_url.password().unwrap_or_default();
    let host = connection_host(superuser_url).expect("URL must have a host");
    let port = connection_port(superuser_url).unwrap_or(5432);

    let status = process::Command::new(&psql_binary)
        .arg("-h")
        .arg(host.as_ref())
        .arg("-p")
        .arg(port.to_string())
        .arg("-U")
        .arg(username)
        .arg("-d")
        .arg(database)
        .arg("-c")
        .arg(sql)
        .env("PGPASSWORD", password)
        .status()
        .map_err(Error::RunPsql)?;

    if !status.success() {
        return Err(Error::PsqlFailed(status));
    }

    Ok(())
}

/// Creates a user and database with the given credentials using psql.
pub fn create_user_and_database(
    superuser_url: &Url,
    db_name: &str,
    db_user: &str,
    db_pw: &str,
) -> Result<(), Error> {
    // Create user
    run_psql_command(
        superuser_url,
        "postgres",
        &format!(
            "CREATE ROLE {} LOGIN ENCRYPTED PASSWORD {};",
            escape_ident(db_user),
            escape_string(db_pw)
        ),
    )?;

    // Create database
    run_psql_command(
        superuser_url,
        "postgres",
        &format!(
            "CREATE DATABASE {} OWNER {};",
            escape_ident(db_name),
            escape_ident(db_user)
        ),
    )?;

    Ok(())
}

/// Creates a new fixture database with random credentials.
fn create_fixture_db(superuser_url: &Url) -> Result<Url, Error> {
    // Generate unique credentials with random IDs
    let random_id = generate_random_string();
    let db_name = format!("fixture_db_{}", random_id);
    let db_user = format!("fixture_user_{}", random_id);
    let db_pw = format!("fixture_pass_{}", random_id);

    // Create user and database
    create_user_and_database(superuser_url, &db_name, &db_user, &db_pw)?;

    // Build the URL for the new database
    let mut url = superuser_url.clone();
    url.set_username(&db_user).expect("Failed to set username");
    url.set_password(Some(&db_pw))
        .expect("Failed to set password");
    url.set_path(&db_name);

    Ok(url)
}

/// Finds an unused port by binding to port 0 and letting the OS assign one.
///
/// This function has a race condition, there is no guarantee that the OS won't reassign the port as
/// soon as it is released again. Sadly this is our only recourse, as Postgres does not allow
/// passing `0` as the port number.
fn find_unused_port() -> io::Result<u16> {
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let port = listener.local_addr()?.port();
    Ok(port)
}

/// A wrapped postgres instance.
///
/// Contains a handle to a running Postgres process. Once dropped, the instance will be shut down
/// and its temporary files removed. An explicitly supplied data directory is preserved.
#[derive(Debug)]
pub struct Postgres {
    /// Connection URL without credentials.
    connection_url: Url,
    /// Administrative credentials.
    credentials: Credentials,
    /// PostgreSQL process and its temporary directory.
    #[allow(dead_code)] // Only used for its `Drop` implementation.
    process: PostgresProcess,
    /// Path to the `psql` binary.
    psql_binary: path::PathBuf,
    /// Directory containing the PostgreSQL cluster.
    data_dir: path::PathBuf,
}

/// Resources owned by a PostgreSQL process.
#[derive(Debug)]
struct PostgresProcess {
    /// Guard for the PostgreSQL process group leader.
    instance: ProcessGuard,
    /// Directory holding all temporary data.
    tmp_dir: tempfile::TempDir,
}

impl Drop for PostgresProcess {
    fn drop(&mut self) {
        if self.instance.shutdown().is_err() {
            self.tmp_dir.disable_cleanup(true);
            // Do not repeat the bounded shutdown when the guard is dropped.
            let _ = self.instance.take();
        }
    }
}

/// A virtual client for a running postgres.
///
/// Contains credentials and enough information to connect to its parent instance.
#[derive(Debug)]
pub struct PostgresClient<'a> {
    instance: &'a Postgres,
    /// Client URL with credentials.
    client_url: Url,
}

/// Builder for a postgres instance.
///
/// Usually constructed via [`Postgres::build`].
#[derive(Debug)]
pub struct PostgresBuilder {
    /// Data directory.
    data_dir: Option<path::PathBuf>,
    /// TCP listening port.
    ///
    /// If not set, [`find_unused_port`] will be used to determine the port.
    port: Option<u16>,
    /// TCP bind host.
    host: String,
    /// Whether to use fast settings for disposable servers.
    fast: bool,
    /// Whether to request shutdown when the spawning thread exits.
    #[cfg(target_os = "linux")]
    shutdown_on_parent_death: bool,
    /// Whether to connect over TCP.
    tcp: bool,
    /// Name of the superuser.
    superuser: String,
    /// Explicit password for the superuser.
    superuser_pw: Option<String>,
    /// Path to `postgres` binary.
    postgres_binary: Option<path::PathBuf>,
    /// Path to `initdb` binary.
    initdb_binary: Option<path::PathBuf>,
    /// Path to `pg_isready` binary.
    pg_isready_binary: Option<path::PathBuf>,
    /// Path to `psql` binary.
    psql_binary: Option<path::PathBuf>,
    /// PostgreSQL server configuration overrides.
    postgres_options: Vec<(String, String)>,
    /// How long to wait between startup probe attempts.
    probe_delay: Duration,
    /// Time until giving up waiting for startup.
    startup_timeout: Duration,
    /// Override for the mode-dependent grace period before forceful cleanup.
    shutdown_timeout: Option<Duration>,
    /// Time to wait for forceful cleanup to complete.
    force_shutdown_timeout: Duration,
}

impl Postgres {
    /// Creates a new Postgres database builder.
    #[inline]
    pub fn build() -> PostgresBuilder {
        PostgresBuilder {
            data_dir: None,
            port: None,
            host: "127.0.0.1".to_string(),
            fast: false,
            #[cfg(target_os = "linux")]
            shutdown_on_parent_death: false,
            tcp: false,
            superuser: "postgres".to_string(),
            superuser_pw: None,
            postgres_binary: None,
            initdb_binary: None,
            pg_isready_binary: None,
            psql_binary: None,
            postgres_options: Vec::new(),
            probe_delay: Duration::from_millis(100),
            startup_timeout: Duration::from_secs(10),
            shutdown_timeout: None,
            force_shutdown_timeout: DEFAULT_FORCE_TIME,
        }
    }

    /// Returns a postgres client with superuser credentials.
    #[inline]
    pub fn as_superuser(&self) -> PostgresClient<'_> {
        self.as_user(&self.credentials.user, &self.credentials.password)
    }

    /// Returns a postgres client that uses the given credentials.
    #[inline]
    pub fn as_user(&self, username: &str, password: &str) -> PostgresClient<'_> {
        let mut client_url = self.connection_url.clone();
        client_url
            .set_username(username)
            .expect("Failed to set username");
        client_url
            .set_password(Some(password))
            .expect("Failed to set password");
        PostgresClient {
            instance: self,
            client_url,
        }
    }

    /// Returns the directory containing the PostgreSQL cluster.
    pub fn data_dir(&self) -> &path::Path {
        &self.data_dir
    }

    /// Returns the superuser URL for this instance.
    pub fn superuser_url(&self) -> Url {
        self.as_superuser().client_url
    }
}

impl<'a> PostgresClient<'a> {
    /// Runs a `psql` command against the database.
    ///
    /// Creates a command that runs `psql -h (host) -p (port) -U (username) -d (database)` with
    /// `PGPASSWORD` set.
    pub fn psql(&self, database: &str) -> process::Command {
        let mut cmd = process::Command::new(&self.instance.psql_binary);

        let username = self.client_url.username();
        let password = self.client_url.password().unwrap_or_default();

        let host = connection_host(&self.client_url).expect("Client URL must have a host");
        let port = connection_port(&self.client_url).expect("Client URL must have a port");

        cmd.arg("-h")
            .arg(host.as_ref())
            .arg("-p")
            .arg(port.to_string())
            .arg("-U")
            .arg(username)
            .arg("-d")
            .arg(database)
            .env("PGPASSWORD", password);

        cmd
    }

    /// Runs the given SQL commands from an input file via `psql`.
    pub fn load_sql<P: AsRef<path::Path>>(&self, database: &str, filename: P) -> Result<(), Error> {
        let status = self
            .psql(database)
            .arg("-f")
            .arg(filename.as_ref())
            .status()
            .map_err(Error::RunPsql)?;

        if !status.success() {
            return Err(Error::PsqlFailed(status));
        }

        Ok(())
    }

    /// Runs the given SQL command through `psql`.
    pub fn run_sql(&self, database: &str, sql: &str) -> Result<(), Error> {
        let status = self
            .psql(database)
            .arg("-c")
            .arg(sql)
            .status()
            .map_err(Error::RunPsql)?;

        if !status.success() {
            return Err(Error::PsqlFailed(status));
        }

        Ok(())
    }

    /// Creates a new database with the given owner.
    ///
    /// This typically requires superuser credentials, see [`Postgres::as_superuser`].
    #[inline]
    pub fn create_database(&self, database: &str, owner: &str) -> Result<(), Error> {
        self.run_sql(
            "postgres",
            &format!(
                "CREATE DATABASE {} OWNER {};",
                escape_ident(database),
                escape_ident(owner)
            ),
        )
    }

    /// Creates a new user on the system that is allowed to login.
    ///
    /// This typically requires superuser credentials, see [`Postgres::as_superuser`].
    #[inline]
    pub fn create_user(&self, username: &str, password: &str) -> Result<(), Error> {
        self.run_sql(
            "postgres",
            &format!(
                "CREATE ROLE {} LOGIN ENCRYPTED PASSWORD {};",
                escape_ident(username),
                escape_string(password)
            ),
        )
    }

    /// Returns the `Postgres` instance associated with this client.
    #[inline]
    pub fn instance(&self) -> &Postgres {
        self.instance
    }

    /// Returns a libpq-style connection URL.
    pub fn url(&self, database: &str) -> Url {
        let mut url = self.client_url.clone();
        url.set_path(database);
        url
    }

    /// Returns the client URL for this client.
    pub fn client_url(&self) -> &Url {
        &self.client_url
    }
}

impl PostgresBuilder {
    /// Enables faster settings for a disposable PostgreSQL server.
    ///
    /// This disables runtime durability and uses immediate shutdown. It must not be used when the
    /// database needs to survive an operating system crash or server shutdown.
    #[inline]
    pub fn fast(&mut self) -> &mut Self {
        self.fast = true;
        self
    }

    /// Requests immediate shutdown when the spawning thread exits (Linux only).
    #[cfg(target_os = "linux")]
    pub fn shutdown_on_parent_death(&mut self) -> &mut Self {
        self.shutdown_on_parent_death = true;
        self
    }

    /// Sets the postgres data directory.
    ///
    /// If not set, a temporary directory will be used. Existing clusters are reused.
    #[inline]
    pub fn data_dir<T: Into<path::PathBuf>>(&mut self, data_dir: T) -> &mut Self {
        self.data_dir = Some(data_dir.into());
        self
    }

    /// Sets the location of the `initdb` binary.
    #[inline]
    pub fn initdb_binary<T: Into<path::PathBuf>>(&mut self, initdb_binary: T) -> &mut Self {
        self.initdb_binary = Some(initdb_binary.into());
        self
    }

    /// Sets the location of the `pg_isready` binary.
    #[inline]
    pub fn pg_isready_binary<T: Into<path::PathBuf>>(&mut self, pg_isready_binary: T) -> &mut Self {
        self.pg_isready_binary = Some(pg_isready_binary.into());
        self
    }

    /// Sets the TCP bind address and enables TCP connections.
    #[inline]
    pub fn host(&mut self, host: String) -> &mut Self {
        self.host = host;
        self.tcp = true;
        self
    }

    /// Sets the TCP listening port and enables TCP connections.
    ///
    /// If no port is set, the builder will attempt to find an unused port through binding to port `0`. This
    /// is somewhat racy, but the only recourse, since Postgres does not support binding to port
    /// `0`.
    #[inline]
    pub fn port(&mut self, port: u16) -> &mut Self {
        self.port = Some(port);
        self.tcp = true;
        self
    }

    /// Enables TCP connections on an automatically selected port.
    #[inline]
    pub fn tcp(&mut self) -> &mut Self {
        self.tcp = true;
        self
    }

    /// Sets the location of the `postgres` binary.
    #[inline]
    pub fn postgres_binary<T: Into<path::PathBuf>>(&mut self, postgres_binary: T) -> &mut Self {
        self.postgres_binary = Some(postgres_binary.into());
        self
    }

    /// Adds a PostgreSQL server configuration override.
    ///
    /// The option is passed to `postgres` as `-c NAME=VALUE`.
    #[inline]
    pub fn postgres_option<K, V>(&mut self, name: K, value: V) -> &mut Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.postgres_options.push((name.into(), value.into()));
        self
    }

    /// Sets the startup probe delay.
    ///
    /// Between two startup probes, waits this long.
    #[inline]
    pub fn probe_delay(&mut self, probe_delay: Duration) -> &mut Self {
        self.probe_delay = probe_delay;
        self
    }

    /// Sets the location of the `psql` binary.
    #[inline]
    pub fn psql_binary<T: Into<path::PathBuf>>(&mut self, psql_binary: T) -> &mut Self {
        self.psql_binary = Some(psql_binary.into());
        self
    }

    /// Sets the maximum time to probe for startup.
    #[inline]
    pub fn startup_timeout(&mut self, startup_timeout: Duration) -> &mut Self {
        self.startup_timeout = startup_timeout;
        self
    }

    /// Sets the maximum time to wait for graceful shutdown.
    ///
    /// Defaults to five seconds in fast mode and twenty seconds otherwise.
    /// An explicit timeout takes precedence regardless of builder call order.
    #[inline]
    pub fn shutdown_timeout(&mut self, shutdown_timeout: Duration) -> &mut Self {
        self.shutdown_timeout = Some(shutdown_timeout);
        self
    }

    /// Sets the maximum time to wait for forceful shutdown.
    #[inline]
    pub fn force_shutdown_timeout(&mut self, force_shutdown_timeout: Duration) -> &mut Self {
        self.force_shutdown_timeout = force_shutdown_timeout;
        self
    }

    /// Sets the initial superuser password.
    #[inline]
    pub fn superuser_pw<T: Into<String>>(&mut self, superuser_pw: T) -> &mut Self {
        self.superuser_pw = Some(superuser_pw.into());
        self
    }

    /// Resolves shutdown signals and timeouts for the configured mode.
    fn shutdown_policy(&self) -> ShutdownPolicy {
        let (signal, default_grace_time) = if self.fast {
            (Signal::SIGQUIT, Duration::from_secs(5))
        } else {
            (Signal::SIGINT, Duration::from_secs(20))
        };
        ShutdownPolicy::Graceful {
            signal,
            grace_time: self.shutdown_timeout.unwrap_or(default_grace_time),
            force_time: self.force_shutdown_timeout,
        }
    }

    /// Starts the Postgres server.
    ///
    /// Reuses saved setup when available and waits for authenticated database access.
    pub fn start(&self) -> Result<Postgres, Error> {
        let port = if self.tcp {
            self.port
                .unwrap_or_else(|| find_unused_port().expect("failed to find an unused port"))
        } else {
            DEFAULT_POSTGRES_PORT
        };

        let postgres_binary = self
            .postgres_binary
            .clone()
            .map(Ok)
            .unwrap_or_else(|| which::which("postgres").map_err(Error::FindPostgres))?;
        let pg_isready_binary = self
            .pg_isready_binary
            .clone()
            .map(Ok)
            .unwrap_or_else(|| which::which("pg_isready").map_err(Error::FindPgIsready))?;
        let psql_binary = self
            .psql_binary
            .clone()
            .map(Ok)
            .unwrap_or_else(|| which::which("psql").map_err(Error::FindPsql))?;

        let tmp_dir = tempfile::tempdir().map_err(Error::CreateDatabaseDir)?;
        let data_dir = self
            .data_dir
            .clone()
            .unwrap_or_else(|| tmp_dir.path().join("db"));
        let saved_state = State::load(&data_dir)?;
        let initialized = saved_state.is_some();
        let state = saved_state.unwrap_or_else(|| State {
            admin: Credentials {
                user: self.superuser.clone(),
                password: self
                    .superuser_pw
                    .clone()
                    .unwrap_or_else(generate_random_string),
            },
            user: None,
            database: None,
        });

        if !initialized {
            let initdb_binary = self
                .initdb_binary
                .clone()
                .map(Ok)
                .unwrap_or_else(|| which::which("initdb").map_err(Error::FindInitdb))?;
            let superuser_pw_file = tmp_dir.path().join("superuser-pw");
            fs::write(&superuser_pw_file, state.admin.password.as_bytes())
                .map_err(Error::WriteTemporaryPw)?;

            let mut initdb = process::Command::new(initdb_binary);
            initdb.args([
                // No default locale (== 'C').
                "--no-locale",
                // Require a password for all users.
                "--auth=md5",
                // Set default encoding to UTF8.
                "--encoding=UTF8",
            ]);
            if self.data_dir.is_none() {
                initdb.arg("--nosync");
            }
            let initdb_status = initdb
                .arg("--pgdata")
                .arg(&data_dir)
                .arg("--pwfile")
                .arg(&superuser_pw_file)
                .arg("--username")
                .arg(&state.admin.user)
                .status()
                .map_err(Error::RunInitDb)?;
            if !initdb_status.success() {
                return Err(Error::InitDbFailed(initdb_status));
            }
        }

        // Start the database.
        let mut postgres_command = process::Command::new(postgres_binary);
        postgres_command
            .arg("-D")
            .arg(&data_dir)
            .arg("-p")
            .arg(port.to_string())
            .arg("-k")
            .arg(tmp_dir.path());
        if self.fast {
            for option in [
                "fsync=off",
                "synchronous_commit=off",
                "full_page_writes=off",
            ] {
                postgres_command.arg("-c").arg(option);
            }
        }
        for (name, value) in &self.postgres_options {
            postgres_command.arg("-c").arg(format!("{name}={value}"));
        }
        if self.tcp {
            postgres_command.arg("-h").arg(&self.host);
        } else {
            postgres_command.arg("-c").arg("listen_addresses=");
        }

        #[cfg(target_os = "linux")]
        if self.shutdown_on_parent_death {
            postgres_command.parent_death_signal(Signal::SIGQUIT);
        }
        let instance =
            ProcessGuard::spawn_process_group(&mut postgres_command, self.shutdown_policy())
                .map_err(Error::LaunchPostgres)?;
        let process = PostgresProcess { instance, tmp_dir };

        // Wait for the server to become ready to accept connections.
        let started = Instant::now();
        loop {
            let mut pg_isready_command = process::Command::new(&pg_isready_binary);
            pg_isready_command.arg("-h");
            if self.tcp {
                pg_isready_command.arg(&self.host);
            } else {
                pg_isready_command.arg(process.tmp_dir.path());
            }
            let status = pg_isready_command
                .arg("-p")
                .arg(port.to_string())
                .stdout(process::Stdio::null())
                .stderr(process::Stdio::null())
                .status();

            match status {
                Ok(exit_status) if exit_status.success() => break,
                _ => {
                    if started.elapsed() >= self.startup_timeout {
                        return Err(Error::StartupTimeout);
                    }
                    thread::sleep(self.probe_delay);
                }
            }
        }

        let connection_url = if self.tcp {
            Url::parse(&format!("postgres://{}:{}", self.host, port))
                .expect("Failed to construct TCP URL")
        } else {
            let socket_dir = process.tmp_dir.path().to_string_lossy();
            let encoded_socket_dir = utf8_percent_encode(&socket_dir, NON_ALPHANUMERIC).to_string();
            Url::parse(&format!("postgres://{encoded_socket_dir}:{port}"))
                .expect("Failed to construct Unix socket URL")
        };
        let pg = Postgres {
            connection_url,
            credentials: state.admin.clone(),
            process,
            psql_binary,
            data_dir,
        };
        let output = pg
            .as_superuser()
            .psql("postgres")
            .args([
                "-XwAt",
                "-c",
                "SELECT split_part(pg_read_file('postmaster.pid'), chr(10), 1)",
            ])
            .stderr(process::Stdio::inherit())
            .output()
            .map_err(Error::RunPsql)?;
        if !output.status.success() {
            return Err(Error::PsqlFailed(output.status));
        }
        let expected_pid = pg
            .process
            .instance
            .id()
            .expect("PostgreSQL process is guarded");
        if String::from_utf8_lossy(&output.stdout).trim() != expected_pid.to_string() {
            return Err(Error::UnexpectedPostgres);
        }
        if !initialized {
            state.store(pg.data_dir())?;
        }
        Ok(pg)
    }
}

/// Generates a random hex string 32 characters long.
fn generate_random_string() -> String {
    let raw: [u8; 16] = rand::random();
    format!("{:x}", hex_fmt::HexFmt(&raw))
}

/// Escapes an identifier by wrapping in quote char. Any quote character inside the unescaped string
/// will be doubled.
fn quote(quote_char: char, unescaped: &str) -> String {
    let mut result = String::new();

    result.push(quote_char);
    for c in unescaped.chars() {
        if c == quote_char {
            result.push(quote_char);
            result.push(quote_char);
        } else {
            result.push(c);
        }
    }
    result.push(quote_char);

    result
}

/// Escapes an identifier.
fn escape_ident(unescaped: &str) -> String {
    quote('"', unescaped)
}

/// Escapes a string.
fn escape_string(unescaped: &str) -> String {
    quote('\'', unescaped)
}

/// Parses the `PGDB_TESTS_URL` environment variable if set.
///
/// The URL must be a complete Postgres URL with superuser credentials.
///
/// Returns `Ok(Some(url))` if valid, `Ok(None)` if not set, or `Err` if invalid.
pub fn parse_external_test_url() -> Result<Option<Url>, Error> {
    match env::var("PGDB_TESTS_URL") {
        Ok(url_str) => {
            let url = Url::parse(&url_str)
                .map_err(|e| Error::InvalidExternalUrl(ExternalUrlError::ParseError(e)))?;

            if url.scheme() != "postgres" {
                return Err(Error::InvalidExternalUrl(ExternalUrlError::InvalidScheme));
            }

            if url.host_str().is_none() {
                return Err(Error::InvalidExternalUrl(ExternalUrlError::MissingHost));
            }

            if url.username().is_empty() {
                return Err(Error::InvalidExternalUrl(ExternalUrlError::MissingUsername));
            }

            Ok(Some(url))
        }
        Err(_) => Ok(None),
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use process_guard::{DEFAULT_FORCE_TIME, ShutdownPolicy, Signal};
    use url::Url;

    use super::Postgres;

    /// Resolves mode defaults without overwriting explicit timeout settings.
    #[test]
    fn shutdown_policy_respects_mode_and_explicit_timeout() {
        for fast in [false, true] {
            for fast_first in [false, true] {
                for timeout in [None, Some(Duration::ZERO), Some(Duration::from_secs(7))] {
                    let mut builder = Postgres::build();
                    if fast && fast_first {
                        builder.fast();
                    }
                    if let Some(timeout) = timeout {
                        builder.shutdown_timeout(timeout);
                    }
                    if fast && !fast_first {
                        builder.fast();
                    }
                    assert_eq!(
                        builder.shutdown_policy(),
                        ShutdownPolicy::Graceful {
                            signal: if fast {
                                Signal::SIGQUIT
                            } else {
                                Signal::SIGINT
                            },
                            grace_time: timeout.unwrap_or(Duration::from_secs(if fast {
                                5
                            } else {
                                20
                            })),
                            force_time: DEFAULT_FORCE_TIME,
                        }
                    );
                }
            }
        }
    }

    #[test]
    fn connection_parameters_decode_socket_urls() {
        let url =
            Url::parse("postgres://dev@%2Ftmp%2Fpgdb:5432/dev").expect("socket URL must be valid");

        assert_eq!(super::connection_host(&url).as_deref(), Some("/tmp/pgdb"));
        assert_eq!(super::connection_port(&url), Some(5432));
    }

    #[test]
    fn can_change_superuser_pw() {
        let pg = Postgres::build()
            .superuser_pw("helloworld")
            .start()
            .expect("could not build postgres database");

        let su = pg.as_superuser();
        su.create_user("foo", "bar")
            .expect("could not create normal user");

        // Command executed successfully, check we used the right password.
        assert_eq!(su.client_url().password(), Some("helloworld"));
    }

    #[test]
    fn fast_mode_disables_runtime_durability() {
        let pg = Postgres::build()
            .fast()
            .start()
            .expect("could not build postgres database");
        let output = pg
            .as_superuser()
            .psql("postgres")
            .args([
                "-Atc",
                "SELECT current_setting('fsync'), current_setting('synchronous_commit'), current_setting('full_page_writes')",
            ])
            .output()
            .expect("could not query postgres settings");

        assert!(output.status.success());
        assert_eq!(
            String::from_utf8_lossy(&output.stdout).trim(),
            "off|off|off"
        );
    }

    #[test]
    fn instances_support_isolated_sockets_and_tcp() {
        let a = Postgres::build()
            .start()
            .expect("could not build postgres database");
        let b = Postgres::build()
            .start()
            .expect("could not build postgres database");
        let tcp = Postgres::build()
            .tcp()
            .start()
            .expect("could not build TCP postgres database");

        let a_url = a.superuser_url();
        let b_url = b.superuser_url();
        let tcp_url = tcp.superuser_url();
        let a_host = super::connection_host(&a_url).expect("URL must have a host");
        let b_host = super::connection_host(&b_url).expect("URL must have a host");
        let tcp_host = super::connection_host(&tcp_url).expect("URL must have a host");

        assert!(a_host.starts_with('/'));
        assert!(b_host.starts_with('/'));
        assert_ne!(a_host, b_host);
        assert_eq!(super::connection_port(&a_url), Some(5432));
        assert_eq!(super::connection_port(&b_url), Some(5432));
        assert_eq!(tcp_host, "127.0.0.1");
    }

    #[test]
    fn forceful_shutdown_waits_before_removing_temporary_directory() {
        let pg = Postgres::build()
            .shutdown_timeout(Duration::ZERO)
            .start()
            .expect("could not build postgres database");
        let temporary_directory = pg.process.tmp_dir.path().to_path_buf();

        drop(pg);

        assert!(!temporary_directory.exists());
    }

    #[test]
    fn ensure_proper_db_reuse_when_using_fixtures() {
        let db_url = crate::db_fixture();
        let db_url2 = crate::db_fixture();

        match (&db_url, &db_url2) {
            (crate::DbInstance::Local { .. }, crate::DbInstance::Local { .. }) => {
                // When using local databases, verify they have fixture prefixes
                assert!(db_url.as_str().contains("fixture_user_"));
                assert!(db_url.as_str().contains("fixture_pass_"));
                assert!(db_url.as_str().contains("fixture_db_"));

                assert!(db_url2.as_str().contains("fixture_user_"));
                assert!(db_url2.as_str().contains("fixture_pass_"));
                assert!(db_url2.as_str().contains("fixture_db_"));

                // Verify they have different databases/users
                assert_ne!(db_url.as_str(), db_url2.as_str());
            }
            (crate::DbInstance::External { .. }, crate::DbInstance::External { .. }) => {
                // When using external database, verify separate databases are created
                assert!(db_url.as_str().contains("fixture_user_"));
                assert!(db_url.as_str().contains("fixture_pass_"));
                assert!(db_url.as_str().contains("fixture_db_"));

                assert!(db_url2.as_str().contains("fixture_user_"));
                assert!(db_url2.as_str().contains("fixture_pass_"));
                assert!(db_url2.as_str().contains("fixture_db_"));

                // Verify they have different databases/users
                assert_ne!(db_url.as_str(), db_url2.as_str());

                // But they should use the same host/port
                assert_eq!(db_url.as_url().host_str(), db_url2.as_url().host_str());
                assert_eq!(db_url.as_url().port(), db_url2.as_url().port());
            }
            _ => panic!("Inconsistent DbUrl types returned from db_fixture"),
        }
    }

    #[test]
    fn external_db_cleanup_on_drop() {
        // Only run this test when external database is configured
        if crate::parse_external_test_url().unwrap().is_none() {
            return;
        }

        let superuser_url = crate::parse_external_test_url().unwrap().unwrap();
        let psql_binary = which::which("psql").unwrap_or_else(|_| "psql".into());

        // Create a database fixture
        let (db_name, db_user) = {
            let db_url = crate::db_fixture();

            // Extract the database and user names from URL
            match &db_url {
                crate::DbInstance::External { url, .. } => {
                    let db_name = url.path().trim_start_matches('/').to_string();
                    let db_user = url.username().to_string();
                    (db_name, db_user)
                }
                _ => panic!("Expected external database"),
            }
        }; // db_url is dropped here, should trigger cleanup

        // Give Drop some time to execute
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Check if database was dropped
        let check_db_exists = |name: &str| -> bool {
            let username = superuser_url.username();
            let password = superuser_url.password().unwrap_or_default();
            let host = superuser_url.host_str().unwrap();
            let port = superuser_url.port().unwrap_or(5432);

            let output = std::process::Command::new(&psql_binary)
                .arg("-h")
                .arg(host)
                .arg("-p")
                .arg(port.to_string())
                .arg("-U")
                .arg(username)
                .arg("-d")
                .arg("postgres")
                .arg("-t")
                .arg("-c")
                .arg(format!(
                    "SELECT 1 FROM pg_database WHERE datname = '{}'",
                    name
                ))
                .env("PGPASSWORD", password)
                .output()
                .expect("Failed to check database existence");

            String::from_utf8_lossy(&output.stdout).trim() == "1"
        };

        // Check if user was dropped
        let check_user_exists = |name: &str| -> bool {
            let username = superuser_url.username();
            let password = superuser_url.password().unwrap_or_default();
            let host = superuser_url.host_str().unwrap();
            let port = superuser_url.port().unwrap_or(5432);

            let output = std::process::Command::new(&psql_binary)
                .arg("-h")
                .arg(host)
                .arg("-p")
                .arg(port.to_string())
                .arg("-U")
                .arg(username)
                .arg("-d")
                .arg("postgres")
                .arg("-t")
                .arg("-c")
                .arg(format!("SELECT 1 FROM pg_roles WHERE rolname = '{}'", name))
                .env("PGPASSWORD", password)
                .output()
                .expect("Failed to check user existence");

            String::from_utf8_lossy(&output.stdout).trim() == "1"
        };

        // Verify cleanup
        assert!(
            !check_db_exists(&db_name),
            "Database should have been dropped"
        );
        assert!(
            !check_user_exists(&db_user),
            "User should have been dropped"
        );
    }
}