
//////////////////////////////////////////////////////////////////////////////////////////////////
// app.js - main module to read the file from Sharepoint Office 365 and then save into HANA
// Author - Jay Malla @Licensed To Code
//////////////////////////////////////////////////////////////////////////////////////////////////
var hdbutility = require('./hdbutility');
var sharepointutility = require('./sharepointutility');
// Read all of the main configurable parameters
var config = require('config');
//////////////////////////////////////////////////////////////////////////////////////////////////
// Here is our main....
//////////////////////////////////////////////////////////////////////////////////////////////////
var sharepointExcelURL;
var schema;
var table;
var sqlArrayResults;
console.log("Let's start this journey");
//Command line usage (Note that the exact sequence is important)
//node.exe app.js -f sharepointurl -s schema -t table
// Let's extract the variables sharepointurl, schema, table from the command line
process.argv.forEach(function (value, index, array) {
console.log(index + ': ' + value);
if (array.length < 😎 {
console.error("Not enough parameters supplied");
throw (new Error("Not enough parameters supplied"));
}
switch (index) {
case 3:
console.log('FileName' + ': ' + value);
sharepointExcelURL = value;
sharepointExcelURL.replace('\\', '');
break;
case 5:
console.log('Schema' + ': ' + value);
schema = value;
break;
case 7:
console.log('Schema' + ': ' + value);
table = value;
break;
}
});
//If not supplied through command line, then read from the config file
//if (!schema) {config.get('schema')};
//if (!table) {config.get('table')};
//if (!sharepointExcelURL) {config.get('sharepointExcelURL')};
var hdbConnectionDetails = config.get('hdbConnectionDetails');
var oauth_info = config.get('oauth_info');
mainlogic();
//////////////////////////////////////////////////////////////////////////////////////////////////
// mainlogic is the main function that runs the main logic
//////////////////////////////////////////////////////////////////////////////////////////////////
async function mainlogic() {
try {
// Set the credentials from the configuration module which has read the default.json
const credentials = {
client: {
id: oauth_info.client_id,
secret: oauth_info.client_secret
},
auth: {
tokenHost: oauth_info.tokenHost,
authorizePath: oauth_info.authorizePath,
tokenPath: oauth_info.tokenPath
},
options: {
bodyFormat: 'form',
authorizationMethod: 'body'
}
};
////////////////////////////////////////////////////////////////
// Use Sharepoint Utility to get Excel
var sharepointclient = sharepointutility.createClient(credentials);
sharepointclient.getExcelFileFromSharepoint(sharepointExcelURL, schema, table, oauth_info.scope)
// If Excel file is retrieved
.then(result => {
console.log(result);
console.log("Excel File retrieved as array of SQL statements");
sqlArrayResults = result;
////////////////////////////////////////////////////////////////
// Save to HANA Database
var hdbclient = hdbutility.createClient(hdbConnectionDetails);
hdbclient.setSchema(schema);
hdbclient.setTable(table);
hdbclient.insertIntoHANA_ReturningPromise(sqlArrayResults)
.then(result => {
console.log(result);
console.log("Data uploaded to SAP HANA Table");
})
.catch(error => {
console.error(error);
console.log("Could not upload the data to SAP HANA table. Please fix issues and try again. Check config file and input parameters.");
});
})
.catch(error => {
console.error(error);
console.log("Could not read the Excel file from Sharepoint");
});
} catch (err) {
console.log(err);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// sharepointutility.js - sharepoint module to integrate with Sharepoint
// Author - Jay Malla @Licensed To Code
//////////////////////////////////////////////////////////////////////////////////////////////////
var graph = require('@microsoft/microsoft-graph-client');
// Class sharepointutility - object constructor function
function sharepointutility(credentials) {
// Set the credentials Info
this.credentials = credentials;
// We need to store a reference to this - since we will need this later on
self = this;
//////////////////////////////////////////////////////////////////////////////////////////////////
// This method async function connects to Sharepoint
this.getExcelFileFromSharepoint = async function getExcelFileFromSharepoint(sharepointExcelURL, schema, table, inputscope) {
return new Promise(async function (resolve, reject) {
self.sharepointExcelURL = sharepointExcelURL;
self.schema = schema;
self.table = table;
self.inputscope = inputscope;
const oauth2 = require('simple-oauth2').create(credentials);
var accessToken;
const tokenConfig = {
scope: inputscope // also can be an array of multiple scopes, ex. ['<scope1>, '<scope2>', '...']
};
// Get the access token object for the client
try {
const result = await oauth2.clientCredentials.getToken(tokenConfig);
accessToken = result.access_token;
} catch (error) {
console.log('Access Token error', error.message);
reject(error);
return;
}
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
////////////////////////////////////////////////////////////////
// Get the Sharepoint Excel file
var sharepointurl = sharepointExcelURL;
const result = await client
.api(sharepointurl)
.get();
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Let's do an HTTP post for the same:
var request = require('request');
var bearer = "Bearer " + accessToken;
var httpurl = "https://graph.microsoft.com/v1.0";
// Set the headers
var headers = {
'Content-Type': 'application/json',
'Authorization': bearer
}
// Configure the request
var options = {
url: httpurl + sharepointurl,
method: 'GET',
headers: headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body);
var sqlArrayResults;
sqlArrayResults = self.generateSQLarrayFromResults(result.formulas);
resolve(sqlArrayResults);
return;
}
})
////////////////////////////////////////////////////////////////
/*
////////////////////////////////////////////////////////////////
// Convert the Excel file results to an array of SQL
var sqlArrayResults;
sqlArrayResults = self.generateSQLarrayFromResults(result.formulas);
resolve(sqlArrayResults);
return;
////////////////////////////////////////////////////////////////
*/
});
};
this.generateSQLarrayFromResults = function generateSQLarrayFromResults(sharepointTable) {
var columnsString;
var sqlArray = [];
sharepointTable.forEach((element, index) => {
//Assumption - the first row has the table headings
if (index == 0) {
var processArray = (array) => {
var sqlString = "(";
array.forEach((element, index) => {
console.log(element);
if (index < (array.length - 1)) {
sqlString = sqlString + element + ",";
} else {
sqlString = sqlString + element + ")";
}
});
return sqlString;
}
columnsString = processArray(element);
} else {
if (element[0] != '') { //As long as there are other entries
var valuesArrayString;
var tempString = "insert into \"" + this.schema + "\".\"" + this.table + "\" " + columnsString + " values "; // + element[0] + "," + "'" + element[1] + "'" + "," + "'" + element[2] + "'" + ")";
var processValuesArray = (array) => {
var sqlString = "(";
array.forEach((element, index) => {
console.log(element);
if (index < (array.length - 1)) {
if (typeof (element) == "number") {
sqlString = sqlString + element + ",";
} else {
sqlString = sqlString + "'" + element + "'" + ",";
}
} else {
if (typeof (element) == "number") {
sqlString = sqlString + element + ")";
} else {
sqlString = sqlString + "'" + element + "'" + ")";
}
}
});
return sqlString;
}
var valuesArrayString;
valuesArrayString = processValuesArray(element);
tempString = tempString + valuesArrayString;
console.log(tempString);
sqlArray.push(tempString);
}
}
});
return sqlArray;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
exports.createClient = function (credentials) {
return new sharepointutility(credentials);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
// hdbutility.js - database module save into HANA
// Author - Jay Malla @Licensed To Code
//////////////////////////////////////////////////////////////////////////////////////////////////
// Class hdbutility - object constructor function
function hdbutility(hdbConnectionInfo) {
// Set the hdbConnection Info
this.hdbConnectionInfo = hdbConnectionInfo;
//property method to set schema name
this.setSchema = function (schema) {
this.schema = schema;
};
//property method to set the table name
this.setTable = function (table) {
this.table = table;
};
// We need to store a reference to this - since we will need this later on
self = this;
//////////////////////////////////////////////////////////////////////////////////////////////////
// This method async function runs the SQL Array of statements in the HANA database - but order is not gauranteed
this.insertIntoHANA_ReturningPromise = async function insertIntoHANA_ReturningPromise(sqlArray) {
return new Promise(function (resolve, reject) {
var inputSQLArray = sqlArray;
var results = [];
var hdb = require('hdb');
var hdbclient = hdb.createClient(self.hdbConnectionInfo);
hdbclient.on('error', function (err) {
reject(err);
return;
});
hdbclient.connect(function (err) {
if (err) {
reject(err);
return;
}
// First delete the entries from the table
var strQuery = 'delete from \"' + self.schema + '\".\"' + self.table + '\"';
hdbclient.exec(strQuery, function (err, rows) {
//hdbclient.end();
if (err) {
reject(err);
return;
}
console.log('Table Contents before SQL Inserts:', JSON.stringify(rows));
/////////////////////////////////////////////////////////////////////////
// Recursive approach to go through Array and execute SQL statements
var iterateOverArray = (index) => {
// if the end of Array reached..
if (index == inputSQLArray.length) {
// Read all of the the entries in that table and log this to see if all records inserted...
strQuery = 'select * from \"' + self.schema + '\".\"' + self.table + '\"';
hdbclient.exec(strQuery, function (err, rows) {
hdbclient.end();
if (err) {
reject(err);
return;
}
console.log('Table Contents After SQL Inserts:', JSON.stringify(rows));
resolve(JSON.stringify(rows));
return;
});
} else {
// If the end of the Array has not been reached....
// Execute the insert into the table
hdbclient.exec(inputSQLArray[index], (err, rows) => {
//hdbclient.end();
if (err) {
console.error('Execute error:', err);
//return callback(err);
reject(err);
return;
}
//otherwise capture the results and move to the next array member for the iteration
console.log('Results executing SQL ' + inputSQLArray[index] + ' = ' + JSON.stringify(rows));
results.push('Results executing SQL ' + inputSQLArray[index] + ' = ' + JSON.stringify(rows));
iterateOverArray(index + 1);
});
}
}
/////////////////////////////////////////////////////////////////////////
//Calling the recursive function...
iterateOverArray(0); // Initiate the recursive function that iterates through the array and executes the SQL
/////////////////////////////////////////////////////////////////////////
});
});
});
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
exports.createClient = function (hdbConnectionInfo) {
return new hdbutility(hdbConnectionInfo);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
11 | |
10 | |
9 | |
7 | |
5 | |
5 | |
5 | |
4 | |
3 | |
3 |