Update google sheet by rowid using API - google-sheets-api

I have employee in one sheet and I get row id of the searched employee on the page now I want to update the same record with the row id so that my time of searching the employee is saved. Is there any way to do this?
function getEmployeeName_(){
try{
var username = getUserName_();
var formObject = {verb:'GET',url:'/Employees?Emp_Email='+g_obj.current_user_email};
var response_obj = processForm(formObject);
response_obj = JSON.parse(response_obj);
var userObj = {};
if(response_obj != undefined && response_obj.status != undefined && response_obj.status == 'success'){
if(response_obj['data'].length >0){
userObj = response_obj['data'][0];
}
}
return userObj.Emp_Name;
}catch(e){
Logger.log(e.message);
return { status: 'error', message: 'Something went wrong while fetching User Name.'};
}
}

To update values in Sheets API, use spreadsheets.values.update. The rowId you're talking about will be a part of range property using A1Notation.
To check samples on using sheets values.update, check Sheet Operations.

Related

API call to BigQuery.jobs.get failed with error

I am currently using a sheet script to load data from sheets into BigQuery, however when I run the dataUpload() function I get the error below. I have correctly inserted the BQ project id, data id etc. and allowed the required permissions.
Any help will be greatly appreciated. A more refined script will also be great.
8:41:10 AM Error GoogleJsonResponseException: API call to
bigquery.jobs.get failed with error: Not found: Job
big-query-test-xxxxxx:job_0vRPgne07b25coS7TBTuasdB6JSF dataUpload #
Copy of Combined.gs:93 report_submission # Copy of Combined.gs:4
function dataUpload() {
var projectId= 'big-query-test-xxxxxx'; // GCP project name
var datasetId= 'test_data'; // Bigquery dataset name
var tableId= 'Test_Test'; // Bigquery table name
var lastColumn = 15; // Count of column (column A = 1)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var select_sheet = ss.getSheets()[0];
// get name of sheet
var select_sheet = ss.getSheetByName("Sheet1");
// This logs the value in the very last cell of this sheet
var lastRow = select_sheet.getLastRow();
// var lastColumn = select_sheet.getLastColumn();
if (lastRow < 2){
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert("Empty!!");
return ;
}
var range = select_sheet.getRange(1, 1, lastRow, lastColumn);
let rows = range.getValues();
// Normalize the headers (first row) to valid BigQuery column names.
// https://cloud.google.com/bigquery/docs/schemas#column_names
rows[0] = rows[0].map((header) => {
header = header.toLowerCase().replace(/[^\w]+/g, '_');
if (header.match(/^\d/))
header = '_' + header;
return header;
});
// Create the BigQuery load job config. For more information, see:
// https://developers.google.com/apps-script/advanced/bigquery
let loadJob = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1,
writeDisposition: 'WRITE_TRUNCATE',
}
}
};
// BigQuery load jobs can only load files, so we need to transform our
// rows (matrix of values) into a blob (file contents as string).
// For convenience, we convert the rows into a CSV data string.
// https://cloud.google.com/bigquery/docs/loading-data-local
let csvRows = rows.map(values =>
// We use JSON.stringify() to add "quotes to strings",
// but leave numbers and booleans without quotes.
// If a string itself contains quotes ("), JSON escapes them with
// a backslash as \" but the CSV format expects them to be
// escaped as "", so we replace all the \" with "".
values.map(value => JSON.stringify(value).replace(/\\"/g, '""'))
);
let csvData = csvRows.map(values => values.join(',')).join('\n');
let blob = Utilities.newBlob(csvData, 'application/octet-stream');
// Run the BigQuery load job.
try {
var result = BigQuery.Jobs.insert(loadJob, projectId, blob);
} catch (e) {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert(e);
return e;
}
// Get job ID
let json_result = JSON.parse(result);
let job_id = json_result['jobReference']['jobId'];
// Get job info
var job_info = BigQuery.Jobs.get(projectId,job_id);
let json_job_info = JSON.parse(job_info);
// Loop for job Complete
while (json_job_info['status']['state']=='RUNNING'){
job_info = BigQuery.Jobs.get(projectId,job_id);
json_job_info = JSON.parse(job_info);
}
// If job failed, alert error message
if (json_job_info['status']['errors']){
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert(JSON.stringify(json_job_info['status']['errors'][0]['message']));
}
// alert job complete message
else{
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.alert("Upload Complete");
}
Logger.log(
'Load job started. Click here to check your jobs: ' +
`https://console.cloud.google.com/bigquery?project=${projectId}&page=jobs`
);
}

Updating a value in SQL (better-sqlite3) with Node.JS

I currently have a database of people with each individual person and they hold a status value. I am trying to change their status value.
const id = parseInt(req.params.id , 10);
const { valid, messageObj } = validateId(id);
if (!valid) {
res.status(400).send(messageObj);
}
let { status, priority } = req.body;
let people = db.prepare('select * from people').all();
const person = people.find(person => person.id === id);
if(status !== 'none' & status == 'ready' || status == 'done'){
let updates = db.query(
'UPDATE people SET ? WHERE ?',
[{ status: status }, { id: id }]
);
}
I keep getting an error of db.query is not a function but I get that for every function that I try.
Pretty new to SQL but just trying to figure this out or any documentation that will help me as the better-sqlite3 doesn't have any update functions in the official documentation.
I cannot find a function called query() in the better-sqlite3 API for the Database class. I think that you would need to prepare() a Statement object, then run() it.
Also, column names cannot be passed as bound parameters. Your query should look like:
UPDATE people SET status = ? WHERE name = ?
You would need to change this:
let updates =
db.query('UPDATE people SET ? WHERE ?', [{ status: status }, { id: id }]);
To:
const stmt = db.prepare('UPDATE people SET status = ? WHERE id = ?');
const updates = stmt.run(status, id);
According to templates you can use javascript syntax to replace variables to its value.
let updates = db.exec(`UPDATE people SET status='${status}' WHERE id='${id}'`);

BigQuery Result save as google sheets through api

In Google BigQuery WebUI, it shows query result screen after executing a query, and it shows the button of "Save as Google Sheets". I like this feature but would like to automate this, is there such function through the REST API that I could do?
It doesn’t seem like there is a straightforward way to do this directly with the BigQuery API. There are few workarounds for this though:
You can use the BigQuery API to query your data and then the GoogleSheets API to upload it to Google Sheets.
You can use Google Apps Script. If you go to this link, you click on “New Script”, you can run the code below. You can adapt this to your needs. You can also add a trigger to run the script every hour/minute …
Here the code snippet from this link:
function runQuery() {
// Replace this value with the project ID listed in the Google
// Cloud Platform project.
var projectId = 'XXXXXXXX';
var request = {
query: 'SELECT TOP(word, 300) AS word, COUNT(*) AS word_count ' +
'FROM publicdata:samples.shakespeare WHERE LENGTH(word) > 10;'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Get all the rows of results.
var rows = queryResults.rows;
while (queryResults.pageToken) {
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
pageToken: queryResults.pageToken
});
rows = rows.concat(queryResults.rows);
}
if (rows) {
var spreadsheet = SpreadsheetApp.create('BiqQuery Results');
var sheet = spreadsheet.getActiveSheet();
// Append the headers.
var headers = queryResults.schema.fields.map(function(field) {
return field.name;
});
sheet.appendRow(headers);
// Append the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
sheet.getRange(2, 1, rows.length, headers.length).setValues(data);
Logger.log('Results spreadsheet created: %s',
spreadsheet.getUrl());
} else {
Logger.log('No rows returned.');
}
}

