MCPcopy Create free account
hub / github.com/apecloud/myduckserver / StartPostgresServer

Function StartPostgresServer

pgserver/logrepl/common_test.go:37–74  ·  view source on GitHub ↗

StartPostgresServer configures a starts a fresh Postgres server instance in a Docker container and returns the port it is running on. If unable to start up the server, an error is returned.

()

Source from the content-addressed store, hash-verified

35// StartPostgresServer configures a starts a fresh Postgres server instance in a Docker container
36// and returns the port it is running on. If unable to start up the server, an error is returned.
37func StartPostgresServer() (containerName string, dsn string, port int, err error) {
38 port = findFreePort()
39
40 // Use a random name for the container to avoid conflicts
41 containerName = "postgres-test-" + strconv.Itoa(rand.Int())
42
43 // Build the Docker command to start the Postgres container
44 // NOTE: wal_level must be set to logical for logical replication to work.
45 // Otherwise: ERROR: logical decoding requires "wal_level" >= "logical" (SQLSTATE 55000)
46 cmd := exec.Command("docker", "run",
47 "--rm", // Remove the container when it stops
48 "-d", // Run in detached mode
49 "-p", fmt.Sprintf("%d:5432", port), // Map the container's port 5432 to the host's port
50 "-e", "POSTGRES_PASSWORD=password", // Set the root password
51 "--name", containerName, // Give the container a name
52 "postgres:latest", // Use the latest Postgres image
53 "-c", "wal_level=logical", // Enable logical replication
54 "-c", "max_wal_senders=30", // Set the maximum number of WAL senders
55 // "-c", "wal_sender_timeout=10000", // Set the WAL sender timeout (in milliseconds)
56 )
57
58 // Execute the Docker command
59 output, err := cmd.CombinedOutput()
60 if err != nil {
61 return "", "", -1, fmt.Errorf("unable to start MySQL container: %v - %s", err, output)
62 }
63
64 // Wait for the MySQL server to be ready
65 dsn = fmt.Sprintf("postgres://postgres:password@localhost:%v/postgres", port)
66 err = waitForSqlServerToStart(dsn)
67 if err != nil {
68 return "", "", -1, err
69 }
70
71 fmt.Printf("Postgres server started in container %s on port %v \n", containerName, port)
72
73 return
74}
75
76// waitForSqlServerToStart polls the specified database to wait for it to become available, pausing
77// between retry attempts, and returning an error if it is not able to verify that the database is

Callers 1

RunReplicationScriptsFunction · 0.85

Calls 2

findFreePortFunction · 0.85
waitForSqlServerToStartFunction · 0.85

Tested by

no test coverage detected