GoLang query for MySQL appending to a JSON field - mysql

I'm trying to write a query that would append my JSON variable("data") to a JSON field in my database. I have a table called cart with three fields inside: id type int, status type varchar and items type json. So basically I'm trying to write a query where it would find my cart by the id and it would add an item to the end of my item field so far what I have is this:
query, err := db.Exec("UPDATE cart SET items = JSON_ARRAY_APPEND(#items, '$', 'data') where id = 1")
I know this is not enough. How can I add my variable instead of 'data' to this query? Could anyone help me?
Thank you.

My guess would be a parameterized update:
db.Exec("UPDATE cart SET items = JSON_ARRAY_APPEND(#items, '$', ?) where id = ?", data, 1)

Related

SQL Query Update subtract variable

I am working on developing an inventory application. I have a table ShopInventory_Parts
When a user selects an item from the table, a window appears.
From here, the data from the item selected in the table is displayed in their respective fields. The last field is where the user is able to enter in the quantity that they will be "Checking Out" from the inventory.
When the user enters in the quantity checked out, I have a SQL script that will write to another table called ShopInventory_Parts_Checkout - and this is working correctly
My query for this is:
query = "INSERT INTO ShopInventory_Parts_Checkout (Name,Manufacturer,PartNum,assetID,quantityCheckedOut,t_stamp) VALUES (?,?,?,?,?,?)"
args = [Name,Manufacturer,PartNum,assetID,quantityCheckedOut,t_stamp]
result = system.db.runPrepUpdate(query,args)
My question is, how can I get the 'quantity' in my ShopInventory_Parts table to subtract from the quantity based on the user entry?
Right now, I have the following SQL query and it is returning "NULL"
query = "UPDATE ShopInventory_Parts SET quantity = (quantity - updatedQuantity) WHERE assetID=(?)"
args = [assetID]
result = system.db.runPrepUpdate(query,args)
I apologize if this seems very basic, but I just cannot get it working. Any help would be greatly appreciated.
Thank you
The Python variable needs to be in the args list, not the SQL. And pass the quantity being checked out, not the updated quantity (otherwise the two calculations cancel each other out).
query = "UPDATE ShopInventory_Parts SET quantity = quantity - ? WHERE assetID = ?"
args = [quantityCheckedOut, assetID]
result = system.db.runPrepUpdate(query,args)

Removal from JSON array in MySQL

I'm managing a followers list through a JSON array. I'm using JSON_ARRAY_APPEND to add a follower:
UPDATE users
SET follows = JSON_ARRAY_APPEND(follows, '$', "followerToBeAdded")
WHERE username = "user"
However, I'm unable to remove a follower from this list. If I try JSON REMOVE, it just erases the whole JSON array instead of just removing a particular follower from the list.
Any idea of a possible query for it?
As you've added the MySQL tag in the question so the following response is inaccordance with MySQL.
Let's consider the users table with the two columns username and json column follows. Assume we've a username x and one follower a to begin with.
Let's add 2nd and 3rd follower
UPDATE users SET follows = JSON_ARRAY_APPEND(follows, '$', 'b') where username ='x';
UPDATE users SET follows = JSON_ARRAY_APPEND(follows, '$', 'c') where username ='x';
Removal: Let's say we want to remove the follower b
To check the follower to be removed
SELECT JSON_SEARCH(follows, 'one', 'b') FROM users;
Above will give path to the object to be deleted in the array.
UPDATE users SET follows = JSON_REMOVE(follows, JSON_UNQUOTE(JSON_SEARCH(follows, 'one', 'b'))) WHERE JSON_SEARCH(follows, 'one', 'b') IS NOT NULL;

How to query data from JSON Column with Object Array

Assuming I have below table structure:
And address_collection has a value of this per table row entry:
How would I be able to query a specific json object from the array based on an address_uid assigned to user_id?
JSON_EXTRACT() and its -> alias doesn't work (returns null) because as I understand, it only works on a single JSON Object.
Example:
SELECT
u.*
FROM
user u
WHERE
u.user_id = 1
AND
u.address_collection->"$.address_uid" = "a83b662f-60de-4d3d-ab05-43b0746fb2a2";
Above example yields no result due to u.address_collection->"$.address_uid" = "a83b662f-60de-4d3d-ab05-43b0746fb2a2";
Modifying that line to u.address_collection->"$[0].address_uid" = "a83b662f-60de-4d3d-ab05-43b0746fb2a2"; doesn't work either as the result of the left part returns a collection of address_uid from the object array instead of searching it.

mysql extract_json value from array

I have a MySQL DB containing a table named "products".
This table contains a Json Data_type column named "values".
I would like to find the path to extract a specific value :
select JSON_EXTRACT(values, '$.COD')
from products
where id = '1'
returns :
"COD": {"<channels>": {"<locales>": "3699999999999"}}
And what I want is "3699999999999".
It is pretty obvious that my path is not the good one, but I can't find the solution.
Thanks for your help !
You can try
SELECT JSON_EXTRACT(`values`, '$.COD.<channels>.<locales>') FROM products WHERE id = '1';
For more details please refer mysql-for-your-json

Postgresql update json data property

I created a field name is result and type is text. I just want to update 'lat' in column. When I use this query I get syntax error. How can I do?
The column data is
"{"lat":"48.00855","lng":"58.97342","referer":"https:\/\/abc.com\/index.php"}"
Query is
update public.log set (result::json)->>'lat'=123 where id=6848202
Syntax error is
ERROR: syntax error at or near "::"
Use the jsonb concatenation operator (Postgres 9.5+):
update log
set result = result::jsonb || '{"lat":"123"}'
where id = 6848202
In Postgres 9.4 use json_each() and json_object_agg() (because jsonb_object_agg() does not exists in 9.4).
update log
set result = (
select json_object_agg(key, case key when 'lat' then '123' else value end)
from json_each(result)
)
where id = 6848202
Both solutions assume that the json column is not null. If it does not contain the lat key, the first query will create it but the second will not.
In PostgreSQL 13, You can:
update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;
In case the column is still null, you can use coalesce. The answer is provided here: PostgreSQL 9.5 - update doesn't work when merging NULL with JSON
I also tried to update json value in json type field, but couldn't find appropriate example. So I've connected to postgres DB using PgAdmin4, opened desired table and changed desired field's value, then looked at Query History to see what command it uses to change it.
So, finally, I've got the next simple python code for own purposes to update json field in postgres db:
import psycopg2
conn = psycopg2.connect(host='localhost', dbname='mydbname', user='myusername', password='mypass', port='5432')
cur = conn.cursor()
cur.execute("UPDATE public.mytable SET options = '{\"credentials\": \"required\", \"users\": [{\"name\": \"user1\", \"type\": \"string\"}]}'::json WHERE id = 8;")
cur.execute("COMMIT")