JSON_OBJECT functionality in Mysql 5.7 - mysql-5.7

Conditionally building JSON OBJECT in Mysql 5.7
Following query producing Null as an object
select JSON_OBJECT('abc','12345','id', CASE WHEN null is null THEN NULL ELSE JSON_OBJECT('a',1) END);
But expected result is {"abc": 12345, "id": null}

After some time, found the solution: (from Mysql official documentation).
By using CAST('null' as JSON)
select JSON_OBJECT('abc','12345','id', CASE WHEN (null is null) THEN CAST('null' AS JSON) ELSE (JSON_OBJECT('a',1)) END);

Related

How apply where only a column is not null in adonis query builder

I need to check if the column percentage_correct >= parCorrect if percentage_correct <> NULL
I try something like:
const unidadeSequenceAtualEstudante = await Database.select("*")
.from("student_quiz_historics")
.where("student_id", idEstudante)
.where(function(){
this
.whereNotNull("percentage_correct")
.where("percentage_correct", ">=", parQtdAcerto)
})
.where("class_id", idClasse)
.where("book_id", idLivro)
.where("execution_back_status", "<>", "Cancelado")
.orderBy("sequence", "desc")
.first();
But when i have only records with the percentage_correct null, they still are trying to apply this where.
I'm having a little trouble replicating your problem. What you have there should work, but it's possible you're not considering something about SQL's behaviour with regard to NULL: anything compared to NULL is NULL, which is why the IS NOT NULL syntax exists. So for example:
foo=# SELECT 1 >= NULL;
?column?
----------
NULL
(1 row)
foo=# SELECT NULL >= 1;
?column?
----------
NULL
(1 row)
This means that you can kind of get away with not checking for the null at all, because only rows that meet the condition will be returned:
const unidadeSequenceAtualEstudante = await Database.select("*")
.from("student_quiz_historics")
.where({
book_id: idLivro,
class_id: idClasse,
student_id: idEstudante
})
.where('percentage_correct', '>=', parQtdAcerto)
.where("execution_back_status", "<>", "Cancelado")
.orderBy("sequence", "desc")
.first();
Is this a good idea? Debatable. I think it's probably fine for this purpose, but we shouldn't assume that NULL is the same thing as FALSE, because it isn't.
If you're still having trouble with your query, you'd need to provide more details about which database you're using, what your schema is and what kind of errors your getting.

SELECT VALUE COUNT(1) FROM (SELECT DISTINCT c.UserId FROM root c) AS t not working

In a Cosmos DB stored procedure, I'm using a inline sql query to try and retrieve the distinct count of a particular user id.
I'm using the SQL API for my account. I've run the below query in Query Explorer in my Cosmos DB account and I know that I should get a count of 10 (There are 10 unique user ids in my collection):
SELECT VALUE COUNT(1) FROM (SELECT DISTINCT c.UserId FROM root c) AS t
However when I run this in the Stored Procedure portal, I either get 0 records back or 18 records back (total number of documents). The code for my Stored Procedure is as follows:
function GetDistinctCount() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT VALUE COUNT(1) FROM (SELECT DISTINCT c.UserId FROM root c) AS t',
function(err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
var body = {code: 404, body: "no docs found"}
response.setBody(JSON.stringify(body));
} else {
var response = getContext().getResponse();
var body = {code: 200, body: feed[0]}
response.setBody(JSON.stringify(body));
}
}
)
}
After looking at various feedback forums and documentation, I don't think there's an elegant solution for me to do this as simply as it would be in normal SQL.
the UserId is my partition key which I'm passing through in my C# code and when I test it in the portal, so there's no additional parameters that I need to set when calling the Stored Proc. I'm calling this Stored Proc via C# and adding any further parameters will have an effect on my tests for that code, so I'm keen not to introduce any parameters if I can.
Your problem is caused by that you missed setting partition key for your stored procedure.
Please see the statements in the official document:
And this:
So,when you execute a stored procedure under a partitioned collection, you need to pass the partition key param. It's necessary! (Also this case explained this:Documentdb stored proc cross partition query)
Back to your question,you never pass any partition key, equals you pass an null value or "" value for partition key, so it outputs no data because you don't have any userId equals null or "".
My advice:
You could use normal Query SDK to execute your sql, and set the enableCrossPartitionQuery: true which allows you scan entire collection without setting partition key. Please refer to this tiny sample:Can't get simple CosmosDB query to work via Node.js - but works fine via Azure's Query Explorer
So I found a solution that returns the result I need. My stored procedure now looks like this:
function GetPaymentCount() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT DISTINCT VALUE(doc.UserId) from root doc' ,
{pageSize:-1 },
function(err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
var body = {code: 404, body: "no docs found"}
response.setBody(JSON.stringify(body));
} else {
var response = getContext().getResponse();
var body = {code: 200, body: JSON.stringify(feed.length)}
response.setBody(JSON.stringify(body));
}
}
)
}
Essentially, I changed the pageSize parameter to -1 which returned all the documents I knew would be returned in the result. I have a feeling that this will be more expensive in terms of RU/s cost, but it solves my case for now.
If anyone has more efficient alternatives, please comment and let me know.

