Javascript dynamic ALTER sql getting erred - javascript

Here is the error message I get. Not sure what's missing
Execution error in stored procedure COMPARE_UPDATE_METADATA_BETWEEN_STAGES: SQL compilation
Error: syntax error line 1 at position 104 unexpected ' V'. At Statement.execute,
line 30 position 66
Actual dynamic SQL query I retrieve using .getSqlText()
"ALTER TABLE DEV2.SCHEMANAME.TBLNAME ADD COLUMN FAC_ID NUMBER(38,10); "
It works fine when I execute the SQL manually.
create or replace procedure Compare_Update_Metadata_Between_STAGES(
SRC_DBNAME string,
SRC_SCHEMANAME string,
TRGT_DBNAME string,
TRGT_SCHEMANAME string,
TBLNAME string
) returns variant
language javascript as $$
var stage_table_control = " SELECT DISTINCT UPPER(COLUMN_NAME) AS COL_NAME, UPPER(DATA_TYPE) AS DATA_TYP, "
stage_table_control += " CASE WHEN DATA_TYPE = 'TEXT' THEN 'VARCHAR(' || CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) || ')' "
stage_table_control += " WHEN DATA_TYPE IN ('TIMESTAMP_NTZ', 'DATE', 'TIMESTAMP_LTZ','TIMESTAMP_TZ') THEN DATA_TYPE || '(' || CAST(DATETIME_PRECISION AS VARCHAR) || ')' "
stage_table_control += " WHEN DATA_TYPE IN ('NUMBER', 'FLOAT') THEN 'NUMBER('||CAST(NUMERIC_PRECISION AS VARCHAR) || ',' || CAST(NUMERIC_PRECISION_RADIX AS VARCHAR) || ')' "
stage_table_control += " WHEN DATA_TYPE IN ('BOOLEAN','VARIANT','BINARY') THEN DATA_TYPE END AS CHAR_LEN "
stage_table_control += " FROM DEV.INFORMATION_SCHEMA.COLUMNS "
stage_table_control += " WHERE TABLE_SCHEMA = " + String.fromCharCode(39) + SRC_SCHEMANAME + String.fromCharCode(39)
stage_table_control += " AND TABLE_CATALOG = " + String.fromCharCode(39) + SRC_DBNAME + String.fromCharCode(39)
stage_table_control += " AND TABLE_NAME = " + String.fromCharCode(39) + TBLNAME + String.fromCharCode(39)
stage_table_control += " AND COLUMN_NAME NOT IN " + " ( SELECT UPPER(COLUMN_NAME) FROM DEV2.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = " + String.fromCharCode(39) + TRGT_SCHEMANAME + String.fromCharCode(39)
stage_table_control += " AND TABLE_NAME = " + String.fromCharCode(39) + TBLNAME + String.fromCharCode(39) + ")"
var stage_sql_statement = snowflake.createStatement({sqlText: stage_table_control});
var stage_resultSet = stage_sql_statement.execute();
var stage_column_name_array = "";
while (stage_resultSet.next()) {
var stage_column_name = stage_resultSet.getColumnValue(1);
var stage_data_type = stage_resultSet.getColumnValue(2);
var stage_char_len = stage_resultSet.getColumnValue(3);
var alterSQL = "ALTER TABLE " + TRGT_DBNAME + "." + TRGT_SCHEMANAME + "." + TBLNAME + " ADD COLUMN " + stage_column_name + String.fromCharCode(160) + stage_char_len + ";"
var sql_statement1 = snowflake.createStatement({sqlText: alterSQL});
var resultSet1 = sql_statement1.execute();
// var resultSet1 = sql_statement1.getSqlText();
//alterSQL = "";
}
return alterSQL;
$$
// + " " + //this is what causing an error i believe in below alter
statement
var alterSQL = "ALTER TABLE " + TRGT_DBNAME + "." +
TRGT_SCHEMANAME + "." + TBLNAME + " ADD COLUMN " +
stage_column_name + " " + stage_char_len +
";"

