From c5f0b46e77e528b15d5ca2a9f3d5f6a1d45930cb Mon Sep 17 00:00:00 2001 From: kolaente Date: Sun, 5 Dec 2021 12:11:50 +0100 Subject: [PATCH] feat: add support for different postgres versions --- dump_postgres.go | 16 +++++++++++++++- dump_postgres_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/dump_postgres.go b/dump_postgres.go index bb26fd9..7f32dae 100644 --- a/dump_postgres.go +++ b/dump_postgres.go @@ -3,6 +3,7 @@ package main import ( "fmt" "github.com/docker/docker/api/types" + "strings" ) type PostgresDumper struct { @@ -43,10 +44,23 @@ func (d *PostgresDumper) buildConnStr() string { return fmt.Sprintf("postgresql://%s:%s@%s:%s/%s", user, pw, host, port, db) } +func findPgVersion(env []string) string { + for _, s := range env { + if strings.HasPrefix(s, "PG_MAJOR=") { + return strings.TrimPrefix(s, "PG_MAJOR=") + } + } + + return "" +} + func (d *PostgresDumper) Dump() error { fmt.Printf("Dumping postgres database from container %s...\n", d.Container.Name) connStr := d.buildConnStr() - return runAndSaveCommand(getDumpFilename(d.Container.Name), "pg_dump", "--dbname", connStr) + // The postgres version must match the one the db server is running + pgVersion := findPgVersion(d.Container.Config.Env) + + return runAndSaveCommand(getDumpFilename(d.Container.Name), "pg_dump"+pgVersion, "--dbname", connStr) } diff --git a/dump_postgres_test.go b/dump_postgres_test.go index 8e31a7f..aff2f65 100644 --- a/dump_postgres_test.go +++ b/dump_postgres_test.go @@ -115,3 +115,28 @@ func TestPostgresDumper_buildConnStr(t *testing.T) { }) } } + +func TestFindPGVersionFromEnv(t *testing.T) { + t.Run("no PG_MAJOR", func(t *testing.T) { + pgVersion := findPgVersion([]string{}) + if pgVersion != "" { + t.Errorf("Version is not empty") + } + }) + t.Run("pg 14", func(t *testing.T) { + pgVersion := findPgVersion([]string{ + "POSTGRES_PASSWORD=test", + "POSTGRES_USER=user", + "POSTGRES_DB=test", + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/14/bin", + "GOSU_VERSION=1.14", + "LANG=en_US.utf8", + "PG_MAJOR=14", + "PG_VERSION=14.1-1.pgdg110+1", + "PGDATA=/var/lib/postgresql/data", + }) + if pgVersion != "14" { + t.Errorf("Version is not 14") + } + }) +}