VOOZH about

URL: https://www.cdata.com/kb/tech/xml-odbc-mysql-apps-script.rst

โ‡ฑ Connect to XML Data in Google Apps Script via SQL Gateway


Connect to XML Data in Google Apps Script via SQL Gateway

๐Ÿ‘ Jerod Johnson
Jerod Johnson
Director, Technology Evangelism
Use the ODBC Driver for XML and the SQL Gateway to access XML data from Google Apps Script.

Google Apps Script gives you the ability to create custom functionality within your Google documents, including Google Sheets, Google Docs, and more. With the CData SQL Gateway, you can create a MySQL interface for any ODBC driver, including the hundreds of drivers by CData for sources like XML. The MySQL protocol is natively supported through the JDBC service in Google Apps Script, so by utilizing the SQL Gateway, you gain access to live XML data within your Google documents.

This article discusses connecting to the ODBC Driver for XML from Google Apps Script, walking through the process of configuring the SQL Gateway and providing sample scripting for processing XML data in a Google Spreadsheet.

Our script only reads data from a specified table, but you can easily extend the script to incorporate update functionality.

Real-Time Connectivity Through SQL Gateway

With SQL Gateway, your local ODBC data sources can look and behave like a standard MySQL database. Simply create a new MySQL remoting service in the SQL Gateway for the ODBC Driver for XML and ensure that the SQL Gateway is installed on a web-facing machine (or can connect to a hosted SSH server).

Connect to XML Data

If you have not already done so, provide values for the required connection properties in the data source name (DSN). You can use the built-in Microsoft ODBC Data Source Administrator to configure the DSN. This is also the last step of the driver installation. See the "Getting Started" chapter in the help documentation for a guide to using the Microsoft ODBC Data Source Administrator to create and configure a DSN.

Connecting to Local or Cloud-Stored (Box, Google Drive, Amazon S3, SharePoint) XML Files

CData Drivers let you work with XML files stored locally and stored in cloud storage services like Box, Amazon S3, Google Drive, or SharePoint, right where they are.

Setting connection properties for local files

Set the URI property to local folder path.

Setting connection properties for files stored in Amazon S3

To connect to XML file(s) within Amazon S3, set the URI property to the URI of the Bucket and Folder where the intended XML files exist. In addition, at least set these properties:

  • AWSAccessKey: AWS Access Key (username)
  • AWSSecretKey: AWS Secret Key

Setting connection properties for files stored in Box

To connect to XML file(s) within Box, set the URI property to the URI of the folder that includes the intended XML file(s). Use the OAuth authentication method to connect to Box.

Dropbox

To connect to XML file(s) within Dropbox, set the URI proprerty to the URI of the folder that includes the intended XML file(s). Use the OAuth authentication method to connect to Dropbox. Either User Account or Service Account can be used to authenticate.

SharePoint Online (SOAP)

To connect to XML file(s) within SharePoint with SOAP Schema, set the URI proprerty to the URI of the document library that includes the intended XML file. Set User, Password, and StorageBaseURL.

SharePoint Online REST

To connect to XML file(s) within SharePoint with REST Schema, set the URI proprerty to the URI of the document library that includes the intended XML file. StorageBaseURL is optional. If not set, the driver will use the root drive. OAuth is used to authenticate.

Google Drive

To connect to XML file(s) within Google Drive, set the URI property to the URI of the folder that includes the intended XML file(s). Use the OAuth authentication method to connect and set InitiateOAuth to GETANDREFRESH.

The property is the controlling property over how your data is represented into tables and toggles the following basic configurations.

  • Document (default): Model a top-level, document view of your XML data. The data provider returns nested elements as aggregates of data.
  • FlattenedDocuments: Implicitly join nested documents and their parents into a single table.
  • Relational: Return individual, related tables from hierarchical data. The tables contain a primary key and a foreign key that links to the parent document.

See the Modeling XML Data chapter for more information on configuring the relational representation. You will also find the sample data used in the following examples. The data includes entries for people, the cars they own, and various maintenance services performed on those cars.

Create a MySQL Remoting Service for XML Data

See the SQL Gateway Overview to set up connectivity to XML data as a virtual MySQL database. You will configure a MySQL remoting service that listens for MySQL requests from clients. The service can be configured in the SQL Gateway UI.

๐Ÿ‘ Creating a MySQL Remoting Service in SQL Gateway (Salesforce is shown)

Configure Remote Access

If your ODBC Driver and the remoting service are installed on-premise (and not accessible from Google Apps Script), you can use the reverse SSH tunneling feature to enable remote access. For detailed instructions, read our Knowledge Base article: SQL Gateway SSH Tunneling Capabilities.

