SQLite: Current date plus one day in where clause - javascript

I need to get 3 queries on an 'appointment' table.
where appointment.start_date is today,
where appointment.start_date = today+1 day, and
where appointment.start_date is > today+1 day.
I've got 1. down fine.
var resultSet = conn.execute('SELECT * FROM appointments WHERE date() = date(start_date)');
For 2., I've tried this:
var resultSet = conn.execute('SELECT * FROM appointments WHERE date("now", "+1day") = date(start_date, "+1day")');
I got date('now', '+1day') from this link this link but it returns the same results as the first query.
Can someone help with these queries?

If you're using exactly what's posted, I'd say you have a spacing problem
SQLite uses '+1 day' and you have posted '+1day'
Barring any explicit error messages, with the space it should work

I'm not sure for SQLite, but try next code:
var now = new Date();
var nowStr = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate();
var nowPlus1 = new Date(Number(now)+24*60*60*1000);
var nowPlus1Str = nowPlus1.getFullYear()+"-"+(nowPlus1.getMonth()+1)+"-"+nowPlus1.getDate();
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date = '" + nowStr + "'");
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date = '" + nowPlus1Str + "'");
var resultSet = conn.execute("SELECT * FROM appointments WHERE start_date > '" + nowPlus1Str + "'");

Sorry totally my own idiosity my query was wrong: WHERE date("now", "+1day") = date(start_date, "+1day") should have read WHERE date("now", "+1day") = date(start_date) I had an extra +1 day. Doh!

Try with "plus one day" instead of "+1 day". Its not documented, but worked for me in another code.
var resultSet = conn.execute('SELECT * FROM appointments WHERE date("now plus one day") = date(start_date plus one day")');

Related

Javascript function in snowflake to append tablename with current date

I have recently started to use snowflake and have been stuck at this issue:
I want to clone a table called AB_USER to AB_USER_(current_date). I have written following code to accomplish this:
CREATE or replace PROCEDURE backup_proc()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var tab_name = `AB_USER_BCK_2020_`+ current_date();
stat = `create or replace table staging.` + tab_name + ` clone staging.AB_USER`;
var rs = snowflake.execute( { sqlText: stat} );
return 'Done.';
$$;
The problem is I cannot find appropriate function to get current date. Snowflake provides a JS environment but I don't know which function to use to get current date.
I am very new to snowflake so any help in this will be much appreciated.
Thanks.
CURRENT_DATE is an SQL command, so you need to call it as SQL statement with snowflake.execute.
As I see, you want to get values of month and day from current date, so you can use the following procedure:
CREATE or replace PROCEDURE backup_proc()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
var curdate = snowflake.execute( { sqlText: "SELECT TO_CHAR(CURRENT_DATE,'MMDD') as curdate"} );
curdate.next();
var tab_name = "AB_USER_BCK_2020_"+ curdate.getColumnValue('CURDATE');
var stat = "create or replace table staging." + tab_name + " clone staging.AB_USER";
var rs = snowflake.execute( { sqlText: stat} );
return "Done.";
$$
;

How to increment msg.payload[i] in node-red

We are working on an ubuntu server, where we have installed node-red. What we want is to take data from one table on our MySQL Database, and then move it to another table.
Our flow looks like this:
Our 'Select Tolerance' node contains:
msg.topic = "SELECT * FROM Tolerance";
return msg;
Simple code, which selects data from our database. If we connect a debug node like this:
We then see an output looking like this:
We want to pick all data, so we need to go through all objects in the array and make sure to take all values and send them over to our new database table. We're using the 'New Tolerance' node to do so, and 'New Tolerance' contains:
var i;
var secured = 1;
for (i = 0; i < msg.payload.length; i++) {
var time_start = msg.payload[i].time_start
var time_end = msg.payload[i].time_end
var temperatur_lpn = msg.payload[i].temperatur_lpn
var temperatur_rising = msg.payload[i].temperatur_rising
var temperatur_weather = msg.payload[i].temperatur_weather
var temp_compare_WL = msg.payload[i].temp_compare_WL
var temp_compare_WR = msg.payload[i].temp_compare_WR
var out = "INSERT INTO Sunrise_Tolerance (time_start, time_end, temperatur_lpn, temperatur_rising, temperatur_weather, temp_compare_WL, temp_compare_WR, secured)"
out = out + " VALUES ('" + time_start + "','" + time_end + "','" + temperatur_lpn + "','" + temperatur_rising + "','" + temperatur_weather + "','" + temp_compare_WL + "','" + temp_compare_WR + "','" + secured + "');"
msg.topic = out;
return msg;
}
The problem is that we only receive the first row of data (first object in the array) and not the rest. Can anyone figure out why we dont receive all data, but only the first?
The problem comes the fact you have a return statement inside the for loop.
That will exit the function the first time it reaches that point - so your loop never loops.
If you want to send multiple messages you should use node.send(msg); in your for loop. The only thing to watch out for is if you call node.send with the same object multiple times, as the message is passed by reference, you would get some odd side-effects. As you only care about msg.topic in this instance, you can afford to create a new message object each time.
So, instead of the return msg statement, you could do:
for (i ... ) {
var out = "INSERT ...";
...
node.send({topic: out});
}
// Return without any arguments so no further messages are sent.
return;

