How to create a Search all columns in SuiteScript 2.0 version - netsuite

How I can create select * from in suitescript?
I need all columns from the object.

you can use the 'N/query'
require(['N/query'], function(query) {
var sql = "SELECT * from TRANSACTION WHERE TRANSACTION_ID=XXXX;
var resultIterator = query.runSuiteQLPaged({
query: sql,
pageSize: 10
}).iterator();
resultIterator.each(function(page) {
var pageIterator = page.value.data.iterator();
pageIterator.each(function(row) {
log.debug('ID: ' + row.value.getValue(0) + ', Context: ' + row.value.getValue(1));
return true;
});
return true;
});
});
Before you do that run the query in ODBC because some columns cannot been loaded (pdf,xml data)

Related

Optimize NetSuite restlet to avoid timeout error

I'm writing a restlet that will return all Bill, Credit Card, and Journal transactions within a NetSuite account (see code below). My issue is that given the volume of data (100k+ transaction records), I'm getting a timeout error. Is there any way for me to optimize my code to avoid this timeout error? Is there a way for me to pass the restlet parameters around the PageRanges and just make multiple calls?
/**
*#NApiVersion 2.x
*#NScriptType Restlet
*/
define(['N/error', 'N/search'],
function(error, search) {
function doValidation(args, argNames, methodName) {
for (var i = 0; i < args.length; i++)
if (!args[i] && args[i] !== 0)
throw error.create({
name: 'MISSING_REQ_ARG',
message: 'Missing a required argument: [' + argNames[i] + '] for method: ' + methodName
});
}
function _get(context) {
doValidation('GET');
var mySearch = search.create({
type: search.Type.TRANSACTION,
columns: ['account', 'recordtype','trandate', 'tranid', 'memo', 'amount', 'department', 'entity' ],
filters: [['recordtype', 'is', 'vendorbill'], 'or', ['recordtype', 'is', 'creditcardcharge'],'or', ['recordtype', 'is', 'journalentry']]
});
results = []
var myPagedData = mySearch.runPaged({
pageSize: 1000
})
myPagedData.pageRanges.forEach(function(pageRange){
var myPage = myPagedData.fetch({index: pageRange.index})
results.push(myPage.data)
})
return results
}
return {
get: _get,
};
});
You can refresh the restLet for time exceed error as it has 5 minute(300 seconds) time limit only.
you can use N/runtime moduleto get its governance limit and N/cache module to store the already done data.
check the remaining governance and curren t time in loop.
and break the loop and call again restLet after storing already done data using cache module. Pass remaining data as a parameter while calling.
var script_startdate = new Date(); // this will be in starting on script
function
script_Start_time = script_startdate.getTime();
for(var i=0;i<i+2;i++){ // here i used infinity loop, you can use yours
var script_workdate = new Date();
var script_workTime = script_workdate.getTime();
remainingTime= script_workTime - script_Start_time;
var remainingContentIndex=content.indexOf(content[i]);
var remainingUsage = runtime.getCurrentScript().getRemainingUsage();
if ((remainingTime> 240000) ||(remainingUsage<80))break;
}
if ((substraction > 240000) ||(remainingUsage<80))
{
var myCacheRecId = cache.getCache({
name: 'temporaryCacheRecId',
scope: cache.Scope.PUBLIC
});
myCacheRecId.put({
key: 'myvar',
value: "already completed data""
});
var slice_index=remainingContentIndex+1;
var remainingContent=content.slice(slice_index);
var content=content.toString(remainingContent);
redirect.redirect({
scriptId: 'customscript_scriptid,
deploymentId: 'customdeploy_deployid',
parameters: {
content: content
}
});
log.debug("called restlet", "called restlet");
};

use the + key to add new row in Tabulator

am trying to add new row to tabulator using the key board ,so i followed the given below steps
Created an extended part as below
Tabulator.prototype.extendModule("keybindings", "actions", {
"addNewRow":function(){ //delete selected rows
var id = Math.floor((Math.random() * 10000) + 1) * -1;
Tabulator.addRow({ iD: id });
},
});
hut i found that to add new row i need to refer to the tabulator object to do so , i need this to be generic to all my tabulators in the whole site ,so i do not want to refer to tabulator object every time
to run ti now i must have it like below
Tabulator.prototype.extendModule("keybindings", "actions", {
"addNewRow":function(){ //delete selected rows
var id = Math.floor((Math.random() * 10000) + 1) * -1;
tblgridPage1.addRow({ iD: id });
},
});
You can use the scope that the module is executed in to do this, so your code should look like this:
Tabulator.prototype.extendModule("keybindings", "actions", {
"addNewRow":function(){
var id = Math.floor((Math.random() * 10000) + 1) * -1;
this.table.addRow({ iD: id });
},
});
the this.table gives you access to the table that the function is being executed on

Order by Desc in Node js and Mssql giving me the wrong output