Connecting to XML Data with Apps Script

At this point, you should have configured the SQL Gateway for XML data. All that is left now is to use Google Apps Script to access the MySQL remoting service and work with your XML data in Google Sheets.

In this section, you will create a script (with a menu option to call the script) to populate a spreadsheet with XML data. We have created a sample script and explained the different parts. You can view the raw script at the end of the article.

1. Create an Empty Script

To create a script for your Google Sheet, click Tools Script editor from the Google Sheets menu:

๐Ÿ‘ Open Script Editor

2. Declare Class Variables

Create a handful of class variables to be available for any functions created in the script.

//replace the variables in this block with real values as needed
var address = 'my.server.address:port';
var user = 'SQL_GATEWAY_USER';
var userPwd = 'SQL_GATEWAY_PASSWORD';
var db = 'CData XML Sys';

var dbUrl = 'jdbc:mysql://' + address + '/' + db;

3. Add a Menu Option

This function adds a menu option to your Google Sheet, allowing you to use the UI to call your function.

function onOpen() {
 var spreadsheet = SpreadsheetApp.getActive();
 var menuItems = [
 {name: 'Write data to a sheet', functionName: 'connectToXMLData'}
 ];
 spreadsheet.addMenu('XML Data', menuItems);
} 
๐Ÿ‘ The newly added Menu option.

4. Write a Helper Function

This function is used to find the first empty row in a spreadsheet.

/*
 * Finds the first empty row in a spreadsheet by scanning an array of columns
 * @return The row number of the first empty row.
 */
function getFirstEmptyRowByColumnArray(spreadSheet, column) {
 var column = spreadSheet.getRange(column + ":" + column);
 var values = column.getValues(); // get all data in one call
 var ct = 0;
 while ( values[ct] && values[ct][0] != "" ) {
 ct++;
 }
 return (ct+1);
}

5. Write a Function to Write XML Data to a Spreadsheet

The function below writes the XML data, using the Google Apps Script JDBC functionality to connect to the MySQL remoting service, SELECT data, and populate a spreadsheet. When the script is run, two input boxes will appear:

The first one asking the user to input the name of a sheet to hold the data (if the spreadsheet does not exist, the function creates it)

๐Ÿ‘ Input box for sheet selection.

and the second one asking the user to input the name of a XML table to read. If an invalid table is chosen, an error message appears and the function is exited.

๐Ÿ‘ Input box for table selection.

It is worth noting that, while the function is designed to be used as a menu option, it could be extended for use as a formula in a spreadsheet.

/*
 * Reads data from a specified XML 'table' and writes it to the specified sheet.
 * (If the specified sheet does not exist, it is created.)
 */
function connectToXMLData() {
 var thisWorkbook = SpreadsheetApp.getActive();

 //select a sheet and create it if it does not exist
 var selectedSheet = Browser.inputBox('Which sheet would you like the data to post to?',Browser.Buttons.OK_CANCEL);
 if (selectedSheet == 'cancel')
 return;

 if (thisWorkbook.getSheetByName(selectedSheet) == null)
 thisWorkbook.insertSheet(selectedSheet);
 var resultSheet = thisWorkbook.getSheetByName(selectedSheet);
 var rowNum = 2;

 //select a XML 'table'
 var table = Browser.inputBox('Which table would you like to pull data from?',Browser.Buttons.OK_CANCEL);
 if (table == 'cancel')
 return;

 var conn = Jdbc.getConnection(dbUrl, user, userPwd);

 //confirm that var table is a valid table/view
 var dbMetaData = conn.getMetaData();
 var tableSet = dbMetaData.getTables(null, null, table, null);
 var validTable = false;
 while (tableSet.next()) {
 var tempTable = tableSet.getString(3);
 if (table.toUpperCase() == tempTable.toUpperCase()){
 table = tempTable;
 validTable = true;
 break;
 }
 } 
 tableSet.close();
 if (!validTable) {
 Browser.msgBox("Invalid table name: " + table, Browser.Buttons.OK);
 return;
 }

 var stmt = conn.createStatement();

 var results = stmt.executeQuery('SELECT * FROM ' + table);
 var rsmd = results.getMetaData();
 var numCols = rsmd.getColumnCount();

 //if the sheet is empty, populate the first row with the headers
 var firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, "A");
 if (firstEmptyRow == 1) {
 //collect column names
 var headers = new Array(new Array(numCols));
 for (var col = 0; col < numCols; col++){
 headers[0][col] = rsmd.getColumnName(col+1);
 }
 resultSheet.getRange(1, 1, headers.length, headers[0].length).setValues(headers);
 } else {
 rowNum = firstEmptyRow;
 }

 //write rows of XML data to the sheet
 var values = new Array(new Array(numCols));
 while (results.next()) {
 for (var col = 0; col < numCols; col++) {
 values[0][col] = results.getString(col + 1);
 }
 resultSheet.getRange(rowNum, 1, 1, numCols).setValues(values);
 rowNum++;
 }

 results.close();
 stmt.close();
}
 

