Skip to content

Commit

Permalink
[TT-1262] add method to execute pg_dump inside Postgres container (#1038
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Tofel authored Aug 6, 2024
1 parent 0583756 commit d3b174f
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion docker/test_env/postgres.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package test_env

import (
"context"
"fmt"
"io"
"net/url"
Expand All @@ -11,9 +12,11 @@ import (

"github.com/docker/go-connections/nat"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
tc "github.com/testcontainers/testcontainers-go"
tcexec "github.com/testcontainers/testcontainers-go/exec"
tcwait "github.com/testcontainers/testcontainers-go/wait"

"github.com/smartcontractkit/chainlink-testing-framework/docker"
Expand Down Expand Up @@ -176,7 +179,9 @@ func (pg *PostgresDb) startOrRestartContainer(withReuse bool) error {
return nil
}

func (pg *PostgresDb) ExecPgDump(stdout io.Writer) error {
// ExecPgDumpFromLocal executes pg_dump from local machine by connecting to external Postgres port. For it to work pg_dump
// needs to be installed on local machine.
func (pg *PostgresDb) ExecPgDumpFromLocal(stdout io.Writer) error {
cmd := exec.Command("pg_dump", "-U", pg.User, "-h", "127.0.0.1", "-p", pg.ExternalPort, pg.DbName) //nolint:gosec
cmd.Env = []string{
fmt.Sprintf("PGPASSWORD=%s", pg.Password),
Expand All @@ -186,6 +191,40 @@ func (pg *PostgresDb) ExecPgDump(stdout io.Writer) error {
return cmd.Run()
}

// ExecPgDumpFromContainer executed pg_dump from inside the container. It dumps it to temporary file inside the container
// and then writes to the writer.
func (pg *PostgresDb) ExecPgDumpFromContainer(writer io.Writer) error {
tmpFile := "/tmp/db_dump.sql"
command := []string{"pg_dump", "-U", pg.User, "-f", tmpFile, pg.DbName}
env := []string{
fmt.Sprintf("PGPASSWORD=%s", pg.Password),
}

ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Minute)

_, _, err := pg.Container.Exec(ctx, command, tcexec.WithEnv(env))
if err != nil {
cancelFn()
return errors.Wrap(err, "Failed to execute pg_dump")
}

reader, err := pg.Container.CopyFileFromContainer(ctx, tmpFile)
if err != nil {
cancelFn()
return errors.Wrapf(err, "Failed to open for reading %s temporary file with db dump", tmpFile)
}

_, err = io.Copy(writer, reader)
if err != nil {
cancelFn()
return errors.Wrapf(err, "Failed to send data from %s temporary file with db dump", tmpFile)
}

cancelFn()

return nil
}

func (pg *PostgresDb) getContainerRequest() *tc.ContainerRequest {
return &tc.ContainerRequest{
Name: pg.ContainerName,
Expand Down

0 comments on commit d3b174f

Please sign in to comment.