Is there a way to use parameterized queries with this code?

I've gotten this from the forum already, but one of the answers provided a way to use search parameters in a url string. Some of my tables are too big to load in a browser, so apparently I will have to find out how to add search parameters to this code. The only reason I didn't use the other code was that it showed how to do that with a calendar.
I know nothing about JSON/jQuery/razor/c#. Please help.
#{
var db = Database.Open("LGOnline");
var result = db.Query("SELECT * FROM CashOS");
var data = result.Select(x => new
{
ID = x.ID,
STORE_NO = x.STORE_NO,
DATE = x.DATE,
MWS_AMOUNT = x.MWS_AMOUNT,
FINAL_AMOUNT = x.FINAL_AMOUNT
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
Update: I am using Microsoft WebMatrix 3. I am able to get the data from my tables with this code and it converts them to JSON. I just don't need all of it at once.
Update: I got it to do what I was trying to do. It isn't pretty, and I am open for any number of suggestions, but this made it to where I can type in the url and add &STORE_NO=55 and also i can select a date if I want to.
#{
var db1 = Database.Open("LGOnline");
var formValue2 = Request.Form["STORE_NO"];
var formValue3 = Request.Form["DATE"];
if (IsPost)
{
Response.Redirect("test.cshtml?&STORE_NO=" + formValue2 + "&DATE=" + formValue3);
}
var Keyword2 = Request.QueryString["STORE_NO"]; //Retrieves passed variable from the database search page for STORE_NO
var Keyword3 = Request.QueryString["DATE"]; //Retrieves passed variable from the database search page for DATE
var sqlQ = "SELECT * FROM CashOS WHERE STORE_NO LIKE #0 AND DATE LIKE #1";
var dataQ = db1.Query(sqlQ, "%" + Keyword2 + "%", "%" + Keyword3 + "%");
var requestedData = dataQ.Select(x => new
{
ID = x.ID,
STORE_NO = x.STORE_NO,
DATE = x.DATE,
MWS_AMOUNT = x.MWS_AMOUNT,
FINAL_AMOUNT = x.FINAL_AMOUNT
}).ToArray();
Json.Write(dataQ, Response.Output);
Response.ContentType = "application/json";
}
This is the output by the way:
[{"ID":28,"STORE_NO":55,"DATE":"/Date(1442811600000)/","MWS_AMOUNT":10.1600,"FINAL_AMOUNT":10.1600}]
Thank You all for your help!!

Compare timestamp in two different formats - GAS

I am using the enhanced workflow script that was posted by Mogsdad here.
I have managed to work out a few issues but one that I am stuck on at the moment is the error that comes up from this section -
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, timestamp);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
I get the "Request not available" error because the ArrayLib.indexOf object is comparing the time stamp that is being presented from the same source but via two different 'routes'.
The timestamp from the 'timestamp' variable looks like this - "17/03/2015 18:00:11"
...and the timestamp contained in the 'data' variable (that should match the timestamp variable) looks like this - "Tue Mar 17 2015 00:30:10 GMT-0700 (PDT)".
I am assuming that the two different formats is what is resulting in the ArrayLib.indexOf object returning a '-1' result and hence the error message.
Any thoughts on what I need to do to get the matching working successfully ?
Create a new Date object for the timestamp value, so that you can ensure they can be compared. The code should look like:
var dateFromTimestamp = new Date(timestamp);
After looking around at a few other posts I came up with a solution that seems to work pretty well and overcomes the issues with using the timestamp.
I put an array formula in the first column of the response sheet that created a ticket number -
=ArrayFormula(if(B2:B,"AFR"&text(row(A2:A)-1,"00000"),iferror(1/0)))
Then I retrieved the ticket number (var cellVal) and sent it with the email. The response email brings the approval value to the correct line every time....so far.
function sendEmail(e) {
// Response columns: Timestamp Requester Email Item Cost
var email = e.namedValues["Requester Email"];
var item = e.namedValues["Item"];
var cost = e.namedValues["Cost"];
//var timestamp = e.namedValues["Timestamp"];
var row = e.range.getRow();
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1pFL0CEW5foe8nAtk0ZwwTleYrBn2YulMu_eKPDEFQaw').getSheetByName("Form Responses 1");
var range = sheet.getDataRange();
var cellval = range.getCell(row,1).getValue();
//var origMail = range.getCell(row,3).getValue();
Logger.log(cellval);
//Logger.log(origMail);
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["Requester Email"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+row+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+row+'&cellval='+cellval;
var html = "<body>"+
"<h2>Please review</h2><br />"+
"Request from: " + email + "<br />"+
"Ticket No: " + cellval + "<br />"+
"For: "+item +", at a cost of: $" + cost + "<br /><br />"+
"Approve<br />"+
"Reject<br />"+
"</body>";
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
"Approval Request",
"Requires html",
{htmlBody: html});
}

