How to update json data in postgresql database using laravel? - json

how to change next data in database:
jsonData = [{"given_date": "2 1.05. 2002 year"}]
to
jsonData = [{"given_date": "21.05.2002"}]

Postgresql update with regex:
UPDATE table
SET given_date = regexp_replace(given_date, '(\s|[a-zA-Z])', '','');
regexp_replace takes the value in given_date and be replaced by third parameter (empty string), according to the second regular parameter (match the spaces and alphabets). The fourth parameter is option like 'g(global)', 'i(ignore case)';
Postgresql regexp_replace reference
Laravel update with regex:
\DB::table('tablename')
->where(...)
->update([
'given_date' => \DB::raw("regexp_replace(given_date, '(\s|[a-zA-Z])', '','')")
]);

Related

How do I set the placeholder for `knex`'s` raw` method to null?

I tried invoke bulk update query on mysql using knex raw method.
const ids:number[] = [1,2,3];
const values:string[] = ['apple', null, "orange"]
knex('testtable').raw(
`
UPDATE
TEST_TABLE
SET
COL1 = ELT(FIELD(id, :searchIds), :searchValues),
UPDATE_DATE = NOW()
WHERE ID IN (:searchIds)
`,
{ searchIds: ids, searchValues: values },
);`enter code here`
However, the intended result was not obtained.
This is because values contains a string and null, but theraw method's placeholders do not allow nulls.
Please tell me ,How do I set null to placeholder?
Binding array of values in knex doesn't work like that. SQL has multiple type of arrays, so those cannot be mapped to SQL unambiguous manner.
In docs: https://knexjs.org/#Raw-Bindings is an example how to pass arrays of values to knex.
const myArray = [1,2,3]
knex.raw(
`select * from users where id in (${myArray.map(() => '?').join(',')})`,
[...myArray]
);
In this case using named bindings pretty much impossible (actually named bindings are converted to positional bindings inside knex so there wont be even performance hit because of that).

How replace null value with {} in mysql?

I am trying to fetch value from table where null status value should get replace with {}(empty json object), so that I have used below mysql function
IFNULL(status, '{}') as status from table;
but its output is '{}' but I want output as only {} (without single quotes)
Also I have tried with below options as well
IFNULL(status, "{}") --> output -"{}"
IFNULL(status, '{}') --> output -'{}'
IFNULL(status, {}) --> output -Mysql error`
Expected output is only empty j son object Please suggest any solution.
Check the function JSON_UNQUOTE :
SELECT JSON_UNQUOTE(IFNULL(status, "{}")) as status FROM table
mysql is not supporting JSON_UNQUOTE function in case you are converting that mysql result into json object. so work around is to use replace string function(java or any other language) in your framework.
EX.
String rs = str.replace(""{","{"); // Replace '"{' with '{'
String rs = str.replace("}"","}"); // Replace '}"' with '}'

Append a string value to an exisiting json value in mysql

I'm new to MySQL. I'm trying to add a string value to a json value in MySQL. The column name is IPConfig. This is the current json string in the column.
{"theme":"black", "button1link":"http//sample.com", "name":"pp"}
I have to append a "www" to button1link value.
Thanks in advance!
Here you can try
UPDATE table SET DATA= JSON_SET(DATA, "$.button1link", INSERT("http//sample.com", 7, 0,'www')) WHERE 1 = 1;
But for this to work, you will need MySQL 5.7+
You can have insert function docs here.

REGEX for selecting multiple value in string

I need an sql select statement to retrieve 04:30 and test.zip from this string:
{"TIME":"04:30","DATE":"11\/25\/2013","FILENAME":["test.zip"]}
use this \[(.*?)\]
it return value between [ and ]
and for 04:30 use TIME":(.*?),
it return value after "TIME":
Can't you just decode it and use PHP? (assuming you can't change the way it's stored in the db)
<?php
$str = '{"TIME":"04:30","DATE":"11/25/2013","FILENAME":["test.zip"]}';
$o = json_decode($str);
$time = $o->TIME;
$file = $o->FILENAME[0];
var_dump($time); //"04:30"
var_dump($file); //"test.zip"
Regex replaces etc in MySQL require a UDF (user-defined function) mysql-udf-regexp
If none of the above are viable solutions (change DB structure, do it with PHP, use a MySQL UDF), you'll need to get creative. It would require a known, static format of that string, but you could replace some parts and substring others. For example:
SELECT SUBSTRING(REPLACE(`column_name`,'{"TIME":"',''),1,5) AS `time` FROM `table_name`
File is more complex, this example assuming only one filename in the array
SELECT REPLACE(SUBSTRING(`column_name`,LOCATE('"FILENAME":["',`column_name`)+13),'"]}','') AS `file` FROM `table_name`
Those two field selections get 04:30 and test.zip respectively (you can of course use those functions in the same statement, rather than separately like I have, by comma separating them)

MySQL Dynamic Query Statement in Python with Dictionary

Very similar to this question MySQL Dynamic Query Statement in Python
However what I am looking to do instead of two lists is to use a dictionary
Let's say i have this dictionary
instance_insert = {
# sql column variable value
'instance_id' : 'instnace.id',
'customer_id' : 'customer.id',
'os' : 'instance.platform',
}
And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.
Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.
sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)
Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary
Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at http://mail.python.org/pipermail/tutor/2010-December/080701.html. Relevant part:
Here's what I came up with when I tried to make a generalized version
of the above:
def add_row(cursor, tablename, rowdict):
# XXX tablename not sanitized
# XXX test for allowed keys is case-sensitive
# filter out keys that are not column names
cursor.execute("describe %s" % tablename)
allowed_keys = set(row[0] for row in cursor.fetchall())
keys = allowed_keys.intersection(rowdict)
if len(rowdict) > len(keys):
unknown_keys = set(rowdict) - allowed_keys
print >> sys.stderr, "skipping keys:", ", ".join(unknown_keys)
columns = ", ".join(keys)
values_template = ", ".join(["%s"] * len(keys))
sql = "insert into %s (%s) values (%s)" % (
tablename, columns, values_template)
values = tuple(rowdict[key] for key in keys)
cursor.execute(sql, values)
filename = ...
tablename = ...
db = MySQLdb.connect(...)
cursor = db.cursor()
with open(filename) as instream:
row = json.load(instream)
add_row(cursor, tablename, row)
Peter
If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for returning a dictionary of values, but it can't execute from a dict.