Home > front end >  pq: password authentication failed for user "user-name" while accessing postgres in vscode
pq: password authentication failed for user "user-name" while accessing postgres in vscode

Time:02-28

I am making an API using Golang, and I am using Postgres as database. I have used the following command:-

args := "host="   host   " port="   port   " dbName="   dbName   "username="   username   " sslmode=disable password="   password
    db, err := gorm.Open("postgres", args)
    if err != nil {
        log.Fatal(err)
    }
db.AutoMigrate(models.Hospital{})
    DB = db

But while I build the model, I am getting the error as:-

pq: password authentication failed for user "Ansh Joshi"

Though when I try to login using the same password in pgAdmin, I am able to log in it perfectly fine. Then the thing I am not able to understand is why I am unable to connect it while using vscode.

Any help would be much appreciated. Thank you in advance...

CodePudding user response:

In the connection string, 'username' is not an accepted synonym for 'user'. And 'dbName' is not an accepted synonym for 'dbname'.

So the "Ansh Joshi" for the user name in the error message is not coming from the value you passed in, but instead is (apparently) falling back to the default, which is to use your OS username. When you can successfully connect from pgAdmin, you are presumably using a different user name than "Ansh Joshi": a user name that does match the password. The presence in the error message of a user name which differs from the correct one should have tipped you off about the nature of the error.

The password error preempts the other errors you get. If you hadn't failed with the password error, you probably would have failed with something like FATAL: unrecognized configuration parameter "username".

CodePudding user response:

I'm not sure your code to open connection with gorm is correct.

In the documentation, it's write like this

dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

I recommend you to set dsn with fmt.Sprintf for more readable.
Because your user have space, you should add ' in start and end user

This is the example:

    args := fmt.Sprintf("host=%s port=%s dbname=%s user='%s' password=%s sslmode=%s", host, port, dbName, username, password, sslmode)
    fmt.Println(args)

    db, err := gorm.Open(postgres.Open(args), nil)
    if err != nil {
        log.Fatal(err)
    }

  • Related