How replace null value with {} in mysql? - 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 '}'

Related

mySql JSON string field returns encoded

First week having to deal with a MYSQL database and JSON field types and I cannot seem to figure out why values are encoded automatically and then returned in encoded format.
Given the following SQL
-- create a multiline string with a tab example
SET #str ="Line One
Line 2 Tabbed out
Line 3";
-- encode it
SET #j = JSON_OBJECT("str", #str);
-- extract the value by name
SET #strOut = JSON_EXTRACT(#J, "$.str");
-- show the object and attribute value.
SELECT #j, #strOut;
You end up with what appears to be a full formed JSON object with a single attribute encoded.
#j = {"str": "Line One\n\tLine 2\tTabbed out\n\tLine 3"}
but using JSON_EXTRACT to get the attribute value I get the encoded version including outer quotes.
#strOut = "Line One\n\tLine 2\tTabbed out\n\tLine 3"
I would expect to get my original string with the \n \t all unescaped to the original values and no outer quotes. as such
Line One
Line 2 Tabbed out
Line 3
I can't seem to find any JSON_DECODE or JSON_UNESCAPE or similar functions.
I did find a JSON_ESCAPE() function but that appears to be used to manually build a JSON object structure in a string.
What am I missing to extract the values to the original format?
I like to use handy operator ->> for this.
It was introduced in MySQL 5.7.13, and basically combines JSON_EXTRACT() and JSON_UNQUOTE():
SET #strOut = #J ->> '$.str';
You are looking for the JSON_UNQUOTE function
SET #strOut = JSON_UNQUOTE( JSON_EXTRACT(#J, "$.str") );
The result of JSON_EXTRACT() is intentionally a JSON document, not a string.
A JSON document may be:
An object enclosed in { }
An array enclosed in [ ]
A scalar string value enclosed in " "
A scalar number or boolean value
A null — but this is not an SQL NULL, it's a JSON null. This leads to confusing cases because you can extract a JSON field whose JSON value is null, and yet in an SQL expression, this fails IS NULL tests, and it also fails to be equal to an SQL string 'null'. Because it's a JSON type, not a scalar type.

Fetch records with query Args in Go