Sequelize/NodeJS TINYINT converted into buffer issue

I am using sequelize in nodejs. My Table structure contains one field data type is TINYINT. While I retrieving this field it return Buffer 01.
My expected result is either 0 or 1 boolean value.
Table Structure
myField: {
type: Sequelize.TINYINT(1)
}
I got solution to check data type TINYINT result like following.
if(myField && myField[0]=='1'){
//true
}else{
//false
}

How to call stored proc in postgres using sequelize passing json parameter

I am new to postgresql and sequelize ORM.
I am trying to call a stored procedure which inserts data to a table.
CREATE OR REPLACE FUNCTION public.sp_eoi(
obj json)
RETURNS void
LANGUAGE 'sql' AS $BODY$
INSERT INTO public."tbl_eoi" ("SE_CUST_ID", "SE_VENDOR_ID", "SE_VENUE_ID")
SELECT (rec->>'custId')::integer, (rec->>'vendorId')::integer, (rec->>'venueId')::integer FROM
json_array_elements(obj-> 'data')rec $BODY$;
Json input passed from node application
{ custId : 1, vendorId : 1, venueId : 1}
I am calling proc
sequelize.query(
'call sp_eoi(:param)',
{replacements: { param: [ { custId:1 , vendorId: 1,venueId : 1 } ] }})
.spread(function(outputValue , records) {
console.log(records);
}).error(function(err){
res.json(err);
});
But there is always the error as "Unhandled rejection Error: Invalid value {custId: ..}
I am totally new to this and have been trying to find the problem for the last two days.
Any help would be really appreciated.
Thanks
A bit late for the party... however:
td; dr;
Postgres uses functions (you can call them stored procedures), but it does not CALL them, it SELECT them
Here's the link to a similar problem: https://stackoverflow.com/a/38115374/1163927

What is returned from Mongoose query that finds no matches?

I'm a little confused reading the Mongoose documentation.
If I run a query in mongoose which matches no documents in the collection, what are the values of err and results in the callback function callback(err, results)? I just don't know what Mongoose considers an "error". As a mathematician, returning the empty set (i.e. results array empty) seems perfectly valid and shouldn't be an "error" - the query executed fine, there was just no matching documents. On the other hand, some may consider it an "error". From mongoose docs, either:
err = null, results = []
err = null, results = null
err = error document, results = null
It depends on the query. If it is a find, then results == []. If it is a findOne, then results == null. No errors if everything else is ok.
If conditions were valid but no matches were found:
find: err is null, result is []
findOne and findById: err is null, result is null
However, if some condition was invalid (e.g. field is string but you pass an object, or you pass an invalid _id)
For all three: err is {..}, result is undefined
If using .find(),
The handy way would be
models.<your collection name>.find({ _id: `your input` }).then(data => {
if (data.length == 0) return // throw your error to the console;
});

Resources