jquery load append datepicker function

I have the following function that produces numbered input fields with ids and names of the current timestamp they're were created. I'm trying to attach a datepicker to each one created, hence the unique/timestamp id's.
Can anybody suggest a way for me to go about doing this?
I believe the datepicker function needs to be produced under each input field created but I don't know how to produce a JavaScript function with JavaScript. I'm thinking maybe I can use jQuery's load() function and call a PHP script that produces a unique function and loads it into a div. Is that the best way to tackle this? Thanks!
<script>
var number = 0;
var num;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10){var month = "0"+month;}
if (day<10){var day = "0"+day;}
var fullyear = month+"/"+day+"/"+year;
num = event.timeStamp
$('#box').append( number+". <input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10'/><br><br>");
var idtag = "#"+num;
});
</script>
Why not just set up the datepicker when you create the input?
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#box').append(number).append(picker);
Also you should make "id" values that look like valid identifiers instead of plain numbers.
Look at #Pointy's answer for an actual solution, he was quicker than me, my answer will not actually solve your problem, I just would like to mention a few points to note.
Try to indent your code properly, so it's easy to read for you after looking at it in a month's time. You might know now what it does exactly, but it will be a pain to figure it out in the long term.
As unlikely as it is, it can't be guaranteed that the same event won't fire twice in the same millisecond, I would avoid using event.timeStamp for generating unique IDs. It's just a personal preference though, it will probably never happen, I just don't like to rely on timers for uniqueness. You have your incrementing number variable already, you should use that, that will definitely be unique.
When writing HTML into a string, I would rather use the proper standard markup. Use ' as your string boundaries and " for your HTML attributes.
Lastly, inside your if(month<10){...} condition, don't redefine the variable you have already defined within your function. It would probably not throw an error or have any negative effect, but we can only thank the current forgiving javascript implementation for that, redefinition should not be allowed in the same scope.
Finally make sure you put all your jQuery initialisation code into the jQuery ready function to make sure the DOM and jQuery itself has fully loaded.
And sorry for the rant... ;)
$(function(){
var number = 0;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
// Insert #Pointy's solution in here...
});
});
You can add a fict
<input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10' class='fake-class'/>
And then, you can load the datepicker object like this:
$('.fake-class').each(function(){
$(this).datepicker();
});
Hope it helps
Just a little correction about the variable num and number, #Pointy was using num and #DarthJDG was using number. Here is the complete code that worked for me
In Script:
var num = 0;
$('#btn').click(function(event) {
<!-- Set the default date to be todays date, can be removed for blank-->
num++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
<!-- End -->
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#holder').append(num).append(picker);
}
And in the HTML:
<input type="button" id="btn" value="button">
<div id="holder">
</div>

Categories