Extracting results from a SELECT * in node pg - javascript

I have a Postgresql stored function defined as following:
CREATE OR REPLACE FUNCTION SessionGet(
sid varchar)
RETURNS "SESSION" AS $$
SELECT * FROM "SESSION" WHERE "SESSION_ID" = sid;
$$ LANGUAGE sql;
I call it from node using the PG module with:
SELECT SessionGet('SID-1'::varchar);
The session table is defined as:
CREATE TABLE "SESSION"
(
"SESSION_ID" character varying NOT NULL DEFAULT ''::character varying,
"SESSION" json NOT NULL DEFAULT '{}'::json,
"LAST_UPDATE" bigint DEFAULT 0,
CONSTRAINT "SESSION_PK" PRIMARY KEY ("SESSION_ID")
)
WITH (
OIDS=FALSE
);
I am trying to retrieve the returned result as following:
client.query(sql, function(err, result) {
done(); // Releasing connection to the pool
if ( err ) {
callback(err);
} else if ( result.rows.length > 0 ) {
var ttmp = result.rows[0];
var tmp1 = ttmp[0];
console.log("Res[0]: " + tmp1);
callback(err,result.rows[0]);
} else {
callback(err);
}
});
Although result.rows.length is > 0, result.rows[0][0] is undefined. How can I retrieve the field values from the returned row?

I have solved my issue by sending a SQL statement (SELECT * FROM "SESSION" WHERE "SESSION_ID" = '...';) rather than relying on a stored function.
I have also changed the name of the SESSION column to SESSION_JS, as giving the name of a table to a column too seems to be an issue, though no error message is displayed.

Related

Getting JSON data from snowflake stored procedure parameter and inserting it in target table

I have a requirement to receive JSON data in a Stored Proc parameter and insert the same in the snowflake target table (user_json_feedback). JSON Data has three key elements(User, EntityID, and Entity Type), whereas the target table has five columns (User, ID, Entity Type, Region, and Date). The region will have a default value of "NA," and the date will be the current date.
If the inserts are successful, it returns true; otherwise, it returns false.
I am struggling with the syntax and parsing issues here, as I am very new to writing procedures.
Here is what I have been trying to do, which is giving me errors obviously but serves the algorithm of my intent.
CREATE OR REPLACE SP_UPDATE_JSON_DATA (JSON_DATA VARIANT)
RETURNS BOOLEAN
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS
$$
//Declare variables
var REGION = 'NA'
var V_DATE = `select current_date;`;
var DATE_STMT= snowflake.createStatement({sqlText: V_DATE });
var curr_date = DATE_STMT.execute();
var src_json = JSON.parse(JSON_DATA);
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region ,date)//
select src_json:USER,src_json:ENTITY_ID,src_json:ENTITY_TYPE,REGION,curr_date;`;
try {
snowflake.execute (
{sqlText: sql_command}
);
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
The function call with parameters will be like
call SP_UPDATE_JSON_DATA ('[{"USER":"XYZ","ENTITY_ID":"BMT0001","ENTITY_TYPE":"BMT"},{"USER":"ABC","ENTITY_ID":"BMT0002","ENTITY_TYPE":"BMT"}]');
Thanks in advance for the help!
theres a few things here.
Firstly the step to get current date. curr_date is a result set object. to extract the value and use it later, you need to read the first row with .next() then GetColumnValue to read the column content. to pass it later as a well formatted string you'll wanna convert with .toISOString().
Secondly the parsed json returns an array in this case so you'll need to iterate over the array to insert the individual records. As it's not known ahead of time if the variant will contain an array you're best checking if the parsed json is an array and handle it accordingly
Last tweak was altering the return type so you get the verbose feedback you're expecting from your return calls.
Updated code:
CREATE OR REPLACE TEMPORARY TABLE user_json_feedback
(
user VARCHAR(100)
,id VARCHAR(100)
,etype VARCHAR(100)
,region VARCHAR(100)
,date TIMESTAMP_NTZ
);
CREATE OR REPLACE TEMPORARY PROCEDURE SP_UPDATE_JSON_DATA(JSON_DATA VARIANT)
RETURNS STRING
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS
$$
//Declare variables
var REGION = 'NA'
var V_DATE = `select current_date;`;
var DATE_STMT= snowflake.createStatement({sqlText: V_DATE });
var DATE_STMT_RES = DATE_STMT.execute();
DATE_STMT_RES.next()
var curr_date = DATE_STMT_RES.getColumnValue(1).toISOString();
var src_json = JSON.parse(JSON_DATA);
try {
if (Array.isArray(src_json)){
for (key in src_json){
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region,date)//
VALUES(:1,:2,:3,:4,:5)`;
snowflake.execute (
{
sqlText: sql_command,
binds: [src_json[key].USER,src_json[key].ENTITY_ID,src_json[key].ENTITY_TYPE,REGION,curr_date]
}
);
}
}
else {
var sql_command =
`INSERT INTO user_json_feedback (user,id,etype,region,date)//
VALUES(:1,:2,:3,:4,:5)`;
snowflake.execute (
{
sqlText: sql_command,
binds: [src_json.USER,src_json.ENTITY_ID,src_json.ENTITY_TYPE,REGION,curr_date]
}
);
}
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
--Need to cast variable string as variant.
--ARRAY example
call SP_UPDATE_JSON_DATA ('[{"USER":"XYZ","ENTITY_ID":"BMT0001","ENTITY_TYPE":"BMT"},{"USER":"ABC","ENTITY_ID":"BMT0002","ENTITY_TYPE":"BMT"}]'::VARIANT);
--Single object example
call SP_UPDATE_JSON_DATA ('{"USER":"JST","ENTITY_ID":"BMT0003","ENTITY_TYPE":"BMT"}'::VARIANT);
SELECT *
FROM user_json_feedback;
Result set:
While all this works, you may well be better served just inserting the whole variant into a table and relying on snowflake's significant semi-structured data querying capabilities. Certainly for large payloads you'll find much better performance from bulk loading to a variant column in a table then parsing in a view.

