gorm raw query argument

73 Views Asked by At

I am trying to get some records from postgresql database using gorm raw query.

includedStates := []string{"new", "old"}
selectStatement := `select u.department, u.position, u.city, u.join_date, v.name as venture,
      ud.first_name_fa, ud.last_name_fa, ud.cellphone from my_schema.users u
      inner join my_schema.ventures v on u.venture_id = v.id
      left join my_schema.details ud on ud.user_id = u.id
      where status in ? AND join_date::date = (NOW() + INTERVAL '?' day)::date;`

var result []models.User

if err := ur.db.
    Raw(selectStatement, includedStates, days).
    Scan(&result).Error; err != nil {
    return nil, err
}

But I get following error on Scan:

expected 3 arguments, got 4 

I have exactly two variables and I pass the string query plus two arguments to the Raw method.

Besides, I got the query from logs and it returns records with no error in the database console.

EDIT 1:

The days variable is the input of the method with type int.

If I remove the quotation around second ?, gorm assumes it is a variable and I get the following error (I passed number 4 to the method in this case):

syntax error at or near "$4" (SQLSTATE 42601)

EDIT 2:

I have fixed it by removing the second ? and use it inline; not as a variable:

selectStatement := `select u.department, u.position, u.city, u.join_date, v.name as venture,
      ud.first_name_fa, ud.last_name_fa, ud.cellphone from my_schema.users u
      inner join my_schema.ventures v on u.venture_id = v.id
      left join my_schema.details ud on ud.user_id = u.id
      where status in ? AND join_date::date = (NOW() + INTERVAL '` + strconv.Itoa(days) + `' day)::date;`

I still don't know what is wrong with the first query, since it was a normal integer variable. So, I will keep the question open.

0

There are 0 best solutions below