Dojo Datagrid - Get the row number

I am trying to retrieve the line number in dojo data grid. rowIndex function would not help me much because I need the 'line number' and NOT 'row number' when sorted.
The scenario:
I would like to set the focus on one specific row and this focus should remain even after sorting. But if I use the code below, it does not select the correct row.
For example, the index 1 is on the 5th line after sorting. However, the e.item.id still remains as 1, expected is 5.
calendar.on("itemClick", function (e)
{
MyGrid.doclick({ rowIndex: e.item.id });
MyGrid.scrollToRow(e.item.id);
});
Additionally, I also tried...
calendar.on("itemClick", function (e)
{
var identity = MyGrid._by_idx[e.item.id].idty;
var gridItem = MyGrid.getItem(identity);
var gridItemIndex = MyGrid.getItemIndex(gridItem);
MyGrid.doclick({ rowIndex: gridItemIndex });
MyGrid.scrollToRow(e.item.id);
});
Could you please let me know how to get the correct row after fitering? I thank you for your time.
Wishes,
Santosh
Okay, I figured out the answer.
GetGridItemIndexByGridItem = function (gridItem) {
var indexLength = MyGrid._by_idx.length;
var element = null;
var gridItemIndex = -1;
for (var i = 0; i < indexLength; i++) {
element = MyGrid._by_idx[i];
if (element.item.Guid == gridItem.Guid) {
gridItemIndex = i;
}
}
return gridItemIndex;
}
Best Wishes