select query in MySQL NodeJS

I am making search route for property table where user can enter city, state, street_address , minamount , max_amount to search for different properties. My problem is if user only enter one or two fileds search should be filter by those field only. and if user does not enter any parameters, it should show every property.
const sqlQuery = `SELECT * FROM property WHERE state = ? AND city = ? AND street_address = ? AND min_amount >= ? AND max_amount <= ?; `
const values = [req.body.state, req.body.city, req.body.street_address ,req.body.min_amount,req.body.max_amount];
let data = [];
db.query (sqlQuery, values, function (err, results, fields) {
if (err) {
console.log(err)
}
if (results.length >= 1) {
}
You need to construct your sqlQuery manually by checking the existence of each parameter and appending a corresponding WHERE clause individually for each parameter, if this parameter exists.

Snowflake JavaScript procedure how to update a field from an object that is not in a stage?

I am trying to do a JavaScript procedure on Snowflake to update a table with relevant values in a JavaScript array.
Assume that I have the following table:
And having this array:
var arr = {"gender_value": "Gender", "age_range": "Age Range"}
So the final result of my updated table would be:
I tried something like:
var query = "
MERGE INTO mytable m
USING (SELECT * FROM "+arr+" )
";
But I don't think it is possible to SELECT from an object if it is not in a stage.
You are going to have to parse your array in SQL to get structure for the MERGE. Another alternative is to store array in temporary table. But I don't see any issues getting this to work, see my example:
create or replace table so_test
(
question_name varchar
,answer varchar
,question_label varchar
);
insert into so_test values ('gender_value','Female',null),('age_range','>60',null);
merge into so_test
using
(
select
g.key as join_key
,g.value as join_value
from
(
select parse_json(column1) as arr from values ('{"gender_value": "Gender", "age_range": "Age Range"}')
) x,
lateral flatten(input => x.arr) g
)src
on so_test.question_name = src.join_key
when matched then update
set question_label = src.join_value;
--proc example
CREATE OR REPLACE PROCEDURE "ARRAY_TEST_SP"(sp_input varchar)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS
$$
var v_array = SP_INPUT;
var v_merge = `merge into so_test
using
(
select
g.key as join_key
,g.value as join_value
from
(
select parse_json(column1) as arr from values (?)
) x,
lateral flatten(input => x.arr) g
)src
on so_test.question_name = src.join_key
when matched then update
set question_label = src.join_value;`;
var v_stmt = snowflake.createStatement(
{
sqlText: v_merge,
binds:[v_array]
}
);
try {
v_stmt.execute()
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
call ARRAY_TEST_SP('{"gender_value": "Gender", "age_range": "Age Range"}');

REST API Javascript How to write condition that checks if SQL query returns 0 rows

I have db airport, there is TABLE tourists and in it COLUMN: id and also i have TABLE: flights, and there is column: listoftouristsbyid which is array of integers. I need to check if i passed to REST API request integer that is id of Tourist that not EXISTS. Means there is no tourist with given id (id is primary, autoincrementing key). I wrote something like that:
app.post('/flights', function(req, res) {
pool.connect(function(err,client,done) {
if(err) {
return console.log("Error fetching clients", err);
}
client.query("SELECT tourists.id FROM tourists WHERE tourists.id = " + req.body.listoftouristsbyid[i], function (err, result) {
done();
if (result.rows === 0) {
return console.log("Tourist "+req.body.listoftouristsbyid[i]+" you want to add does not exist" + err);
}
})
client.query('INSERT INTO flights(departuredate, arrivaldate, numberofseats, listoftouristsbyid, ticketprice) VALUES($1, $2, $3, $4, $5)',
[req.body.departuredate, req.body.arrivaldate, req.body.numberofseats, req.body.listoftouristsbyid, req.body.ticketprice]);
done();
res.redirect('/flights');
})
})
I know ITS A VALID QUERY, because when i type it in PSQL shell it returns
airport=#
SELECT tourists.id FROM tourists WHERE tourists.id = 15;
id
----
(0 rows)
But its not working as javascript code - means code should terminate with error, but condition is not fulfiled. How do i write condition in Javascript that catches when SELECT tourists.id FROM tourists WHERE tourists.id = 15 gives 0 rows?
In MySQL, When you perform a read operation, It will give you value in Array. So, get the length of the result array by result.length
check if it is equal to zero.
When you perform a write or update operation, the result will contain a property affectedRows Which will tell you the number of rows affected.
Print the result using console.sql('%j', result) and See if there is some option in PostGreSQL(Most probably there is).

How to insert json data into MariaDB using Nodejs?

I'm inserting JSON data into MariaDB using NodeJs. Getting below error while inserting data. Please advise what cause to get error. Actually Column data1 no empty or null values.Why am i getting below error ?
{ [Error: Column 'data1' cannot be null] code: 1048 }
Table Structure
CREATE TABLE `from_excel` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`data1` VARCHAR(50) NULL DEFAULT NULL,
`data2` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
Code which i'm using to insert data.
var Client = require('mariasql');
var c = new Client({
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
db : 'Metrics'
});
const workbook = xlsx.readFile(__dirname + '/test.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
var json=xlsx.utils.sheet_to_json(worksheet);
console.log(json.length);
for(var i=0;i<json.length;i++)
{
var post = {data1: json[i].data1, data2: json[i].data2};
var sql = c.query('INSERT INTO elements_from_excel (data1,data2) VALUES (?,?)', post, function(err, result) {
console.log(sql);
if(err){console.log(err);}
else {console.log("success");}
});
}
c.end();
What could be happening is that the resulting insert statement being run is as follows:
INSERT into from_excel (data1, data2) VALUES (`data1` = \'data1value\', `data2` = \'value\', ?)
Try replacing the query string with the following instead:
var post = {data1: json[i].data1, data2: json[i].data2};
var sql = c.query('INSERT INTO from_excel SET ?', post, function(err, result) {
console.log(sql);
if(err){console.log(err);}
else {console.log("success");}
It should be INSERT INTO from_excel VALUES (?), although it's quite possible that you'll encounter other errors when you fix this one.
Make sure the function you are calling receive the exact type of data they expect.

Categories

Resources