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 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions canned/postgresql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package canned

import (
"context"
"database/sql"
"database/sql/driver"
"fmt"

"github.com/docker/go-connections/nat"
"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

connectorVars := map[string]interface{}{
"port": port,
"user": req.User,
"password": req.Password,
"database": req.Database,
}

req.WaitingFor = wait.ForSQL(postgresConnectorFromTarget, connectorVars)

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")
}
}

return postgresC, nil
}

func postgresConnectorFromTarget(ctx context.Context, target wait.StrategyTarget, variables wait.SQLVariables) (driver.Connector, error) {

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

mappedPort, err := target.MappedPort(ctx, nat.Port(variables["port"].(string)))
if err != nil {
return nil, err
}

connString := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
host,
mappedPort.Int(),
variables["user"],
variables["password"],
variables["database"],
)

return pq.NewConnector(connString)
}
34 changes: 34 additions & 0 deletions canned/postgresql_test.go
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
56 changes: 56 additions & 0 deletions wait/sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package wait

import (
"context"
"time"

"database/sql"
"database/sql/driver"

"github.com/pkg/errors"
)

type SQLVariables map[string]interface{}

type SQLConnectorFromTarget func(ctx context.Context, target StrategyTarget, variables SQLVariables) (driver.Connector, error)

var _ Strategy = (*SQLStrategy)(nil)

type SQLStrategy struct {
startupTimeout time.Duration
ConnectorSource SQLConnectorFromTarget
SQLVariables SQLVariables
}

func NewSQLStrategy(ds SQLConnectorFromTarget, sv SQLVariables) *SQLStrategy {
return &SQLStrategy{
startupTimeout: defaultStartupTimeout(),
ConnectorSource: ds,
SQLVariables: sv,
}
}

func ForSQL(ds SQLConnectorFromTarget, sv SQLVariables) *SQLStrategy {
return NewSQLStrategy(ds, sv)
}

func (ws *SQLStrategy) WaitUntilReady(ctx context.Context, target StrategyTarget) error {

conn, err := ws.ConnectorSource(ctx, target, ws.SQLVariables)
if err != nil {
return errors.Wrap(err, "could not retrieve the SQL connector from the provided function")
}

db := sql.OpenDB(conn)

for {
_, err := db.ExecContext(ctx, "SELECT 1")
if err != nil {
time.Sleep(500 * time.Millisecond)
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe there should be a max wait time, just in case?

Copy link
Author

Choose a reason for hiding this comment

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

Whoops... you're right. I completely forgot.
I did the same as in wait/log.go now. Also added the fluent builders as in LogStrategy for consistency

continue
}
break
}

return nil
}