Call a Stored Procedure in HANA - javascript

I am trying to call a stored procedure in java from my .xsjs file. The procedure gets 2 input parameters and returns one. I can call it from an SQL console without any problem by writing:
call "MYSCHEMA"."MyPackage.procedures::addUserC50" ('name', 'lastname', ?)
This is the code in my .xsjs file, I think that it fails in the prepareCall statement. I have tried different combinations (with and without double quotation marks, with and without the name of the schema/package, with and without "(?,?,?)", with and without "{ }".... But nothing works, I always get the 500 Internal server error when I try to execute it.
Does anybody know where the error is or what is the exact syntax for the prepareCall method?
var output = 0,
query = "";
var conn;
var cstmt;
try {
conn = $.db.getConnection();
query = "{ call \"MYSCHEMA\".\"MyPackage.procedures/addUserC50\"(?,?,?) }";
cstmt = conn.prepareCall(query); // <-- Fails
cstmt.setString(1, userName);
cstmt.setString(2, userLastname);
cstmt.execute();
output = cstmt.getInteger(3);
conn.commit();
$.response.status = $.net.http.OK;
$.response.setBody("Successfully created: " + output);
}
catch (e) {
$.response.status = $.net.http.BAD_REQUEST;
$.response.setBody("0");
}
finally {
if (cstmt !== null)
cstmt.close();
if (conn !== null)
conn.close();
}
This is the error that gives back: InternalError: dberror(Connection.prepareCall): 328 - invalid name of function or procedure: MyPackage.procedures/addUserC50: line 1 col 18 (at pos 17) at ptime/query/checker/check_call.cc:21
According to this documentation, it should be something like
var myCallableStatement = myconnection.prepareCall("{call myprocedure(?)}");
Thank you

I managed to make it run, this is the syntax that worked:
query = "call \"MyPackage.procedures::addUserC50\"(?, ?, ?)";
Thank you for your help #shofmn

There could be different reasons why the call is failing. You can investigate your error much easier if you return the error message in the HTTP response. You can do this easily:
try {
// Your code execution here
}
catch (e) {
$.response.contentType = "text/html";
$.response.setBody(e.name + ": " + e.message));
}
If the error message doesn't help you solving the problem, paste the error message in here so that it is more easy for us to investigate as well.

Related

Replace certain character in Discord.JS

