0

I am making a simple CRUD app with Golang using a postgres database hosted on my computer. I am using the sql driver https://github.com/lib/pq. I am able to successfully store users in the database from a POST request with the following code

func createUser(name string, email string, password string) {
  psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)
  db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
  _, err = db.Exec("INSERT INTO USERDATA (name,email,password) VALUES($1,$2,$3);", name, email, password)
    if err != nil {
        panic(err)
    }
  db.Close()
}

However When I try to use very similar code to look up a user with data from a GET request it give the error "pq: relation "userdata" does not exist". I do not understand how it cannot find the sql table userdata when it is able to create a user in that table. The following code is the code that generates the error.

func lookUpEmail(email string) User {
  psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)
  db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }

  if err = db.Ping(); err != nil {
    fmt.Println("ERROR 0")
    panic(err)
    }
  fmt.Println(os.Stdout,"Succesfully connected")

  row := db.QueryRow("SELECT * FROM USERDATA WHERE email = $1", email)
  if row.Err() != nil {
    fmt.Println("ERROR 1")
    panic(row.Err())
  }
  user := new(User)
  err = row.Scan(&user.name,&user.email,&user.password)
  if err != nil {
    fmt.Println("ERROR 2")
    panic(err)
  }
  return *user
}

This code returns error : "pq: relation "userdata" does not exist"

If I type in the query "SELECT * FROM USERDATA WHERE email = (insert email)" into my sql console it works fine.

1 Answers1

0

check carefully your dbname=%s parameter and check does your table actually created in %s namespace. In postgres you need to for example \c test where 'test' is namespace(db) name, if not you can try to create db in the next way by using docker-compose file

version: "3"

services:
  postgres:
    image: postgres
    container_name: 'postgres'
    ports:
      - 5432:5432
    volumes:
      - /_postgres:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: test

volumes:
  postgres:
    driver: local
Set volumes related to you directory
Mike Tkachuk
  • 59
  • 2
  • 6