Skip to content

Commit

Permalink
chore: Use generic db url for postgresql container (#1493)
Browse files Browse the repository at this point in the history
* Use generic db url for postgresql container

Before we where using the PG specific url format but most tools would
expect the url on the generic one (i.e https://github.com/golang-migrate/migrate).

People could indeed write their own connString mapper but that would be
unnecessary. (Ideally tools would not try to parse the url and instead
just use the string but sometimes they might need to, thus using the
generic format would work most of the times)

* use strings.join
  • Loading branch information
kevinrobayna authored Aug 11, 2023
1 parent 4b48269 commit c4236fb
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
11 changes: 4 additions & 7 deletions modules/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package postgres
import (
"context"
"fmt"
"net"
"path/filepath"
"strings"

"github.com/testcontainers/testcontainers-go"
)
Expand Down Expand Up @@ -35,12 +37,8 @@ func (c *PostgresContainer) ConnectionString(ctx context.Context, args ...string
return "", err
}

extraArgs := ""
for _, arg := range args {
extraArgs += " " + arg
}

connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s %s", host, containerPort.Port(), c.user, c.password, c.dbName, extraArgs)
extraArgs := strings.Join(args, "&")
connStr := fmt.Sprintf("postgres://%s:%s@%s/%s?%s", c.user, c.password, net.JoinHostPort(host, containerPort.Port()), c.dbName, extraArgs)
return connStr, nil
}

Expand All @@ -58,7 +56,6 @@ func WithConfigFile(cfg string) testcontainers.CustomizeRequestOption {
req.Files = append(req.Files, cfgFile)
req.Cmd = append(req.Cmd, "-c", "config_file=/etc/postgresql.conf")
}

}

// WithDatabase sets the initial database to be created when the container starts
Expand Down
5 changes: 5 additions & 0 deletions modules/postgres/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ func TestPostgres(t *testing.T) {
assert.NoError(t, err)
// }

// Ensure connection string is using generic format
id, err := container.MappedPort(ctx, "5432/tcp")
assert.NoError(t, err)
assert.Equal(t, fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable&application_name=test", user, password, "localhost", id.Port(), dbname), connStr)

// perform assertions
db, err := sql.Open("postgres", connStr)
assert.NoError(t, err)
Expand Down

0 comments on commit c4236fb

Please sign in to comment.