I am working on a project where I have to call the Last data from Mssql database to check the last date and current date of the data to set the JobNumber. I was able to retrieve the data from database by execute query "Select Top 1 from TableName Order by ColumnName" But the issue arisen up when I use Order by ColumnName Desc. However, my console.log out put is give me the accurate data of the record set but when i tried to assign that record set value into a variable then the output was giving me the wrong data
my Console log out put is:
{ recordsets: [ [ [Object] ] ],
recordset: [ { StartTime: 2018-12-05T23:52:21.000Z, JobNumber: '113' } ],
output: {},
rowsAffected: [ 1 ] }
Image of the Variable output:
My Database Last Data
Coding for the Retrieve data
var sql = "Select TOP 1 StartTime, JobNumber FROM arduino ORDER BY StartTime DESC"
db.executeSql(sql, function (rows, err) {
if (err) {
console.log("Error with connection");
}
else {
console.log(rows);
var StartDateTime = rows.recordset[0].StartTime;
var JobNumber = rows.recordset[0].JobNumber;
var JobNum = parseInt(JobNumber);
if(JobNum == null)
{
JobNo = 1;
}
else if (SensStart == StartDateTime)
{
JobNo = JobNum;
}
else
{
JobNo = JobNum + 1;
}
What am i doing wrong here?
Thank you
I have found a solution by below coding
var dateString = StartDateTime;
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD') ;
Thanks

How to pass order info to sequelize.js raw query?

In sequelize, I can use
my_table.findAll({ order: [['datetime', 'desc']] })
to query data and order by a column. But when I try to use parameterized raw query like:
var input_parameters = {order_column: 'datetime', order: 'desc'};
sequelize.query('select * from my_table order by :order_column :order', { replacements: input_parameters, type: models.sequelize.QueryTypes.SELECT });
It can't return the correct order because
the order info asc/desc is escaped in the query, the final prepared query is like 'select * from my_table order by 'datetime' 'desc''.
Is there a way to pass order info to raw parameterized query?
This might not be the sequelize way, but...what if:
let order_column = 'something';
let order = 'DESC';
sequelize.query(`select * from my_table order by ${order_column} ${order}`, { type: models.sequelize.QueryTypes.SELECT });
UPDATE:
This is the right answer
await sequelize.query(
'SELECT * FROM projects ORDER BY ? ?',
{
replacements: ['something', 'desc'],
type: QueryTypes.SELECT,
}
);
This way sequelize still protects you from sql injection.
I wondered samething. But I think there's no options in raw query.
So I usually define class methods in model to use method much sequelize-like follows.
/**
* usage :
*
* model.findSomething({
* where: whereCondition,
* limit: limit,
* offset: offset,
* order: [
* ['col1', 'asc'],
* ['col2', 'desc']
* ]})
*/
model.findSomething = function ({where, limit, offset, order}) {
let sql = 'SELECT col1, col2 FROM some_table '
... (build where conditions)
// build order conditions
if (order && order.length > 0) {
let orderBy = ' ORDER BY '
for (let i = 0; i < order.length; i++) {
if (order[i].length > 0) { // [column] or [column, asc/desc]
orderBy += (i > 0 ? ', ' : ' ') + order[i].join(' ')
}
}
sql += orderBy
} else {
sql += ` ORDER BY comment_group, comment_depth, comments.comment_id`
}
... (build limit and offset)
}
Before you call sequelize.query, just build the sql statement first.
Too late answer, but I hope this let help you.
let order_column = 'something';
let order = 'DESC';
sequelize.query('select * from my_table order by " + order_column +' ' order, { replacements: input_parameters, type: models.sequelize.QueryTypes.SELECT })

Copying data from one DB to another with node-sqlite - formatting the 'insert' statement

I'm writing a small utility to copy data from one sqlite database file to another. Both files have the same table structure - this is entirely about moving rows from one db to another.
My code right now:
let tables: Array<string> = [
"OneTable", "AnotherTable", "DataStoredHere", "Video"
]
tables.forEach((table) => {
console.log(`Copying ${table} table`);
sourceDB.each(`select * from ${table}`, (error, row) => {
console.log(row);
destDB.run(`insert into ${table} values (?)`, ...row) // this is the problem
})
})
row here is a js object, with all the keyed data from each table. I'm certain that there's a simple way to do this that doesn't involve escaping stringified data.
If your database driver has not blocked ATTACH, you can simply tell the database to copy everything:
ATTACH '/some/where/source.db' AS src;
INSERT INTO main.MyTable SELECT * FROM src.MyTable;
You could iterate over the row and setup the query with dynamically generated parameters and references.
let tables: Array<string> = [
"OneTable", "AnotherTable", "DataStoredHere", "Video"
]
tables.forEach((table) => {
console.log(`Copying ${table} table`);
sourceDB.each(`select * from ${table}`, (error, row) => {
console.log(row);
const keys = Object.keys(row); // ['column1', 'column2']
const columns = keys.toString(); // 'column1,column2'
let parameters = {};
let values = '';
// Generate values and named parameters
Object.keys(row).forEach((r) => {
var key = '$' + r;
// Generates '$column1,$column2'
values = values.concat(',', key);
// Generates { $column1: 'foo', $column2: 'bar' }
parameters[key] = row[r];
});
// SQL: insert into OneTable (column1,column2) values ($column1,$column2)
// Parameters: { $column1: 'foo', $column2: 'bar' }
destDB.run(`insert into ${table} (${columns}) values (${values})`, parameters);
})
})
Tried editing the answer by #Cl., but was rejected. So, adding on to the answer, here's the JS code to achieve the same:
let sqlite3 = require('sqlite3-promise').verbose();
let sourceDBPath = '/source/db/path/logic.db';
let tables = ["OneTable", "AnotherTable", "DataStoredHere", "Video"];
let destDB = new sqlite3.Database('/your/dest/logic.db');
await destDB.runAsync(`ATTACH '${sourceDBPath}' AS sourceDB`);
await Promise.all(tables.map(table => {
return new Promise(async (res, rej) => {
await destDB.runAsync(`
CREATE TABLE ${table} AS
SELECT * FROM sourceDB.${table}`
).catch(e=>{
console.error(e);
rej(e);
});
res('');
})
}));

Resources