postgresqlgocommand-line

how to pipe pasword string to another cmd get started with golang


i want exactly to run postgres backup using pgdump_all, but when starting it using cmd package in golang it shows in terminal it need postgres password to run the job , i searched previously and find out some way to use stdin pip of cmd get run , but even with a lot effort on it , still can not make any result and still show me in terminal it need password ... and more crazy to me ... even when i personally type the password in terminal still shows me wrong password ... i even added PGPASSWORD as env variable before run command but still not working

os.Setenv("PGPASSWORD", "secret")
cmd := exec.Command("C:\Program Files\PostgreSQL\17\bin\pg_dumpall.exe", --username="postgres", -p 5432, -w, > ".\backup\backup.dump")

stdin, err := cmd.StdinPipe()
if err != nil {
    fmt.Println("not get in ... \n " + err.Error())
}
defer stdin.Close()

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

err = cmd.Start()
if err != nil {
    fmt.Println("not started ... \n " + err.Error())
}

_, err = io.WriteString(stdin, "secret"+"\r\n")
if err != nil {
    fmt.Println("not input... \n " + err.Error())
}

err = cmd.Wait()
if err != nil {
    fmt.Println("not wait ... \n " + err.Error())
}

i need a way to pass password string to pgdump_all get run


Solution

  • it is very frequent trap when trying to automate pg_dumpall (or any PostgreSQL ) from Go (or any source). What you are experiencing is not about stdin piping but about how PostgreSQL client programs handle validation. try the following.

    1. Use PGPASSWORD Variable, which sets the user name used to connect to the database

    2. Use a .pgpass File your file should be created with ~/.pgpass