dojo 1.8: populate select box with items from database including null values

Hi I just want to populate the select or comboBox.
I am able to populate both with the searchAttr to any string from JSON. But not so when there are null values.
JSON string :
[{"batch":"0000001000"},{"batch":"0000"},{"batch":""},{"batch":null}]
dojo code:
var selBatch = new ComboBox //located at the left side of the page and it is the second select box in a row
(
{ id:'ID_selBatch',
value:'',
searchAttr:'batch',
placeHolder:'Select...',
style:{width:'150px'},
}, 'node_selBatch'
);
on(selTest, 'change', function(valueCard)
{
var selectedTest = this.get('displayedValue');
var selBatch = registry.byId('ID_selBatch');
console.debug('Connecting to gatherbatches.php ...');
request.post('gatherbatches.php',
{ data:{nameDB:registry.byId('ID_selPCBA').value, nameCard : valueCard},
handleAs: "json"}).then
(
function(response)
{
var memoStore2 = new Memory({data:response});
selBatch.set('store', memoStore2);
selBatch.set('value','');
console.debug('List of batches per Test is completed! Good OK! ');
},
function(error)
{
alert("Batch's Error:"+error);
console.debug('Problem: Listing batches per Test in select Test is BAD!');
}
);
selBatch.startup();
});
Error :
TypeError: _32[this.searchAttr] is null
defer() -> _WidgetBase.js (line 331)
_3() -> dojo.js (line 15)
_f.hitch(this,fcn)(); -> _WidgetBase.js (line 331)
Please advise though it might strange to have null values populate in the select box but these null values are related to data in other columns in database, so the null values included so that I can apply mysql scripts later. Or do you have other better suggestion?
Clement
You can create a QueryFilter as in this jsfiddle to achieve what you want, but it might be simpler to have two data items. Your original model with possibly null batch properties, and the model you pass to the store which is used by the ComboBox.
But anyway, this can work:
function createQueryFilter(originalQuery, filter) {
return function () {
var originalResults = originalQuery.apply(this, arguments);
var results = originalResults.filter(filter);
return QueryResults(results);
};
}
and
var memoStore = new Memory({
data: data
});
memoStore.query = createQueryFilter(memoStore.query, function (item) {
console.log(item);
return !!item.batch;
});
and the dummy data:
function createData1() {
var data = [];
for (var i = 0; i < 10; i++) {
data.push({
name: "" + i,
batch: (0 === i % 2) ? "batch" + i : null
});
}
return data;
}
Screenshot. The odd numbered batch items are null in my example.