Now, before you say that this has been posted before, I have a different situation.
With that out of the way, let's get on with the question.
I am making a Discord bot for a friend that does duties for the group and things like that.
Quick note too, I am using the Sitepoint version of Discord.JS because I'm a beginner.
I want the bot to send a message to a certain channel when the show gets canceled for a reason. For example, they would send something like this:
afv!cancel Roblox went down.
or something similar.
But every time it sends a message, every space turns into a comma like this:
:x: The show has been cancelled because: "Roblox,went,down.". Sorry for that!
Here's the index.js code that handles executing commands:
bot.on('message', msg => {
const args = msg.content.split(/ +/);
const command = args.shift().toLowerCase();
const prefix = command.startsWith("afv!");
if (prefix == true) {
console.info(`Called command: ${command}`);
if (!bot.commands.has(command)) return;
msg.delete(1);
try {
bot.commands.get(command).execute(msg, args, bot);
} catch (error) {
console.error(error);
msg.reply('there was an error trying to execute that command!');
};
And the cancelled.js file:
module.exports = {
name: 'afv!cancel',
description: "in-case the show gets cancelled",
execute(msg, args, bot) {
if (msg.member.roles.find(r => r.name === "Bot Perms")) {
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
bot.user.setActivity("AFV! | afv!help", { type: 'PLAYING' });
} else {
msg.reply('you are missing the role: Bot Perms!');
}
},
};
By the way, upon executing the command, it prints this:
TypeError: args.replace is not a function
Thanks for reading! :)
From what I can see, here
const reason = args.replace(/,/g, " ");
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + args + '". *Sorry for that!*');
you are making a const reason, wherein you try to handle that as a string and replace all commas with spaces. Unfortunately, even though it can be displayed in a string and looks to be one, in reality it is an array, so replace() won't work on it. To be able to use replace() you need to first transform your array to an actual string:
const reason = args.join().replace(/,/g, " ");
With that done you won't be seeing this pesky "not a function" error, and you can easily use reason to display your message:
bot.channels.get('696135370987012240').send(':x: **The show has been cancelled** because: "' + reason + '". *Sorry for that!*');

how to implement mysql query first in nodejs? ( or to implement condition query first )

it is first time to use node js So this question can be very basic question. I tried to use callback instead of just returning value but I couldn't solve the problem.
I heard that mysql query is executed after other code in node js.
But I want to put (if condition) query in the middle of the code and check the condition before implementing codes below query.
I am doing IoT thing ( sensor + android app + aws ubuntu server with nodejs and using mysql for database )
I want to check if the sensor is working fine before adding data to server database.
So, I put the code to check if sensors are working fine before storing data in database. ( check by comparing the results from two sensors. )
But the problem is that mysql query(to check if the sensors are right) is executed later than other code in node.js so I cannot check the condition in the middle.
How can I run condition query in the middle of the code and return any condition value?
app.get('/log', function(req, res){
r = req.query;
result_error = error_check(r.nickname);
console.log("error check result"+result_error);
insert_temp(r.nickname,r.left_num,r.right_num);
//this function is called after error_check function, but when I saw the result, console.log in this function is called earlier than error_check function
res.end('OK:' + JSON.stringify(req.query));
});
function error_check(nickname){
var sql = mysql.format('select sum(left_num) as left_sum, sum(right_num) as right_sum from temp where nickname = ? and today_date = date(current_date());',nickname);
var query = connection.query(sql,function(err,result){
if (err) throw err;
console.log("Error check/// left_sum is "+result[0].left_sum + " right_sum is "+result[0].right_sum);
if ((result[0].left_sum - result[0].right_sum >=30 )|| (result[0].right_sum - result[0].left_sum >=30 )){
console.log("Sensor is broken");
return 1;
}
else{
return -1;
}
});
console.log(query);
}
/////////////////////////////but the result is
error check result undefined
(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1
(this is from error_check function! this function is called before inset_temp function. error_check function is executed late...so I cannot check if sensor is wrong )
Error check/// left_sum is 0 right_sum is 45
Sensor is broken
///but if we see the result from console/////
error check result undefined
(this is from insert_temp function! )nickname is ? left_num is ? right_num is ? gucheol 0 1
Error check/// left_sum is 0 right_sum is 45
Sensor is broken
(this is from error_check function! this function is called before insert_temp function. error_check function is executed late...so I cannot check if sensor is wrong )
connection.query is a asynchronous function so that will execute in end of event loop.
Instant of asynchronous way you can use synchronous way using util.promisify().
You can use like below to work your code,
app.get('/log', function(req, res){
r = req.query;
var sql = mysql.format('select sum(left_num) as left_sum, sum(right_num) as right_sum from temp where nickname = ? and today_date = date(current_date());',r.nickname);
var query = connection.query(sql,function(err,result){
if (err) throw err;
if ((result[0].left_sum - result[0].right_sum >=30 )|| (result[0].right_sum - result[0].left_sum >=30 )){
console.log("Sensor is broken");
res.end("NOT OK: Sensor is broken");
}
else{
insert_temp(r.nickname,r.left_num,r.right_num);
res.end('OK:' + JSON.stringify(req.query));
}
});
});
Let me know if some error occur with this code.

Calling Firebase Function from Unity throws error

I am having problems with my Unity3D calling Firebase Functions function. My code is actually copied from https://firebase.google.com/docs/functions/callable.
My function code is following: (just copied this file actually)
https://github.com/firebase/quickstart-js/blob/a579893cfa33121952aeed9069c1554ed4e65b7e/functions/functions/index.js#L44-L50
and in Unity I have this:
//Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = "message";
data["push"] = true;
//Call the function and extract the operation from the result.
var function = FirebaseFunctions.DefaultInstance.GetHttpsCallable("addMessage");
function.CallAsync(data).ContinueWith((task) => {
if (task.IsFaulted)
{
foreach (var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
Debug.Log(inner.Message);
}
}
}
else
{
Debug.Log("Finished: " + task.Result.Data);
}
});
But I am getting this result:
Response is not valid JSON object.
What am I doing wrong?
Thank you for your help!!!
I was still working on that problem and suddenly it worked. I dont know why to be honest, because the could looks exactely the same and I did not change anything on that.

Websocket output received by browser, complains about "Invalid UTF-8 sequence in header value "

When I load the page in my browser, the page gets served correctly. When the javascript executes, Chrome's console output says:
Invalid UTF-8 sequence in header value
I have searched for that string, and am unable to find any mention of it for golang.
How do I go about telling golang not to write unicode characters to web sockets?
I assume that this is the cause of the problem, as the "Network" tab only reveals an empty request and response for this.
CCSSE:
main.go:
package main
import (
"fmt"
"net/http"
"log"
"code.google.com/p/go.net/websocket"
//"github.com/garyburd/go-websocket/websocket"
)
const listenAddress = "localhost:9999"
func wsHandler(webSck *websocket.Conn) {
fmt.Fprint(webSck, "Rpy")
fmt.Println("Sent \"Rpy\" to web socket", webSck)
//more code here
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.Handle("/ws", websocket.Handler(wsHandler))
err := http.ListenAndServe(listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}
static/main.js
var socket = new WebSocket("ws://localhost:9999/ws");
socket.onopen = function() {
socket.onmessage = function(m) {
console.log("Received: " + m);
};
socket.send("Req\n");
};
EDIT:
As suggested by #Intermernet, I have set the Sec-WebSocket-Protocol header. To no avail, still getting Invalid UTF-8 sequence in header value.
Note also that the reason I need to do webSck.Config().Header = make(http.Header) is that it is nil - confirmed by the log statement on webSck.Config(). Tack on to this another question - why do I have to do this; is there an intialisation step that I have missed somewhere?
func wsHandler(webSck *websocket.Conn) {
webSck.Config().Header = make(http.Header)
webSck.Config().Header.Add("Sec-WebSocket-Protocol", "chat")
fmt.Printf("ws.Config() %#v\n", webSck.Config())
var buf []byte;
buf = []byte("Rpy")
_, err := webSck.Write(buf)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Sent \"Rpy\" to web socket %#v\n", webSck)
}
}
Can this issue be related to recent change in code.google.com/p/go.net/websocket ?
https://code.google.com/p/go/source/detail?r=1e65ca1b2499c473ec267ca1d6759b3dc920a599&repo=net
Sorry for the comment in the form of an answer, I can't comment yet...
Are you setting Sec-WebSocket-Protocol header on the websocket Config? (https://code.google.com/p/go/source/browse/websocket/websocket.go?repo=net#74 and https://www.rfc-editor.org/rfc/rfc6455#page-59)
That error message seems to crop up on Google many times relating to incompatibility or conflict with that header.
Something like:
func wsHandler(webSck *websocket.Conn) {
webSck.Config.Header.Add("Sec-WebSocket-Protocol", "chat")
fmt.Fprint(webSck, "Rpy")
fmt.Println("Sent \"Rpy\" to web socket", webSck)
//more code here
}
Also, I think it's preferred to use the Write function on the websocket (https://code.google.com/p/go/source/browse/websocket/websocket.go?repo=net#205) as it encapsulates/converts the written data into frames.
So more like:
func wsHandler(webSck *websocket.Conn) {
webSck.Config.Header.Add("Sec-WebSocket-Protocol", "chat")
_, _ = webSck.Write("Rpy")
fmt.Println("Sent \"Rpy\" to web socket")
//more code here
}
But obviously checking the error from Write!
Hope that helps.
EDIT: Remove the extraneous ", webSck" from the fmt.Println .

How to catch exceptions in javascript?

I want to catch exceptions in javascript if an insertion query is not done.
I have written the code below:
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
var rec = new ActiveXObject("ADODB.Record");
adoConn.Open="DRIVER={MySQL ODBC 3.51 Driver};SERVER=172.25.37.145;" + "DATABASE=confluence;UID=root;PASSWORD=somePassword;OPTION=3";
//Connectionstring
alert('Database Connected');
adoConn.Execute("insert into `session` (SessionId,Timestamp) values ('"+SessionId+"','"+SessionCurrenttime+"')");
If I get the same session id then the query was not executed as it is the primary key in the database.
To be complete, here's the full structure
try {
// your code that can throw exception goes here
} catch(e) {
//do stuff with the exception
} finally {
//regardless if it worked or not, do stuff here (cleanup?)
}
<script language="JavaScript">
try
{
colours[2] = "red";
}
catch (e)
{
alert("Oops! Something bad just happened. Calling 911...");
}
</script>
(Ripped from http://www.devshed.com/c/a/JavaScript/JavaScript-Exception-Handling/)
try {
// your code that can throw exception goes here
} catch(e) {
//do stuff with the exception
}
FYI - the code you posted looks, well, for want of a better word, ugly! (No offense) Couldn't you use DWR or some other JavaScript framework (depending on your language choice) to hide all the DB connection stuff at the back end and just have the javascript calling the back end code and doing something with the response?
try {
adoConn.Execute("insert into session (SessionId,Timestamp) values ('"
+ SessionId + "','"
+ SessionCurrenttime + "')");
} catch(e) {
/*use error object to inspect the error: e.g. return e.message */
}

Categories

Resources