I am trying to raise the user defined error in snowflake using LANGUAGE JAVASCRIPT,
how to raise the error, can you please help me with that
try
{
declare
exception_1 exception (-20001, 'no record in table');
begin
var output_trunc_query = `select count(*) from xyz`;
var output_trunc_stmt = snowflake.createStatement({ sqlText: output_trunc_query});
var output_trunc = output_trunc_stmt.execute();
var return_count = ""
while (output_trunc.next()) {
return_count += output_trunc.getColumnValue(1);
}
if(return_count>0)
{
var output_trunc_query = `delete from xyz`;
var output_trunc_stmt = snowflake.createStatement({ sqlText: output_trunc_query});
var output_trunc = output_trunc_stmt.execute();
return "Succeeded";
}
else
{
raise exception_1;
}
end
}
catch (err)
{
return "Fail";
}
You can't mix Snowflake Scripting (SQL) code and JavaScript. I don't understand why you need to raise a user defined exception if you will catch it in the same SP. Anyway, I removed try/catch to see the exception I raised, and here is the code:
CREATE OR REPLACE PROCEDURE test_sp()
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var output_trunc_query = `select count(*) from xyz`;
var output_trunc_stmt = snowflake.createStatement({ sqlText: output_trunc_query});
var output_trunc = output_trunc_stmt.execute();
var return_count = ""
while (output_trunc.next()) {
return_count += output_trunc.getColumnValue(1);
}
if(return_count>0)
{
var output_trunc_query = `delete from xyz`;
var output_trunc_stmt = snowflake.createStatement({ sqlText: output_trunc_query});
var output_trunc = output_trunc_stmt.execute();
return "Succeeded";
}
else
{
var exception_stmt = `declare
exception_1 exception (-20001, 'no record in table');
begin
raise exception_1;
end;`;
snowflake.createStatement({ sqlText: exception_stmt}).execute();
}
$$
;
call test_sp();
Fails with:
Uncaught exception of type 'EXCEPTION_1' on line 4 at position 15 : no record in table
At Statement.execute, line 23 position 63
Related
I wrote it in one of the hmi design programs. It´s IoT software.
After connecting with the source (my fall Siemens Logo 8) - PLC hardware, I get the ReferenceError, when I click on every button. These are my triggers to fire up the function. They are connected to start the animation.
What should I change to get rid of this errors?
Thanks,
RJ
var TUP= function fAUFmachen() {
var animateAUF2 = LeitstandSCHENKERRadeburg.getElementById('animateAUF2');
var animateAUF3 = LeitstandSCHENKERRadeburg.getElementById('animateAUF3');
var animateAUF4 = LeitstandSCHENKERRadeburg.getElementById('animateAUF4');
var animateAUF5 = LeitstandSCHENKERRadeburg.getElementById('animateAUF5');
var animateAUF6 = LeitstandSCHENKERRadeburg.getElementById('animateAUF6');
var animateAUF7 = LeitstandSCHENKERRadeburg.getElementById('animateAUF7');
var animateAUF8 = LeitstandSCHENKERRadeburg.getElementById('animateAUF8');
var animateAUF9 = LeitstandSCHENKERRadeburg.getElementById('animateAUF9');
animateAUF2.beginElement();
animateAUF3.beginElement();
animateAUF4.beginElement();
animateAUF5.beginElement();
animateAUF6.beginElement();
animateAUF7.beginElement();
animateAUF8.beginElement();
animateAUF9.beginElement();
}
var TDOWN= function fZUmachen() {
var animateZU2 = LeitstandSCHENKERRadeburg.getElementById('animateZU2');
var animateZU3 = LeitstandSCHENKERRadeburg.getElementById('animateZU3');
var animateZU4 = LeitstandSCHENKERRadeburg.getElementById('animateZU4');
var animateZU5 = LeitstandSCHENKERRadeburg.getElementById('animateZU5');
var animateZU6 = LeitstandSCHENKERRadeburg.getElementById('animateZU6');
var animateZU7 = LeitstandSCHENKERRadeburg.getElementById('animateZU7');
var animateZU8 = LeitstandSCHENKERRadeburg.getElementById('animateZU8');
var animateZU9 = LeitstandSCHENKERRadeburg.getElementById('animateZU9');
animateZU2.beginElement();
animateZU3.beginElement();
animateZU4.beginElement();
animateZU5.beginElement();
animateZU6.beginElement();
animateZU7.beginElement();
animateZU8.beginElement();
animateZU9.beginElement();
}
var LE1UP= function LE1UPmachen() {
var LE1animateUP = LeitstandSCHENKERRadeburg.getElementById('LE1animateUP');
LE1animateUP.beginElement();
}
var LE1DOWN= function LE1DOWNmachen() {
var LE1animateDOWN = LeitstandSCHENKERRadeburg.getElementById('LE1animateDOWN');
LE1animateDOWN.beginElement();
}
var LE2UP= function LE2UPmachen() {
var LE2animateUP = LeitstandSCHENKERRadeburg.getElementById('LE2animateUP');
LE2animateUP.beginElement();
}
var LE2DOWN= function LE2DOWNmachen() {
var LE2animateDOWN = LeitstandSCHENKERRadeburg.getElementById('LE2animateDOWN');
LE2animateDOWN.beginElement();
}
var LAUP= function LAUPmachen() {
var LAanimateUP = LeitstandSCHENKERRadeburg.getElementById('LAanimateUP');
LAanimateUP.beginElement();
}
var LADOWN= function LADOWNmachen() {
var LAanimateDOWN = LeitstandSCHENKERRadeburg.getElementById('LAanimateDOWN');
LAanimateDOWN.beginElement();
}
var ULUP= function ULUPmachen() {
var ULanimateUP = LeitstandSCHENKERRadeburg.getElementById('ULanimateUP');
ULanimateUP.beginElement();
}
var ULDOWN= function ULDOWNmachen() {
var ULanimateDOWN = LeitstandSCHENKERRadeburg.getElementById('ULanimateDOWN');
ULanimateDOWN.beginElement();
}
var AUP= function AUPmachen() {
var AanimateUP = LeitstandSCHENKERRadeburg.getElementById('AanimateUP');
AanimateUP.beginElement();
}
var ADOWN= function ADOWNmachen() {
var AanimateDOWN = LeitstandSCHENKERRadeburg.getElementById('AanimateDOWN');*/
AanimateDOWN.beginElement();
}
fAUFmachen();
fZUmachen();
LE1UPmachen();
LE1DOWNmachen();
LE2UPmachen();
LE2DOWNmachen();
LAUPmachen();
LADOWNmachen();
ULUPmachen();
ULDOWNmachen();
AUPmachen();
ADOWNmachen();
TUPmachen();
TDOWNmachen();
Your code calls
LE1DOWNmachen()
But the only function definition that contains that label is this:
var LE1DOWN= function LE1DOWNmachen() {
var LE1animateDOWN = LeitstandSCHENKERRadeburg.getElementById('LE1animateDOWN');
LE1animateDOWN.beginElement();
}
But this code is not defining a function called LE1DOWNmachen(). It is actually equivalent to this:
var LE1DOWN = function() {
var LE1animateDOWN = LeitstandSCHENKERRadeburg.getElementById('LE1animateDOWN');
LE1animateDOWN.beginElement();
}
The LE1DOWNmachen is meaningless here. It is being ignored. To invoke this function, you need to call
LE1DOWN();
Demo:
var LE1DOWN = function LE1DOWNmachen() {
console.log("Here!");
}
// This works
LE1DOWN();
// But this throws a reference error
LE1DOWNmachen();
If you want the function to be called LE1DOWNmachen, then define it like this:
function LE1DOWNmachen() {
console.log("Here!");
}
or this
var LE1DOWNmachen = function() {
console.log("Here!");
}
If you want both names to work, you can do this:
function LE1DOWNmachen() {
console.log("Here!");
}
var LE1DOWN = LE1DOWNmachen;
I have read the documentation but can not get spark.sql.columnNameOfCorruptRecord default value even with google searching.
The second question - how PERMISSIVE mode works when spark.sql.columnNameOfCorruptRecord is empty or null?
According to the code (19/01/2021) it's _corrupt_record:
val COLUMN_NAME_OF_CORRUPT_RECORD = buildConf("spark.sql.columnNameOfCorruptRecord")
.doc("The name of internal column for storing raw/un-parsed JSON and CSV records that fail " +
"to parse.")
.version("1.2.0")
.stringConf
.createWithDefault("_corrupt_record")
Regarding how PERMISSIVE mode works, you can see this in FailSafeParser[T]:
def parse(input: IN): Iterator[InternalRow] = {
try {
rawParser.apply(input).toIterator.map(row => toResultRow(Some(row), () => null))
} catch {
case e: BadRecordException => mode match {
case PermissiveMode =>
Iterator(toResultRow(e.partialResult(), e.record))
case DropMalformedMode =>
Iterator.empty
case FailFastMode =>
throw new SparkException("Malformed records are detected in record parsing. " +
s"Parse Mode: ${FailFastMode.name}. To process malformed records as null " +
"result, try setting the option 'mode' as 'PERMISSIVE'.", e)
}
}
private val toResultRow: (Option[InternalRow], () => UTF8String) => InternalRow = {
if (corruptFieldIndex.isDefined) {
(row, badRecord) => {
var i = 0
while (i < actualSchema.length) {
val from = actualSchema(i)
resultRow(schema.fieldIndex(from.name)) = row.map(_.get(i, from.dataType)).orNull
i += 1
}
resultRow(corruptFieldIndex.get) = badRecord()
resultRow
}
} else {
(row, _) => row.getOrElse(nullResult)
}
}
If it isn't specified, it'll fallback to the default value defined in the configuration.
i'm trying to extract data from the ANTLR parse tree, but not fully grasping how this should be done correctly
Let's say i have the following two SQL queries:
// language=SQL
val sql3 = """
CREATE TABLE session(
id uuid not null
constraint account_pk
primary key,
created timestamp default now() not null
)
""".trimIndent()
// language=SQL
val sql4 = """
CREATE TABLE IF NOT EXISTS blah(
id uuid not null
constraint account_pk
primary key,
created timestamp default now() not null
)
""".trimIndent()
Now i parse both of them:
val visitor = Visitor()
listOf(sql3, sql4).forEach { sql ->
val lexer = SQLLexer(CharStreams.fromString(sql))
val parser = SQLParser(CommonTokenStream(lexer))
visitor.visit(parser.sql())
println(visitor.tableName)
}
In my visitor if i visit the tableCreateStatement, i get the parse tree, but obviously just grabbing child1 will work for sql3, but not for sql4 since child1 in sql4 is IF NOT EXISTS
class Visitor : SQLParserBaseVisitor<Unit>() {
var tableName = ""
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
tableName = ctx?.getChild(1)?.text ?: ""
super.visitCreate_table_statement(ctx)
}
}
Is there a way to find a specific token in the parse tree?
I'm assuming the payload has something to do with it, but since it's of type Any, i'm not sure what to check it against
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
ctx?.children?.forEach {
if (it.payload.javaClass == SQLParser::Schema_qualified_nameContext) {
tableName = it.text
}
}
super.visitCreate_table_statement(ctx)
}
EDIT: the .g4 files are from
https://github.com/pgcodekeeper/pgcodekeeper/tree/master/apgdiff/antlr-src
this seems to work
override fun visitCreate_table_statement(ctx: SQLParser.Create_table_statementContext?) {
ctx?.children?.forEach {
if (it.payload.javaClass == Schema_qualified_nameContext::class.java) {
tableName = it.text
}
}
super.visitCreate_table_statement(ctx)
}
For branching trees
fun walkLeaves(
childTree: ParseTree = internalTree,
leave: (childTree: ParseTree) -> Unit) {
if (childTree.childCount == 0) {
if (!childTree.text?.trim().isNullOrBlank()) {
leave(childTree)
}
} else {
for (i in 0 until childTree.childCount) {
walkLeaves(childTree = childTree.getChild(i), leave = leave)
}
}
}
fun extractSQL(
childTree: ParseTree,
tokens: MutableList<String> = mutableListOf()
): String {
walkLeaves(childTree = childTree) { leave ->
tokens.add(leave.text)
}
...
}
I'm still learning Ionic and programming in general. I followed a link on the internet and I was able to create the white and read the necessary data, but I am not able to insert data in the created table. Can anyone help me with this?
I follow this tutorial: ionic-sqlite
My code:
getRegiao() { // Regiões //
return new Promise<Regiao[]>((resolve, reject) => {
let sql = "SELECT NOM_REGIAO, ID " +
"FROM TB_REGIAO "
this.executeQuery(sql).then(data => {
let regioes = [];
if (data != undefined)
data.forEach(function (row) {
let regiao: Regiao = { nom_regiao: row[0], id: row[1] }
regioes.push(regiao);
});
resolve(regioes);
}).catch(error => {
console.log(error);
});
});
}
addUser() {
let sql = "INSERT INTO TB_USUARIO (EMAIL) VALUES ('BLITCRANK#HOTMAIL.COM')";
// let sql = "SELECT EMAIL FROM TB_USUARIO";
this.executeQuery(sql);
}
executeQuery(sql: string) {
let db: any;
return new Promise<any>((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.dbName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = (e) => {
let uInt8Array = new Uint8Array(xhr.response);
db = new SQL.Database(uInt8Array);
let contents = db.exec(sql);
console.log(contents);
if (contents.length > 0)
resolve(contents[0].values);
else
resolve("query executada sem retorno")
};
xhr.send();
});
}
Please use this plugin , this is the plugin that I am using.
Take note in using execute sql like this db.executeSql('create table danceMoves(name VARCHAR(32))', {})
But rather use this db.executeSql('create table danceMoves(name VARCHAR(32))', [])
I dont know why instead of using object '{}' they replace it as array '[]' I think they forgot to update the documentaion
I have created an ajax call in jquery to my server, the trouble I'm facing now is that my response is printing ? even though the correct integer value is written into the output stream. Ajax function is given below.
$dntb.on('click', 'button', function(event) {
var i = $(this).closest('tr').index(); //have to get the row where the button is clicked
var sditmId = $("#sditm").val();
var sdhedId = $("#sdhed").val();
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = ""+response;
$("#stk").val(stk);
});
});
This function is called on click of an issue button in my table shown below
The server code is given below
int stk = null;
switch (userPath) {
case "/getstock":
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId")); //value to write into the output stream.
break;
case "/temp":
//er = opo.checkCatUniqueForEdit(request.getParameter("catName"), request.getParameter("catId"));
break;
}
System.out.println(stk); //Printing correctly
response.setContentType("text/html");
response.getWriter().write(stk);
Code to get the value
public int getStockData(String sditm, String sdhed) {
int stk = 0;
try {
String query = "Select stk.Stk_instk from tbstk stk inner join tbsditm itm on itm.Sditm_prdid=stk.Stk_prdid where itm.Sditm_sdhed=" + sdhed + " and itm.Sditm_id=" + sditm;
Statement stmt = dcon.con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
stk = rs.getInt("Stk_instk");
}
} catch (SQLException ex) {
Logger.getLogger(Op_OrdConf.class.getName()).log(Level.SEVERE, null, ex);
}
return stk;
}
The ajax call happens successfully but when I alert the response I'm getting and I'm getting the value correctly in the server but in the client side it is ?. Please help me solve this
Not sure but seems that you are missing a comma here:
stk = opo.getStockData(request.getParameter("sditmId"), request.getParameter("sdhedId"));
//----------------------------------------------------^-----i think this is missing.
As per your comment i would suggest you to explicitly set the dataType to html:
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = "" + response;
$("#stk").val(stk);
},"html"); //<----------add the dataType here.
I converted the int value returning from the function as given below to String, it seems to be some conflict between the content type and the value written into the output stream
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId"));