Repository navigation
Expand file tree
/
Copy pathdatabase.go
More file actions
112 lines (99 loc) · 2.52 KB
/
Copy pathdatabase.go
File metadata and controls
112 lines (99 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package testenv
import (
"cmp"
"context"
"fmt"
"net/netip"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/network"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func (b *Builder) DBEnable(v bool) *Builder {
b.dbEnable = v
return b
}
func (b *Builder) DBImage(v string) *Builder {
b.dbImage = v
return b
}
func (b *Builder) DBUser(v string) *Builder {
b.dbUser = v
return b
}
func (b *Builder) DBPass(v string) *Builder {
b.dbPass = v
return b
}
func (b *Builder) DBName(v string) *Builder {
b.dbName = v
return b
}
func (b *Builder) DBPort(v string) *Builder {
b.dbPort = v
return b
}
func SetupDatabase(ctx context.Context, image, dbUser, dbPass, dbName, hostPort string) (_ *gorm.DB, _ func() error, xerr error) {
image = cmp.Or(image, "postgres:17.4-alpine3.21")
dbUser = cmp.Or(dbUser, "postgres")
dbPass = cmp.Or(dbPass, "postgres")
dbName = cmp.Or(dbName, "postgres")
req := testcontainers.ContainerRequest{
Image: image,
ExposedPorts: []string{"5432/tcp"},
Env: map[string]string{
"POSTGRES_USER": dbUser,
"POSTGRES_PASSWORD": dbPass,
"POSTGRES_DB": dbName,
},
Cmd: []string{"postgres", "-c", "fsync=off"},
WaitingFor: wait.ForLog("database system is ready to accept connections").WithOccurrence(2),
}
if hostPort != "" {
req.HostConfigModifier = func(hostConfig *container.HostConfig) {
hostConfig.PortBindings = network.PortMap{
network.MustParsePort("5432/tcp"): {
{
HostIP: netip.IPv4Unspecified(),
HostPort: hostPort,
},
},
}
}
}
container, err := testcontainers.GenericContainer(ctx,
testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
},
)
if err != nil {
return nil, nil, fmt.Errorf("fail to start container: %w", err)
}
defer func() {
if xerr != nil {
container.Terminate(context.Background())
}
}()
endpoint, err := container.Endpoint(ctx, "")
if err != nil {
return nil, nil, fmt.Errorf("fail to get endpoint: %w", err)
}
dsn := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", dbUser, dbPass, endpoint, dbName)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, nil, fmt.Errorf("no underlying sqlDB: %w", err)
}
return db, func() error {
return cmp.Or(
sqlDB.Close(),
container.Terminate(context.Background()),
)
}, nil
}