How to translate/convert a Postgresql IN query as variable and send the variable using Golang and SQLC with a proper struct?

Viewed 52

First of all, if someone has a better sentence for my question, feel free to comment.

I want to translate this query into Golang

SELECT
    mou."id",
    mou."name",
    mou.description,
    mou.img_url,
    um.favorite 
FROM
    majors_of_universities mou
    JOIN field_of_studies fos ON mou.field_of_studies_id = fos."id"
    JOIN univ_major um ON mou."id" = um.majors_of_universities_id 
WHERE
    mou."name" ILIKE '%%' 
    AND fos."name" IN ( 'IT & Software', 'Analisis Data & Statistik' ) 
ORDER BY
    mou."name" 
    LIMIT 99 OFFSET 0;

This query works well, btw. I'm using sqlc as a generator and by it rules (CMIIW), I changed...

  • '%%' to $1
  • 'IT & Software', 'Analisis Data & Statistik' to $2
  • 99 to $3
  • 0 to $4

so it become a variable. little did I know, the $2 generated into a string data type. what I want is it generated into an array of string data type, because I found out that Golang can translate an array of string from ["1", "2", "3"] into '1', '2', '3' , just like what I want to input inside postgres IN parenthesis.

in Golang side, I made a custom struct like this

type SearchMajorReq struct {
    Name           string   `json:"name"`
    FieldOfStudies []string `json:"field_of_studies"`
    Limit          int32    `json:"limit"`
    Page           int32    `json:"page"`
}

in hope that this is the correct data type to send a JSON req body like this

{
    "name":"",
    "field_of_studies": ["1", "2", "3"],
    "limit": 10,
    "page": 1
}

but it doesn't works. I have an error in FieldOfStudies part. How can I solve this?

0 Answers
Related