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

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?

Related

How to filter data through WHERE json statement - postgres

structure of column is> SELECT "startedByAttendanceEntry" FROM "attendance_block"
[
{
person: {
firstName: "Koste";
lastName: "Litaci";
};
}
...
]
Data type is json, I can't change type or any of the structure of db
What I want to achieve is to select only elements with person firstName = Koste AND lastName = Litaci
what I tried
SELECT "startedByAttendanceEntry"
FROM "attendance_block"
WHERE 'person' ->> 'lastName' = 'Litaci'
AND 'person' ->> 'firstName' = 'Koste'
and many more all end it with err saying driverError: error: operator is not unique: unknown ->> unknown
Well, 'person' is a varchar/text constant, and thus you cannot apply a JSON operator on it. Additionally your JSON contains an array, so access through ->> won't work either because you need to specify the array index.
You can use the contains operator #> to find a specific key/value pair in the array. As you chose to not use the recommended jsonb type, you need to cast the column:
where "startedByAttendanceEntry"::jsonb #> '[{"person":{"firstName": "Koste", "lastName": "Litaci"}}]'
TOPIC AUTHOR EDIT:
all the code to work was as follow
SELECT "startedByAttendanceEntry"
FROM "attendance_block"
WHERE "startedByAttendanceEntry"::jsonb #> '{"person":{"firstName": "Koste", "lastName": "Litaci"}}'

How to bind an array to a parameter used alongside IN operator in sequelize query

I had to write a custom postgres sql query, so I used sequelize.query method. But I am a bit lost in how I can bind an array to a parameter used alongside an IN operator. The current code looks something like this, with obviously doesn't work.
sequelize.query('SELECT * FROM students WHERE grade IN $grades', {
bind: { grades: ['A+', 'A'] },
type: sequelize.QueryTypes.SELECT,
});
Use = any instead of in. Change the query text to
SELECT * FROM students WHERE grade = any(string_to_array($grades, ','))
or
SELECT * FROM students WHERE grade = any(('{'||$grades||'}')::text[])
and bind grades as a string, 'A+,A'.
The second option works for other data types too.

Error while inserting array and JSON into PostgreSQL using Codeigniter 3.1.10

I am working on a project which uses Codeigniter 3.1.10 framework and PostgreSQL as database. and I am passing a form value from controller to model like the following:
$data = array(
'field1' => $value1,
'field2' => $value2,
'field3' => $value3
)
$result = $this->modal->function_insert($data);
where value 1 is string, value2 is an array and value3 is JSON. I am trying to insert data to PostgreSQL. In table, data types are correctly defined which are respectively text, text[] and jsonb.
While in modal my code goes like this:
public function function_insert($data)
{
$result = $this->db->insert('table_name', $data);
}
I am getting the following error from codeigniter:
Severity: Notice
Message: Array to string conversion
Filename: database/DB_driver.php
Line Number: 1471
Backtrace:
And the query shows like this:
INSERT INTO "table_name" ("field1", "field2", "field3") VALUES ('1', Array, Array)
Is there any issue in my code, data that I pass to model or something else.
It is not possible to direct insert of PHP Arrays into the database. You have to do some tricks like in the below examples.
1. For inserting PHP Array into Postgres Column value of type Array
$phpArray = [1,3,3];
$pgColValue = '{'.implode($phpArray,',').'}';
echo $pgColValue;
//outputs
{1,3,3} // Treated as postgres array
2. For inserting JSON. Use PHP built in function name json_encode() for conveting PHP array to JSON string.
$phpArray = [1,3,3];
$pgColValue = json_encode($phpArray);
echo $pgColValue;
//outputs
[1,3,3]

How to format PostgreSQL jsonb_set as a prepared statement

var query=`UPDATE "public"."vehicle_ads"
SET options=
jsonb_set(
options,
'{$1, ${subgroup}, -1}',
'{"name": "${optionName}"}'::jsonb
)
WHERE "vehicleId"=${id}`;
I'm having the following issues with the above query. If I replace $1 with ${group}, no error. But if I leave $1 and pass group as a prepared statement, I get the error...
bind message supplies 1 parameters, but prepared statement "" requires 0
My goal is to tokenize the entire query, e.g.:
var query=`UPDATE "public"."vehicle_ads"
SET options=
jsonb_set(
options,
'{$1, $2, -1}',
'{"name": $3}'::jsonb
)
WHERE "vehicleId"=$4`;
Then...
could not determine data type of parameter $1
I know I'm lost in a formatting soup of template strings and Postgres, unsure what needs ticks, single quotes, or double. Any help is greatly appreciated.
EDIT:
Here's what I'm doing with detail.
I have a nested object with vehicle options data stored as a jsonb field. It has the form:
{
"Group": {
"SubGroup": [
{
"name": string,
"hasOption": bool
}
...
]
...
}
...
}
I want to edit the name in a sub group. For instance Powertrain.Drivetrain[0].name='AWD';
You'll have to convert the variable to text before converting it to jsonb using to_jsonb
UPDATE table SET body = jsonb_set(options, '{key}', to_jsonb($1::text));

Updating an array of objects fields in crate

I created a table with following syntax:
create table poll(poll_id string primary key,
poll_type_id integer,
poll_rating array(object as (rating_id integer,fk_user_id string, israted_image1 integer, israted_image2 integer, updatedDate timestamp, createdDate timestamp )),
poll_question string,
poll_image1 string,
poll_image2 string
)
And I inserted a record without "poll_rating" field which is actually an array of objects fields.
Now when I try to update a poll_rating with the following commands:
update poll set poll_rating = [{"rating_id":1,"fk_user_id":-1,"israted_image1":1,"israted_image2":0,"createddate":1400067339.0496}] where poll_id = "f748771d7c2e4616b1865f37b7913707";
I'm getting an error message like this:
"SQLParseException[line 1:31: no viable alternative at input '[']; nested: ParsingException[line 1:31: no viable alternative at input '[']; nested: NoViableAltException;"
Can anyone tell me why I get this error when I try to update the array of objects fields.
Defining arrays and objects directly in SQL statement is currently not supported by our SQL parser, please use parameter substitution using placeholders instead as described here:
https://crate.io/docs/current/sql/rest.html
Example using curl is as below:
curl -sSXPOST '127.0.0.1:4200/_sql?pretty' -d#- <<- EOF
{"stmt": "update poll set poll_rating = ? where poll_id = ?",
"args": [ [{"rating_id":1,"fk_user_id":-1,"israted_image1":1,"israted_image2":0,"createddate":1400067339.0496}], "f748771d7c2e4616b1865f37b7913707" ]
}
EOF