Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

canned postgresql #98

Closed
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
147 changes: 147 additions & 0 deletions canned/postgresql.go
@@ -0,0 +1,147 @@
package canned

import (
"context"
"database/sql"
"fmt"
"net"
"os"
"syscall"
"time"

_ "github.com/lib/pq"
"github.com/pkg/errors"
testcontainers "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)

const (
user = "user"
password = "password"
database = "database"
image = "postgres"
defaultTag = "11.5"
port = "5432/tcp"
)

type PostgreSQLContainerRequest struct {
testcontainers.GenericContainerRequest
User string
Password string
Database string
}

type postgresqlContainer struct {
Container testcontainers.Container
db *sql.DB
req PostgreSQLContainerRequest
}

func (c *postgresqlContainer) GetDriver(ctx context.Context) (*sql.DB, error) {

host, err := c.Container.Host(ctx)
if err != nil {
return nil, err
}

mappedPort, err := c.Container.MappedPort(ctx, port)
if err != nil {
return nil, err
}

db, err := sql.Open("postgres", fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host,
mappedPort.Int(),
c.req.User,
c.req.Password,
c.req.Database,
))
if err != nil {
return nil, err
}

return db, nil
}

func PostgreSQLContainer(ctx context.Context, req PostgreSQLContainerRequest) (*postgresqlContainer, error) {

provider, err := req.ProviderType.GetProvider()
if err != nil {
return nil, err
}

// With the current logic it's not really possible to allow other ports...
req.ExposedPorts = []string{port}

if req.Env == nil {
req.Env = map[string]string{}
}

// Set the default values if none were provided in the request
if req.Image == "" {
req.Image = fmt.Sprintf("%s:%s", image, defaultTag)
}

if req.User == "" {
req.User = user
}

if req.Password == "" {
req.Password = password
}

if req.Database == "" {
req.Database = database
}

req.Env["POSTGRES_USER"] = req.User
req.Env["POSTGRES_PASSWORD"] = req.Password
req.Env["POSTGRES_DB"] = req.Database

req.WaitingFor = wait.ForAll(
wait.ForLog("database system is ready to accept connections"),
wait.ForListeningPort(port),
)

c, err := provider.CreateContainer(ctx, req.ContainerRequest)
if err != nil {
return nil, errors.Wrap(err, "failed to create container")
}

postgresC := &postgresqlContainer{
Container: c,
req: req,
}

if req.Started {
if err := c.Start(ctx); err != nil {
return postgresC, errors.Wrap(err, "failed to start container")
}

db, err := postgresC.GetDriver(ctx)
if err != nil {
return nil, err
}

for {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this is because the postgres container "bounces" and logs the "database system is ready to accept connections" twice?

In the java testcontainer that's handled by having the Wait code have a state and wait for it twice.

I think I prefer this, as it keeps the Waits simple

Copy link
Author

@borgoat borgoat Sep 29, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I don't understand why the Postgres container is doing that, but basically the process gets restarted, so you'd have to wait for the second "database system is ready to accept connections". So I tried to mimic the Java implementation for the generic JDBC containers.

I realised though, the wait strategy I put there is basically pointless? 🤔

I have another proposal to make the same wait process into a proper SQLStrategy wait strategy.

_, err := db.ExecContext(ctx, "SELECT 1")
if err != nil {
fmt.Print(err)
if v, ok := err.(*net.OpError); ok {
if v2, ok := (v.Err).(*os.SyscallError); ok {
if v2.Err == syscall.ECONNRESET {
time.Sleep(500 * time.Millisecond)
continue
}
}
}

return nil, err
}
break
}
}

return postgresC, nil
}
34 changes: 34 additions & 0 deletions canned/postgresql_test.go
@@ -0,0 +1,34 @@
package canned

import (
"context"
"testing"

testcontainers "github.com/testcontainers/testcontainers-go"
)

func TestWriteIntoAPostgreSQLContainerViaDriver(t *testing.T) {

ctx := context.Background()

c, err := PostgreSQLContainer(ctx, PostgreSQLContainerRequest{
Database: "hello",
GenericContainerRequest: testcontainers.GenericContainerRequest{
Started: true,
},
})
if err != nil {
t.Fatal(err.Error())
}
defer c.Container.Terminate(ctx)

sqlC, err := c.GetDriver(ctx)
if err != nil {
t.Fatal(err.Error())
}

_, err = sqlC.ExecContext(ctx, "CREATE TABLE example ( id integer, data varchar(32) )")
if err != nil {
t.Fatal(err.Error())
}
}
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -17,6 +17,7 @@ require (
github.com/gorilla/context v1.1.1 // indirect
github.com/gorilla/mux v1.6.2 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/lib/pq v1.2.0
github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c // indirect
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Expand Up @@ -38,6 +38,8 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w=
Expand Down Expand Up @@ -71,6 +73,7 @@ golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down