I Need help for fetch records from table using Go.
My Problem is that i'm writing MySQL query and add another where clause i.e HPhone number, Here HPhone number inserted in data base with format like 999-999-9999.And i passed this HPhone Number in format like 9999999999. which is not matching with correct data base field value. And i used SUBSTRING for add hyphen between numbers but it does not get records but when i passed like 999-999-9999 without SUBSTRING it return records.
Here i demonstrate how i used this.
strQry = `SELECT * from table WHERE Depot = ?`
if HPhone != "" {
strQry += ` AND HPhone = ?`
}
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
queryArgs = append(queryArgs, "SUBSTRING("+HPhone+",1,3)"+"-"+"SUBSTRING("+HPhone+",4,3)"+"-"+"SUBSTRING("+HPhone+",7,4)")
}
Help would be appreciated.
Thanks in advance.
Instead of SUBSTRING you can use REPLACE like so:
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
strQry += ` AND REPLACE(HPhone, '-', '') = ?`
queryArgs = append(queryArgs, HPhone)
}
If possible I would suggest you normalize your data, i.e. decide on a canonical format for a particular data type and everytime your program receives some input that contains that data type you format it into its canonical form, that way you can avoid having to deal with SUBSTRING, or REPLACE, or multiple inconsistent formats etc.
This won't work as you are using prepared statements, and the argument you are building when HPhone is not empty will be used in escaped form - so when executing the query, it won't compare the HPhone values with the computed result of some substring, but with a string containing SUBSTRING(9999...

How to match a JSON response value to Postman environment variable?

If an environment variable is set in Postman, for example year, then I'd like to check if the JSON response for the field birthYear matches the value of the variable.
I am trying with the following test:
var jsonData = JSON.parse(responseBody);
tests['Contents'] = environment.year === jsonData.birthYear;
This test always fails. birthYear is 1910 and year is also 1910.
If I try the same test but for a field that has a string value then it works correctly - pass when the values match and fail when they don't.
How should I proceed in order to test the integer values as well as the string ones?
You're using Strict Equality Comparison (===). Environments and globals in postman are all strings. So strict comparison with a number will fail. Instead use ==
tests['Contents'] = environment.year == jsonData.birthYear;

Updating integer column from jsonb member fails with: column is of type integer but expression is of type jsonb

In a PostgreSQL 9.5 table I have an integer column social.
When I try to update it in a stored procedure given the following JSON data (an array with 2 objects, each having a "social" key) in the in_users variable of type jsonb:
'[{"sid":"12345284239407942","auth":"ddddc1808197a1161bc22dc307accccc",**"social":3**,"given":"Alexander1","family":"Farber","photo":"https:\/\/graph.facebook.com\/1015428423940942\/picture?type=large","place":"Bochum,
Germany","female":0,"stamp":1450102770},
{"sid":"54321284239407942","auth":"ddddc1808197a1161bc22dc307abbbbb",**"social":4**,"given":"Alxander2","family":"Farber","photo":null,"place":"Bochum,
Germany","female":0,"stamp":1450102800}]'::jsonb
Then the following code is failing:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = t->'social',
WHERE sid = t->>'sid';
END LOOP;
with the error message:
ERROR: column "social" is of type integer but expression is of type jsonb
LINE 3: social = t->'social',
^
HINT: You will need to rewrite or cast the expression.
I have tried changing that line to:
social = t->'social'::int,
but then I get the error:
ERROR: invalid input syntax for integer: "social"
LINE 3: social = t->'social'::int,
^
Why doesn't PostgreSQL recognize that the data is integer?
From the JSON-TYPE-MAPPING-TABLE I was having the impression that JSON number would be auto-converted to PostgreSQL numeric type.
A single set-based SQL command is far more efficient than looping:
UPDATE words_social w
SET social = (iu->>'social')::int
FROM JSONB_ARRAY_ELEMENTS(in_users) iu -- in_user = function variable
WHERE w.sid = iu->>'sid'; -- type of sid?
To answer your original question:
Why doesn't PostgreSQL recognize that the data is integer?
Because you were trying to convert the jsonb value to integer. In your solution you already found that you need the ->> operator instead of -> to extract text, which can be cast to integer.
Your second attempt added a second error:
t->'social'::int
In addition to the above: operator precedence. The cast operator :: binds stronger than the json operator ->. Like you found yourself already, you really want:
(t->>'social')::int
Very similar case on dba.SE:
Querying JSONB in PostgreSQL
I've ended up using:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = (t->>'social')::int
WHERE sid = t->>'sid';
IF NOT FOUND THEN
INSERT INTO words_social (social)
VALUES ((t->>'social')::int);
END IF;
END LOOP;

EF6 Contains() works with only interned Strings

I want to filter my entity by name property. I use Contains() method. When I pass parameter as "E" it works but if I pass as variable it doesn't work.
Code is below :
if (!String.IsNullOrWhiteSpace(searchingModel.LanguageNameContains))
query = query.Where(n => n.Name.Contains(searchingModel.LanguageNameContains));
if (!String.IsNullOrWhiteSpace(searchingModel.LanguageCodeContains))
query = query.Where(n => n.Code.Contains(searchingModel.LanguageCodeContains));
return query;
Above example doesn't work. But if I write like this
if (!String.IsNullOrWhiteSpace(searchingModel.LanguageNameContains))
query = query.Where(n => n.Name.Contains("E"));
if (!String.IsNullOrWhiteSpace(searchingModel.LanguageCodeContains))
query = query.Where(n => n.Code.Contains("En"));
return query;
It works. I have debugged lots of times. I passed same parameters as variable and as constants. If I pass as constant it works but If I pass as variable it doesn't work. Curiously enough, The same code works MySql.Data.Entity 6.9.3 but now I am using 6.9.5 and it doesn't work. Is it a bug or my mistake ?
Generated SQL :
-when I pass parameter as variable:
SELECT
Extent1.Id,
Extent1.Code,
Extent1.Name
FROM Languages AS Extent1
WHERE Extent1.Name LIKE '%p__linq__0%'
-- p__linq__0: 'E' (Type = String, Size = 1)
-- Executing at 30.12.2014 22:30:40 +02:00
-- Completed in 0 ms with result: EFMySqlDataReader
when I pass as interned string :
SELECT
Extent1.Id,
Extent1.Code,
Extent1.Name
FROM Languages AS Extent1
WHERE Extent1.Name LIKE '%E%'
Second one returns rows but first one doesn't return any rows.