Not able to use query results inside Javascript UDF in Snowflake - javascript

Thankyou for your time.
I am working on a problem in Snowflake database. I am basically trying to create a Javascript UDF like following -
CREATE OR REPLACE FUNCTION getACity()
RETURNS STRING
LANGUAGE JAVASCRIPT
AS
'function getCity() {
var str;
$$ str = select * from CITY where name="Laflin" //This is the problem
$$
return str;
}';
As you can see I am trying to use data from another table in my function, but its not happening and I get following error -
JavaScript compilation error: Uncaught SyntaxError: Unexpected
identifier in getACity at ' str = select * from CITY where
name="Laflin"' position 21
I understand the syntax I am using to execute a query inside a javascript function is not correct, but I am not even sure if it is possible in Snowflake.
I have following questions -
Can I execute a query inside a javascript UDF and use the results in ongoing function ?
Can I call a Javascript UDF inside another Javascript UDF ? If this is possible it will work for me as well.
I have gone through Snowflake documentation but could not find any help specific to this case.
Thankyou again for your time. Much appreciated !

To answer your questions:
Snowflake JavaScript UDFs do not allow executing queries inside them in any form today.
you can not use JS UDFs in ther JS UDFs
You CAN use SQL UDFs for that, but that can only produce one column, e.g.
create or replace function getcityid()
returns string as '
select id from CITY where name='Laflin'
';
Or use VIEWs, e.g.
create or replace view cities as select * from CITY where name='Laflin'
If you explain exactly what you try to achieve, this should help.
Also, note that "Laflin" in SQL refers to a column named Laflin, not to a string with a value Laflin. Use 'Laflin' for that.

Snowflake JavaScript UDF do not support to run sql however you can use procedure to do that however procedure will only return one value/not the table function result.
For details about the Snowflake please refer the documentation
https://docs.snowflake.net/manuals/sql-reference/stored-procedures-overview.html#benefits-of-stored-procedures

Related

How to use Prepared statements with npm sqlite library on node js

I am using this library for connecting my node js application to an sqlite database. I saw its documentation for how to use prepared statements here but it is very brief and I cannot understand how to use it for my use case.
Lets say I have an sql string like this:
const sql = "INSERT INTO tbl(name) VALUES (?)"
So as per the documentation guess I should first create a statement and then use bind to populate it:
const stmt = await db.prepare(sql)
stmt.bind({? : "John"})
Is this the right way to do this? Also once I have created the Prepared statement how am I supposed to run this. All the examples mentioned in the docs are select statements, but if it is an insert statement I suppose stmt.get() or stmt.all() method are not correct as there is no result set to return here. How then am I supposed to do this?
I don't know the sqlite library too well, but the following example from the documentation performs a parameterised INSERT statement:
const result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {
':col': 'something'
})
I think you're focusing on the phrase 'prepared statement' a little too much.
Instead of looking only for this exact phrase, look for any use of parameters whose values are passed separately to the main SQL string. The example above fits this: there is a parameter :col which appears in the SQL string and the value for it is provided in an object passed to db.run alongside the SQL string.

Javascript Dynamic variable names not working

I have a table in a form with a list of products where there is an input for each (let's call it 'pc'). Each input is named as 'pc' and product id with an id as the same. IE: 'pc100', 'pc101', etc. Each input has an onkeyup event to call a function to populate a price where I pass the product id (onkeyup='myfunction(100) The function receives the id but I cannot configure the javascript to that id. I will have the rest of the code as long as I can get the dynamic variable name. The internet is full of all kinds of things like eval() and window[] and I have tried every possible combination I can think of/find. I know it's possible to get this to work. So...how can I get this alert to work?
Most the results I will give me 'pc100' when I need 'Heres my test'
function myfunction(idpro) {
var pc331 = 'Heres my test';
alert( "pc" + idpro );
}
Don't use dynamic variable names. Do use look-ups in data structures:
function f(id) {
var pc = {
331: "Here's my test"
}
console.log(pc[id]);
}
Dynamic variables are a huge problem, especially from a security perspective. If you were naive and used eval someone could construct an id value that executes arbitrary JavaScript and then you have an XSS problem.

JavaScript + MySQL: use fields as parameter in result

I'm quite new to JavaScript and I have the following issue:
I have a Node.JS server on which a webclient can connect and execute functions. One function is to look into a MySQL database and gather information.
The query is done right and I obtain the correct raw information as for example:
Here is my code:
So I correctly get the column names using the fields (fields[0].name = Count_0)variable and I am able to get the correct value using the result (result[0].Count_0 = Gray).
However, I am unable to merge the two lines in order to create the list of colors using something like this in a loop: result[0].fields[0].name = Gray
Is there an easier way to do this or not ?
Thanks,
Nicola.
In Javascript, you can use the [] operator to access a variably-named property in an object.
Instead of using result[0].fields[0].name, use
result[0][fields[0].name]
You won't get any runtime errors for accessing a property that doesn't exist, so you'll want to check whether that value is undefined before using it somewhere else.
It seems you want to get the color. If so, you can get the color by this
let color = result[0][fields[0].name];
The idea is use fields[0].name as key of result[0].
This is the breakdown of above single line.
let key = fields[0].name;
let color = result[0][key];

AlaSQL set result to variable for use elsewhere

I'm fairly new to JavaScript and AlaSQL, so sorry if this is obvious.
I'm trying to save the result of my AlaSQL query to a variable so I can use it elsewhere in my code. As a bit of context, I'm querying a CSV file, and I'm wanting to get the max, min and a certain row of a particular column, so I can then use this elsewhere. At the moment I'm just trying it on the max aspect.
<script>
alasql.promise('VALUE OF SELECT MAX(PM1) FROM CSV("http://localhost:8000/assets/interpolated.csv", {separator:","})').then(function(res){console.log(res); document.getElementById("testingId5").innerHTML = res}).catch(function(err){console.log('Error:', err);});
</script>
This produces a result and logs it in the console, and shows it onscreen, but I want to set it to a variable to be able to use too!
I've tried just adding var test = res; within the .then(function(res){}) part, but with no luck.
Thanks in advance.

Parse Identifiers from String containing code (Using JavaScript)

The problem I am trying to solve is this
Given a string containing code (entered by the user via some kind of web based form), such as:
"a = b + 5; return Math.abs(a);"
Extract a list of tokens that are considered identifiers:
a, b
In general are there readily available existing solutions? If not, what is a good starting point for writing an simple algorithm for this purpose?
I tried http://ace.c9.io/#nav=about, but was not able to find a method that readily returned the token type of an entire document. According to the API reference getTokens(Number row) should return the information I want. However, this method ended up returning the entire line as type text
Thank you in advance

Categories