The function below calls and sends an email for ALL rows that are marked "Closed"; but I want it to only email the one that gets marked "Closed"; not older, previously closed rows and I don't know how to correct this, please help.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3;
var numRows = 5000;
var dataRange = sheet.getRange(startRow, 1, numRows, 5000);
var data = dataRange.getValues();
var FinalMessage;
for (var i in data) {
var row = data[i];
if (row.includes("Closed")){
// Logger.log("CLOSED" + row);
var emailAddress = ""
var TSRNumber = row[19];
var IssueType = row[4];
var Customer = row[5];
var TankCode = row[13];
var City = row[9];
var State = row[10];
var Region = row[0];
var Terminal = row[1];
switch (Terminal) {
case "Riga MI":
emailAddress = "xxxxxx#xxxx.com";
break;
case "Other":
default:
emailAddress = "xxxx#xxxx.com";
break;
}
var subject = "CLOSED - TSR #" + TSRNumber + " for " + Customer + " in " + City + " " + State
+ " ( " + Region + " )";
var message = "TSR # " + TSRNumber + " for " + Customer + " in " + City + " " + State + " ( "
+ Region + " ) " + "is now Closed" +'\n' +'\n' + "Link to TSR Database: " +
"https://xxxxx.com"
MailApp.sendEmail(emailAddress, "NO-REPLY#xxxxx.com", subject, message);
}
}
}
You would need an installable trigger for this scenario:
function createTrigger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ScriptApp.newTrigger('sendEmail').forSpreadsheet(ss).onEdit().create();
}
This function, when executed manually, will create a trigger for the spreadsheet that will fire when a cell is edited.
Then the sendEmail function itself would then read the edited cell, validate, and fill out the fields as usual:
function sendEmail(e) {
var sheet = SpreadsheetApp.getActiveSheet();
if ((e.range.getRow() >= 3) && (e.range.getValue() === "Closed")) {
var row = sheet.getRange(e.range.getRow(),1,1,20).getValues();
var emailAddress = ""
var TSRNumber = row[19];
var IssueType = row[4];
var Customer = row[5];
var TankCode = row[13];
var City = row[9];
var State = row[10];
var Region = row[0];
var Terminal = row[1];
switch (Terminal) {
case "Riga MI":
emailAddress = "xxxxxx#xxxx.com";
break;
case "Other":
default:
emailAddress = "xxxx#xxxx.com";
break;
}
var subject = "CLOSED - TSR #" + TSRNumber + " for " + Customer + " in " + City + " " + State
+ " ( " + Region + " )";
var message = "TSR # " + TSRNumber + " for " + Customer + " in " + City + " " + State + " ( "
+ Region + " ) " + "is now Closed" +'\n' +'\n' + "Link to TSR Database: " +
"https://xxxxx.com"
MailApp.sendEmail(emailAddress, "NO-REPLY#xxxxx.com", subject, message);
}
}
References:
Installable Triggers
Related
Values are not inserting in table login even though the query's response is showing "inserted" but table is not updated with the new row.
var mysql = require('mysql')
router.get('/save',function(req,res){
var uname = req.query.username;
var em = req.query.email;
var pass = req.query.pass;
var gender = req.query.gender;
var dob = req.query.date;
var con = mysql.createConnection({
host:"localhost",
user:"root",
password:"abcd1234",
database:"nodedb"
});
con.query('insert into login(username, email, password, gender, DOB)
VALUES("' + uname + '","' + em + '","' + pass + '","' + gender + '","' + dob + '")',function(err,rows,fields){
console.log(rows);
res.send("inserted");
});
con.end();
});
module.exports = router;
result shows
"inserted"
although the values are not inserted in my table.
var mysql = require('mysql')
router.get('/save',function(req,res){
var uname = req.query.username;
var em = req.query.email;
var pass = req.query.pass;
var gender = req.query.gender;
var dob = req.query.date;
var con = mysql.createConnection({
host:"localhost",
user:"root",
password:"abcd1234",
database:"nodedb"
});
var sql = "INSERT INTO login (username, email, password, gender, DOB) VALUES ('" + uname + "'" + ',' + "'" + em + "'" + ',' + "'" + pass + "'" + ',' + "'" + gender + "'" + ',' + "'" + dob + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
console.log(result);
});
});
module.exports = router;
Try the code above....
Note sql keywords are written in capital letters.
By the way, using raw sql in nodejs is tiresome so its better that you try using an ORM some time
I have tried doing this several ways, and maybe node.js is the wrong language to use for this purpose, but I thought it could be quickly done with it. I am taking a contacts table with names and addresses, and converting it to two tables with a one-to-many relationship, so that one contact can have multiple addresses. The desired data structure is like this:
Contact Table
contactId
firstName
lastName
phone
email
etc...
Address Table
addressId
contactId
street
city
state
etc...
Currently all fields are in the same table.
The result I am getting is that the data in the second query never changes. So if I write the contact query first, then it works as expected, but the addresses all end up as duplicates of one contact's address. If I insert the address record first, then I get duplicate records of one contact. I tried nesting the queries first, but I split them out when I got this behavior. My thinking was that I could write the queries . I need to write the contact and get the ID back, then write the address with the contactID. OR I need to write the address and get THAT ID back, and then write the contact, get that ID, and then do an update query to put the contactId into the address record. This last method is the attempt shown in the code below.
Here is my code currently:
var sql = "SELECT * FROM pfPeople";
connection.query(sql, function(err, result, fields) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var names = result[i].fullName.replace(/"/g, "'").split(" ");
var sql2 = "INSERT INTO contact (firstName, lastName, title, phone1, phone2, fax, email1, notes, org) VALUES (" +
"\"" + names[0] + "\", \"" + names[1] + "\", \"" + result[i].title.replace(/"/g, "'") + " \", \"" + result[i].phone1 + "\", \"" +
result[i].phone2 + "\", " + "\"" + result[i].phone3 + "\", \"" + result[i].email + "\", \"" + result[i].notes.replace(/"/g, "'") + "\", \"" +
result[i].org.replace(/"/g, "'") + "\")";
var street = result[i].street;
var city = result[i].city;
var state = result[i].state;
var zip = result[i].zip;
var country = result[i].country;
var sql3 = "INSERT INTO address (address1, city, state, zip, country) VALUES (" +
"\"" + street + "\", \" " + city + "\", \"" + state + "\", \"" + zip + "\", \"" + country + "\")";
var contactId;
var addressId;
connection.query(sql2, function(err, cResult) {
if (err) throw err;
var contactId = cResult.insertId;
console.log("Inserted ID: " + contactId);
});
connection.query(sql3, function(err, aResult) {
if (err) throw err;
var addressId = aResult.insertId;
});
var sql4 = "UPDATE address set contactId = " + contactId + " WHERE (addressId = " + addressId + ")";
connection.query(sql4, function(err, uRes) {
console.log("Address updated " + addressId + " " + contactId);
});
if (i > 3) break;
}
});
well i add some promises to make it easier. the problem was you didnt wait for the responses to finish. try this code
var sql = "SELECT * FROM pfPeople";
connection.query(sql, function(err, result, fields) {
if (err) throw err;
for (var i = 0; i < result.length; i++) {
var names = result[i].fullName.replace(/"/g, "'").split(" ");
var sql2 = "INSERT INTO contact (firstName, lastName, title, phone1, phone2, fax, email1, notes, org) VALUES (" +
"\"" + names[0] + "\", \"" + names[1] + "\", \"" + result[i].title.replace(/"/g, "'") + " \", \"" + result[i].phone1 + "\", \"" +
result[i].phone2 + "\", " + "\"" + result[i].phone3 + "\", \"" + result[i].email + "\", \"" + result[i].notes.replace(/"/g, "'") + "\", \"" +
result[i].org.replace(/"/g, "'") + "\")";
var street = result[i].street;
var city = result[i].city;
var state = result[i].state;
var zip = result[i].zip;
var country = result[i].country;
var sql3 = "INSERT INTO address (address1, city, state, zip, country) VALUES (" +
"\"" + street + "\", \" " + city + "\", \"" + state + "\", \"" + zip + "\", \"" + country + "\")";
const contacPromise = new Promise((resolve,reject) =>{
connection.query(sql2, function(err, cResult) {
if (err) return reject( err);
resolve( cResult.insertId);
});
})
const addressPromise = new Promise((resolve,reject) =>{
connection.query(sql3, function(err, aResult) {
if (err) return reject( err);
resolve(aResult.insertId);
});
})
Pomise.all([contacPromise,addressPromise])
.then(([contactId,addressId]) =>{
var sql4 = "UPDATE address set contactId = " + contactId + " WHERE (addressId = " + addressId + ")";
connection.query(sql4, function(err, uRes) {
console.log("Address updated " + addressId + " " + contactId);
});
})
.catch(err => throw err)
if (i > 3) break;
}
});
I am writing node js application which fetches 100 000 records from SQL server database and insert those into mysql database. I have done with code but my application not give me expected performance.
My selection of 100k records takes 9-10 sec and bulk insertion process takes 3-4 sec. I want node to speed up selection process (need 3-4 sec to select record from sql server). I tried using 2 ways but still unable to achieve expected time.
/*First Way*/
var sql = require('mssql');
var mysql = require("mysql");
var sizeof = require('sizeof');
var moment = require('moment');
var config = {
user: '**',
password: '*****',
server: '******',
database: '*******'
}
var connection1 = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
connection1.connect();
sql.connect(config, function(err) {
if(err)
console.log(err);
console.log('Connecting to Sql Server');
console.time('Overall Time-Taken');
var request = new sql.Request();
console.time('Time-Taken to fetch');
request.query('select TOP 100000 * from ShipmentAuditLog WITH (NOLOCK)', function(err, recordset) {
if(err)
console.log(err);
else{
//console.log(sizeof(recordset));
console.timeEnd('Time-Taken to fetch');
syncing(recordset);
}
});
});
function mapping(row) {
var formatedString = '';
var CreatedDate = new moment(row.CreatedDate).format('YYYY-MM-DD HH:mm:ss');
row.Process = row.Process.replace(/'/g,"\\'");
if(row.Comment != null){
formatedString = row.Comment;
formatedString = formatedString.replace(/'/g,"\\'");
row.Comment = formatedString;
}
return "('" + row.ShippingID + "','" + row.BagNo + "','" + row.ProcessLocation + "','" + row.Process + "','" + row.Comment + "','" + CreatedDate + "','" + row.CreatedBy + "','" + row.LastModifiedDate + "','" + row.LastModifiedBy + "','" + row.DestinationLocation + "','" + row.VenderLostShipmentsDebitId + "', NOW())";
//return "('" + row.ShippingID + "','" + row.BagNo + "','" + row.ProcessLocation + "','" + row.Process + "','" + row.Comment + "','" + CreatedDate + "','" + row.CreatedBy + "','" + row.LastModifiedDate + "','" + row.LastModifiedBy + "','" + row.DestinationLocation + "','" + row.VenderLostShipmentsDebitId + "')";
}
var syncing = function(recordset){
//var columns = [];
var values = [];
/*for(col in recordset[0]){
columns.push(col);
}*/
/*for(var i=0,len = recordset.length;i<len;i+=1){
values.push(mapping(recordset[i]));
}*/
recordset.forEach(function(record){
values.push(mapping(record));
})
//console.log(values);
console.time('Time-Taken to Insert');
var QRY = connection1.query('INSERT INTO shipmentauditlog VALUES'+ values.join(','), function(err, result) {
if (err) {
console.log(err);
}
else {
console.timeEnd('Time-Taken to Insert');
console.timeEnd('Overall Time-Taken');
}
});
//console.log(QRY.sql);
}
/*Second Way*/
var sql = require('mssql');
var mysql = require("mysql");
var moment = require('moment');
var config = {
user: '**',
password: '***',
server: '****',
database: '****',
stream: true
}
var connection1 = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
connection1.connect();
var values = [];
function mapResult(row){
var formatedString = '';
var CreatedDate = new moment(row.CreatedDate).format('YYYY-MM-DD HH:mm:ss');
row.Process = row.Process.replace(/'/g,"\\'");
if(row.Comment != null){
formatedString = row.Comment;
formatedString = formatedString.replace(/'/g,"\\'");
row.Comment = formatedString;
}
return "('" + row.ShippingID + "','" + row.BagNo + "','" + row.ProcessLocation + "','" + row.Process + "','" + row.Comment + "','" + CreatedDate + "','" + row.CreatedBy + "','" + row.LastModifiedDate + "','" + row.LastModifiedBy + "','" + row.DestinationLocation + "','" + row.VenderLostShipmentsDebitId + "', NOW())";
}
var connection = new sql.Connection(config, function(err) {
if(err)
console.log(err);
console.log('Connecting to Sql Server');
console.time('Overall Time-Taken');
var request = new sql.Request(connection);
//request.stream = true;
request.query('select TOP 100000 * FROM ShipmentAuditLog WITH (NOLOCK)'); // or request.execute(procedure);
request.on('recordset',function(col){
console.time('Time-Taken to fetch');
});
// Emitted for each row
request.on('row', function(row) {
//Build array with resultset for bulk insert
values.push(mapResult(row));
});
request.on('error', function(err) {
console.log(err);
});
// Emitted for the last one
request.on('done', function(returnValue) {
console.timeEnd('Time-Taken to fetch');
// Function which perform bulk insert into mysql
syncing(values);
connection.close();
});
});
var syncing = function(values){
/*var startTime = new Date();
console.log("Start Time :"+ startTime);*/
console.time('Time-Taken to Insert');
var qry = connection1.query('INSERT INTO shipmentauditlog VALUES'+values.join(','),function(err,res){
if(err)
console.log(err);
else{
/*var endTime = new Date();
console.log('End Time:'+ endTime);*/
console.timeEnd('Time-Taken to Insert');
console.timeEnd('Overall Time-Taken');
}
});
}
I have created a Google Form for our local scout district, to notify that they will be taking the section out and about. This is all working fine as is the notification email. What I am trying to do is automatically create a calendar event, this will be later shared through out website so that the management team can view and see where all of the scouts are.
Anyway back on track, the fields that I have so far are:
function CalendarSubmit(e){
var Group = e.values[1];
var ActivityDateStart = e.values[2];
var ActivityTimeStart = e.values[3];
var ActivityDateEnd = e.values[4];
var ActivityTimeEnd = e.values[5];
var Activity = e.values[6];
var Location = e.values[7];
var Description = e.values[8];
var AuthLeader = e.values[9];
var AuthLeaderNo = e.values[10];
var AuthLeaderPermit = e.values[11];
var LeaderCharge = e.values[12];
var LeaderChargeNo = e.values[13];
var LeaderEmail = e.values[14]
var Adults = e.values[15];
var Beavers = e.values[16];
var Cubs = e.values[17];
var Scouts = e.values[18];
var Explorers = e.values[19];
var Other = e.values[20];
var InTouchName = e.values[21];
var InTouchContact = e.values[22];
var ManagerEmail = e.values[23];
var RA = e.values[24];
var Rules = e.values[25];
}
I want the calendar title to use the Variable Title, where
var Title = group + " - " + Activity;
Start and Finish Times:
var Start = ActivityDateStart + ActivityTimeStart;
var End = ActivityDateEnd + ActivityTimeEnd;
Location:
var LOC = Location
Description:
var calDescription = "Location of Activity: " + Activity + " /n" +
"Description of Activity: " + Description + " /n/n" +
"Leader in Charge: " + LeaderCharge + " /n" +
"No. of Adults (18+): " + Adults + " /n" +
"No. of Beavers: " + Beavers + " /n" +
"No. of Cubs: " + Cubs + " /n" +
"No. of Scouts: " + Scouts + " /n" +
"No. of Explorers/Young Leaders: " + Explorers + " /n" +
"No. of Non-Uniformed Young People (Under 18): " + Other;
The trouble I am having is that I am not sure how to script all of the above into the CalendarApp.
My problem is: if I change the query string below to select * from table;, it works fine. but if I execute the query string below, it throws an error:
SQL error: Invalid column number. Cannot less than or equal zero.
This is the code:
columnHeader = " 'id', 'pat_name', 'pat_age' ";
var filename = $('serType') + $('serId') + ".csv";
var reporting_exportQuery = "select " + columnHeader +
" union all " +
"select * " +
"from " + $('serType') +
" into outfile 'C://mytest/reports/service reports/"+$('serType') + "/" + "" + filename + "' " +
"fields terminated by ',' " +
"lines terminated by '\\n';";
var test = "select * from Age;";
reporting_DBConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver',:D);
logger.info(reporting_exportQuery);
var result = reporting_DBConn.executeCachedQuery(reporting_exportQuery);
You are adding(union) one column columnHeader with all columns (*) from table. You can do like this
SELECT 'columnHeader',table_alias.* FROM TABLE table_alias...
var filename = $('serType') + $('serId') + ".csv";
var reporting_exportQuery =
"select 'columnHeader',table_alias.* " +
"from " + $('serType') table_alias+
" into outfile 'C://mytest/reports/service reports/"+$('serType') + "/" + "" + filename + "' " +
"fields terminated by ',' " +
"lines terminated by '\\n';";
var test = "select * from Age;";
reporting_DBConn = DatabaseConnectionFactory.createDatabaseConnection('com.mysql.jdbc.Driver','jdbc:mysql://localhost:3310/cnwlreports', :D);
logger.info(reporting_exportQuery);
var result = reporting_DBConn.executeCachedQuery(reporting_exportQuery);
My guess is columnHeader have a diferent number of columns than select * in the union part.
Step to debug.
print the result string reporting_exportQuery
try running that string on the MySql.
Added:
First Select doesn't have FROM part
.
var reporting_exportQuery =
"select " + columnHeader +
"FROM SomeTable" <--- need FROM
" union all " +
"select " + columnHeader + <--- need same columns