Based on the error message and lack of actual argument(they were replaced by placeholders:
error: syntax error line 1 at position 104 unexpected ' V'. At Statement.execute,
It is possible that the name contains space in identifier that was not properly enclosed with "".
One possible place of such occurence is:
stage_table_control += " FROM DEV.INFORMATION_SCHEMA.COLUMNS "
stage_table_control += " WHERE TABLE_SCHEMA = " + String.fromCharCode(39) + SRC_SCHEMANAME + String.fromCharCode(39)
Instead of concatenating SQL String(which is prone to SQL-Injection attack) parameter binding should be preferred:
stage_table_control += " FROM DEV.INFORMATION_SCHEMA.COLUMNS "
stage_table_control += " WHERE TABLE_SCHEMA = :1 "
stage_table_control += " AND TABLE_CATALOG = :2 "
// ...
var stage_sql_statement = snowflake.createStatement({sqlText: stage_table_control
, binds: [SRC_SCHEMANAME , SRC_DBNAME , ...]});

Related

Why is Java (Nashnorn library) not evaluationg JS code correctly?

I have code that works fine in JavaScript IDE like Webstorm, but when I try to port it to Java, using the Nashorn library (to run JS within a Java program), I get these errors: "Name: undefined, Age: undefined" (with possibly others to follow depending what's wrong here.)
Below is the full code. This coding approach below seems to work in general, but there are cases like this where I don't get the expected results.
Would appreciate any help or suggestions.
Thanks!
public class JavaScriptEvaluationExample
{
public static void main(String[] args) throws ScriptException, NoSuchMethodException
{
// Basic JavaScript evaluation
String json = "{\n" +
" \"name\": \"John\",\n" +
" \"age\": 30,\n" +
" \"cars\": [\n" +
" {\n" +
" \"name\": \"Ford\",\n" +
" \"models\": [\n" +
" \"Fiesta\",\n" +
" \"Focus\",\n" +
" \"Mustang\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"BMW\",\n" +
" \"models\": [\n" +
" \"320\",\n" +
" \"X3\",\n" +
" \"X5\"\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"name\": \"Fiat\",\n" +
" \"models\": [\n" +
" \"500\",\n" +
" \"Panda\"\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
String jsScript = "function parseJSONFields(param)\n" +
"{\n" +
" var result = \"\";\n" +
" var carName =\"\" ;\n" +
" var models = \"\";\n" +
" var name = param.name + \",\";\n" +
" var age = param.age;\n" +
" result = \"Name: \" + name + \" Age: \" + age + \"\\n\";\n" +
" for (item in param.cars)\n" +
" {\n" +
" result += \" \"+ \" >> \" + param.cars[item].name +\": \"\n" +
" result+= \" \" + param.cars[item].models\n" +
" result += \"\\n\";\n" +
" }\n" +
" return result;\n" +
"}";
System.out.println(runJS("parseJSONFields", json, jsScript));
}
// ------------------------------------------------------------------------------------------------
private static Object runJS(String functionName, String param, String script) throws ScriptException, NoSuchMethodException
// ------------------------------------------------------------------------------------------------
{
Object resultString = "";
String errorResultString = "";
ScriptEngine js = null;
try
{
if (param.length() > 0)
{
js = new ScriptEngineManager().getEngineByName("javascript");
js.eval(script);
Invocable inv = (Invocable) js;
}
}
catch (Exception e)
{
errorResultString = e.getMessage() + " ---> " + e.getMessage();
}
return errorResultString.length() > 0 ? errorResultString
: ((Invocable) js).invokeFunction(functionName, param);
}
}
Thanks to all who replied.
The problem was, as the first person noted, that I forgot the JSON.parse() statement to convert the string to a JSON object.
Thanks very much again.

How to get JSON result in grid/tabular format while calling an API?

I'm using railway API in my website and want the Train data in grid format. Please help me with the same.
I want all the variables (Train name, Train number, Departure Time, Arrival Time, Travel Time, Availability Status) in a table format. I'm calling two APIs to get the final result. How can I achieve this using AngularJs?
function between(trainData) {
var total = trainData.TotalTrains;
for (i = 0; i < total; i++) {
var source = trainData.Trains[i].Source;
var destination = trainData.Trains[i].Destination;
var name = trainData.Trains[i].TrainName;
var number = trainData.Trains[i].TrainNo;
var ttime = trainData.Trains[i].TravelTime;
var deptime = trainData.Trains[i].DepartureTime;
var arrtime = trainData.Trains[i].ArrivalTime;
$('.' + className + '').append("<br/>" + name + "(" + number + ")" + " " + ttime + " " + deptime + " " + arrtime + "<br/>");
}
}
}
you can append with the in the end like
$('.' + className + '').append("<table><tr><th>name</th><th>number </th><th>ttime </th><th>deptime </th><th>arrtime </th><th>classcode </th><th>status </th><th>jdate </th></tr><tr><td>" + name + "</td><td>" + number + "</td><td>" + ttime + "</td><td>" + deptime + " </td><td>" + arrtime + " </td><td>" + classcode + "</td><td>" + status + "</td><td>" + jdate + "</td></tr></table>");

Posting from multiple dynamically created HTML textarea elements

Given the following snippet:
out.println("<form action=" + "./post" + " " + "method=" + "post" + " " + "id=" + "tweetForm" + ">");
for (int i = 1; i <= twParser.currentTweetIndex; i++) {
output = twParser.tweetArray[i] + newLine;
out.println("<p>");
out.println("<textarea" + " " + "name=text" + " " + "id=\"styled\"" + " " + "maxlength=140" + " " + "cols=" + "140" + " " + "rows=" + "1" + " " + "tag=" + "text_" + String.valueOf(i) + " " + "form=" + "tweetForm" + " " + "onfocus=\"setbg('#e5fff3');\" onblur=\"setbg('white')\"" + ">" + output + "</textarea>");
out.println("<span class=label-style-countdown" + " " + "id=" + "chars" + String.valueOf(i) + ">" + String.valueOf(140 - twParser.tweetArray[i].length()) + "</span> characters remaining");
out.println("<p>");
}
out.println("<input type=" + "submit" + " " + "name=" + "post" + " " + "value=" + "post" + " " + "style=\"float: left;\"" + "/>");
out.println("<button type=\"reset\" value=\"Reset\">Reset</button>"
...that creates HTML multiple textarea elements and posts them to a servlet. But since all the textareas have the same name, only the contents of the first textarea are posted.
Is there a way to post them all?
Thanks
To have multiple inputs from same name you can use name array like
<textarea name="text[]">You text here</textarea>
which will post all the values having same name as an array.
PS: This can be done with any input types expect radio buttons
On this line:
out.println("<textarea" + " " + "name=text" + " " ...
Append i to the name of the textarea, such that the names increase as text1, text2 etc.
out.println("<textarea" + " " + "name=text" + i.toString() + " " ...
Perform the same loop on the server when receiving the POST request to receive from each textarea.

Can someone resolve the error in this code

rs = stmt.executeQuery("select c1.itemname,c1.itemcalorie,p.restname,p.location from categorie1 c1 ,Place p
where p.pincode = '" + pincode1 + "' and c1.itemid IN
("select c1.itemid from categorie1 c1 where c1.itemcalorie <='" + cal1 + "' and c1.itemcalorie >='" + cal1-400 + "' and c1.restid = p.restid ") ");
You have too many extra quotes:
rs = stmt.executeQuery(
"
SELECT c1.itemname,
c1.itemcalorie,
p.restname,
p.location
FROM categorie1 c1,
place p
WHERE p.pincode = '" + pincode1 + "'
AND c1.itemid IN (SELECT c1.itemid
FROM categorie1 c1
WHERE c1.itemcalorie <= '" + cal1 + "'
AND c1.itemcalorie >= '" + cal1-400 + "'
AND c1.restid = p.restid)
"
);
Im not sure wihch language is this (I hope it is not javascript) but the code is not safe look into parametrized query.

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Categories