For example, I want to retrieve all placeholder in a string, using Javascript / node :
SELECT * FROM myOrders WHERE order_id = {orderId} and order_date = {orderDate}
as array : ['orderId','orderDate'].
Is there any library I can use?
You can use a regular expression:
var placeholders = sql.match(/\{\w+\}/g).map(s=>s.slice(1,-1));
Demonstration:
var sql = "SELECT * FROM myOrders WHERE order_id = {orderId} and order_date = {orderDate}";
var placeholders = sql.match(/\{\w+\}/g).map(s=>s.slice(1,-1));
document.write(JSON.stringify(placeholders))
Note: if you're using an old version of Node (i.e. without arrow functions), use
var placeholders = sql.match(/\{\w+\}/g).map(function(s){ return s.slice(1,-1) });
Related
var get_end_time = "select CURRENT_TIME()";
var time_sql = {sqlText: get_end_time};
var time_create = snowflake.createStatement(time_sql);
var time_exec_end = time_create.execute();
time_exec_end.next();
var end_time = time_exec_end.getColumnValue(1);
I have this code above in a JavaScript stored procedure in snowflake, this query produces: 11:27:35.181000000
How can I strip this to only give me 11:27:35?
JavaScript Procedure is returning type as string,
so value cannot be interpreted in snowflake as time
or to apply time-base formats.
Code without any formatting for time -
CREATE OR REPLACE PROCEDURE test_time()
RETURNS STRING
LANGUAGE javascript
AS
$$
var get_end_time = "select CURRENT_TIME()";
var time_sql = {sqlText: get_end_time};
var time_create = snowflake.createStatement(time_sql);
var time_exec_end = time_create.execute();
time_exec_end.next();
var end_time = time_exec_end.getColumnValue(1);
return end_time;
$$
;
call test_time();
TEST_TIME
06:20:47.250000000
Use TO_CHAR to get desired format and return same.
CREATE OR REPLACE PROCEDURE test_time()
RETURNS STRING
LANGUAGE javascript
AS
$$
var get_end_time = "select to_char(CURRENT_TIME())";
var time_sql = {sqlText: get_end_time};
var time_create = snowflake.createStatement(time_sql);
var time_exec_end = time_create.execute();
time_exec_end.next();
var end_time = time_exec_end.getColumnValue(1);
return end_time;
$$
;
call test_time();
TEST_TIME
06:27:50
JavaScript does not have a date data-type.
If we are using SQL based procedure which returns datetype date/timestamp,
then its interpretation is as per set format.
In below code there are no format functions applied.
create or replace procedure test_time()
returns date
language sql as
$$
begin
return (select current_timestamp());
end;
$$
;
alter session set timestamp_output_format='hh24:mi:ss.sss';
call test_time();
TEST_TIME
07:03:48.48S
alter session set timestamp_output_format='hh24:mi:ss.ff';
call test_time();
TEST_TIME
07:05:07.236000000
alter session set timestamp_output_format='hh24:mi:ss';
call test_time();
TEST_TIME
07:05:39
Usually we will use SQL queries like below, we will pass params with predifined number $1
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($1)', ['1'])
But I want to pass multiple params without predifined $1. Any way to resolve this?
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($$)', ['1','2','3'])
One approach dynamically builds the IN clause based on the expected number of parameters. Consider:
var params = ['1','2','3'];
var inClause = '?' + ', ?'.repeat(params.length - 1);
var sql = 'SELECT * FROM sample_data WHERE code IN (' + inClause + ')';
console.log(sql);
Once we have a statement with the right number of placeholders, we can simply bind the collection or array with no trouble.
I want to save my formulas to SQL and use it in both the controller side and javascript side on my .net core project.
{H}+({FA}*2)+{VW}
Formulas are like this format. I want to change values of H, FA and VW with numbers.
string str2 = "{H}+({FA}*2)+{VW}";
string str3 = string.Format(str2, 60, 10, 20);
string value = new DataTable().Compute(str, null).ToString();
I can calculate like this on the controller side. (If there is a better way for it i can get advice too.)
I need to do on JavaScript side too. What should I do?
EDIT;
Btw C# code doesn't work, here is the working one i need a modular thing but i don't know how to do it.
var H = "150";
var VW = "200";
var FA = "20";
string str = $"{H}+{VW}*2";
string value = new DataTable().Compute(str, null).ToString();
I can use string.replace but I've 26 variable and will be complex. I'm adding more examples to formulas.
string formula1 = {H}+({FA}*2)+{VW};
string formula2 = {W}+({FA}*2)+{HW};
string formula3 = {FA}*2+{GFH}-{MTF};
string formula4 = {VSP}/{FA}+{GFV}*(A+B+C);
string formula5 = {TH}+{W}*2+{FT}*2;
***EDIT2:
I'm thinking about to use this on C# side.
public void CalculateTest()
{
List<varKeyDto> varKeys = new List<varKeyDto>(){
new varKeyDto(){
Variable = "H",
Value ="150"
},
new varKeyDto(){
Variable = "VW",
Value ="200"
},
new varKeyDto(){
Variable = "FA",
Value ="20"
},
};
string formula = "{H}+({FA}*2)+{VW}";
string cmptd = ReturnFormula(formula, varKeys);
}
public string ReturnFormula(string formula, List<varKeyDto> varKeys)
{
string formulaString = formula;
foreach (var varKey in varKeys)
{
formulaString = formulaString.Replace("{" + varKey.Variable + "}", varKey.Value);
}
string value = new DataTable().Compute(formulaString, null).ToString();
return value;
}
You could process the string to extract the variable names and make it valid JavaScript code and use all that to create a Function, here is an example:
const str = '{H}+({FA}*2)+{VW}';
const vars = str.match(/{[A-Z]+}/g).map(v => v.replace(/[{}]/g, ''));
const fnBody = str.replace(/[{}]/g, '');
const fn = new Function(...vars, `return ${fnBody}`);
const result = fn(60, 10, 20);
console.log(result);
The generated function looks something like this:
function (H, FA, VW) {
return H+(FA*2)+VW
}
You cannot format string with such custom literals, they have to be like - {0} {1} {2} and so on.
You can use .Replace instead -
var formulaString = formula.Replace("{H}", "1").Replace("{FA}", "2").Replace("{VW}", "3");
string value = new DataTable().Compute(formulaString, null).ToString();
In javascript you can use .replaceAll-
var formula = "{H}+({FA}*2)+{VW}";
var formulaString = formula.replaceAll("{H}", 1).replaceAll("{FA}", 2).replaceAll("{VW}", 3)
console.log(eval(formulaString));
I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here
I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>
I'd like to create a javascript timestamp based on a rails date_select and time_select property. I attached an onChange function to the select helper and fetching the innerhtml to read the values into a div which works fine. Now I want to use those strings from the select property and create a timestamp in js (using it for validations).
I did first try this by making integers from the innerhtml values:
function insertText10()
{
var start_day = document.new_link['link[start_at(3i)]'];
var start_month = document.new_link['link[start_at(2i)]'];
var start_year = document.new_link['link[start_at(1i)]'];
var start_hour = document.new_link['link[start_at(4i)]'];
var start_minute = document.new_link['link[start_at(5i)]'];
var selOption1 = start_day[start_day.selectedIndex];
var selOption2 = start_month[start_month.selectedIndex];
var selOption3 = start_year[start_year.selectedIndex];
var selOption4 = start_hour[start_hour.selectedIndex];
var selOption5 = start_minute[start_minute.selectedIndex];
start_date = new Date(parseInt(selOption3.innerHTML),parseInt(selOption2.innerHTML),parseInt(selOption1.innerHTML),parseInt(selOption4.innerHTML),parseInt(selOption5.innerHTML),0,0);
then by using strings:
start_date = new Date(selOption3.innerHTML+selOption2.innerHTML+selOption1.innerHTML+selOption4.innerHTML+selOption5.innerHTML);
but neither works.
What am I doing wrong?
--
PS: I checked the w3s docu http://www.w3schools.com/jsref/jsref_obj_date.asp to find the solution above.
Solved:
start_date = new Date(parseInt(selOption3.value),parseInt(selOption2.value),parseInt(selOption1.value),parseInt(selOption4.value),parseInt(selOption5.value),0,0);