When the function is completed, you have a spreadsheet populated with your XML data and you can now leverage all of the calculating, graphing, and charting functionality of Google Sheets anywhere you have access to the Internet.


Complete Google Apps Script

//replace the variables in this block with real values as needed
var address = 'my.server.address:port';
var user = 'SQL_GATEWAY_USER';
var userPwd = 'SQL_GATEWAY_PASSWORD';
var db = 'CData XML Sys';

var dbUrl = 'jdbc:mysql://' + address + '/' + db;

function onOpen() {
 var spreadsheet = SpreadsheetApp.getActive();
 var menuItems = [
 {name: 'Write table data to a sheet', functionName: 'connectToXMLData'}
 ];
 spreadsheet.addMenu('XML Data', menuItems);
}

/*
 * Finds the first empty row in a spreadsheet by scanning an array of columns
 * @return The row number of the first empty row.
 */
function getFirstEmptyRowByColumnArray(spreadSheet, column) {
 var column = spreadSheet.getRange(column + ":" + column);
 var values = column.getValues(); // get all data in one call
 var ct = 0;
 while ( values[ct] && values[ct][0] != "" ) {
 ct++;
 }
 return (ct+1);
}

/*
 * Reads data from a specified 'table' and writes it to the specified sheet.
 * (If the specified sheet does not exist, it is created.)
 */
function connectToXMLData() {
 var thisWorkbook = SpreadsheetApp.getActive();

 //select a sheet and create it if it does not exist
 var selectedSheet = Browser.inputBox('Which sheet would you like the data to post to?',Browser.Buttons.OK_CANCEL);
 if (selectedSheet == 'cancel')
 return;

 if (thisWorkbook.getSheetByName(selectedSheet) == null)
 thisWorkbook.insertSheet(selectedSheet);
 var resultSheet = thisWorkbook.getSheetByName(selectedSheet);
 var rowNum = 2;

 //select a XML 'table'
 var table = Browser.inputBox('Which table would you like to pull data from?',Browser.Buttons.OK_CANCEL);
 if (table == 'cancel')
 return;

 var conn = Jdbc.getConnection(dbUrl, user, userPwd);

 //confirm that var table is a valid table/view
 var dbMetaData = conn.getMetaData();
 var tableSet = dbMetaData.getTables(null, null, table, null);
 var validTable = false;
 while (tableSet.next()) {
 var tempTable = tableSet.getString(3);
 if (table.toUpperCase() == tempTable.toUpperCase()){
 table = tempTable;
 validTable = true;
 break;
 }
 } 
 tableSet.close();
 if (!validTable) {
 Browser.msgBox("Invalid table name: " + table, Browser.Buttons.OK);
 return;
 }

 var stmt = conn.createStatement();

 var results = stmt.executeQuery('SELECT * FROM ' + table);
 var rsmd = results.getMetaData();
 var numCols = rsmd.getColumnCount();

 //if the sheet is empty, populate the first row with the headers
 var firstEmptyRow = getFirstEmptyRowByColumnArray(resultSheet, "A");
 if (firstEmptyRow == 1) {
 //collect column names
 var headers = new Array(new Array(numCols));
 for (var col = 0; col < numCols; col++){
 headers[0][col] = rsmd.getColumnName(col+1);
 }
 resultSheet.getRange(1, 1, headers.length, headers[0].length).setValues(headers);
 } else {
 rowNum = firstEmptyRow;
 }

 //write rows of XML data to the sheet
 var values = new Array(new Array(numCols));
 while (results.next()) {
 for (var col = 0; col < numCols; col++) {
 values[0][col] = results.getString(col + 1);
 }
 resultSheet.getRange(rowNum, 1, 1, numCols).setValues(values);
 rowNum++;
 }

 results.close();
 stmt.close();
}

Ready to get started?

Download a free trial of the XML ODBC Driver to get started:

 Download Now

Learn more:

๐Ÿ‘ XML Documents Icon
XML ODBC Driver

The XML ODBC Driver is a powerful tool that allows you to connect with live XML data stores, directly from any applications that support ODBC connectivity.

Access XML data like you would any standard database - read, write, and update etc. through a standard ODBC Driver interface.