From 5be325405d77f5225e7cc95da2ac8595c9559a15 Mon Sep 17 00:00:00 2001 From: Cookie <2061803022@qq.com> Date: Thu, 5 Dec 2024 16:00:52 +0800 Subject: [PATCH] Fix: Postgres fails to connect when using special characters (#7262) * Update client.go * Update remote.go * Update client.go --- backend/utils/postgresql/client.go | 6 +++++- backend/utils/postgresql/client/remote.go | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/backend/utils/postgresql/client.go b/backend/utils/postgresql/client.go index 2122c28bb..125588752 100644 --- a/backend/utils/postgresql/client.go +++ b/backend/utils/postgresql/client.go @@ -32,7 +32,11 @@ func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) { return client.NewLocal(connArgs, conn.Address, conn.Username, conn.Password, conn.Database), nil } - connArgs := fmt.Sprintf("postgres://%s:%s@%s:%d/?sslmode=disable", conn.Username, conn.Password, conn.Address, conn.Port) + // Escape username and password to handle special characters + escapedUsername := url.QueryEscape(username) + escapedPassword := url.QueryEscape(password) + + connArgs := fmt.Sprintf("postgres://%s:%s@%s:%d/?sslmode=disable", escapedUsername, escapedPassword, conn.Address, conn.Port) db, err := sql.Open("pgx", connArgs) if err != nil { return nil, err diff --git a/backend/utils/postgresql/client/remote.go b/backend/utils/postgresql/client/remote.go index b4a954181..8a030fc7a 100644 --- a/backend/utils/postgresql/client/remote.go +++ b/backend/utils/postgresql/client/remote.go @@ -134,7 +134,7 @@ func (r *Remote) Backup(info BackupInfo) error { } fileNameItem := info.TargetDir + "/" + strings.TrimSuffix(info.FileName, ".gz") backupCommand := exec.Command("bash", "-c", - fmt.Sprintf("docker run --rm --net=host -i %s /bin/bash -c 'PGPASSWORD=%s pg_dump -h %s -p %d --no-owner -Fc -U %s %s' > %s", + fmt.Sprintf("docker run --rm --net=host -i %s -e PGPASSWORD='%s' /bin/bash -c 'pg_dump -h %s -p %d --no-owner -Fc -U %s %s' > %s", imageTag, r.Password, r.Address, r.Port, r.User, info.Name, fileNameItem)) _ = backupCommand.Run() b := make([]byte, 5) @@ -177,7 +177,7 @@ func (r *Remote) Recover(info RecoverInfo) error { }() } recoverCommand := exec.Command("bash", "-c", - fmt.Sprintf("docker run --rm --net=host -i %s /bin/bash -c 'PGPASSWORD=%s pg_restore -h %s -p %d --verbose --clean --no-privileges --no-owner -Fc -U %s -d %s --role=%s' < %s", + fmt.Sprintf("docker run --rm --net=host -i %s -e PGPASSWORD='%s' /bin/bash -c 'pg_restore -h %s -p %d --verbose --clean --no-privileges --no-owner -Fc -U %s -d %s --role=%s' < %s", imageTag, r.Password, r.Address, r.Port, r.User, info.Name, info.Username, fileName)) pipe, _ := recoverCommand.StdoutPipe() stderrPipe, _ := recoverCommand.StderrPipe()