Skip to content

Commit 890939b

Browse files
committed
2 parents b6c6d53 + 1f762d3 commit 890939b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

sqlserver/sqlserver.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@ package sqlserver
33
import (
44
"context"
55
"fmt"
6+
"io"
7+
"strings"
68

79
"github.com/docker/go-connections/nat"
10+
"github.com/google/uuid"
811
"github.com/testcontainers/testcontainers-go"
912
"github.com/testcontainers/testcontainers-go/wait"
1013
)
@@ -49,3 +52,19 @@ func (container *msSqlContainer) ConnectionString(ctx context.Context) (string,
4952

5053
return uri, nil
5154
}
55+
56+
func (container *msSqlContainer) ExecCommand(ctx context.Context, scriptContent string) (string, error) {
57+
scriptFilePath := strings.Join([]string{"./tmp", fmt.Sprintf("%s.sql", uuid.NewString())}, "/")
58+
err := container.CopyToContainer(ctx, []byte(scriptContent), scriptFilePath, 493)
59+
if err != nil {
60+
return "", err
61+
}
62+
_, reader, err := container.Exec(ctx, []string{"/opt/mssql-tools/bin/sqlcmd", "-b", "-r", "1", "-U", container.config.username, "-P", container.config.password, "-i", scriptFilePath})
63+
if err != nil {
64+
return "", err
65+
}
66+
if b, err := io.ReadAll(reader); err == nil {
67+
return string(b), nil
68+
}
69+
return "", err
70+
}

sqlserver/sqlserver_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,28 @@ func TestSqlServerContainerPing(t *testing.T) {
4747
subject := client.QueryRow("SELECT 1")
4848
assert.NoError(t, subject.Err())
4949
}
50+
51+
func TestSqlServerContainerExecCommand(t *testing.T) {
52+
if testing.Short() {
53+
t.Skip("skipping integration test")
54+
}
55+
config := NewSqlServerContainerConfigurationBuilder().Build()
56+
// Arrange
57+
ctx := context.Background()
58+
59+
container, err := StartContainer(ctx, config)
60+
if err != nil {
61+
t.Fatal(err)
62+
}
63+
t.Cleanup(func() {
64+
if err := container.Terminate(ctx); err != nil {
65+
t.Fatalf("failed to terminate container: %s", err)
66+
}
67+
})
68+
69+
result, err := container.ExecCommand(ctx, "SELECT 1;")
70+
71+
assert.NoError(t, err)
72+
73+
assert.Contains(t, result, "1 rows affected")
74+
}

0 commit comments

Comments
 (0)