CData Python Connector for XML

Build 26.0.9655

CData Python Connector for XML

Overview

The CData Python Connector for XML allows developers to write Python scripts with connectivity to XML. The connector wraps the complexity of accessing XML data in an interface commonly used by Python connectors to common database systems.

Key Features

  • WHL installation packages that enable installation with "pip install".
  • Supported for Python 3.10 or newer on Windows, Linux, and macOS.
  • Write and execute SQL queries to fetch and update data in XML.
  • Custom dialect class that enables SQLAlchemy 1.3 and 1.4 to use this connector.

Getting Started

See Getting Started to install the connector to your Python distribution and to create a basic connection to XML.

Using the Python Connector/Using from Tools

See Using the Connector for examples of executing basic SELECT, INSERT, UPDATE, DELETE, and EXECUTE queries with the module's provided classes.

See Using from Tools to connect XML data to tools such as Pandas or Petl.

SQLAlchemy ORM

SQLAlchemy can be leveraged to model the tables in XML with mapped classes. See From SQLAlchemy for instructions for configuring the Python connector with SQLAlchemy.

Pandas

Pandas' DataFrames can be used alongside the connector to generate analytical graphics. See From Pandas for a guide.

Schema Discovery

See Schema Discovery to query the provided system tables, which allows users to discover the available tables, views, and stored procedure, alongside additional information about their columns or parameters.

Advanced Features

Advanced Features details additional features supported by the connector, such as defining user defined views, ssl configuration, remoting, caching, firewall/proxy settings, and advanced logging.

SQL Compliance

See SQL Compliance for a syntax reference and code examples outlining the supported SQL.

Connection String Options

The Connection properties describe the various options that can be used to establish a connection.

CData Python Connector for XML

Getting Started

Connecting to XML

For information on the available WHL files for supported environments, and how to install the appropriate file for your Python distribution, see Package Installation.

For information on the module to import, and how to configure the necessary connection properties in a connection string, see Establishing a Connection.

Other available connection properties can be used to configure other aspects of the connector capabilities.

Python Version Support

The CData Python Connector for XML can be installed and used in Python 3.10 or newer.

XML Version Support

The connector models XML-based REST APIs as bidirectional database tables and XML files as views (local XML files, files stored on popular cloud services, and FTP servers). The connector abstracts connecting to remote data as well as data processing: TLS/SSL, HTTP/FTP, and authentication. The major authentication schemes are supported, including HTTP Basic, Digest, NTLM, OAuth, and FTP.

See Also

  • Using the Connector: Establish connections and query XML through Python code.
  • From SQLAlchemy: Use SQLAlchemy to establish a connection with dialect URL, and interact with XML data using mapped classes and Sessions.

CData Python Connector for XML

Viewing Remote XML Metadata

The CData Python Connector for XML is designed for streaming XML only.

This streamed file content does not include all of the metadata associated with remotely stored XML files, such as file and folder name.

If access to both the file metadata and the actual file content is needed, then the CData Python Connector for XML must be used in tandem with the associated file system driver(s) for the service the XML files are remotely stored in.

The following file system drivers are available:

  • AmazonS3
  • Box
  • Dropbox
  • FTP
  • GoogleCloudStorage
  • IBLCloudObjectStorage
  • OneDrive
  • SFTP

See the relevant CData file system driver's documentation for a configuration guide for connecting to stored XML file metadata.

CData Python Connector for XML

Package Installation

Dependencies

The Python connectors require that Python 3.10 or newer be installed.

Installation

The CData Python Connector for XML is available as a WHL file for Windows, Linux, and Mac. Each connector is built using the Python 3.10 Stable ABI (indicated by the abi3 tag in the filename), so a single wheel supports any Python 3.10 or newer installation — there is no need to match your exact Python minor version. Use the "pip install" command with the appropriate WHL file for your platform.

Windows:

pip install cdata_xml_connector-26.0.9655-cp310-abi3-win_amd64.whl

Linux:

pip install cdata_xml_connector-26.0.9655-cp310-abi3-linux_x86_64.whl

macOS:

pip install cdata_xml_connector-26.0.9655-cp310-abi3-macosx_12_0_arm64.whl

The macOS wheel supports arm64 (Apple Silicon) architectures only on macOS 12 and newer.

Regardless of the environment, certain distributions might require that the "pip3 install" command be used instead, to differentiate from a Python 2 distribution that might exist already. After installation, confirm whether the connector is successfully installed by running the "pip list" command. If "cdata_xml_connector" is present in the list output by the command, then the installation was successful.

Upgrading

When upgrading, "pip install" does not automatically clean up old JRE files. To avoid leftover files that could cause JVM errors, uninstall the previous version before installing the new one.

Licensing

After the installation is complete, a separate step is needed to activate a license for the connector. Among the CData assets in the distribution's site packages, there is an install-license tool that activates this license. From within the distribution's site-packages folder, after navigating to the "cdata/installlic_xml" folder, simply use a command like the below to activate the license. Omitting the <key> argument activates a trial license:

  • Windows:
    ./install-license.exe <key>
  • Linux / Mac:
    ./install-license.sh <key>

Sometimes, file access issues may cause pip to install the connector in a fallback file path that is not the python distribution's main or primary site-packages location. This can make it difficult to find where the connector was installed, and from there, the license activator. In that event, this python script below will print out the full file path of the connector's native file. This file will be stored in the mentioned cdata folder, from which the installlic_xml folder is trivial to find:

import os
import cdata.xml
path = os.path.abspath(cdata.xml.__file__)
print(path)

Uninstallation

If the connector needs to be uninstalled for any reason, do so by running the pip uninstall command, as in the example below:

pip uninstall cdata-xml-connector

CData Python Connector for XML

Establishing a Connection

The objects available within our connector are accessible from the "cdata.xml" module. To use the module's objects directly:

  1. Import the module as follows:
    import cdata.xml as mod
  2. To establish a connection string, call the connect() method from the connector object using an appropriate connection string, such as:
    mod.connect("DataModel=Relational;URI=C:\people.xml")

The CData Python Connector for XML allows connecting to local and remote XML resources. Set the URI property to the XML resource location, in addition to any other properties necessary to connect to your data source.

Connecting to Local Files

Set the ConnectionType to Local. Local files support SELECT\INSERT\UPDATE\DELETE queries.

Set the URI to a folder containing XML files: C:\folder1.

Connecting to Cloud-Hosted XML Files

While the connector is capable of pulling data from XML files hosted on a variety of cloud data stores, INSERT, UPDATE, and DELETE are not supported outside of local files in this connector.

If you need INSERT/UPDATE/DELETE cloud files, you can download the corresponding CData connector for that cloud host (supported via stored procedures), make changes with the local file's corresponding connector, then upload the file using the cloud source's stored procedures.

As an example, if you wanted to update a file stored on SharePoint, you could use the CData SharePoint connector's DownloadDocument procedure to download the XML file, update the local XML file with the CData XML connector, then use the SharePoint connector's UploadDocument procedure to upload the changed file to SharePoint.

A unique prefix at the beginning of the URI connection property is used to identify the cloud data store being targed by the connector and the remainder of the path is a relative path to the desired folder (one table per file) or single file (a single table).

Amazon S3

Set the following to identify your XML resources stored on Amazon S3:

See Connecting to Amazon S3 for more information regarding how to connect and authenticate to XML files hosted on Amazon S3.

Azure Blob Storage

Set the following to identify your XML resources stored on Azure Blob Storage:

  • ConnectionType: Set this to Azure Blob Storage.
  • URI: Set this to the name of your container and the name of the blob. For example: azureblob://mycontainer/myblob.

See Connecting to Azure Blob Storage for more information regarding how to connect and authenticate to XML files hosted on Amazon Blob Storage.

Azure Data Lake Storage

Set the following to identify your XML resources stored on Azure Data Lake Storage:

  • ConnectionType: Set this to Azure Data Lake Storage Gen1, Azure Data Lake Storage Gen2, or Azure Data Lake Storage Gen2 SSL.
  • URI: Set this to the name of the file system, the name of the folder which contains your XML files, and the name of an XML file. For example:
    • Gen 1: adl://myfilesystem/folder1
    • Gen 2: abfs://myfilesystem/folder1
    • Gen 2 SSL: abfss://myfilesystem/folder1

See Connecting to Azure Data Lake Storage for more information regarding how to connect and authenticate to XML files hosted on Azure Data Lake Storage.

Azure File Storage

Set the following properties to connect:

  • ConnectionType: Set this to Azure Files.
  • URI: Set this the name of your azure file share and the name of the resource. For example: azurefile://fileShare/remotePath.
  • AzureStorageAccount (Required): Set this to the account associated with the Azure file.

You can authenticate either an Azure access key or an Azure shared access signature. Set one of the following:

Box

Set the following to identify your XML resources stored on Box:

  • ConnectionType: Set this to Box.
  • URI: Set this the name of the file system, the name of the folder which contains your XML files, and the name of an XML file. For example: box://folder1.

See Connecting to Box for more information regarding how to connect and authenticate to XML files hosted on Box.

Dropbox

Set the following to identify your XML resources stored on Dropbox:

  • ConnectionType: Set this to Dropbox.
  • URI: Set this to the path to a XML file. For example: dropbox://folder1.

See Connecting to Dropbox for more information regarding how to connect and authenticate to XML files hosted on Dropbox.

FTP

The connector supports both plaintext and SSL/TLS connections to FTP servers.

Set the following connection properties to connect:

  • ConnectionType: Set this to either FTP or FTPS.
  • URI: Set this to the address of the server followed by the path to the XML file. For example: ftp://localhost:990/folder1or ftps://localhost:990/folder1.
  • User: Set this to your username on the FTP(S) server you want to connect to.
  • Password: Set this to your password on the FTP(S) server you want to connect to.

Google Cloud Storage

Set the following to identify your XML resources stored on Google Cloud Storage:

  • ConnectionType: Set this to Google Cloud Storage.
  • URI: Set this to the path to the name of the file system, the name of the folder which contains your XML files, and the name of a XML file. For example: gs://bucket/remotePath.

See Connecting to Google Cloud Storage for more information regarding how to connect and authenticate to XML files hosted on Google Cloud Storage.

Google Drive

Set the following to identify your XML resources stored on Google Drive:

  • ConnectionType: Set this to Google Drive.
  • URI: Set to the path to the name of the file system, the name of the folder which contains your XML files, and the name of an XML file. For example: gdrive://folder1.

See Connecting to Google Drive for more information regarding how to connect and authenticate to XML files hosted on Google Drive.

HDFS

Set the following to identify your XML resources stored on HDFS:

  • ConnectionType: Set this to HDFS or HDFS Secure.
  • URI: Set this to the path to a XML file. For example:
    • HDFS: webhdfs://host:port/remotePath
    • HDFS Secure: webhdfss://host:port/remotePath
    • Cloudera Ozone (via the HttpFS gateway): webhdfs://<Ozone server>:<port>/user/myuser
      • You must use Kerberos authentication to access XML files stored on Ozone.
      • Ensure that you have Ozone 718.2.x on the Ozone cluster.
      • Cloudera Manager version 7.10.1 is required.

There are two authentication methods available for connecting to HDFS data source, Anonymous Authentication and Negotiate (Kerberos) Authentication.

Anonymous Authentication

In some situations, you can connect to HDFS without any authentication connection properties. To do so, set the AuthScheme property to None (default).

Authenticate using Kerberos

When authentication credentials are required, you can use Kerberos for authentication. See Using Kerberos for details on how to authenticate with Kerberos.

HTTP Streams

Set the following to identify your XML resources stored on HTTP streams:

  • ConnectionType: Set this to HTTP or HTTPS.
  • URI: Set this to the URI of your HTTP(S) stream. For example:
    • HTTP: http://remoteStream
    • HTTPS: https://remoteStream

See Connecting to HTTP Streams for more information regarding how to connect and authenticate to XML files hosted on HTTP Streams.

IBM Cloud Object Storage

Set the following to identify your XML resources stored on IBM Cloud Object Storage:

  • ConnectionType: Set this to IBM Object Storage Source.
  • URI: Set this to the bucket and folder. For example: ibmobjectstorage://bucket1/remotePath.
  • Region: Set this property to your IBM instance region. For example: eu-gb.

See Connecting to IBM Object Storage for more information regarding how to connect and authenticate to XML files hosted on IBM Cloud Object Storage.

OneDrive

Set the following to identify your XML resources stored on OneDrive:

  • ConnectionType: Set this to OneDrive.
  • URI: Set this to the path to a XML file. For example: onedrive://remotePath.

See Connecting to OneDrive for more information regarding how to connect and authenticate to XML files hosted on OneDrive.

OneLake

Set the following to identify your XML resources stored on OneLake:

  • ConnectionType: Set this to OneLake.
  • URI: Set this to the name of the workspace, followed by the item and item type. Optionally, include the folder path to be used as the root folder. For example: onelake://Workspace/Test.LakeHouse/Files/CustomFolder.

See Connecting to OneLake for more information regarding how to connect and authenticate to XML files hosted on OneLake.

Oracle Cloud Storage

Set the following properties to authenticate with IAMSecretKey:

  • ConnectionType: Set the ConnectionType to Oracle Cloud Storage.
  • URI: Set this to an XML document in a bucket: os://bucket/remotePath.
  • AccessKey: Set this to an Oracle Cloud Access Key.
  • SecretKey: Set this to an Oracle Cloud Secret Key.
  • OracleNamespace: Set this to an Oracle cloud namespace.
  • Region (optional): Set this to the hosting region for your S3-like Web Services.

SFTP

Set the following to identify your XML resources stored on SFTP:

  • ConnectionType: Set this to SFTP.
  • URI: Set this to the address of the server followed by the path. For example: sftp://server:port/remotePath.

See Connecting to SFTP for more information regarding how to connect and authenticate to XML files hosted on SFTP.

SharePoint Online

Set the following to identify your XML resources stored on SharePoint Online:

  • ConnectionType: Set this to SharePoint GRAPH, SharePoint REST V1.
  • URI: Set this to a document library containing XML files. For example:
    • SharePoint Online REST: spgraph://remotePath
    • SharePoint Online REST V1: sprestv1://remotePath

      Use the Sharepoint URL as the remote path. Not the display name.

If your files are stored in a non-root-level SharePoint Online site (for example, under /sites/<your site>/), be sure to set the StorageBaseURL property to the full path of the SharePoint site.

  • To access files in the top-level document library:
    • URI: Set this to spgraph://Documents/ or sprestv1://Documents/
    • StorageBaseURL: Set this to https://<your domain>.sharepoint.com/sites/<your site>/
  • To access a subfolder within that site:
    • URI: Set this to spgraph://Documents/<subfolder>/ or sprestv1://Documents/<subfolder>/
    • StorageBaseURL: Set this to https://<your domain>.sharepoint.com/sites/<your site>/

Using the full SharePoint site URL ensures the connector can properly locate files stored in non-root-level locations within your organization's SharePoint Online environment.

See Connecting to SharePoint Online for more information regarding how to connect and authenticate to XML files hosted on SharePoint Online.

SharePoint On Premise

Set the following to identify your XML resources stored on SharePoint On Premise:

  • ConnectionType: Set this to SharePoint REST V1, or SharePoint SOAP.
  • URI: Set this to a document library containing XML files. For example:
    • SharePoint On Premise REST V1: sprestv1://remotePath
    • SharePoint On Premise SOAP: sp://remotePath

      Use the Sharepoint URL as the remote path. Not the display name.

See Connecting to SharePoint On Premise for more information regarding how to connect and authenticate to XML files hosted on SharePoint On Premise.

Securing XML Connections

By default, the connector attempts to negotiate SSL/TLS by checking the server's certificate against the system's trusted certificate store. To specify another certificate, see the SSLServerCert property for the available formats to do so.

CData Python Connector for XML

Configuring JNI

Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the Java virtual machine into native applications.

The connector leverages the JNI for improved performance on Mac and Linux.

Configure the Config INI File

The Linux and Mac editions of the XML python connector are configured with an ini file. This file is used to set several parameters, including JNI behavior. This file is to be located in:

{path_to_distribution_site-packages}/cdata/config.ini

Ensure that any configuration properties you set in the ini file fall under the following section name (adjust the 311 number if you are using an different python version from 3.11):

  • For Linux:
    [xml.cpython-311-x86_64-linux-gnu.so]
  • For Mac:
    [xml.cpython-311-darwin.so]

Configure the JNI connector's behavior by editing the properties in the connector's config.ini file. The connector can be configured as follows:

  • LOGFILE: Set this the same way as the CDATA_LOGFILE envrionment variable below.
  • JAVA_HOME: Configure the path to the JVM library location used to launch the JVM.
  • CLASS_PATH: Use a colon-separated list to configure the paths to the third-party jar libraries.

Configure Environment Variables

Additionally, set the following environment variables:

  • CDATA_JAVA_HOME: Configure the path to the JVM library location used to launch the JVM.
  • CDATA_JVM_OPTIONS: Place JVM options here.
  • CDATA_LOGFILE: Set this in the following scheme: <SCHEME>://<TAG>[|<LEVEL>]

    • SCHEME: The options are STDOUT, FILE.
      • STDOUT: Both the native wrapper and odbc core log into stdout. The Logfile and Verbosity properties can override the behavior of ODBC core.
      • FILE: The native wrapper logs into <FILENAME> while the odbc core logs into <FILENAME>.driver.log. The Logfile and Verbosity properties can override the behavior of ODBC core.
    • TAG
      • For STDOUT, set this to 1. For FILE, set this to the filename.
    • LEVEL
      • Set to one of: FATAL | ERROR | WARNING | INFO | DEBUG

The following are some examples of this syntax:

  • STDOUT://1|DEBUG
  • FILE:///tmp/my_py.log|DEBUG

Custom Logger

The Python connector supports a custom logging mechanism for redirecting log output to any destination, such as a cloud storage service or logging framework. Use setCustomLoggerFactory() to register a factory function that creates a logger instance for each connection.

The factory function receives the context string from the Logfile connection property (the portion after CUSTOM://) and must return an object with a writeLog(verbosity, message) method.

To enable custom logging:

  1. Call setCustomLoggerFactory() with your factory function before opening connections.
  2. Set Logfile to CUSTOM:// followed by a context string to identify the connection.
  3. Set Verbosity to the desired log level.

The following example demonstrates a custom logger factory that creates a separate logger instance per connection:

import cdata.xml as mod
import time

class MyLogger:
    def __init__(self, loggerId):
        self.loggerId = loggerId
    def writeLog(self, verbosity, message):
        print("[MyLogger " + self.loggerId + "] " + message)

def createLogger(context):
    return MyLogger(context[len("MyLoggerId="):])

mod.setCustomLoggerFactory(createLogger)

conn1 = mod.connect("...;Logfile=CUSTOM://MyLoggerId=1;Verbosity=2;")
# do something with conn1
time.sleep(1)  # Wait for logs to flush from conn1

conn2 = mod.connect("...;Logfile=CUSTOM://MyLoggerId=2;Verbosity=2;")
# do something with conn2
time.sleep(1)  # Wait for logs to flush from conn2

CData Python Connector for XML

Connecting to XML Data Sources

After connecting to your data source, set DataModel to more closely match the data representation to the structure of your data.

Connecting to XML

Below are example connection strings to XML files or streams, using the connector's default data modeling configuration (see below)

Service provider URI formats Connection example
Local Single File Path (One table)
file://localPath/file.xml
URI=C:/folder1/file.xml;
Directory Path (One aggregated table from all files)
file://localPath/
URI=C:/folder1/;
HTTP or HTTPS http://remoteStream
https://remoteStream
URI=http://www.host1.com/streamname1;
Amazon S3 Single File Path (One table)
s3://remotePath/file.xml
URI=s3://bucket1/folder1/file.xml;AWSSecretKey=secret1;AWSRegion=OHIO;
Directory Path (One aggregated table from all files)
s3://remotePath/
URI=s3://bucket1/folder1/;AWSSecretKey=secret1;AWSRegion=OHIO;
Azure Blob Storage Single File Path (One table)
azureblob://mycontainer/myblob/file.xml
URI=azureblob://mycontainer/myblob/file.xml;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=azureblob://mycontainer/myblob/file.xml;AzureStorageAccount=myAccount;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Directory Path (One aggregated table from all files)
azureblob://mycontainer/myblob/
URI=azureblob://mycontainer/myblob/;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=azureblob://mycontainer/myblob/;AzureStorageAccount=myAccount;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Google Drive Single File Path (One table)
gdrive://remotePath/file.xml
gdrive://SharedWithMe/remotePath/file.xml
URI=gdrive://folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
URI=gdrive://SharedWithMe/folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Directory Path (One aggregated table from all files)
gdrive://remotePath/
gdrive://SharedWithMe/remotePath/
URI=gdrive://folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
URI=gdrive://SharedWithMe/folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
One Drive Single File Path (One table)
onedrive://remotePath/file.xml
onedrive://SharedWithMe/remotePath/file.xml
URI=onedrive://folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
URI=onedrive://SharedWithMe/folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Directory Path (One aggregated table from all files)
onedrive://remotePath/
onedrive://SharedWithMe/remotePath/
URI=onedrive://folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
URI=onedrive://SharedWithMe/folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Box Single File Path (One table)
box://remotePath/file.xml
URI=box://folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Directory Path (One aggregated table from all files)
box://remotePath/
URI=box://folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;
Dropbox Single File Path (One table)
dropbox://remotePath/file.xml
URI=dropbox://folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;OAuthClientId=oauthclientid1;OAuthClientSecret=oauthcliensecret1;CallbackUrl=http://localhost:12345;
Directory Path (One aggregated table from all files)
dropbox://remotePath/
URI=dropbox://folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;OAuthClientId=oauthclientid1;OAuthClientSecret=oauthcliensecret1;CallbackUrl=http://localhost:12345;
SharePoint SOAP Single File Path (One table)
sp://remotePath/file.xml
URI=sp://Shared Documents/folder1/file.xml;User=user1;Password=password1;StorageBaseURL=https://subdomain.sharepoint.com;
Directory Path (One aggregated table from all files)
sp://remotePath/
URI=sp://Shared Documents/folder1/;User=user1;Password=password1;StorageBaseURL=https://subdomain.sharepoint.com;
SharePoint REST V1 Single File Path (One table)
sprestv1://remotePath/file.xml
URI=sprestv1://Shared Documents/folder1/file.xml;User=user1;Password=password1;AuthScheme=NTLM;StorageBaseURL=http://sharepointserver/sites/mysite;
URI=sprestv1://Shared Documents/folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=AzureAD;StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;
Directory Path (One aggregated table from all files)
sprestv1://remotePath/
URI=sprestv1://Shared Documents/folder1/;User=user1;Password=password1;AuthScheme=NTLM;StorageBaseURL=http://sharepointserver/sites/mysite;
URI=sprestv1://Shared Documents/folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=AzureAD;StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;
SharePoint GRAPH Single File Path (One table)
spgraph://remotePath/file.xml
URI=spgraph://Shared Documents/folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;StorageBaseURL=https://subdomain.sharepoint.com;
Directory Path (One aggregated table from all files)
spgraph://remotePath/
URI=spgraph://Shared Documents/folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;StorageBaseURL=https://subdomain.sharepoint.com;
FTP or FTPS Single File Path (One table)
ftp://server:port/remotePath/file.xml
ftps://server:port/remotepath/file.xml
URI=ftps://localhost:990/folder1/file.xml;User=user1;Password=password1;
Directory Path (One aggregated table from all files)
ftp://server:port/remotePath/
ftps://server:port/remotepath/;
URI=ftps://localhost:990/folder1/;User=user1;Password=password1;
SFTP Single File Path (One table)
sftp://server:port/remotePath/file.xml
URI=sftp://127.0.0.1:22/folder1/file.xml;User=user1;Password=password1;
URI=sftp://127.0.0.1:22/folder1/file.xml;SSHAuthmode=PublicKey;SSHClientCert=myPrivateKey
Directory Path (One aggregated table from all files)
sftp://server:port/remotePath/
URI=sftp://127.0.0.1:22/folder1/;User=user1;Password=password1;
URI=sftp://127.0.0.1:22/folder1/;SSHAuthmode=PublicKey;SSHClientCert=myPrivateKey
Azure Data Lake Store Gen1 Single File Path (One table)
adl://remotePath/file.xml
adl://Account.azuredatalakestore.net@remotePath/file.xml
URI=adl://folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;AzureStorageAccount=myAccount;AzureTenant=tenant;
URI=adl://myAccount.azuredatalakestore.net@folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;AzureTenant=tenant;
Directory Path (One aggregated table from all files)
adl://remotePath/
adl://Account.azuredatalakestore.net@remotePath/
URI=adl://folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;AzureStorageAccount=myAccount;AzureTenant=tenant;
URI=adl://myAccount.azuredatalakestore.net@folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;AzureTenant=tenant;
Azure Data Lake Store Gen2 Single File Path (One table)
abfs://myfilesystem/remotePath/file.xml
abfs://myfilesystem@accountName.dfs.core.windows.net/remotepath/file.xml
URI=abfs://myfilesystem/folder1/file.xml;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=abfs://myfilesystem@myAccount.dfs.core.windows.net/folder1/file.xml;AzureAccessKey=myKey;
Directory Path (One aggregated table from all files)
abfs://myfilesystem/remotePath/
abfs://myfilesystem@accountName.dfs.core.windows.net/remotepath/
URI=abfs://myfilesystem/folder1/;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=abfs://myfilesystem@myAccount.dfs.core.windows.net/folder1/;AzureAccessKey=myKey;
Azure Data Lake Store Gen2 with SSL Single File Path (One table)
abfss://myfilesystem/remotePath/file.xml
abfss://myfilesystem@accountName.dfs.core.windows.net/remotepath/file.xml
URI=abfss://myfilesystem/folder1/file.xml;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=abfss://myfilesystem@myAccount.dfs.core.windows.net/folder1/file.xml;AzureAccessKey=myKey;
Directory Path (One aggregated table from all files)
abfss://myfilesystem/remotePath/
abfss://myfilesystem@accountName.dfs.core.windows.net/remotepath/
URI=abfss://myfilesystem/folder1/;AzureStorageAccount=myAccount;AzureAccessKey=myKey;
URI=abfss://myfilesystem@myAccount.dfs.core.windows.net/folder1/;AzureAccessKey=myKey;
Wasabi Single File Path (One table)
wasabi://bucket1/remotePath/file.xml
URI=wasabi://bucket/folder1/file.xml;AccessKey=token1;SecretKey=secret1;Region='us-west-1';
Directory Path (One aggregated table from all files)
wasabi://bucket1/remotePath/
URI=wasabi://bucket/folder1/;AccessKey=token1;SecretKey=secret1;Region='us-west-1';
Google Cloud Storage Single File Path (One table)
gs://bucket/remotePath/file.xml
URI=gs://bucket/folder1/file.xml;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;ProjectId=test;
Directory Path (One aggregated table from all files)
gs://bucket/remotePath/
URI=gs://bucket/folder1/;InitiateOAuth=GETANDREFRESH;AuthScheme=OAuth;ProjectId=test;
Oracle Cloud Storage Single File Path (One table)
os://bucket/remotePath/file.xml
URI=os://bucket/folder1/file.xml;AccessKey='myKey';SecretKey='mySecretKey';OracleNameSpace='myNameSpace' Region='us-west-1';
Directory Path (One aggregated table from all files)
os://bucket/remotePath/
URI=os://bucket/folder1/;AccessKey='myKey';SecretKey='mySecretKey';OracleNameSpace='myNameSpace' Region='us-west-1';
Azure File Single File Path (One table)
azurefile://fileShare/remotePath/file.xml
URI=azurefile://bucket/folder1/file.xml;AzureStorageAccount='myAccount';AzureAccessKey='mySecretKey';
URI=azurefile://bucket/folder1/file.xml;AzureStorageAccount='myAccount';AzureSharedAccessSignature='mySharedAccessSignature';
Directory Path (One aggregated table from all files)
azurefile://fileShare/remotePath/
URI=azurefile://bucket/folder1/;AzureStorageAccount='myAccount';AzureAccessKey='mySecretKey';
URI=azurefile://bucket/folder1/;AzureStorageAccount='myAccount';AzureSharedAccessSignature='mySharedAccessSignature';
IBM Object Storage Source Single File Path (One table)
ibmobjectstorage://bucket1/remotePath/file.xml
URI=ibmobjectstorage://bucket/folder1/file.xml;AuthScheme='IAMSecretKey';AccessKey=token1;SecretKey=secret1;Region='eu-gb';
URI=ibmobjectstorage://bucket/folder1/file.xml;ApiKey=key1;Region='eu-gb';AuthScheme=OAuth;InitiateOAuth=GETANDREFRESH;
Directory Path (One aggregated table from all files)
ibmobjectstorage://bucket1/remotePath/
URI=ibmobjectstorage://bucket/folder1/;AuthScheme='IAMSecretKey';AccessKey=token1;SecretKey=secret1;Region='eu-gb';
URI=ibmobjectstorage://bucket/folder1/;ApiKey=key1;Region='eu-gb';AuthScheme=OAuth;InitiateOAuth=GETANDREFRESH;
Hadoop Distributed File System Single File Path (One table)
webhdfs://host:port/remotePath/file.xml
URI=webhdfs://host:port/folder1/file.xml
Directory Path (One aggregated table from all files)
webhdfs://host:port/remotePath/
URI=webhdfs://host:port/folder1/
Secure Hadoop Distributed File System Single File Path (One table)
webhdfss://host:port/remotePath/file.xml
URI=webhdfss://host:port/folder1/file.xml
Directory Path (One aggregated table from all files)
webhdfss://host:port/remotePath/
URI=webhdfss://host:port/folder1/

Modeling XML Data

The DataModel property controls how your data is represented into tables.

  • Document (default): Model a top-level, document view of your XML data. The connector returns nested object arrays as aggregated XML objects.
  • FlattenedDocuments: Implicitly join nested array objects and parent objects into a single table.
  • Relational: View nested object arrays as individual, related tables containing a primary key and a foreign key that links to the parent document.

Next Steps

  • See Parsing Hierarchical Data for examples showing how to query a dataset in each DataModel configuration.
  • See Modeling XML Data for information on customizing schema discovery and how to execute SQL to XML.
  • See Fine-Tuning Data Access for more advanced connection settings: fine-tune the default data modeling settings, connect through a firewall, or troubleshoot connections.

CData Python Connector for XML

Connecting to Amazon S3

Before You Connect

Obtain AWS Keys

To obtain the credentials for an IAM user:

  1. Sign into the IAM console.
  2. In the navigation pane, select Users.
  3. To create or manage the access keys for a user, select the user and then navigate to the Security Credentials tab.

To obtain the credentials for your AWS root account:

  1. Sign into the AWS Management console with the credentials for your root account.
  2. Select your account name or number.
  3. In the menu that displays, select My Security Credentials.
  4. To manage or create root account access keys, click Continue to Security Credentials and expand the "Access Keys" section.

Connecting to Amazon S3

Specify the following to connect to data:

  • AWSRegion: Set this to the region where your XML data is hosted.
  • StorageBaseURL (optional): Specify the base S3 service URL only if it has a different URL from "amazonaws.com". Make sure to specify the full URL. For example: http://127.0.0.1:9000.

Authenticating to Amazon S3

There are several authentication methods available for connecting to XML including:

  • Root Credentials
  • AWS Role, as an AWS Role (from an EC2 Instance or by specifying the root credentials)
  • SSO (ADFS, Okta, PingFederate)
  • Temporary Credentials
  • Credentials File
  • EKS Pod Identity

Root Credentials

To authenticate using account root credentials, set these parameters:

Note: Amazon discourages using root credentials for anything beyond simple testing. The account root credentials have the full permissions of the user, posing a security risk and making this the least secure authentication method.

If multi-factor authentication is required, specify the following:

  • CredentialsLocation: The location of the settings file where MFA credentials are saved.
  • MFASerialNumber: The serial number of the MFA device if one is being used.
  • MFAToken: The temporary token available from your MFA device.
This causes the connector to submit the MFA credentials in the request to retrieve temporary authentication credentials.

Note: If you want to control the duration of the temporary credentials, set the TemporaryTokenDuration property (default: 3600 seconds).

Using AWS From an EC2 Instance

Set AuthScheme to AwsEC2Roles.

If you are using the connector from an EC2 Instance and have an IAM Role assigned to the instance, you can use the IAM Role to authenticate. Since the connector automatically obtains your IAM Role credentials and authenticates with them, it is not necessary to specify AWSAccessKey and AWSSecretKey.

If you are also using an IAM role to authenticate, you must additionally specify the following:

  • AWSRoleARN: Specify the Role ARN for the role you'd like to authenticate with. This causes the connector to attempt to retrieve credentials for the specified role.
  • AWSExternalId (optional): Only required if you are assuming a role in another AWS account.

IMDSv2 Support

The XML connector now supports IMDSv2. Unlike IMDSv1, the new version requires an authentication token. Endpoints and response are the same in both versions.

In IMDSv2, the XML connector first attempts to retrieve the IMDSv2 metadata token and then uses it to call AWS metadata endpoints. If it is unable to retrieve the token, the connector reverts to IMDSv1.

AWS Web Identity

Set AuthScheme to AwsWebIdentity.

If you are either using XML from a container configured to assume role with web identity (such as a Pod in an EKS cluster with an OpenID Provider) or have authenticated with a web identity provider associated with an IAM role (and have thus obtained an identity token), you can exchange the web identity token and IAM role information for temporary security credentials to authenticate and access AWS services.

If the container has AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE specified in the environment variables, XML automatically obtains the credentials.

You can also authenticate by specifying both AWSRoleARN and AWSWebIdentityToken to execute the AssumeRoleWithWebIdentity API operation.

AWS IAM Roles

To authenticate through AWS, set AuthScheme to AwsIAMRoles.

To authenticate as an AWS role, set these properties:

  • AWSAccessKey: The access key of the IAM user to assume the role for.
  • AWSSecretKey: The secret key of the IAM user to assume the role for.
  • AWSRoleARN: Specify the Role ARN for the role you'd like to authenticate with. This will cause the connector to attempt to retrieve credentials for the specified role.
  • AWSExternalId (optional): Only required if you are assuming a role in another AWS account.

If multi-factor authentication is required, specify the following:

  • CredentialsLocation: The location of the settings file where MFA credentials are saved.
  • MFASerialNumber: The serial number of the MFA device if one is being used.
  • MFAToken: The temporary token available from your MFA device.
This causes the connector to submit the MFA credentials in the request to retrieve temporary authentication credentials.

Note: If you want to control the duration of the temporary credentials, set the TemporaryTokenDuration property (default: 3600 seconds).

Note: In some circumstances it might be preferable to use an IAM role for authentication, rather than the direct security credentials of an AWS root user. If you are specifying the AWSAccessKey and AWSSecretKey of an AWS root user, you cannot use roles.

ADFS

To connect to ADFS, set these properties:

To authenticate to ADFS, set these SSOProperties:

  • RelyingParty: The value of the ADFS server's Relying Party Identifier.

Example connection string:

AuthScheme=ADFS;User=username;Password=password;SSOLoginURL='https://sts.company.com';SSOProperties='RelyingParty=https://saml.salesforce.com';

ADFS Integrated

The ADFS Integrated flow indicates you are connecting with the user credentials of the currently logged in Windows user. To use the ADFS Integrated flow, do not specify the User and Password, but otherwise follow the same steps noted above under ADFS.

Okta

To connect to Okta, set these properties:

If you are either using a trusted application or proxy that overrides the Okta client request OR configuring MFA, you must use combinations of SSOProperties to authenticate using Okta. Set any of the following, as applicable:

  • APIToken: When authenticating a user via a trusted application or proxy that overrides the Okta client request context, set this to the API Token the customer created from the Okta organization.
  • MFAType: If you have configured the MFA flow, set this to one of the following supported types: OktaVerify, Email, or SMS.
  • MFAPassCode: If you have configured the MFA flow, set this to a valid passcode.
    If you set this to empty or an invalid value, the connector issues a one-time password challenge to your device or email. After the passcode is received, reopen the connection where the retrieved one-time password value is set to the MFAPassCode connection property.
  • MFARememberDevice: True by default. Okta supports remembering devices when MFA is required. If remembering devices is allowed according to the configured authentication policies, the connector sends a device token to extend MFA authentication lifetime. If you do not want MFA to be remembered, set this variable to False.

Example connection string:

AuthScheme=Okta;SSOLoginURL='https://example.okta.com/home/appType/0bg4ivz6cJRZgCz5d6/46';User=oktaUserName;Password=oktaPassword;

PingFederate

To connect to PingFederate, set these properties:

  • AuthScheme: PingFederate.
  • User: The authenticating PingFederate user.
  • Password: The authenticating user's PingFederate password.
  • SSOLoginURL: The SSO provider's login URL.
  • AWSRoleARN (optional): If you have multiple role ARNs, specify the one you want to use for authorization.
  • AWSPrincipalARN (optional): If you have multiple principal ARNs, specify the one you want to use for authorization.
  • SSOExchangeURL: The Partner Service Identifier URI configured in your PingFederate server instance under: SP Connections > SP Connection > WS-Trust > Protocol Settings. This should uniquely identify a PingFederate SP Connection, so it is a good idea to set it to your AWS SSO ACS URL. You can find it under AWS SSO > Settings > View Details next to the Authentication field.
  • SSOProperties (optional): If you want to include your username and password as an authorization header in requests to Amazon S3, set this to Authscheme=Basic.

To enable mutual SSL authentication for SSOLoginURL, the WS-Trust STS endpoint, configure these SSOProperties:

Example connection string:

authScheme=pingfederate;SSOLoginURL=https://mycustomserver.com:9033/idp/sts.wst;SSOExchangeUrl=https://us-east-1.signin.aws.amazon.com/platform/saml/acs/764ef411-xxxxxx;user=admin;password=PassValue;AWSPrincipalARN=arn:aws:iam::215338515180:saml-provider/pingFederate;AWSRoleArn=arn:aws:iam::215338515180:role/SSOTest2;

Temporary Credentials

To authenticate using temporary credentials, specify the following:

The connector can now request resources using the same permissions provided by long-term credentials (such as IAM user credentials) for the lifespan of the temporary credentials.

To authenticate using both temporary credentials and an IAM role, set all the parameters described above, and specify these additional parameters:

  • AWSRoleARN: The Role ARN for the role you'd like to authenticate with. This prompts the connector to retrieve credentials for the specified role.
  • AWSExternalId (optional): Only required if you are assuming a role in another AWS account.

If multi-factor authentication is required, specify the following:

  • CredentialsLocation: The location of the settings file where MFA credentials are saved.
  • MFASerialNumber: The serial number of the MFA device if one is being used.
  • MFAToken: The temporary token available from your MFA device.
This causes the connector to submit the MFA credentials in the request to retrieve temporary authentication credentials.

Note: If you want to control the duration of the temporary credentials, set the TemporaryTokenDuration property (default: 3600 seconds).

Credentials Files

You can use any credentials file to authenticate, including any configurations related to AccessKey/SecretKey authentication, temporary credentials, role authentication, or MFA.

To do this, set these properties:

For further information, see AWS Command Line Interface User Guide.

EKS Pod Identity

Set AuthScheme to EKSPodIdentity.

If you are running XML from a Pod in an Amazon EKS cluster configured with EKS Pod Identity, the connector automatically retrieves temporary credentials from the EKS Pod Identity Agent running on the node.

The EKS Pod Identity Agent sets the AWS_CONTAINER_CREDENTIALS_FULL_URI and AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variables in the Pod. The connector reads these environment variables to obtain credentials.

If the environment variables are not available, you can specify the values manually using AWSContainerCredentialsFullURI and AWSContainerAuthorizationTokenFile.

Azure AD

This configuration requires two separate Azure AD applications:

  • The "XML" application used for single sign-on, and
  • A custom OAuth application with user_impersonation permission on the "XML" application. (See Creating a Custom OAuth App.)

To connect to Azure AD, set the AuthScheme to AzureAD, and set these properties:

  • OAuthClientId: The application Id of the connector application, listed in the Overview section of the app registration.
  • OAuthClientSecret: The client secret value of the connector application. Azure AD displays this when you create a new client secret.
  • CallbackURL: The redirect URI of the connector application. For example: https://localhost:33333.
  • InitiateOAuth: Set this to GETANDREFRESH.

To authenticate to Azure AD, set these SSOProperties:

  • Resource: The application Id URI of the XML application, listed in the app registration's Overview section. In most cases this is the URL of your custom XML domain.
  • AzureTenant: The Id of the Azure AD tenant where the applications are registered.

Example connection string:

AuthScheme=AzureAD;InitiateOAuth=GETANDREFRESH;OAuthClientId=3ea1c786-d527-4399-8c3b-2e3696ae4b48;OauthClientSecret=xxx;CallbackUrl=https://localhost:33333;SSOProperties='Resource=https://signin.aws.amazon.com/saml;AzureTenant=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';

CData Python Connector for XML

Connecting to Azure Blob Storage

Before You Connect

To obtain the credentials for an AzureBlob user, follow the steps below:

  1. Sign into the Azure portal with the credentials for your root account.
  2. Click on Storage Accounts and select the storage account you want to use.
  3. Under Settings, click Access keys.
  4. Your storage account name and key will be displayed on that page.

Connecting to Azure Blob Storage

Set AzureStorageAccount to your Azure Blob Storage account name.

Authenticating to Azure Blob Storage

You can authenticate to Azure Blob Storage via Access Key, Shared Access Signatures (SAS), AzureAD user, Azure MSI, or Azure Service Principal.

Access Key

Set the following to authenticate with an Azure Access Key:

  • AuthScheme: Set this to AccessKey.
  • AzureAccessKey: Set this to the storage key associated with your Azure Blob Storage account.

Shared Access Signature (SAS)

Set the following to authenticate with an Shared Access Signature (SAS): Follow these steps to create a shared access signature using AzureSharedAccessSignature:

  1. Sign into the Azure Portal with the credentials for your root account. (https://portal.azure.com/)
  2. Click storage accounts and select the storage account you want to use.
  3. Under settings, click Shared Access Signature.
  4. Set the permissions.
  5. Specify when you want the token to expire.
  6. Click Generate SAS and copy the shared access signature it generates.
  7. Set AzureSharedAccessSignature to the shared access signature from the previous step.

AzureAD User

AuthScheme must be set to AzureAD in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Creating a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens the Microsoft identity platform's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from the Microsoft identity platform and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Azure Active Directory. You can then use the connector to get and manage the OAuth token values. See Creating a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI.

There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.

Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Azure Service Principal

The authentication as an Azure Service Principal is handled via the OAuth Client Credentials flow. It does not involve direct user authentication. Instead, credentials are created for just the application itself. All tasks taken by the application are done without a default user context, but based on the assigned roles. The application access to the resources is controlled through the assigned roles' permissions.

Create an AzureAD App and an Azure Service Principal

When authenticating using an Azure Service Principal, you must create and register an Azure AD application with an Azure AD tenant. See Creating an Entra ID (Azure AD) Application for more details.

In your App Registration in portal.azure.com, navigate to API Permissions and select the Microsoft Graph permissions. There are two distinct sets of permissions: Delegated permissions and Application permissions. The permissions used during client credential authentication are under Application Permissions.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.
Complete the Authentication Choose whether to use a client secret or a certificate and follow the relevant steps below.

Client Secret

Set these connection properties:

Certificate

Set these connection properties:

You are now ready to connect. Authentication with client credentials takes place automatically like any other connection, except there is no window opened prompting the user. Because there is no user context, there is no need for a browser popup. Connections take place and are handled internally.

Azure MSI

If you are connecting from an Azure VM with permissions for Azure Data Lake Storage, set AuthScheme to AzureMSI.

CData Python Connector for XML

Creating a Custom OAuth App

There are two types of custom AzureAD applications: AzureAD and AzureAD with an Azure Service Principal. Both are OAuth-based.

When to Create a Custom Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via either a Desktop Application or from a Headless Machine.

You may choose to use your own AzureAD Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Custom AzureAD Applications

You can use a custom AzureAD application to authenticate a service account or a user account. You can always create a custom AzureAD application, but note that desktop and headless connections support embedded OAuth, which simplifies the process of authentication. See "Establishing a Connection" for information about using the embedded OAuth application.

Create a Custom AzureAD App

Follow the steps below to obtain the AzureAD values for your application, the OAuthClientId and OAuthClientSecret.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an application name and select the desired tenant setup. When creating a custom AzureAD application in Azure Active Directory, you can define whether the application is single- or multi-tenant. If you select the default option, "Accounts in this organizational directory only", you must set the AzureTenant connection property to the Id of the Azure AD Tenant when establishing a connection with the CData Python Connector for XML. Otherwise, the authentication attempt fails with an error. If your application is for private use only, "Accounts in this organization directory only" should be sufficient. Otherwise, if you want to distribute your application, choose one of the multi-tenant options.
  5. Set the redirect url to http://localhost:33333, the connector's default. Or, specify a different port and set CallbackURL to the exact reply URL you defined.
  6. Click Register to register the new application. This opens an application management screen. Note the value in Application (client) ID as the OAuthClientId and the Directory (tenant) ID as the AzureTenant.
  7. Navigate to the "Certificates & Secrets" and define the application authentication type. There are two types of authentication available: using a client secret or a certificate. The recommended authentication method is using a certificate.
    • Option 1: Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2: Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will need it as the OAuthClientSecret.
  8. Select API Permissions > Add. If your application connects without a user context, select Application Permissions. If your application authenticates on behalf of a signed-in user, choose Delegated permissions.
  9. Save your changes.
  10. If you have selected to use permissions that require admin consent (such as the Application Permissions), you can grant them from the current tenant on the API Permissions page. Otherwise, follow the steps under "Admin Consent".

Custom AzureAD Service Principal Applications

When authenticating using an Azure Service Principal, you must create both a custom AzureAD application and a service principal that can access the necessary resources. Follow the steps below to create a custom AzureAD application and obtain the connection properties for Azure Service Principal authentication.

Create a Custom AzureAD App with an Azure Service Principal

Follow the steps below to obtain the AzureAD values for your application.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an app name and select Any Azure AD Directory - Multi Tenant. Then set the redirect url to http://localhost:33333, the connector's default.
  5. After creating the application, copy the Application (client) Id value displayed in the "Overview" section. This value is used as the OAuthClientId
  6. Define the app authentication type by going to the "Certificates & Secrets" section. There are two types of authentication available: using a client secret and using a certificate. The recommended authentication method is via a certificate.
    • Option 1 - Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2 - Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will use it as the OAuthClientSecret.
  7. On the Authentication tab, make sure to select Access tokens (used for implicit flows).

CData Python Connector for XML

Connecting to Azure Data Lake Storage

Connecting to Azure Data Lake Storage

Set AzureStorageAccount to your Azure Data Lake Storage account name.

Authenticating to Azure Data Lake Storage

You can authenticate to Azure Data Lake Storage via Access Key, Shared Access Signature (SAS), AzureAD user, Azure MSI, or Azure Service Principal.

Access Key

Set the following to authenticate with an Azure Access Key:

  • AuthScheme: Set this to AccessKey.
  • AzureAccessKey: Set this to the storage key associated with your Azure Data Lake Storage account.

Shared Access Signature (SAS)

Set the following to authenticate with an Shared Access Signature (SAS): Follow these steps to create a shared access signature using AzureSharedAccessSignature:

  1. Sign into the Azure Portal with the credentials for your root account. (https://portal.azure.com/)
  2. Click storage accounts and select the storage account you want to use.
  3. Under settings, click Shared Access Signature.
  4. Set the permissions.
  5. Specify when you want the token to expire.
  6. Click Generate SAS and copy the shared access signature it generates.
  7. Set AzureSharedAccessSignature to the shared access signature from the previous step.

AzureAD User

AuthScheme must be set to AzureAD in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Creating a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens the Microsoft identity platform's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from the Microsoft identity platform and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Azure Active Directory. You can then use the connector to get and manage the OAuth token values. See Creating a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI.

There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.

Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Azure Service Principal

The authentication as an Azure Service Principal is handled via the OAuth Client Credentials flow. It does not involve direct user authentication. Instead, credentials are created for just the application itself. All tasks taken by the application are done without a default user context, but based on the assigned roles. The application access to the resources is controlled through the assigned roles' permissions.

Create an AzureAD App and an Azure Service Principal

When authenticating using an Azure Service Principal, you must create and register an Azure AD application with an Azure AD tenant. See Creating an Entra ID (Azure AD) Application for more details.

In your App Registration in portal.azure.com, navigate to API Permissions and select the Microsoft Graph permissions. There are two distinct sets of permissions: Delegated permissions and Application permissions. The permissions used during client credential authentication are under Application Permissions.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.
Complete the Authentication Choose whether to use a client secret or a certificate and follow the relevant steps below.

Client Secret

Set these connection properties:

Certificate

Set these connection properties:

You are now ready to connect. Authentication with client credentials takes place automatically like any other connection, except there is no window opened prompting the user. Because there is no user context, there is no need for a browser popup. Connections take place and are handled internally.

Azure MSI

If you are connecting from an Azure VM with permissions for Azure Data Lake Storage, set AuthScheme to AzureMSI.

CData Python Connector for XML

Creating a Custom OAuth App

There are two types of custom AzureAD applications: AzureAD and AzureAD with an Azure Service Principal. Both are OAuth-based.

When to Create a Custom Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via either a Desktop Application or from a Headless Machine.

You may choose to use your own AzureAD Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Custom AzureAD Applications

You can use a custom AzureAD application to authenticate a service account or a user account. You can always create a custom AzureAD application, but note that desktop and headless connections support embedded OAuth, which simplifies the process of authentication. See "Establishing a Connection" for information about using the embedded OAuth application.

Create a Custom AzureAD App

Follow the steps below to obtain the AzureAD values for your application, the OAuthClientId and OAuthClientSecret.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an application name and select the desired tenant setup. When creating a custom AzureAD application in Azure Active Directory, you can define whether the application is single- or multi-tenant. If you select the default option, "Accounts in this organizational directory only", you must set the AzureTenant connection property to the Id of the Azure AD Tenant when establishing a connection with the CData Python Connector for XML. Otherwise, the authentication attempt fails with an error. If your application is for private use only, "Accounts in this organization directory only" should be sufficient. Otherwise, if you want to distribute your application, choose one of the multi-tenant options.
  5. Set the redirect url to http://localhost:33333, the connector's default. Or, specify a different port and set CallbackURL to the exact reply URL you defined.
  6. Click Register to register the new application. This opens an application management screen. Note the value in Application (client) ID as the OAuthClientId and the Directory (tenant) ID as the AzureTenant.
  7. Navigate to the "Certificates & Secrets" and define the application authentication type. There are two types of authentication available: using a client secret or a certificate. The recommended authentication method is using a certificate.
    • Option 1: Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2: Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will need it as the OAuthClientSecret.
  8. Select API Permissions > Add. If your application connects without a user context, select Application Permissions. If your application authenticates on behalf of a signed-in user, choose Delegated permissions.
  9. Save your changes.
  10. If you have selected to use permissions that require admin consent (such as the Application Permissions), you can grant them from the current tenant on the API Permissions page. Otherwise, follow the steps under "Admin Consent".

Custom AzureAD Service Principal Applications

When authenticating using an Azure Service Principal, you must create both a custom AzureAD application and a service principal that can access the necessary resources. Follow the steps below to create a custom AzureAD application and obtain the connection properties for Azure Service Principal authentication.

Create a Custom AzureAD App with an Azure Service Principal

Follow the steps below to obtain the AzureAD values for your application.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an app name and select Any Azure AD Directory - Multi Tenant. Then set the redirect url to http://localhost:33333, the connector's default.
  5. After creating the application, copy the Application (client) Id value displayed in the "Overview" section. This value is used as the OAuthClientId
  6. Define the app authentication type by going to the "Certificates & Secrets" section. There are two types of authentication available: using a client secret and using a certificate. The recommended authentication method is via a certificate.
    • Option 1 - Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2 - Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will use it as the OAuthClientSecret.
  7. On the Authentication tab, make sure to select Access tokens (used for implicit flows).

CData Python Connector for XML

Connecting to Box

Connecting to Box

Use the OAuth authentication standard to connect to Box. You can authenticate with a user account or with a service account. A service account is required to grant organization-wide access scopes to the connector. The connector facilitates these authentication flows as described below.

User Accounts (OAuth)

AuthScheme must be set to OAuth in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Create a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens Box's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from Box and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Box. You can then use the connector to get and manage the OAuth token values. See Create a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.
Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Authenticate with a Service Account

Set the AuthScheme to OAuthJWT to authenticate with this method.

Service accounts have silent authentication, without user authentication in the browser. You can also use a service account to delegate enterprise-wide access scopes to the connector.

You need to create an OAuth application in this flow. See Create a Custom OAuth App to create and authorize an app. You can then connect to Box data that the service account has permission to access.

After setting the following connection properties, you are ready to connect:

  • InitiateOAuth: Set to GETANDREFRESH.
  • OAuthClientId: Set to the Client Id in your app settings.
  • OAuthClientSecret: Set to the Client Secret in your app settings.
  • OAuthJWTCertType: Set to "PEMKEY_FILE".
  • OAuthJWTCert: Set to the path to the .pem file you generated.
  • OAuthJWTCertPassword: Set to the password of the .pem file.
  • OAuthJWTCertSubject: Set to "*" to pick the first certificate in the certificate store.
  • OAuthJWTSubjectType: Set to "enterprise" or "user" depending on the Application Access Value you selected in your app settings. The default value of this connection property is "enterprise".
  • OAuthJWTSubject: Set to your enterprise Id if your subject type is set to "enterprise" or your app user Id if your subject type is set to "user".
  • OAuthJWTPublicKeyId: Set to the Id of your public key in your app settings.
When you connect the connector completes the OAuth flow for a service account.
  1. Creates and signs the JWT with the claim set required by the connector.
  2. Exchanges the JWT for the access token.
  3. Saves OAuth values in OAuthSettingsLocation to be persisted across connections.
  4. Submits the JWT for a new access token when the token expires.

CData Python Connector for XML

Create a Custom OAuth App

Creating a Custom OAuth Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via a desktop application or headless application.

You may choose to use your own OAuth Application Credentials when you want to:

  • control branding of the authentication dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Procedure

This procedure creates a custom OAuth application, registers that application, and generates values that are used to configure the OAuthClientId and OAuthClientSecret.

At the Box Enterprise Developer Console:

  1. Log in to your Box developers dashboard.
  2. Click Create New App.
  3. Specify basic application information, as appropriate.
  4. Specify your application type (e.g., Custom App).
  5. Select the User Authentication (OAuth 2.0) authentication method.
  6. Set the Redirect URI:
    • If this is a desktop application or headless machine application, set the Redirect URI to http://localhost:33333 or a different port number.
    • If this is a web application, set the Redirect URI to https://<yourwebappserver>:<port>.
  7. Click Create App.
  8. The next task is to create a public and private key pair.
    • To create a keypair from the Developer Console:
      1. Navigate to the Developer Console Configuration tab.
      2. Scroll down to Add and Manage Public Keys.
      3. Click Generate a Public/Private Keypair. Box creates a keypair in a JSON file, and downloads that file to your desktop. You can then move that file to your application code.

        Note: Box does not back up private keys for security reasons. Be careful to back up the Public/Private JSON file. If you lose your private key, you must reset the entire keypair.

    • To add a keypair manually:
      1. Open a terminal window and run the following OpenSSL commands:
        openssl genrsa -des3 -out private.pem 2048
        openssl rsa -in private.pem -outform PEM -pubout -out public.pem

        Note: To run OpenSSL in a Windows environment, install the Cygwin package.

      2. At the Developer Console, navigate to the configuration tab for the Custom OAuth application you just created.
      3. Scroll down to Add and Manage Public Keys.
      4. Click Add a Public Key.
      5. Click Verify and Save.
  9. Before the custom application can be used, a Box Admin must authorize it within the Box Admin Console.
    1. Navigate to your application within the Developer Console.
    2. Click the Authorization tab.
    3. At the prompt to Submit app for authorization for access to the Enterprise, click Review and Submit.
      Your Box Enterprise Admin approves the application.
  10. Finally, select the scope of user permissions your custom OAuth application must request.

After your application is created and registered, click Configuration from the main menu to access your settings. Note the displayed Redirect URI, Client ID, and Client Secret. You will need these values later.

When JWT Access Scopes Change

If you change the JWT access scopes, you must reauthorize the application in the enterprise admin console:

  1. Click Apps in the main manu.
  2. Select the ellipsis button next to your JWT application name.
  3. Select Reauthorize App in the menu.

CData Python Connector for XML

Connecting to Dropbox

Connecting to Dropbox

Dropbox uses the OAuth authentication standard.

Dropbox OAuth Scopes

You need to choose between using CData's embedded OAuth app or Create a Custom OAuth App.

The embedded app includes the following scopes:

  • account_info.read
  • file_requests.read
  • files.content.read
  • files.content.write
  • files.metadata.read
  • sharing.read
  • sharing.write

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Create a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens Dropbox's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from Dropbox and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Dropbox. You can then use the connector to get and manage the OAuth token values. See Create a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

  • OAuthClientId: Set this to the noted App key value from your OAuth app settings.
  • OAuthClientSecret: Set this to the App secret from your OAuth app settings.

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

  • OAuthClientId: Set this to the noted App key value from your OAuth app settings.
  • OAuthClientSecret: Set this to the App secret from your OAuth app settings.

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.
Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the noted App key value from your OAuth app settings.
  • OAuthClientSecret: (custom applications only) Set this to the App secret from your OAuth app settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the noted App key value from your OAuth app settings.
  • OAuthClientSecret: (custom applications only) Set this to the App secret from your OAuth app settings.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the noted App key value from your OAuth app settings.
  • OAuthClientSecret: (custom applications only) Set this to the App secret from your OAuth app settings.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

CData Python Connector for XML

Create a Custom OAuth App

When To Create a Custom OAuth Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via a desktop application or headless application.

You may choose to use your own OAuth Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Create a Custom OAuth App

  1. Log in to your Dropbox developers dashboard and click Create New App. Select the Dropbox API type. Select the Full Dropbox access for your app.
  2. After creating your app, you can view Configuration from the main menu that displays your app settings.
  3. On the app Settings tab, note the values of App key and App secret for later connector configuration.
  4. Set the Redirect URI and store the specified value for later connector configuration.
    • When setting up a desktop app or headless app, set the Redirect URI to http://localhost:33333 or a different port number.
    • When setting up a web app, set the Redirect URI to https://<yourwebappserver>:<port>.
  5. On the app Permissions tab, select the scope of user permissions your app will request.

No further values need to be specified in the XML app settings.

CData Python Connector for XML

Connecting to Google Cloud Storage

Connecting to Google Cloud Storage

Set the ProjectId property to the Id of the project you want to connect to.

Authenticating to Google Cloud Storage

The connector supports using user accounts, service accounts and GCP instance accounts for authentication.

The following sections discuss the available authentication schemes for Google Cloud Storage:

  • User Accounts (OAuth)
  • Service Account (OAuthJWT)
  • GCP Instance Account

User Accounts (OAuth)

AuthScheme must be set to OAuth in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Create a Custom OAuth App for information about creating custom applications and reasons for doing so.

For authentication, the only difference between the two methods is that you must set two additional connection properties when using custom OAuth applications.

After setting the following connection properties, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH, which instructs the connector to automatically attempt to get and refresh the OAuth access token.
  • OAuthClientId: (custom applications only) Set this to the Client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the Client Secret in the custom OAuth application settings.
When you connect the connector opens the OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process as follows:

  • Extracts the access token from the callback URL.
  • Obtains a new access token when the old one expires.
  • Saves OAuth values in OAuthSettingsLocation that persist across connections.

Web Applications

When connecting via a Web application, you need to create and register a custom OAuth application with Google Cloud Storage. You can then use the connector to acquire and manage the OAuth token values. See Create a Custom OAuth App for more information about custom applications.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Callback URL you specified in your application settings. The stored procedure returns the URL to the OAuth endpoint.
  2. Navigate to the URL that the stored procedure returned in Step 1. Log in to the custom OAuth application and authorize the web application. Once authenticated, the browser redirects you to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set AuthMode to WEB and the Verifier input to the "code" parameter in the query string of the callback URL.

Once you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the driver automatically refresh the OAuth access token, set the following on the first data connection:

On subsequent data connections, the values for OAuthAccessToken and OAuthRefreshToken are taken from OAuthSettingsLocation.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token.

Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

  • OAuthClientId: Set this to the Client Id in your application settings.
  • OAuthClientSecret: Set this to the Client Secret in your application settings.

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application click Google Cloud Storage OAuth endpoint to open the endpoint in your browser.
    • If you are using a custom OAuth application, create the Authorization URL by setting the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the callback URL, which contains the verifier code.
  3. Save the value of the verifier code. Later you will set this in the OAuthVerifier connection property.
Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens. Set the following properties:

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the verifier code.
  • OAuthClientId: (custom applications only) Set this to the Client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the Client Secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

After the OAuth settings file is generated, you need to re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to create and install a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Once you have successfully tested the connection, copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of your OAuth settings file. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Service Accounts (OAuthJWT)

To authenticate using a service account, you must create a new service account and have a copy of the accounts certificate. If you do not already have a service account, you can create one by following the procedure in Create a Custom OAuth App.

For a JSON file, set these properties:

  • AuthScheme: Set this to OAuthJWT.
  • InitiateOAuth: Set this to GETANDREFRESH.
  • OAuthJWTCertType: Set this to GOOGLEJSON.
  • OAuthJWTCert: Set this to the path to the .json file provided by Google.
  • OAuthJWTSubject: (optional) Only set this value if the service account is part of a GSuite domain and you want to enable delegation. The value of this property should be the email address of the user whose data you want to access.

For a PFX file, set these properties instead:

  • AuthScheme: Set this to OAuthJWT.
  • InitiateOAuth: Set this to GETANDREFRESH.
  • OAuthJWTCertType: Set this to PFXFILE.
  • OAuthJWTCert: Set this to the path to the .pfx file provided by Google.
  • OAuthJWTCertPassword: (optional) Set this to the .pfx file password. In most cases you must provide this since Google encrypts PFX certificates.
  • OAuthJWTCertSubject: (optional) Set this only if you are using a OAuthJWTCertType which stores multiple certificates. Should not be set for PFX certificates generated by Google.
  • OAuthJWTIssuer: Set this to the email address of the service account. This address will usually include the domain iam.gserviceaccount.com.
  • OAuthJWTSubject: (optional) Only set this value if the service account is part of a GSuite domain and you want to enable delegation. The value of this property should be the email address of the user whose data you want to access.

GCP Instance Accounts

When running on a GCP virtual machine, the connector can authenticate using a service account tied to the virtual machine. To use this mode, set AuthScheme to GCPInstanceAccount.

CData Python Connector for XML

Create a Custom OAuth App

Creating a Custom OAuth Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting to XML via a desktop application or a headless machine.

(For information on getting and setting the OAuthAccessToken and other configuration parameters, see the Desktop Authentication section of "Connecting to XML".)

However, you must create a custom OAuth application to connect to XML via the Web. And since custom OAuth applications seamlessly support all three commonly-used auth flows, you might want to create custom OAuth applications (use your own OAuth Application Credentials) for those auth flows anyway.

Custom OAuth applications are useful if you want to:

  • control branding of the authentication dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

The following sections describe how to enable the Directory API and create custom OAuth applications for user accounts (OAuth) and Service Accounts (OAuth/JWT).

Enable the Cloud Storage API

Follow these steps to enable the Cloud Storage API:

  1. Navigate to the Google Cloud Console.
  2. Select Library from the left-hand navigation menu. This opens the Library page.
  3. In the search field, enter "Cloud Storage API" and select Cloud Storage API from the search results.
  4. On the Cloud Storage API page, click ENABLE.

Create an OAuth Application

To create custom OAuth applications that retrieve the necessary OAuth connection properties, follow these procedures.

User Accounts (OAuth)

For users whose AuthScheme is OAuth and who need to authenticate over a web application, you must always create a custom OAuth application. (For desktop and headless flows, creating a custom OAuth application is optional.)

Do the following:

  1. Navigate to the Google Cloud Console.
  2. Create a new project or select an existing project.
  3. At the left-hand navigation menu, select Credentials.
  4. If this project does not already have a consent screen configured, click CONFIGURE CONSENT SCREEN to create one. If you are not using a Google Workspace account, you are restricted to creating an External-type Consent Screen, which requires specifying a support email and developer contact email. Additional info is optional.
  5. On the Credentials page, select Create Credentials > OAuth Client ID.
  6. In the Application Type menu, select Web application.
  7. Specify a name for your custom OAuth application.
  8. Under Authorized redirect URIs, click ADD URI and enter a redirect URI.
  9. Click Enter, then CREATE. The Cloud Console returns you to the Credentials page.
    A window opens that displays your client Id and client secret.
  10. Record the client Id and Client Secret for later use as the OAuthClientId and OAuthClientSecret connection properties.

Note: The client secret remains accessible from from the Google Cloud Console.

Service Accounts (OAuthJWT)

Service accounts (AuthScheme OAuthJWT) can be used in an OAuth flow to access Google APIs on behalf of users in a domain. A domain administrator can delegate domain-wide access to the service account.

To create a new service account:

  1. Navigate to the Google Cloud Console.
  2. Create a new project or select an existing project.
  3. At the left-hand navigation menu, select Credentials.
  4. Select Create Credentials > Service account.
  5. On the Create service account page, enter the service account name, ID, and an optional description.
  6. Click DONE. The Cloud Console redisplays the Credentials page.
  7. In the Service Accounts section, select the service account you just created.
  8. Click the Advanced Settings section and enable Domain-Wide Delegation.
  9. Record the Client ID shown for domain-wide delegation. You'll use this in the Admin Console.
  10. In a new tab, navigate to the Google Admin Console.
  11. Go to Security > API Controls > Domain-Wide Delegation.
  12. Click Manage Domain-Wide Delegation, then Add new.
  13. Enter the recorded Client ID and the list of required scopes. See OAuth Scopes and Endpoints for more details.
  14. Back in the Cloud Console, select the KEYS tab for the service account.
  15. Click ADD KEY > Create new key.
  16. Select a supported key type (see OAuthJWTCert and OAuthJWTCertType).
  17. Click CREATE. The key is automatically downloaded to your device.
  18. Record the additional information for later use.

In the service account flow, the connector exchanges a JSON Web Token (JWT) for the OAuthAccessToken. The private key downloaded in the steps above is used to sign the JWT. The connector inherits the permissions granted to the service account, including any scopes configured through domain-wide delegation.

CData Python Connector for XML

Connecting to Google Drive

Authenticating to Google Drive

The connector supports using user accounts, service accounts and GCP instance accounts for authentication.

The following sections discuss the available authentication schemes for Google Drive:

  • User Accounts (OAuth)
  • Service Account (OAuthJWT)
  • GCP Instance Account

User Accounts (OAuth)

AuthScheme must be set to OAuth in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Create a Custom OAuth App for information about creating custom applications and reasons for doing so.

For authentication, the only difference between the two methods is that you must set two additional connection properties when using custom OAuth applications.

After setting the following connection properties, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH, which instructs the connector to automatically attempt to get and refresh the OAuth access token.
  • OAuthClientId: (custom applications only) Set this to the Client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the Client Secret in the custom OAuth application settings.
When you connect the connector opens the OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process as follows:

  • Extracts the access token from the callback URL.
  • Obtains a new access token when the old one expires.
  • Saves OAuth values in OAuthSettingsLocation that persist across connections.

Web Applications

When connecting via a Web application, you need to create and register a custom OAuth application with Google Drive. You can then use the connector to acquire and manage the OAuth token values. See Create a Custom OAuth App for more information about custom applications.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Callback URL you specified in your application settings. The stored procedure returns the URL to the OAuth endpoint.
  2. Navigate to the URL that the stored procedure returned in Step 1. Log in to the custom OAuth application and authorize the web application. Once authenticated, the browser redirects you to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set AuthMode to WEB and the Verifier input to the "code" parameter in the query string of the callback URL.

Once you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the driver automatically refresh the OAuth access token, set the following on the first data connection:

On subsequent data connections, the values for OAuthAccessToken and OAuthRefreshToken are taken from OAuthSettingsLocation.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token.

Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

  • OAuthClientId: Set this to the Client Id in your application settings.
  • OAuthClientSecret: Set this to the Client Secret in your application settings.

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an Internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an Internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an Internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, create the Authorization URL by setting the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the callback URL, which contains the verifier code.
  3. Save the value of the verifier code. Later you will set this in the OAuthVerifier connection property.
Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens. Set the following properties:

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the verifier code.
  • OAuthClientId: (custom applications only) Set this to the Client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the Client Secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

After the OAuth settings file is generated, you need to re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to create and install a connection with the driver on a device that supports an Internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Once you have successfully tested the connection, copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of your OAuth settings file. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Service Accounts (OAuthJWT)

To authenticate using a service account, you must create a new service account and have a copy of the accounts certificate. If you do not already have a service account, you can create one by following the procedure in Create a Custom OAuth App.

For a JSON file, set these properties:

  • AuthScheme: Set this to OAuthJWT.
  • InitiateOAuth: Set this to GETANDREFRESH.
  • OAuthJWTCertType: Set this to GOOGLEJSON.
  • OAuthJWTCert: Set this to the path to the .json file provided by Google.
  • OAuthJWTSubject: (optional) Only set this value if the service account is part of a GSuite domain and you want to enable delegation. The value of this property should be the email address of the user whose data you want to access.

For a PFX file, set these properties instead:

  • AuthScheme: Set this to OAuthJWT.
  • InitiateOAuth: Set this to GETANDREFRESH.
  • OAuthJWTCertType: Set this to PFXFILE.
  • OAuthJWTCert: Set this to the path to the .pfx file provided by Google.
  • OAuthJWTCertPassword: (optional) Set this to the .pfx file password. In most cases you must provide this since Google encrypts PFX certificates.
  • OAuthJWTCertSubject: (optional) Set this only if you are using a OAuthJWTCertType which stores multiple certificates. Should not be set for PFX certificates generated by Google.
  • OAuthJWTIssuer: Set this to the email address of the service account. This address will usually include the domain iam.gserviceaccount.com.
  • OAuthJWTSubject: (optional) Only set this value if the service account is part of a GSuite domain and you want to enable delegation. The value of this property should be the email address of the user whose data you want to access.

GCP Instance Accounts

When running on a GCP virtual machine, the connector can authenticate using a service account tied to the virtual machine. To use this mode, set AuthScheme to GCPInstanceAccount.

CData Python Connector for XML

Create a Custom OAuth App

Creating a Custom OAuth Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting to XML via a desktop application or a headless machine.

(For information on getting and setting the OAuthAccessToken and other configuration parameters, see the Desktop Authentication section of "Connecting to XML".)

However, you must create a custom OAuth application to connect to XML via the Web. And since custom OAuth applications seamlessly support all three commonly-used auth flows, you might want to create custom OAuth applications (use your own OAuth Application Credentials) for those auth flows anyway.

Custom OAuth applications are useful if you want to:

  • control branding of the authentication dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

The following sections describe how to enable the Directory API and create custom OAuth applications for user accounts (OAuth) and Service Accounts (OAuth/JWT).

Enable the Google Drive API

Follow these steps to enable the Google Drive API:

  1. Navigate to the Google Cloud Console.
  2. Select Library from the left-hand navigation menu. This opens the Library page.
  3. In the search field, enter "Google Drive API" and select Google Drive API from the search results.
  4. On the Google Drive API page, click ENABLE.

Create an OAuth Application

To create custom OAuth applications that retrieve the necessary OAuth connection properties, follow these procedures.

User Accounts (OAuth)

For users whose AuthScheme is OAuth and who need to authenticate over a web application, you must always create a custom OAuth application. (For desktop and headless flows, creating a custom OAuth application is optional.)

Do the following:

  1. Navigate to the Google Cloud Console.
  2. Create a new project or select an existing project.
  3. At the left-hand navigation menu, select Credentials.
  4. If this project does not already have a consent screen configured, click CONFIGURE CONSENT SCREEN to create one. If you are not using a Google Workspace account, you are restricted to creating an External-type Consent Screen, which requires specifying a support email and developer contact email. Additional info is optional.
  5. On the Credentials page, select Create Credentials > OAuth Client ID.
  6. In the Application Type menu, select Web application.
  7. Specify a name for your custom OAuth application.
  8. Under Authorized redirect URIs, click ADD URI and enter a redirect URI.
  9. Click Enter, then CREATE. The Cloud Console returns you to the Credentials page.
    A window opens that displays your client Id and client secret.
  10. Record the client Id and Client Secret for later use as the OAuthClientId and OAuthClientSecret connection properties.

Note: The client secret remains accessible from from the Google Cloud Console.

Service Accounts (OAuthJWT)

Service accounts (AuthScheme OAuthJWT) can be used in an OAuth flow to access Google APIs on behalf of users in a domain. A domain administrator can delegate domain-wide access to the service account.

To create a new service account:

  1. Navigate to the Google Cloud Console.
  2. Create a new project or select an existing project.
  3. At the left-hand navigation menu, select Credentials.
  4. Select Create Credentials > Service account.
  5. On the Create service account page, enter the service account name, ID, and an optional description.
  6. Click DONE. The Cloud Console redisplays the Credentials page.
  7. In the Service Accounts section, select the service account you just created.
  8. Click the Advanced Settings section and enable Domain-Wide Delegation.
  9. Record the Client ID shown for domain-wide delegation. You'll use this in the Admin Console.
  10. In a new tab, navigate to the Google Admin Console.
  11. Go to Security > API Controls > Domain-Wide Delegation.
  12. Click Manage Domain-Wide Delegation, then Add new.
  13. Enter the recorded Client ID and the list of required scopes. See OAuth Scopes and Endpoints for more details.
  14. Back in the Cloud Console, select the KEYS tab for the service account.
  15. Click ADD KEY > Create new key.
  16. Select a supported key type (see OAuthJWTCert and OAuthJWTCertType).
  17. Click CREATE. The key is automatically downloaded to your device.
  18. Record the additional information for later use.

In the service account flow, the connector exchanges a JSON Web Token (JWT) for the OAuthAccessToken. The private key downloaded in the steps above is used to sign the JWT. The connector inherits the permissions granted to the service account, including any scopes configured through domain-wide delegation.

CData Python Connector for XML

Connecting to HTTP Streams

Authenticating to HTTP(S)

The connector generically supports connecting to XML data stored on HTTP(S) streams.

Several authentication methods, such as user/password, digest access, OAuth, OAuthJWT, and OAuth PASSWORD flow are supported.

You can also connect to streams that have no authentication set up.

No Authentication

Connect to an HTTP(S) stream with no authentication by setting the AuthScheme connection property to None.

Basic

Set the following to connect:

  • AuthScheme: Set this to Basic.
  • User: Set this to the username associated with your HTTP(S) stream.
  • Password: Set this to the password associated with your HTTP(S) stream.

Digest

Set the following to connect:

  • AuthScheme: Set this to Digest.
  • User: Set this to the username associated with your HTTP(S) stream.
  • Password: Set this to the password associated with your HTTP(S) stream.

OAuth

Set the AuthScheme to OAuth.

OAuth requires the authenticating user to interact with XML using the browser. The connector facilitates this in various ways as described in the following sections.

Before following the procedures below, you need to register an OAuth app with the service containing the XML data you want to work with.

Creating a custom application in most services requires registering as a developer and creating an app in the UI of the service.

This is not necessarily true for all services. In some you must contact the service provider to create the app for you. However it is done, you must obtain the values for OAuthClientId, OAuthClientSecret, and CallbackURL.

Desktop Applications

After setting the following connection properties, you are ready to connect:

  • OAuthVersion: Set this to the OAuth Version, either 1.0 or 2.0.
  • OAuthRequestTokenURL: Required for OAuth 1.0. In OAuth 1.0, this is the URL where the app makes a request for the request token.
  • OAuthAuthorizationURL: Required for OAuth 1.0 and 2.0. This is the URL where the user logs into the service and grants permissions to the application. In OAuth 1.0, if permissions are granted, the request token is authorized.
  • OAuthAccessTokenURL: Required for OAuth 1.0 and 2.0. This is the URL where the request for the access token is made. In OAuth 1.0, the authorized request token is exchanged for the access token.
  • OAuthRefreshTokenURL: Required for OAuth 2.0. In OAuth 2.0, this is the URL where the refresh token is exchanged for a new access token when the old one expires. Note that for your data source this may be the same as the access token URL.
  • OAuthClientId: Set this to the client Id in your app settings. This may also be called the consumer key.
  • OAuthClientSecret: Set this to the client secret in your app settings. This may also be called the consumer secret.
  • CallbackURL: Set this to http://localhost:33333. If you specified a redirect URL in your app settings, this must match.
  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the access token in the connection string.
When you connect, the connector opens the OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. Extracts the access token from the callback URL and authenticates requests.
  2. Refreshes the access token when it expires.
  3. Saves OAuth values in OAuthSettingsLocation to be persisted across connections.

Web Application

When connecting via a Web application, or if the connector is not authorized to open a browser window, use the provided stored procedures to get and manage the OAuth token values.

Set Up the OAuth Flow

Provide the OAuth URLs to authenticate in the Web flow.

  • OAuthRequestTokenURL: Required for OAuth 1.0. In OAuth 1.0, this is the URL where the app makes a request for the request token.
  • OAuthAuthorizationURL: Required for OAuth 1.0 and 2.0. This is the URL where the user logs into the service and grants permissions to the application. In OAuth 1.0, if permissions are granted, the request token is authorized.
  • OAuthAccessTokenURL: Required for OAuth 1.0 and 2.0. This is the URL where the request for the access token is made. In OAuth 1.0, the authorized request token is exchanged for the access token.
  • OAuthRefreshTokenURL: Required for OAuth 2.0. In OAuth 2.0, this is the URL where the refresh token is exchanged for a new access token when the old one expires. Note that for your data source this may be the same as the access token URL.
Get an Access Token

In addition to the OAuth URLs, set the following additional connection properties to obtain the OAuthAccessToken:

  • OAuthClientId: Set this to the client Id in your app settings. This may also be called the consumer key.
  • OAuthClientSecret: Set this to the client secret in your app settings. This may also be called the consumer secret.
  • OAuthVersion: Set this to the OAuth version, either 1.0 or 2.0.

You can then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the AuthMode input to WEB and set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.
  2. Log in and authorize the application. You are redirected back to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB.

    In OAuth 1.0, set the Verifier input to the "oauth_verifier" parameter. Extract the verifier code from the callback URL. Additionally, set the AuthToken and AuthSecret to the values returned by GetOAuthAccessToken.

    In OAuth 2.0, set the Verifier input to the "code" parameter in the query string of the callback URL.

Connect to Data and Refresh the Token

The OAuthAccessToken returned by GetOAuthAccessToken has a limited lifetime. To automatically refresh the token, set the following on the first data connection. Alternatively, use the RefreshOAuthAccessToken stored procedure to manually refresh the token.

OAuth Endpoints

OAuth Tokens and Keys

Initiate OAuth

  • OAuthVersion: Set this to 1.0 or 2.0.
  • InitiateOAuth: Set this to REFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthSettingsLocation: Set this to the location where the connector will save the OAuth values, to be persisted across connections.

On subsequent data connections, set the following:

OAuth JWT

Set AuthScheme to OAuthJWT.

The connector supports using JWT as an authorization grant in situations where a user cannot perform an interactive sign-on. After setting the following connection properties, you are ready to connect:

  • OAuthVersion: Set this to 2.0.
  • OAuthAccessTokenURL: Set this to the URL where the JWT is exchanged for an access token.
  • OAuthJWTCert: Set this to the certificate you want to use. In most cases this will be a path to a PEM or PFX file.
  • OAuthJWTCertType: Set this to the correct certificate type. In most cases this will either PEMKEY_FILE or PFXFILE.
  • OAuthJWTCertPassword: If the certificate is encrypted, set this to the encryption password.
  • OAuthJWTIssuer: Set this to the issuer. This corresponds to the iss field in the JWT.
  • InitiateOAuth: Set this to GETANDREFRESH.

Note that the JWT signature algorithm cannot be set directly. The connector only supports the RS256 algorithm.

The connector will then construct a JWT including the following fields, and submit it to OAuthAccessTokenURL for an access token.

OAuthPassword

AuthScheme: Set this to OAuthPassword.

OAuth requires the authenticating user to interact with XML using the browser. The connector facilitates this in various ways as described in the following sections.

Before following the procedures below, you need to register an OAuth app with the service containing the XML data you want to work with.

Creating a custom application in most services requires registering as a developer and creating an app in the UI of the service.

This is not necessarily true for all services. In some you must contact the service provider to create the app for you. However it is done, you must obtain the values for OAuthClientId, OAuthClientSecret, and CallbackURL.

After setting the following connection properties, you are ready to connect:

  • OAuthVersion: Set this to the OAuth Version, either 1.0 or 2.0.
  • OAuthRequestTokenURL: Required for OAuth 1.0. In OAuth 1.0, this is the URL where the app makes a request for the request token.
  • OAuthAuthorizationURL: Required for OAuth 1.0 and 2.0. This is the URL where the user logs into the service and grants permissions to the application. In OAuth 1.0, if permissions are granted, the request token is authorized.
  • OAuthAccessTokenURL: Required for OAuth 1.0 and 2.0. This is the URL where the request for the access token is made. In OAuth 1.0, the authorized request token is exchanged for the access token.
  • OAuthRefreshTokenURL: Required for OAuth 2.0. In OAuth 2.0, this is the URL where the refresh token is exchanged for a new access token when the old one expires. Note that for your data source this may be the same as the access token URL.
  • OAuthClientId: Set this to the client Id in your app settings. This may also be called the consumer key.
  • OAuthClientSecret: Set this to the client secret in your app settings. This may also be called the consumer secret.
  • CallbackURL: Set this to http://localhost:33333. If you specified a redirect URL in your app settings, this must match.
  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the access token in the connection string.
When you connect, the connector opens the OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. Extracts the access token from the callback URL and authenticates requests.
  2. Refreshes the access token when it expires.
  3. Saves OAuth values in OAuthSettingsLocation to be persisted across connections.

CData Python Connector for XML

Connecting to IBM Object Storage

Before You Connect

Register a New Instance of Cloud Object Storage

If you do not already have Cloud Object Storage in your IBM Cloud account, you can follow the procedure below to install an instance of SQL Query in your account:

  1. Log in to your IBM Cloud account.
  2. Navigate to the Cloud Object Storage page, choose a name for your instance and click Create. You will be redirected to the instance of Cloud Object Storage you just created.

API Key

To connect with IBM Cloud Object Storage, you will need an ApiKey. You can obtain this as follows:

  1. Log in to your IBM Cloud account.
  2. Navigate to the Platform API Keys page.
  3. On the middle-right corner click Create an IBM Cloud API Key to create a new API Key.
  4. In the pop-up window, specify the API Key name and click Create. Note the ApiKey as you can never access it again from the dashboard.

Connecting to IBM Cloud Object Storage

Set Region to to your IBM instance region.

Authenticating to IBM Cloud Object Storage

You can authenticate to IBM Cloud Object Storage using either IAMSecretKey, or OAuth authentication.

IAMSecretKey

Set the following properties to authenticate:

  • AccessKey: Set this to an IBM Access Key (a username).
  • SecretKey: Set this to an IBM Secret Key.
For example:
ConnectionType=IBM Object Storage Source;URI=ibmobjectstorage://bucket1/folder1; AccessKey=token1; SecretKey=secret1; Region=eu-gb;

OAuth

Set the following to authenticate using OAuth authentication.

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • AuthScheme: Set this to OAuth.
  • ApiKey: Set this to the IBM API Key noted during setup.
For example:
ConnectionType=IBM Object Storage Source;URI=ibmobjectstorage://bucket1/folder1; ApiKey=key1; Region=eu-gb; AuthScheme=OAuth; InitiateOAuth=GETANDREFRESH;

When you connect, the connector completes the OAuth process.

  1. Extracts the access token and authenticates requests.
  2. Saves OAuth values in OAuthSettingsLocation to be persisted across connections.

CData Python Connector for XML

Connecting to OneDrive

Connecting to OneDrive

You can connect to OneDrive using an AzureAD user, with MSI authentication, or using an Azure Service Principal.

AzureAD Users

AuthScheme must be set to AzureAD in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Creating a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens the Microsoft identity platform's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from the Microsoft identity platform and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Azure Active Directory. You can then use the connector to get and manage the OAuth token values. See Creating a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI.

There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.

Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Azure Service Principal

The authentication as an Azure Service Principal is handled via the OAuth Client Credentials flow. It does not involve direct user authentication. Instead, credentials are created for just the application itself. All tasks taken by the application are done without a default user context, but based on the assigned roles. The application access to the resources is controlled through the assigned roles' permissions.

Create an AzureAD App and an Azure Service Principal

When authenticating using an Azure Service Principal, you must create and register an Azure AD application with an Azure AD tenant. See Creating an Entra ID (Azure AD) Application for more details.

In your App Registration in portal.azure.com, navigate to API Permissions and select the Microsoft Graph permissions. There are two distinct sets of permissions: Delegated permissions and Application permissions. The permissions used during client credential authentication are under Application Permissions.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.
Complete the Authentication Choose whether to use a client secret or a certificate and follow the relevant steps below.

Client Secret

Set these connection properties:

Certificate

Set these connection properties:

You are now ready to connect. Authentication with client credentials takes place automatically like any other connection, except there is no window opened prompting the user. Because there is no user context, there is no need for a browser popup. Connections take place and are handled internally.

Azure MSI

If you are connecting from an Azure VM with permissions for Azure Data Lake Storage, set AuthScheme to AzureMSI.

CData Python Connector for XML

Creating a Custom OAuth App

There are two types of custom AzureAD applications: AzureAD and AzureAD with an Azure Service Principal. Both are OAuth-based.

When to Create a Custom Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via either a Desktop Application or from a Headless Machine.

You may choose to use your own AzureAD Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Custom AzureAD Applications

You can use a custom AzureAD application to authenticate a service account or a user account. You can always create a custom AzureAD application, but note that desktop and headless connections support embedded OAuth, which simplifies the process of authentication. See "Establishing a Connection" for information about using the embedded OAuth application.

Create a Custom AzureAD App

Follow the steps below to obtain the AzureAD values for your application, the OAuthClientId and OAuthClientSecret.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an application name and select the desired tenant setup. When creating a custom AzureAD application in Azure Active Directory, you can define whether the application is single- or multi-tenant. If you select the default option, "Accounts in this organizational directory only", you must set the AzureTenant connection property to the Id of the Azure AD Tenant when establishing a connection with the CData Python Connector for XML. Otherwise, the authentication attempt fails with an error. If your application is for private use only, "Accounts in this organization directory only" should be sufficient. Otherwise, if you want to distribute your application, choose one of the multi-tenant options.
  5. Set the redirect url to http://localhost:33333, the connector's default. Or, specify a different port and set CallbackURL to the exact reply URL you defined.
  6. Click Register to register the new application. This opens an application management screen. Note the value in Application (client) ID as the OAuthClientId and the Directory (tenant) ID as the AzureTenant.
  7. Navigate to the "Certificates & Secrets" and define the application authentication type. There are two types of authentication available: using a client secret or a certificate. The recommended authentication method is using a certificate.
    • Option 1: Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2: Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will need it as the OAuthClientSecret.
  8. Select API Permissions > Add. If your application connects without a user context, select Application Permissions. If your application authenticates on behalf of a signed-in user, choose Delegated permissions.
  9. Save your changes.
  10. If you have selected to use permissions that require admin consent (such as the Application Permissions), you can grant them from the current tenant on the API Permissions page. Otherwise, follow the steps under "Admin Consent".

Custom AzureAD Service Principal Applications

When authenticating using an Azure Service Principal, you must create both a custom AzureAD application and a service principal that can access the necessary resources. Follow the steps below to create a custom AzureAD application and obtain the connection properties for Azure Service Principal authentication.

Create a Custom AzureAD App with an Azure Service Principal

Follow the steps below to obtain the AzureAD values for your application.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an app name and select Any Azure AD Directory - Multi Tenant. Then set the redirect url to http://localhost:33333, the connector's default.
  5. After creating the application, copy the Application (client) Id value displayed in the "Overview" section. This value is used as the OAuthClientId
  6. Define the app authentication type by going to the "Certificates & Secrets" section. There are two types of authentication available: using a client secret and using a certificate. The recommended authentication method is via a certificate.
    • Option 1 - Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2 - Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will use it as the OAuthClientSecret.
  7. On the Authentication tab, make sure to select Access tokens (used for implicit flows).

CData Python Connector for XML

Connecting to OneLake

Authenticating to OneLake

You can authenticate to OneLake via AzureAD user, Azure MSI, or Azure Service Principal.

AzureAD User

AuthScheme must be set to AzureAD in all user account flows.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Creating a Custom OAuth App for information about creating custom applications and reasons for doing so.

Get and Refresh the OAuth Access Token

After setting the following, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId (custom applications only): Set this to the client Id assigned when you registered your app.
  • OAuthClientSecret (custom applications only): Set this to the client secret assigned when you registered your app.
  • CallbackURL (custom application only): Set this to the redirect URI defined when you registered your app. For example: http://localhost:33333
When you connect, the connector opens the Microsoft identity platform's OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:
  1. The connector obtains an access token from the Microsoft identity platform and uses it to request data.
  2. The OAuth values are saved in the location specified in OAuthSettingsLocation, to be persisted across connections.
The connector refreshes the access token automatically when it expires.

Web Applications

When connecting via a Web application, you need to register a custom OAuth app with Azure Active Directory. You can then use the connector to get and manage the OAuth token values. See Creating a Custom OAuth App for more information.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the Redirect URI you specified in your app settings. The stored procedure returns the URL to the OAuth endpoint.

  2. Navigate to the URL that the stored procedure returned in Step 1. Log in, and authorize the web application. After authenticating, the browser redirects you to the redirect URI. There will be a parameter called code appended to the redirect URI. Note the value of this parameter.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the code parameter in the query string of the redirect URI.

After you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the connector automatically refresh the OAuth access token, set the following on the first data connection.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token. Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver, use OAuth with a user account on a headless machine. You need to authenticate on another device that has an internet browser.

  1. Choose one of two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on a machine with an internet browser and transfer the OAuth authentication values after you authenticate through the usual browser-based flow.
  2. Then configure the connector to automatically refresh the access token on the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:
    • If you are using the Embedded OAuth Application, call the GetOAuthAuthorizationURL stored procedure. Open the URL returned by the stored procedure in a browser.
    • If you are using a custom OAuth application, set the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.
  2. Log in and grant permissions to the connector. You are then redirected to the redirect URI.

There will be a parameter called code appended to the redirect URI. Note the value of this parameter. Later you will set this in the OAuthVerifier connection property.

Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens.

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the noted verifier code (the value of the code parameter in the redirect URI).
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to persist the encrypted OAuth authentication values to the specified location.

Test the connection to generate the OAuth settings file, then re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to install and create a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Test the connection to generate the OAuth settings file, then copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of the OAuth settings file you copied from the machine with the browser. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Azure Service Principal

The authentication as an Azure Service Principal is handled via the OAuth Client Credentials flow. It does not involve direct user authentication. Instead, credentials are created for just the application itself. All tasks taken by the application are done without a default user context, but based on the assigned roles. The application access to the resources is controlled through the assigned roles' permissions.

Create an AzureAD App and an Azure Service Principal

When authenticating using an Azure Service Principal, you must create and register an Azure AD application with an Azure AD tenant. See Creating an Entra ID (Azure AD) Application for more details.

In your App Registration in portal.azure.com, navigate to API Permissions and select the Microsoft Graph permissions. There are two distinct sets of permissions: Delegated permissions and Application permissions. The permissions used during client credential authentication are under Application Permissions.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.
Complete the Authentication Choose whether to use a client secret or a certificate and follow the relevant steps below.

Client Secret

Set these connection properties:

Certificate

Set these connection properties:

You are now ready to connect. Authentication with client credentials takes place automatically like any other connection, except there is no window opened prompting the user. Because there is no user context, there is no need for a browser popup. Connections take place and are handled internally.

Azure MSI

If you are connecting from an Azure VM with permissions for Azure Data Lake Storage, set AuthScheme to AzureMSI.

CData Python Connector for XML

Creating a Custom OAuth App

There are two types of custom AzureAD applications: AzureAD and AzureAD with an Azure Service Principal. Both are OAuth-based.

When to Create a Custom Application

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via either a Desktop Application or from a Headless Machine.

You may choose to use your own AzureAD Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Custom AzureAD Applications

You can use a custom AzureAD application to authenticate a service account or a user account. You can always create a custom AzureAD application, but note that desktop and headless connections support embedded OAuth, which simplifies the process of authentication. See "Establishing a Connection" for information about using the embedded OAuth application.

Create a Custom AzureAD App

Follow the steps below to obtain the AzureAD values for your application, the OAuthClientId and OAuthClientSecret.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an application name and select the desired tenant setup. When creating a custom AzureAD application in Azure Active Directory, you can define whether the application is single- or multi-tenant. If you select the default option, "Accounts in this organizational directory only", you must set the AzureTenant connection property to the Id of the Azure AD Tenant when establishing a connection with the CData Python Connector for XML. Otherwise, the authentication attempt fails with an error. If your application is for private use only, "Accounts in this organization directory only" should be sufficient. Otherwise, if you want to distribute your application, choose one of the multi-tenant options.
  5. Set the redirect url to http://localhost:33333, the connector's default. Or, specify a different port and set CallbackURL to the exact reply URL you defined.
  6. Click Register to register the new application. This opens an application management screen. Note the value in Application (client) ID as the OAuthClientId and the Directory (tenant) ID as the AzureTenant.
  7. Navigate to the "Certificates & Secrets" and define the application authentication type. There are two types of authentication available: using a client secret or a certificate. The recommended authentication method is using a certificate.
    • Option 1: Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2: Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will need it as the OAuthClientSecret.
  8. Select API Permissions > Add a permission > Azure Storage > user_impersonation > Add permissions.
  9. Save your changes.
  10. If you have selected to use permissions that require admin consent (such as the Application Permissions), you can grant them from the current tenant on the API Permissions page. Otherwise, follow the steps under "Admin Consent".

Custom AzureAD Service Principal Applications

When authenticating using an Azure Service Principal, you must create both a custom AzureAD application and a service principal that can access the necessary resources. Follow the steps below to create a custom AzureAD application and obtain the connection properties for Azure Service Principal authentication.

Create a Custom AzureAD App with an Azure Service Principal

Follow the steps below to obtain the AzureAD values for your application.

  1. Log in to https://portal.azure.com.
  2. In the left-hand navigation pane, select All services. Filter and select App registrations.
  3. Click New registrations.
  4. Enter an app name and select Any Azure AD Directory - Multi Tenant. Then set the redirect url to http://localhost:33333, the connector's default.
  5. After creating the application, copy the Application (client) Id value displayed in the "Overview" section. This value is used as the OAuthClientId
  6. Define the app authentication type by going to the "Certificates & Secrets" section. There are two types of authentication available: using a client secret and using a certificate. The recommended authentication method is via a certificate.
    • Option 1 - Upload a certificate: In "Certificates & Secrets", select Upload certificate and the certificate to upload from your local machine.
    • Option 2 - Create a new application secret: In "Certificates & Secrets", select New Client Secret for the application and specify its duration. After saving the client secret, the key value is displayed. Copy this value as it is displayed only once. You will use it as the OAuthClientSecret.
  7. On the Authentication tab, make sure to select Access tokens (used for implicit flows).

Add Service Principal to Workspace

Follow the steps below to add a service principal to a workspace.

  1. Log in to Microsoft Fabric.
  2. Click the gear icon (Settings) on the top right.
  3. Select Admin portal.
  4. In the left-hand navigation pane, select Tenant settings.
  5. Scroll until you find Developer settings.
  6. Expand Service principals can use Fabric APIs.
  7. Enable the option.
  8. Select Apply.
  9. Select the workspace where you want to add your service principal.
  10. Click Manage access.
  11. Click Add people or groups.
  12. Enter the name of your application (verify the ID if there are multiple applications with the same name).
  13. Set the level of access you would like to grant to your application. Contributor is the lowest security level necessary to access OneLake via the API.
  14. Select Add.

CData Python Connector for XML

Connecting to SFTP

Connecting to SFTP

You can authenticate to SFTP using a user and password or an SSH certificate. Additionally, you can connect to an SFTP server that has no authentication enabled.

No Authentication

Set SSHAuthMode to None to connect without authentication, assuming your server supports doing so.

Password

Provide user credentials associated with your SFTP server:

SSH Certificate

Set the following to connect.

CData Python Connector for XML

Connecting to SharePoint Online

Connecting to SharePoint Online (REST)

The following authentication schemes are supported for the REST API:

  • AzureAD
  • MSI
  • AzureServicePrincipal

AzureAD

Azure Active Directory (AzureAD) is a connection type that leverages OAuth to authenticate. OAuth requires the authenticating user to interact with XML using an internet browser. The driver facilitates this in several ways as described below. Set your AuthScheme to AzureAD. The AzureAD flows described below assume that you have done so.

Your organization may require Admin Consent when authorizing a new AzureAD application for your Azure Tenant. In all AzureAD flows, any initial installation and use of an AzureAD application requires that an administrator approve the application for their Azure Tenant.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop authentication. Alternatively, you can create a custom AzureAD application. See Creating a Custom AzureAD App for information about creating custom applications and reasons for doing so.

For authentication, the only difference between the two methods is that you must set two additional connection properties when using custom AzureAD applications.

After setting the following connection properties, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId: (custom applications only) Set this to the client Id in your application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in your application settings.
  • CallbackURL: Set this to the Redirect URL in your application settings.

When you connect the connector opens the OAuth endpoint in your default browser. Log in and grant permissions to the application. The connector then completes the OAuth process:

  1. Extracts the access token from the callback URL and authenticates requests.
  2. Obtains a new access token when the old one expires.
  3. Saves OAuth values in OAuthSettingsLocation. These stored values persist across connections.

Web Applications

When connecting via a Web application, you need to create and register a custom AzureAD application with XML. See Creating a Custom AzureAD App for more information about custom applications. You can then use the connector to acquire and manage the OAuth token values.

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the CallbackURL input to the callback URL you specified in your application settings. If necessary, set the Scope parameter to request custom permissions.

    The stored procedure returns the URL to the OAuth endpoint.

  2. Open the URL, log in, and authorize the application. You are redirected back to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the "code" parameter in the query string of the callback URL. If necessary, set the Scope parameter to request custom permissions.

Once you have obtained the access and refresh tokens, you can connect to data and refresh the OAuth access token either automatically or manually.

Automatic Refresh of the OAuth Access Token

To have the driver automatically refresh the OAuth access token, set the following on the first data connection:

On subsequent data connections, the values for OAuthAccessToken and OAuthRefreshToken are taken from OAuthSettingsLocation.

Manual Refresh of the OAuth Access Token

The only value needed to manually refresh the OAuth access token when connecting to data is the OAuth refresh token.

Use the RefreshOAuthAccessToken stored procedure to manually refresh the OAuthAccessToken after the ExpiresIn parameter value returned by GetOAuthAccessToken has elapsed, then set the following connection properties:

  • OAuthClientId: Set this to the client Id in your application settings.
  • OAuthClientSecret: Set this to the client secret in your application settings.

Then call RefreshOAuthAccessToken with OAuthRefreshToken set to the OAuth refresh token returned by GetOAuthAccessToken. After the new tokens have been retrieved, open a new connection by setting the OAuthAccessToken property to the value returned by RefreshOAuthAccessToken.

Finally, store the OAuth refresh token so that you can use it to manually refresh the OAuth access token after it has expired.

Headless Machines

To configure the driver to use OAuth with a user account on a headless machine, you need to authenticate on another device that has an internet browser.

  1. Choose one of these two options:

    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code" below.
    • Option 2: Install the connector on another machine and transfer the OAuth authentication values after you authenticate through the usual browser-based flow, as described in "Transfer OAuth Settings" below.

  2. Then configure the connector to automatically refresh the access token from the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL.

Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. Choose one of these options:

    • If you are using the Embedded OAuth Application click XML OAuth endpoint to open the endpoint in your browser.
    • If you are using a custom OAuth application, create the Authorization URL by setting the following properties: Then call the GetOAuthAuthorizationURL stored procedure with the appropriate CallbackURL. Open the URL returned by the stored procedure in a browser.

  2. Log in and grant permissions to the connector. You are then redirected to the callback URL, which contains the verifier code.
  3. Save the value of the verifier code. Later you will set this in the OAuthVerifier connection property.
Next, you need to exchange the OAuth verifier code for OAuth refresh and access tokens. Set the following properties:

On the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthVerifier: Set this to the verifier code.
  • OAuthClientId: (custom applications only) Set this to the client Id in your custom OAuth application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in the custom OAuth application settings.
  • OAuthSettingsLocation: Set this to the location of the file where the driver saves the OAuth token values that persist across connections.

After the OAuth settings file is generated, you need to re-set the following properties to connect:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location containing the encrypted OAuth authentication values. Make sure this location grants read and write permissions to the connector to enable the automatic refreshing of the access token.

Option 2: Transfer OAuth Settings

Prior to connecting on a headless machine, you need to create and install a connection with the driver on a device that supports an internet browser. Set the connection properties as described in "Desktop Applications" above.

After completing the instructions in "Desktop Applications", the resulting authentication values are encrypted and written to the location specified by OAuthSettingsLocation. The default filename is OAuthSettings.txt.

Once you have successfully tested the connection, copy the OAuth settings file to your headless machine.

On the headless machine, set the following connection properties to connect to data:

  • InitiateOAuth: Set this to REFRESH.
  • OAuthClientId: (custom applications only) Set this to the client Id assigned when you registered your application.
  • OAuthClientSecret: (custom applications only) Set this to the client secret assigned when you registered your application.
  • OAuthSettingsLocation: Set this to the location of your OAuth settings file. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Azure Service Principal

The authentication as an Azure Service Principal is handled via the OAuth Client Credentials flow. It does not involve direct user authentication. Instead, credentials are created for just the application itself. All tasks taken by the application are done without a default user context, but based on the assigned roles. The application access to the resources is controlled through the assigned roles' permissions.

Create an AzureAD App and an Azure Service Principal

When authenticating using an Azure Service Principal, you must create and register an Azure AD application with an Azure AD tenant. See Creating an Entra ID (Azure AD) Application for more details.

In your App Registration in portal.azure.com, navigate to API Permissions and select the Microsoft Graph permissions. There are two distinct sets of permissions: Delegated permissions and Application permissions. The permissions used during client credential authentication are under Application Permissions.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.
Complete the Authentication Choose whether to use a client secret or a certificate and follow the relevant steps below.

Client Secret

Set these connection properties:

Certificate

Set these connection properties:

You are now ready to connect. Authentication with client credentials takes place automatically like any other connection, except there is no window opened prompting the user. Because there is no user context, there is no need for a browser popup. Connections take place and are handled internally.

MSI

If you are running XML on an Azure VM, you can leverage Managed Service Identity (MSI) credentials to connect:

The MSI credentials are automatically obtained for authentication.

Azure Service Principal

When authenticating using an Azure Service Principal, you must register an application with an Azure AD tenant.

Assign a role to the application

To access resources in your subscription, you must assign a role to the application.

  1. Open the Subscriptions page by searching and selecting the Subscriptions service from the search bar.
  2. Select the particular subscription to assign the application to.
  3. Open the Access control (IAM) and select Add > Add role assignment to open the Add role assignment page.
  4. Select Owner as the role to assign to your created Azure AD app.

Authenticate with an Azure Service Principal

You are ready to connect after setting one of the below connection properties groups, depending on the configured app authentication (client secret or certificate).

Before choosing client secret or certicate authentication, set the following:

Option 1: Authenticating using a Client Secret

Set the following to authenticate with a client secret:

  • AuthScheme: Set this to the AzureServicePrincipal in your app settings.
  • OAuthClientId: Set this to the client Id in your app settings.
  • OAuthClientSecret: Set this to the client secret in your app settings.

Option 2: Authenticating using a JWT Certificate

Set the following to authenticate with a JWT Certificate:

Connecting to SharePoint Online (REST V1)

SharePoint REST V1 uses the SharePoint REST API v1 (_api/web/) with the sprestv1:// URI scheme. It supports both on-premise and SharePoint Online environments. The following authentication schemes are supported for SharePoint Online:

  • AzureAD
  • ADFS
  • Okta
  • OneLogin
  • PingFederate

AzureAD

Azure Active Directory (AzureAD / Entra ID) uses OAuth 2.0 to authenticate with Azure AD and obtain an access token for the SharePoint REST API. Set the AuthScheme to AzureAD. The following connection properties are used to connect:

  • InitiateOAuth: Set this to GETANDREFRESH to have the connector manage the OAuth token exchange and refresh automatically.
  • OAuthClientId: (custom applications only) Set this to the client Id in your Azure AD application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in your Azure AD application settings.
  • CallbackURL: Set this to the Redirect URL configured in your Azure AD application.
  • AzureTenant: (optional) Set this to the Azure AD tenant Id or domain. Defaults to common for multi-tenant applications. Required when connecting to SharePoint On Premise with Entra ID.

The following is an example connection string:

AuthScheme=AzureAD;InitiateOAuth=GETANDREFRESH;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

ADFS

Set the AuthScheme to ADFS. You need to set the following connection properties:

  • User: Set this to the ADFS user.
  • Password: Set this to ADFS password for the user.
  • SSOLoginURL: Set this to the base URL for your ADFS server.

The following is an example connection string:

AuthScheme=ADFS;User=ADFSUserName;Password=ADFSPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

Okta

Set the AuthScheme to Okta. The following connection properties are used to connect to Okta:

  • User: Set this to the Okta user.
  • Password: Set this to Okta password for the user.
  • SSOLoginURL: Set this to your Okta application's embed link.

The following is an example connection string:

AuthScheme=Okta;User=oktaUserName;Password=oktaPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

OneLogin

Set the AuthScheme to OneLogin. The following connection properties are used to connect to OneLogin:

  • User: Set this to the OneLogin user.
  • Password: Set this to OneLogin password for the user.

The following is an example connection string:

AuthScheme=OneLogin;User=OneLoginUserName;Password=OneLoginPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

PingFederate

Set the AuthScheme to PingFederate. The following connection properties are used to connect to PingFederate:

  • User: Set this to the PingFederate user.
  • Password: Set this to PingFederate password for the user.
  • SSOLoginURL: Set this to the base URL for your PingFederate server.

The following is an example connection string:

AuthScheme=PingFederate;User=PingFederateUserName;Password=PingFederatePassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

CData Python Connector for XML

Creating a Custom AzureAD App

When to Create a Custom OAuth App

CData embeds OAuth Application Credentials with CData branding that can be used when connecting via either a Desktop Application or from a Headless Machine. Creating a custom OAuth application is, however, required when using a web application.

You may choose to create your own OAuth Application Credentials when you want to

  • control branding of the Authentication Dialog
  • control the redirect URI that the application redirects the user to after the user authenticates
  • customize the permissions that you are requesting from the user

Creating a Custom OAuth App

Follow the steps below to obtain OAuth values for your app, the OAuthClientId and OAuthClientSecret.

  1. Log in to the Azure Portal.
  2. In the left-hand navigation pane, select Azure Active Directory > App Registrations and click Add.
  3. Enter an application name and select Any Azure AD Directory - Multi Tenant. Then set the redirect url to http://localhost:33333, the connector's default or set a different port of your choice and set CallbackURL to the exact reply URL you defined.
  4. After creating the app, navigate to the "Certificates & Secrets" section, create a client secret for the application, and select a duration.
  5. After you save the key, key value is displayed once. Set OAuthClientSecret to the displayed value. Set OAuthClientId to the Application Id.
  6. Select API Permissions and click Add. If your application connects without a user context, select Application Permissions. If your application authenticates on behalf of a signed-in user, choose Delegated permissions.
  7. In the API Permissions section, click on Add a permission and select Sharepoint. Choose the permissions you want your app to have. To view and edit lists, you have to select (at least) the AllSites.Manage permission.
  8. Save your changes.
  9. If you have selected to use permissions that require admin consent (such as the Application Permissions), you can grant them from the current tenant on the API Permissions page. Otherwise, follow the steps under "OAuth: Admin Consent" in Establishing a Connection.

CData Python Connector for XML

Connecting to SharePoint On Premise

Connecting to SharePoint On Premise

SharePoint On Premise can be accessed using either the SharePoint SOAP or SharePoint REST V1 connection type.

  • SharePoint SOAP uses the SharePoint SOAP API with the sp:// URI scheme.
  • SharePoint REST V1 uses the SharePoint REST API v1 (_api/web/) with the sprestv1:// URI scheme.

Note: SharePoint REST V1 supports connecting to both on-premise and SharePoint Online environments. The SSO authentication schemes (ADFS, Okta, OneLogin, PingFederate) authenticate through Microsoft's SharePoint Online cloud endpoints. For SharePoint Online-specific guidance, see also Connecting to SharePoint Online.

The following authentication schemes are supported for both connection types:

  • User Credentials
  • ADFS
  • Okta
  • OneLogin
  • NTLM

Additionally, SharePoint REST V1 supports:

  • AzureAD (Azure Active Directory / Entra ID)

User Credentials

Set the AuthScheme to Basic. You need to set the following connection properties:

  • User: Set this to the SharePoint user.
  • Password: Set this to SharePoint password for the user.
Below is an example connection string:
AuthScheme=Basic;User=yourUserName;Password=yourPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Shared Documents/';StorageBaseURL=http://sharePointServer/;

AuthScheme=Basic;User=yourUserName;Password=yourPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=http://sharePointServer/sites/mysite;

ADFS

Set the AuthScheme to ADFS. You need to set the following connection properties:

  • User: Set this to the ADFS user.
  • Password: Set this to ADFS password for the user.
  • SSOLoginURL: Set this to the base URL for your ADFS server.
Below are example connection strings:
AuthScheme=ADFS;User=ADFSUserName;Password=ADFSPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Documents/';StorageBaseURL=http://sharePointServer/;

AuthScheme=ADFS;User=ADFSUserName;Password=ADFSPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

Okta

Set the AuthScheme to Okta. The following connection properties are used to connect to Okta:

  • User: Set this to the Okta user.
  • Password: Set this to Okta password for the user.
  • SSOProperties:
    • Domain (optional): It may be required to set this property if the domain configured on the SSO domain is different than the domain of the User.

The following are example connection strings:

AuthScheme=Okta;User=oktaUserName;Password=oktaPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Documents/';StorageBaseURL=http://sharePointServer/;

AuthScheme=Okta;User=oktaUserName;Password=oktaPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

OneLogin

Set the AuthScheme to OneLogin. The following connection properties are used to connect to OneLogin:

  • User: Set this to the OneLogin user.
  • Password: Set this to OneLogin password for the user.
  • SSOProperties:
    • Domain (optional): It may be required to set this property if the domain configured on the SSO domain is different than the domain of the User.

The following are example connection strings:

AuthScheme=OneLogin;User=OneLoginUserName;Password=OneLoginPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Documents/';StorageBaseURL=http://sharePointServer/;

AuthScheme=OneLogin;User=OneLoginUserName;Password=OneLoginPassword;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

NTLM

Set the AuthScheme to NTLM. The following connection properties are used to connect to NTLM:

  • User: Set this to the NTLM user.
  • Password: Set this to NTLM password for the user.

The following are example connection strings:

AuthScheme=NTLM;User=NtlmUsername;Password=NtlmPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Documents/';StorageBaseURL=http://sharePointServer/;

AuthScheme=NTLM;User=NtlmUsername;Password=NtlmPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint SOAP';URI='sp://Documents/mycars.XML';StorageBaseURL=http://sharePointServer/;

AuthScheme=NTLM;User=NtlmUsername;Password=NtlmPassword;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=http://sharePointServer/sites/mysite;

AzureAD

Azure Active Directory (AzureAD / Entra ID) authentication is supported for SharePoint REST V1 only. This uses OAuth 2.0 to authenticate with Azure AD and obtain an access token for the SharePoint REST API. This works for both SharePoint Online and SharePoint Server on-premise (when configured with Entra ID as an OIDC identity provider, e.g. SharePoint Server Subscription Edition). Set the AuthScheme to AzureAD. The following connection properties are used to connect:

  • OAuthClientId: Set this to the client Id in your Azure AD application settings.
  • OAuthClientSecret: Set this to the client secret in your Azure AD application settings.
  • CallbackURL: Set this to the Redirect URL configured in your Azure AD application.
  • InitiateOAuth: Set this to GETANDREFRESH to have the connector manage the OAuth token exchange and refresh automatically.
  • AzureTenant: Set this to the Azure AD tenant Id or domain (e.g. contoso.onmicrosoft.com or a tenant GUID). This is required for SharePoint On Premise.

The following are example connection strings:

AuthScheme=AzureAD;AzureTenant=contoso.onmicrosoft.com;InitiateOAuth=GETANDREFRESH;SharePointEdition=SharePointOnPremise;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://sharePointServer/sites/mysite;

AuthScheme=AzureAD;InitiateOAuth=GETANDREFRESH;ConnectionType='SharePoint REST V1';URI='sprestv1://Documents/';StorageBaseURL=https://subdomain.sharepoint.com/sites/mysite;

CData Python Connector for XML

SSO connections

Authenticating with SSO

Service provider Okta OneLogin ADFS AzureAD
Amazon S3 Y Y Y
Azure Blob Storage
Azure Data Lake Store Gen1
Azure Data Lake Store Gen2
Azure Data Lake Store Gen2 with SSL
Google Drive
OneDrive
Box
Dropbox
SharePoint Online SOAP Y Y Y
SharePoint Online REST
SharePoint REST V1 Y Y Y Y
Wasabi
Google Cloud Storage
Oracle Cloud Storage
Azure File

AzureAD

Azure AD Configuration

The main theme behind this configuration is the OAuth 2.0 On-Behalf-Of flow. It requires two Azure AD applications:

  1. An application used for the single sign-on process to a specific service provider.
    • Amazon S3: Please follow this link for detailed instructions on how to create this application. Make sure you test the connection and you are able to login to the AWS console from Azure AD.

      Save the step "Assign the Azure AD test user" until after provisioning so that you can select the AWS roles when assigning the user.

  2. A "connector" application with user_impersonation permission on the SSO application you created in the previous step. Go to Azure Active Directory > App registrations and register a new application. After you register this application, you need to allow it to make API calls to the SSO application. Go to the API permissions section of the app you registered and click the "Add a permission" box. Select the API of your SSO application by specifying the API name or Application Id and add the user_impersonation permission.

CData Driver Common Properties

The following SSOProperties are needed to authenticate to Azure Active Directory and must be specified for every service provider.

  • Resource: The application Id URI of the SSO application, listed in the Overview section of the app registration.
  • Tenant: The Id of the Azure AD tenant where the applications are registered. You can find this value using the instructions found here.

We will retrieve the SSO SAML response from an OAuth 2.0 On-Behalf-Of flow so the following OAuth connection properties must be specified:

  • OAuthClientId: The application Id of the connector application, listed in the Overview section of the app registration.
  • OAuthClientSecret: The client secret value of the connector application. Azure AD displays this when you create a new client secret (Certificates & secrets section).

Amazon S3

In addition to the common properties, the following properties must be specified when connecting to Amazon S3 service provider:

  • AuthScheme: Set the AuthScheme to AzureAD.
  • AWSRoleARN: The ARN of the IAM role. Find this on the Summary page of the IAM role.
  • AWSPrincipalARN: The ARN of the identity provider. Find this on the identity provider's summary page.
The following is an example connection string:
AuthScheme=AzureAD;InitiateOAuth=GETANDREFRESH;OAuthClientId=d593a1d-ad89-4457-872d-8d7443aaa655;OauthClientSecret=g9-oy5D_rl9YEKfN-45~3Wm8FgVa2F;SSOProperties='Tenant=94be7-edb4-4fda-ab12-95bfc22b232f;Resource=https://signin.aws.amazon.com/saml;';AWSRoleARN=arn:aws:iam::2153385180:role/AWS_AzureAD;AWSPrincipalARN=arn:aws:iam::215515180:saml-provider/AzureAD;

OneLogin

OneLogin Configuration

You must create an application used for the single sign-on process to a specific provider.

  • Sharepoint SOAP: Please follow this link for detailed instructions on how to create this application. Make sure you test the connection and you are able to login to Office 365 from OneLogin. Make sure you have enabled WS-TRUST in your application. Otherwise, the CData driver will not be able to connect.

Sharepoint SOAP

The following properties must be specified when connecting to Sharepoint SOAP service provider:

  • AuthScheme: Set the AuthScheme to OneLogin.
  • User: The username of the OneLogin account.
  • Password: The password of the OneLogin account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='OneLogin';User=test;Password=test;SSOProperties='Domain=test.cdata;';

Sharepoint REST V1

The following properties must be specified when connecting to Sharepoint REST V1 service provider:

  • AuthScheme: Set the AuthScheme to OneLogin.
  • User: The username of the OneLogin account.
  • Password: The password of the OneLogin account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='OneLogin';User=test;Password=test;SSOProperties='Domain=test.cdata;';StorageBaseURL='https://sharepointserver/sites/mysite';

Okta

Okta Configuration

You must create an application used for the single sign-on process to a specific provider.

  • Sharepoint SOAP: Please follow this link for detailed instructions on how to create this application and configure SSO. Make sure you test the connection and you are able to login to Office 365 from Okta. Make sure you have configured SSO using WS-Federation in your application. Otherwise, the CData driver will not be able to connect.
  • Amazon S3: Please follow this link for detailed instructions on how to create this application and configure SSO. Make sure you test the connection and you are able to login to AWS from Okta. Make sure you have configured SSO with SAML 2.0 in your application. Otherwise, the CData driver will not be able to connect. Ensure that the assigned AWS role in the Okta app has access to the S3 bucket you want to connect.

Sharepoint SOAP

The following properties must be specified when connecting to Sharepoint SOAP service provider:

  • AuthScheme: Set the AuthScheme to Okta.
  • User: The username of the Okta account.
  • Password: The password of the Okta account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='Okta';User=test;Password=test;SSOProperties='Domain=test.cdata;';

Sharepoint REST V1

The following properties must be specified when connecting to Sharepoint REST V1 service provider:

  • AuthScheme: Set the AuthScheme to Okta.
  • User: The username of the Okta account.
  • Password: The password of the Okta account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='Okta';User=test;Password=test;SSOProperties='Domain=test.cdata;';StorageBaseURL='https://sharepointserver/sites/mysite';

Amazon S3

The following properties must be specified when connecting to an Amazon S3 service provider:

  • AuthScheme: Set the AuthScheme to Okta.
  • User: The username of the Okta account.
  • Password: The password of the Okta account.
  • SSOLoginURL: Set this to the embedded URL of your AWS Okta SSO app.
  • AWSRoleARN (optional): The ARN of the IAM role. Find this on the Summary page of the IAM role.
  • AWSPrincipalARN (optional): The ARN of the identity provider. Find this on the identity provider's summary page.
  • SSOProperties:
    • APIToken (optional): Set this to the API Token that the customer created from the Okta org. It should be used when authenticating a user via a trusted application or proxy that overrides Okta client request context.
The following is an example connection string:
AuthScheme=Okta;User=OktaUser;Password=OktaPassword;SSOLoginURL='https://{subdomain}.okta.com/home/amazon_aws/0oan2hZLgQiy5d6/272';

ADFS

ADFS Configuration

You must create an application used for the single sign-on process to a specific provider.

  • Sharepoint SOAP: Please follow this link for detailed instructions on how to set up ADFS for Office 365 for Single Sign-On. Make sure you test the connection and you are able to login to Office 365 from ADFS.
  • Amazon S3: Please follow this link for detailed instructions on how to set up ADFS for AWS Single Sign-On. Make sure you test the connection and you are able to login to AWS from ADFS.

Sharepoint SOAP

The following properties must be specified when connecting to a Sharepoint SOAP service provider:

  • AuthScheme: Set the AuthScheme to ADFS.
  • User: The username of the ADFS account.
  • Password: The password of the ADFS account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='ADFS';User=test;Password=test;SSOProperties='Domain=test.cdata;';

Sharepoint REST V1

The following properties must be specified when connecting to a Sharepoint REST V1 service provider:

  • AuthScheme: Set the AuthScheme to ADFS.
  • User: The username of the ADFS account.
  • Password: The password of the ADFS account.
  • SSOProperties:
    • Domain (optional): It may be required to be set this property if the domain configured on the SSO domain is different than the domain of the User.
The following is an example connection string:
AuthScheme='ADFS';User=test;Password=test;SSOProperties='Domain=test.cdata;';StorageBaseURL='https://sharepointserver/sites/mysite';

Amazon S3

The following properties must be specified when connecting to a Sharepoint SOAP service provider:

  • AuthScheme: Set the AuthScheme to ADFS.
  • SSOLoginURL: Set this to the URL of your ADFS instance.
  • User: The username of the ADFS account.
  • Password: The password of the ADFS account.
  • AWSRoleARN (optional): The ARN of the IAM role. Find this on the Summary page of the IAM role.
  • AWSPrincipalARN (optional): The ARN of the identity provider. Find this on the identity provider's summary page.
The following is an example connection string:
AuthScheme=ADFS;User=username;Password=password;SSOLoginURL='https://sts.company.com';
ADFS Integrated

The ADFS Integrated flow indicates you are connecting with the currently logged in Windows user credentials. To use the ADFS Integrated flow, simply do not specify the User and Password, but otherwise follow the same steps in the ADFS guide above.

CData Python Connector for XML

Fine-Tuning Data Access

The CData Python Connector for XML enables the kind of granular control that is useful in more complex deployments or network topologies; you can use the following connection properties to fine-tune data access, connect through a firewall, or troubleshoot connections.

Resource location

The URI should be used to specify an XML resource location. Set the URI property to specify one of the following sources:
  • An empty value automatically assigns the URI to a reference to the current directory, "./". The explicit path to the XML folders depends on the environment of the running application.
  • A path to a folder.
  • A path to a .zip, .tar. or .gz archive file.
    • Include the file, not just the containing directory. For example: C:\Users\Public\Documents\CSVdata.zip
  • A path to a file or stream - in this case you can query the file by executing SELECT * FROM streamedtable.

Modeling tables

Set the following properties to control how the connector models XML as tables:

  • IncludeFiles: Set this to a comma-separated list of file extensions to include into the set of files modeled as tables. (By default, .xml and .txt files are modeled.)
    • Specify files by their file extensions in all-caps, without the '.'. For example: "XML,TXT".
    • Archive files are supported (ZIP, TAR, and GZ) and are modeled as if they were folders.
  • RowScanDepth: Set this to automatically determine data types by scanning rows up to the specified depth.

Parsing and Merging Multiple Files Into A Single Table

The connector supports reading and parsing multiple files within a single directory and merging the data into a single result set.

To enable this feature, the URI property can be set to a directory with a file mask (e.g. C:\MyDataFiles\*.xml) or a directory (e.g. C:\MyDataFiles). When a directory is specified as the URI, IncludeFiles will be used to identify the file types to include.

This functionality is also available on cloud based service providers such as Google Drive (e.g. gdrive://remotepath/*.xml), Amazon S3 (e.g. s3://remotepath/*.xml), FTP (ftp://server:port/remotepath/*.xml), etc.

When setting URI to a directory, be sure to include an ending forward slash (e.g. s3://remotepath/) to denote that its a directory.

A comma-separated list of URIs is supported to include multiple files.

To retrieve all files (including those without a file extension), you can use a file mask of '*' (e.g. s3://remotepath/*) or set IncludeFiles to include a '*' entry.
To include just files without an extension, you can set IncludeFiles to include a 'NOEXT' entry.

When parsing a batch of files, the files are put into a queue.
Each file will be retrieved and parsed in a streaming fashion with each row pushed as it is parsed.
Therefore files will never be stored in memory or stored in a temporary location on disk, thus limiting the amount of memory usage required.

Metadata Discovery

When reading multiple files, the connector will use the first file identified to discovery metadata.
A single file is used for metadata discovery for performance reasons.
In cases where the first identified file contains partial XML data (as compared to the other files in the directory), columns/data for the other files may not be returned.
This is due to the connector not being able to properly identify all the columns available in the selected files from the single file used for metadata discovery.

To work around these cases, a "MetadataDiscoveryURI" option can be set via the Other property (e.g. MetadataDiscoveryURI=file:///C:\MyDataFiles\main.xml).
When a MetadataDiscoveryURI is specified, the connector will use the specified URI to discover tables and columns.
Once the metadata has been discovered, the URI value will be used to retrieve and parse the XML data.

Error Handling

When parsing multiple files, there may be cases where a file is not able to be parsed (such as invalid XML, a network connectivity issue, etc.).
In such cases, the connector will not return an exception message but rather will log the error in a temporary table called ErrorInfo#TEMP.
This is done so that failures don't occur in the middle of reading a large batch of files and having to start over.
Instead the temporary table (ErrorInfo#TEMP) can be queried after the initial query has finished.
This will allow you to identify if there were any files that failed to parse, thus allowing you to retry the failed requests and merging them with your primary result set.

To retrieve the error list, you can issue the following query: SELECT * FROM ErrorInfo#TEMP.
This table contains two columns: URI and Description.
URI contains the URI for the single file that failed (which can be set via the URI property to retry).
Description contains the description as to why the file failed to parse. In the case that no errors occurred, an empty result set will be returned.

Navigating Subdirectories

The connector supports navigating subdirectories when parsing local files.
This functionality is exposed by using the '*' wildcard character in the directory name of the URI value.

For example, suppose you have a 'Data' directory that contains folders with unique names (such as a date value) each of which contain similar XML data files.
You can read all these files into a single table by setting URI to 'file:///C:\Data\*\*.xml' or you can set it to the directory without a file mask 'file:///C:\Data\*'.

Partial directory matching is also supported.
For example, to retrieve all XML files within folders starting with '2018' the following URI value can be used: file:///C:\Data\2018*\*.xml.

Note: Using wildcards in directory names is not applicable when connecting to cloud resources.

CData Python Connector for XML

Using Kerberos

Kerberos

To authenticate to XML with Kerberos, set AuthScheme to NEGOTIATE.

Authenticating to XML via Kerberos requires you to define authentication properties and to choose how Kerberos should retrieve authentication tickets.

Retrieve Kerberos Tickets

Kerberos tickets are used to authenticate the requester's identity. The use of tickets instead of formal logins/passwords eliminates the need to store passwords locally or send them over a network. Users are reauthenticated (tickets are refreshed) whenever they log in at their local computer or enter kinit USER at the command prompt.

The connector provides three ways to retrieve the required Kerberos ticket, depending on whether or not the KRB5CCNAME and/or KerberosKeytabFile variables exist in your environment.

MIT Kerberos Credential Cache File

This option enables you to use the MIT Kerberos Ticket Manager or kinit command to get tickets. With this option there is no need to set the User or Password connection properties.

This option requires that KRB5CCNAME has been created in your system.

To enable ticket retrieval via MIT Kerberos Credential Cache Files:

  1. Ensure that the KRB5CCNAME variable is present in your environment.
  2. Set KRB5CCNAME to a path that points to your credential cache file. (For example, C:\krb_cache\krb5cc_0 or /tmp/krb5cc_0.) The credential cache file is created when you use the MIT Kerberos Ticket Manager to generate your ticket.
  3. To obtain a ticket:
    1. Open the MIT Kerberos Ticket Manager application.
    2. Click Get Ticket.
    3. Enter your principal name and password.
    4. Click OK.

    If the ticket is successfully obtained, the ticket information appears in Kerberos Ticket Manager and is stored in the credential cache file.

The connector uses the cache file to obtain the Kerberos ticket to connect to XML.

Note: If you would prefer not to edit KRB5CCNAME, you can use the KerberosTicketCache property to set the file path manually. After this is set, the connector uses the specified cache file to obtain the Kerberos ticket to connect to XML.

Keytab File

If your environment lacks the KRB5CCNAME environment variable, you can retrieve a Kerberos ticket using a Keytab File.

To use this method, set the User property to the desired username, and set the KerberosKeytabFile property to a file path pointing to the keytab file associated with the user.

User and Password

If your environment lacks the KRB5CCNAME environment variable and the KerberosKeytabFile property has not been set, you can retrieve a ticket using a user and password combination.

To use this method, set the User and Password properties to the user/password combination that you use to authenticate with XML.

Enabling Cross-Realm Authentication

More complex Kerberos environments can require cross-realm authentication where multiple realms and KDC servers are used. For example, they might use one realm/KDC for user authentication, and another realm/KDC for obtaining the service ticket.

To enable this kind of cross-realm authentication, set the KerberosRealm and KerberosKDC properties to the values required for user authentication. Also, set the KerberosServiceRealm and KerberosServiceKDC properties to the values required to obtain the service ticket.

CData Python Connector for XML

Changelog

General Changes

DateVersionSourceCategoryTypeDescription
2026-05-2726.0.9643GeneralConnectionRemoved
  • Removed the deprecated ReplaceInvalidTypesWithNull connection property. Use the ReplaceInvalidValuesWithNull property instead.
2026-05-2226.0.9638PythonRemoved
  • Remove support for Intel x64 architecture on macOS
2026-05-2226.0.9638XMLConnectionAdded
  • Added the PKCEVerifier connection property. For more information, see the Authentication section in the Connection String Options chapter.
2026-05-2126.0.9637XMLConnectionChanged
  • When the ConnectionType connection property is set to "SharePointSOAP", the driver only supports SharePointEdition=SharePointOnPremise. Setting the SharePointEdition connection property to "SharePointOnline" is not supported for this connection type. Use ConnectionType=SharePointGRAPH or ConnectionType=SharePointRESTv1 to connect to SharePoint Online.
2026-05-1326.0.9629XMLConnectionChanged
  • Paths are now resolved relative to the connection URI by the MetadataDiscoveryURI connection property. Previously, this resolution was performed by the Location connection property.
  • The MetadataDiscoveryURI property no longer requires a fully-qualified URI with a storage prefix (for example, "s3://bucket/...") when connecting to a cloud resource. Relative values are now resolved relative to the connection URI.
2026-05-0726.0.9623GeneralData ModelAdded
  • Added the ColumnCapabilities column to the sys_tablecolumns system table. This column is a bit mask denoting the column's write capabilities.
2026-05-0726.0.9623PythonChanged
  • Updated embedded JRE to jre-17.0.19+10 (Linux x64 / MacOs x64).
2026-04-2926.0.9615XMLConnectionAdded
  • Added support for authentication via EKSPodIdentity. For descriptions of the related connection properties (AWSContainerCredentialsFullURI and AWSContainerAuthorizationTokenFile), see the AWS Authentication Properties section of the Connection String Options chapter.
2026-04-2326.0.9609XMLConnectionAdded
  • Added the "SharePoint REST V1" connection type to the ConnectionType connection property. This connection type uses the SharePoint REST V1 API and supports both on-premise and cloud SharePoint instances. The URI prefix for this connection type is "sprestv1://".
2026-04-2326.0.9609XMLConnectionChanged
  • Renamed the "SharePoint REST" connection type to "SharePoint GRAPH" in the ConnectionType connection property and updated its URI prefix from "sprest://" to "spgraph://".
2026-04-1526.0.9601GeneralQuery ExecChanged
  • String comparisons using GREATER, LESS, and CONTAINS operators are now case-insensitive by default.
2026-04-0126.0.9587XMLConnectionRemoved
  • The TestConnectionBehavior connection property's LIST_AND_READ_FILES option has been replaced by a new option, LIST_OR_READ_FILES. Use LIST_OR_READ_FILES instead.
  • The HMAC AuthScheme has been removed. This change affects Oracle Cloud Storage, Wasabi, and IBM Object Storage connections. Use IAMSecretKey instead.
2026-02-1125.0.9538XMLConnectionChanged
  • Added a new option, AUTHENTICATE, to the TestConnectionBehavior connection property. When Authenticate is specified, the driver makes a simple API call to check if the provided credentials are valid.
  • Fixed some incorrect behaviors for all options of the TestConnectionBehavior connection property.
  • Improved error handling, normalized errors, and added error codes to differentiate different storage errors.
2026-02-0925.0.9536XMLAdded
  • Added the new option LIST_OR_READ_FILES to the TestConnectionBehavior connection property.
2026-02-0925.0.9536XMLDeprecated
  • Marked the LIST_AND_READ_FILES option in the TestConnectionBehavior connection property for deprecation.
2026-01-1325.0.9509GeneralAdded
  • Added support for the REGEXP_REPLACE() string function.
2025-12-2125.0.9486PythonAdded
  • Added support for custom loggers in Python connectors on Linux and macOS.
2025-12-0525.0.9470GeneralAdded
  • Added support for the INSERT INTO SELECT statement, with driver-side execution for providers that do not support the operation natively.
2025-10-3025.0.9434PythonChanged
  • Updated embedded JRE to jre-17.0.17+10 (Linux x64 / MacOs x64).
2025-10-0625.0.9410GeneralAdded
  • Support for parsing datetime formats using ".S" and ",S" for milliseconds and nanoseconds.
2025-09-1225.0.9386GeneralAdded
  • Added the IsInsertable, IsUpdateable, and IsDeleteable columns to the sys_tables table.
2025-09-1025.0.9384GeneralChanged
  • All columns in statically defined Views are now reported as read-only.
2025-09-0325.0.9377GeneralChanged
  • Corrected the behavior when IN criteria with NULL values are used in the projection part. It now returns NULL instead of 0. For example, "NULL IN (1,2)" returns "NULL".
2025-09-0125.0.9375GeneralAdded
  • Added support for using the CAST function with infinity values. This function can cast "inf" and "-inf" to DOUBLE, FLOAT, or REAL.
2025-08-2125.0.9364GeneralChanged
  • Report behavior change:
    • Fixed inconsistent string value comparisons in non-table queries.
    • For example, "SELECT 'A' = 'a'" previously returned false, but it now returns true.
2025-08-1325.0.9356GeneralChanged
  • Changed the maximum number of pages held in memory from 15 to 5 for the page providers to decrease heap usage.
2025-07-1825.0.9330XMLRemoved
  • Removed the OAuthGrantType property. The grant type is now set implicitly through the 'AuthScheme' property. For example, you can use the 'OAuthPassword' AuthScheme instead of AuthScheme=OAuth with OAuthGrantType=Password.
2025-07-0725.0.9319PythonRemoved
  • Removed the 32-bit version of Windows Python.
2025-07-0225.0.9314PythonRemoved
  • Removed support for Python 3.9.
2025-06-2525.0.9307GeneralRemoved
  • Removed the "ADLS Gen 1" value from the ConnectionType property.
2025-06-2525.0.9307PythonAdded
  • Added support for Python 3.13 in Windows, Linux, and Mac editions.
2025-06-2525.0.9307PythonRemoved
  • Removed support for Python 3.8 as it is no longer supported.
2025-06-2025.0.9302GeneralAdded
  • Created the following functions:
    • TEXT_ENCODE: encodes a string into a different charset (UTF8 → UTF7 and returns a binary array as the result).
    • TEXT_DECODE: takes a binary array and decodes it back into a string when provided the charset.
    • BASE64_ENCODE: takes a binary array and encodes it as a base64 string (varchar).
    • BASE64_DECODE: takes a base 64-encoded string and decodes it into a binary array.
2025-06-1825.0.9300GeneralChanged
  • The internal code for exception handling has been refactored. Exception messages returned during certain error conditions may now have different wording or formatting.
2025-06-1225.0.9294XMLAdded
  • Added the following stored procedures: UploadFile, DownloadFile, and DeleteFile. These stored procedures accept only file paths that are relative to the connection URI. Note that UploadFile and DownloadFile are not available for ConnectionType=Local.
2025-06-0925.0.9291XMLRemoved
  • Removed the ProjectId property for the Google Cloud Storage ConnectionType.
2025-05-2725.0.9278GeneralRemoved
  • Removed the "Proprietary" enum option from ProxyAuthscheme.
2025-05-1525.0.9266XMLAdded
  • Added support for reading .7z (7-Zip) archive files.
2025-05-1225.0.9263PythonChanged
  • Updated embedded JRE to jre-17.0.15+6 (Linux x64 / MacOS x64) and jre-17.0.15+6 (MacOS aarch64).
2025-04-0725.0.9228XMLAdded
  • Added support for the IAMSecretKey AuthScheme for cloud storage connections that use access and secret key credentials. This naming better reflects the underlying authentication method and aligns with terminology used by cloud storage providers.
2025-04-0725.0.9228XMLDeprecated
  • Deprecated the HMAC AuthScheme. While it remains supported for backward compatibility, it is no longer recommended due to naming ambiguity.
2025-02-1524.0.9177GeneralAdded
  • Added support for converting unsigned integer types to the nearest signed data type that has enough precision to hold the unsigned value.This is done for JDBC only because it does not have support for unsigned data types.
2024-11-2724.0.9097GeneralAdded
  • Added ThreadId to LogModule output. Logfile lines now include the Thread ID associated with the action being performed.
2024-10-1524.0.9054XMLReplaced
  • In the ListFiles stored procedure, replaced the AbsolutePath input with the Path input. This path is relative to the path provided in the URI connection property.
2024-09-3024.0.9039XMLAdded
  • Added the AbsolutePath input to the ListFiles stored procedure. By default, ListFiles lists all XML files in the directory specified by the URI connection property. If an alternative directory is supplied in the AbsolutePath input, this procedure will instead list all XML files in the supplied directory.
2024-08-2324.0.9001XMLAdded
  • Added OAuthPKCE as an authentication option when ConnectionType is set to Google Cloud Storage and Google Drive.
  • Added OAuthClient as an authentication option when ConnectionType is set to Box.
2024-08-2024.0.8998XMLAdded
  • Added support for the following AWS regions: HYDERABAD, MELBOURNE, CALGARY, SPAIN, ISOLATEDUSEAST, ISOLATEDUSEASTB, and ISOLATEDUSWEST.
2024-06-2824.0.8945XMLRemoved
  • Removed the value "Auto" from the ConnectionType connection property. The default value is now "Local".
2024-06-1824.0.8935GeneralAdded
  • Added support for the "TELAVIV" region (Israel) in the AWSRegion connection property.
2024-06-0524.0.8922PythonAdded
  • Added support for Python 3.12.
2024-05-0924.0.8895GeneralChanged
  • The ROUND function previously did not accept negative precision values. That feature has now been restored.
2024-03-1523.0.8840GeneralAdded
  • Created a new SQL function called STRING_COMPARE that provides java's String.compare() ability to SQL queries. Returns a number representative of the compared value of two strings
2023-11-2923.0.8733GeneralChanged
  • The ROUND function doesn't accept the negative precision values anymore.
2023-11-2923.0.8733GeneralChanged
  • The returning types of the FDMonth, FDQuarter, FDWeek, LDMonth, LDQuarter, LDWeek functions are changed from Timestamp to Date.
  • The return type of the ABS function will be consistent with the parameter value type.
2023-11-2823.0.8732GeneralAdded
  • Added the HMACSHA256 formatter to allow for secrets to be decoded if it is in base64 format
2023-10-3123.0.8704XMLChanged
  • Improved handling of invalid XML files when exposing metadata for directory URIs.
2023-08-2923.0.8641PythonAdded
  • Added support for SQLAlchemy 2.0.
2023-06-2023.0.8571GeneralAdded
  • Added the new sys_lastresultinfo system table.
2023-05-1923.0.8539PythonAdded
  • Added support for Python 3.11 on Windows, Linux and Mac.
2023-05-1623.0.8536PythonRemoved
  • Removed support for Python 3.7 on Windows and Linux
2023-04-2523.0.8515GeneralRemoved
  • Removed support for the SELECT INTO CSV statement. The core code doesn't support it anymore.
2023-04-1423.0.8504XMLAdded
  • Added support for the ListFiles stored procedure.
2022-12-1422.0.8383GeneralChanged
  • Added the Default column to the sys_procedureparameters table.
2022-12-0922.0.8378XMLAdded
  • Added the WriteToFile parameter for CreateSchema. This defaults to true and must be disabled to write the schema to FileStream or FileData.
2022-12-0922.0.8378XMLRemoved
  • Removed the FileLocation parameter from CreateSchema. The Location property must be used to set the output directory for created schemas.
2022-11-1522.0.8354PythonChanged
  • Updated embedded JRE to jre8u345-b01(Linux x64 / MacOS x64) and jre-17.0.5+8(MacOS aarch64).
2022-10-3122.0.8339XMLAdded
  • Added support the RefreshOAuth operation which can be used to refresh authentication on long-running queries. It is intended for use where a single script triggers multiple network requests to APIs that use OAuth. It may be invoked with `<api:call op="utiladoRefreshOAuth" />`.
2022-09-3022.0.8308GeneralChanged
  • Added the IsPath column to the sys_procedureparameters table.
2022-09-1422.0.8292XMLAdded
  • Added support for the following file extensions: .tar,.tar.gz,.zip and .gz .Examples:URI=C:\\file_example.tar.gz\\file_example4.zip\\simple XML\\subfolder\\file_example5.zip.gz\\simple XML\\single_object.xml;URI=dropbox://DRIVERS-16547/file_example.tar.gz/file_example2.tar/single_object.xml.gz;
2022-08-3022.0.8277XMLAdded
  • Added support for uploading server-side encrypted objects for Amazon S3 storage source via ServerSideEncryption connection property.
2022-05-2722.0.8182XMLAdded
  • Added ConnectionType connection property to determine the storage type of specified URI.
2022-05-1822.0.8173PythonAdded
  • Added support for Python 3.10 on Windows, Linux, and Mac
  • Added support for Python 3.9 on Mac
  • Added support for Mac M1
2022-05-1822.0.8173PythonRemoved
  • Removed support for Python 3.6 on Windows and Linux
2022-03-1521.0.8109XMLAdded
  • Added support for using JWT with generic http:// sources. Previously it was only available for specific types of sources like gdrive://. Custom JWT is currently only supported for authorization grants, not client credentials.
2022-03-1021.0.8104XMLAdded
  • Added support for Apache HDFS (webhdfs://) as a storage source.
2022-03-0921.0.8103XMLChanged
  • Changed the default method for submitting client_credentials grants with OAuth. Before, client_credentials would submit OAuthClientId and OAuthClientSecret using the HTTP Authorization header. Now the OAuthPasswordGrantType controls this setting and it defaults to OAuthPasswordGrantType=Post. The previous behavior is still available by setting OAuthPasswordGrantType=Basic.
2022-02-1621.0.8082XMLAdded
  • Added support for the XMLFormat property which can be set to XML or XMLTable. XMLTable is a new format which allows column names and values to be stored on separate elements, instead of the usual behavior where the element name determines the column name. Useful for generic table layouts where element names are generic and the actual column name is on an attribute or other element.
2022-01-1321.0.8048XMLAdded
  • Added support for IBM Cloud Object Storage (ibmobjectstorage://) as a storage source.
2022-01-0721.0.8042XMLAdded
  • Added support the sleep operation which can be used to add delays to table operations. This is intended for use with async APIs built around polling. It may be invoked with `<api:call op="utiladoSleep?timeout=x" />` where x is the delay in seconds.
2021-10-0721.0.7950XMLAdded
  • Added support for excluding files based on the ExcludeFiles connection property.
  • Added support for datetime filters in IncludeFiles and ExcludeFiles connection properties. We currently support CreatedDate and ModifiedDate. Ex: ``` ExcludeFiles="TXT,CreatedDate<='2020-11-26T07:39:34-05:00'" ExcludeFiles="TXT,ModifiedDate<=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 50, 000)" ExcludeFiles="ModifiedDate>=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 49, 000),ModifiedDate<=CURRENT_TIMESTAMP()" ```
  • Only the following storage sources will have support for filtering by CreatedDate:
    • Box (box://)
    • GCloudStorage (gs://)
    • GoogleDriveStorageSource (gdrive://)
    • OneDrive (onedrive://)
    • SharePoint (sp://)
    • SharePointREST (sprest://)
2021-09-0221.0.7915GeneralAdded
  • Added support for the STRING_SPLIT table-valued function in the CROSS APPLY clause.
2021-08-0721.0.7889GeneralChanged
  • Added the KeySeq column to the sys_foreignkeys table.
2021-08-0621.0.7888GeneralChanged
  • Added the new sys_primarykeys system table.
2021-07-2321.0.7874GeneralChanged
  • Updated the Literal Function Names for relative date/datetime functions. Previously, relative date/datetime functions resolved to a different value when used in the projection as opposed to the predicate. For example: SELECT LAST_MONTH() AS lm, Col FROM Table WHERE Col > LAST_MONTH(). Formerly, the two LAST_MONTH() methods would resolve to different datetimes. Now, they will match.
  • As a replacement for the previous behavior, the relative date/datetime functions in the criteria may have an 'L' appended to them. For example: WHERE col > L_LAST_MONTH(). This will continue to resolve to the same values that were previously calculated in the criteria. Note that the "L_" prefix will only work in the predicate - it not available for the projection.
2021-06-2421.0.7845XMLAdded
  • Added support for the GOOGLEJSONBLOB JWT certificate type. This works like the existing GOOGLEJSON certificate type except that the certificate is provided as JSON text instead of as a file path.
2021-06-0821.0.7829XMLAdded
  • Added support for the AzureServicePrinciple authentication scheme, which will support both using an OAuthClientSecret, or alternatively using a JWT cert.
2021-06-0521.0.7826XMLAdded
  • Added support to authenticate submitting JWT certs instead of the OAuthClientSecret for the AzureAD authentication scheme.
2021-04-2521.0.7785GeneralAdded
  • Added support for handling client side formulas during insert / update. For example: UPDATE Table SET Col1 = CONCAT(Col1, " - ", Col2) WHERE Col2 LIKE 'A%'
2021-04-2321.0.7783GeneralChanged
  • Updated how display sizes are determined for varchar primary key and foreign key columns so they will match the reported length of the column.
2021-04-2321.0.7783XMLDeprecated
  • SSODomain will not be used anymore for OKTA, OneLogin and ADFS. Instead, Domain should be specified.
  • The AzureAccount connection property is deprecated. Instead, AzureStorageAccount should be used.
2021-04-1621.0.7776GeneralAdded
  • Non-conditional updates between two columns is now available to all drivers. For example: UPDATE Table SET Col1=Col2
2021-04-1621.0.7776GeneralChanged
  • Reduced the length to 255 for varchar primary key and foreign key columns.
2021-04-1621.0.7776GeneralChanged
  • Updated implicit and metadata caching to improve performance and support for multiple connections. Old metadata caches are not compatible - you need to generate new metadata caches if you are currently using CacheMetadata.
2021-04-1621.0.7776GeneralChanged
  • Updated index naming convention to avoid duplicates.
2021-04-1521.0.7775GeneralChanged
  • Kerberos authentication is updated to use TCP by default, but will fall back to UDP if a TCP connection cannot be established.
2021-03-2621.0.7755XMLChanged
  • Updated the way default table names are computed so that the file name is taken The provider will now consistently use the following values when naming the table that uses the root XPath. In order: - The value of the roottablename input attribute, if given. - The value of the TableName connection property, if given. This is a new property for XML and its functonality is the same as the JSON property of the same name. - The filename of either the MetadataDiscoveryURI, or the first URI if that is not provided. The filename does not include the extension. If there is no URI, or the filename is empty (e.g. "/home/user/.xml"), or the URI is for HTTP/HTTPS then the URI is ignored. - The value "XMLData".
  • This change does not apply when the connection is in backwards compatibility mode.
2020-12-2120.0.7660XMLAdded
  • Added support for reporting special types for aggregates. If the user opts in via SupportNativeDataType and are using JDBC, then the driver will report XML as the type name for aggregate columns (nlike JSON there is no XMLArray / XMLObject distinction)

CData Python Connector for XML

Modeling XML Data

In this section we will show how to control the various schemes that the connector offers to bridge the gap with relational SQL and XML services. The CData Python Connector for XML provides a managed way for you to use the two prevailing techniques for dealing with nested XML data:

  • Parsing the data structure and building a relational model based on the existing hierarchy.
  • Drilling down into the nested elements using horizontal and vertical flattening.

Parsing Hierarchical Data

By default, the connector automatically detects the rows in a document, so that you do not need to know the structure of the XML to query it with SQL. Set the DataModel property to choose a basic configuration of how the connector models the rows into tables.

Flattening Objects and Arrays into Rows

To flatten data, you only need to be familiar with two data structures:

  • Object: Any parent element that does not repeat at the same height.
  • Array: Any element that repeats at the same height.

In the following example from the people collection, maintenance is an object array, since each maintenance node has child elements.

<maintenance>
  <date>07-17-2017</date>
  <desc>oil change</desc>
</maintenance>
<maintenance>
  <date>01-03-2018</date>
  <desc>new tires</desc>
</maintenance> 

Configuring Automatic Schema Discovery

The connector discovers columns and data types by scanning the RowScanDepth count of XML objects in XML arrays. Set the FlattenObjects and FlattenArrays properties to configure how nested data is flattened into columns; see Automatic Schema Discovery for examples.

Executing SQL to XML

Any relation you can access through flattening you can also access with an ad-hoc SQL query. The connector enables you to query nested data with the following capabilities:

Customizing Schemas

Customizing Schemas enables you to project your chosen relational structure on top of an XML document. This allows you to choose the names of columns, their data types, and the locations of their values in the document.

System Catalog

The System Tables reflect the schemas you configured, custom schemas or dynamically discovered. The Stored Procedures surface additional functionality in the connector's data processing operations that cannot be modeled as SELECT, INSERT, UPDATE, or DELETE. You can find the reported stored procedures defined in .rsb files in the folder specified by Location -- if Location is not specified, the db subfolder of the installation directory.

CData Python Connector for XML

Raw Data

Below is the raw data used throughout this chapter. The data includes entries for people, the cars they own, and various maintenance services performed on those cars:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <rootAttr1>rootValue1</rootAttr1>
  <people>
    <personal>
      <age>20</age>
      <gender>M</gender>
      <name>
        <first>John</first>
        <last>Doe</last>
      </name>
    </personal>
    <jobs>support</jobs>
    <jobs>coding</jobs>
    <vehicles>
      <type>car</type>
      <model>Honda Civic</model>
      <insurance>
        <company>ABC Insurance</company>
        <policy_num>12345</policy_num>
      </insurance>
      <features>sunroof</features>
      <features>rims</features>
      <maintenance>
        <date>07-17-2017</date>
        <desc>oil change</desc>
      </maintenance>
      <maintenance>
        <date>01-03-2018</date>
        <desc>new tires</desc>
      </maintenance>
    </vehicles>
    <vehicles>
      <type>truck</type>
      <model>Dodge Ram</model>
      <insurance>
        <company>ABC Insurance</company>
        <policy_num>12345</policy_num>
      </insurance>
      <features>lift kit</features>
      <features>tow package</features>
      <maintenance>
        <date>08-27-2017</date>
        <desc>new tires</desc>
      </maintenance>
      <maintenance>
        <date>01-08-2018</date>
        <desc>oil change</desc>
      </maintenance>
    </vehicles>
    <addresses>
      <type>work</type>
      <zip>12345</zip>
    </addresses>
    <addresses>
      <type>home</type>
      <zip>12357</zip>
    </addresses>
    <source>internet</source>
  </people>
  <people>
    <personal>
      <age>24</age>
      <gender>F</gender>
      <name>
        <first>Jane</first>
        <last>Roberts</last>
      </name>
    </personal>
    <jobs>sales</jobs>
    <jobs>marketing</jobs>
    <source>phone</source>
    <vehicles>
      <type>car</type>
      <model>Toyota Camry</model>
      <insurance>
        <company>Car Insurance</company>
        <policy_num>98765</policy_num>
      </insurance>
      <features>upgraded stereo</features>
      <maintenance>
        <date>05-11-2017</date>
        <desc>tires rotated</desc>
      </maintenance>
      <maintenance>
        <date>11-03-2017</date>
        <desc>oil change</desc>
      </maintenance>
    </vehicles>
    <vehicles>
      <type>car</type>
      <model>Honda Accord</model>
      <insurance>
        <company>Car Insurance</company>
        <policy_num>98765</policy_num>
      </insurance>
      <features>custom paint</features>
      <features>custom wheels</features>
      <maintenance>
        <date>10-07-2017</date>
        <desc>new air filter</desc>
      </maintenance>
      <maintenance>
        <date>01-13-2018</date>
        <desc>new brakes</desc>
      </maintenance>
    </vehicles>
    <addresses>
      <type>home</type>
      <zip>98765</zip>
    </addresses>
    <addresses>
      <type>work</type>
      <zip>98753</zip>
    </addresses>
  </people>
  <rootAttr2>rootValue2</rootAttr2>
  <rootAttr3>rootValue3</rootAttr3>
  <rootAttr3>rootValue4</rootAttr3>
</root>

CData Python Connector for XML

Parsing Hierarchical Data

The connector offers three basic configurations to model nested data in XML as tables.

  • Flattened Documents Model: Implicitly join nested object arrays into a single table.
  • Relational Model: Model object arrays as individual tables containing a primary key and a foreign key that links to the parent document.
  • Top-Level Document Model: Model a top-level view of an XML document. Nested object arrays are returned as XML aggregates.

CData Python Connector for XML

Flattened Documents Model

For users who simply need access to the entirety of their XML data, flattening the data into a single table is the best option. The connector will use streaming and only parses the XML data once per query in this mode.

Joining Object Arrays into a Single Table

With DataModel set to "FlattenedDocuments", the connector returns a separate table for each object array, but implicitly JOINed to the parent table. Any nested sibling XPath values (child paths at the same height) will be treated as a SQL CROSS JOIN.

Example

Below is a sample query and the results, based on the sample document in Raw Data and parsing based on the XPaths /root/people, /root/people/vehicles, and /root/people/vehicles/maintenance. This implicitly JOINs the people element with the vehicles element and implicitly JOINs the vehicles element with the maintenance element.

Connection String

Use the following connection string to query the Raw Data in this example.

URI=C:\people.txt;DataModel=FlattenedDocuments;XPath='/root/people;/root/people/vehicles;/root/people/vehicles/maintenance;'

Query

The following query drills into the nested elements in each people element. Since the XPath property included the vehicles node as an XML path, you can query an element of a vehicle explicitly.

SELECT
  [personal.age] AS age,
  [personal.gender] AS gender,
  [personal.name.first] AS name_first,
  [personal.name.last] AS name_last,
  [source],
  [type],
  [model],
  [insurance.company] AS ins_company,
  [insurance.policy_num] AS ins_policy_num,
  [date] AS maint_date,
  [desc] AS maint_desc
FROM
  [people]

Results

With horizontal and vertical flattening based on the described paths, each vehicle element is implicitly JOINed to its parent people element and each maintenance element is implicitly JOINed to its parent vehicle element.

agegenderfirst_namelast_namesourcetypemodelins_companyins_policy_nummaint_datemaint_desc
20MJohnDoeinternetcarHonda CivicABC Insurance123452017-07-17oil change
20MJohnDoeinternetcarHonda CivicABC Insurance123452018-01-03new tires
20MJohnDoeinternettruckDodge RamABC Insurance123452017-08-27new tires
20MJohnDoeinternettruckDodge RamABC Insurance123452018-01-08oil change
24FJaneRobertsphonecarToyota CamryCar Insurance987652017-05-11tires rotated
24FJaneRobertsphonecarToyota CamryCar Insurance987652017-11-03oil change
24FJaneRobertsphonecarHonda AccordCar Insurance987652017-10-07new air filter
24FJaneRobertsphonecarHonda AccordCar Insurance987652018-01-13new brakes

See Also

CData Python Connector for XML

Top-Level Document Model

Using a top-level document view of the data provides ready access to top-level elements. The connector returns nested elements in aggregate, as single columns.

One aspect to consider is performance. You forego the time and resources to process and parse nested elements -- the connector parses the returned data once, using streaming to read the data. Another consideration is your need to access any data stored in nested parent elements, and the ability of your tool or application to process XML.

Modeling a Top-Level Document View

With DataModel set to "Document" (the default), the connector scans only a single element, the top-level element by default. The top-level elements are available as columns due to default object flattening. Nested elements are returned as aggregated XML.

You can set XPath to specify an element other than the top-level one.

Example

Below is a sample query and the results, based on the sample document in Raw Data. The query results in a single "people" table based on the XPath "/root/people".

Connection String

Set the DataModel connection property to "Document" to perform the following query and see the example result set. The connector will scan only the XPath value below:

URI=C:\people.txt;DataModel=Document;XPath='/root/people';

Query

The following query pulls the top-level elements and the subelements of the vehicles element into the results.

SELECT
  [personal.age] AS age,
  [personal.gender] AS gender,
  [personal.name.first] AS name_first,
  [personal.name.last] AS name_last,
  [source],
  [vehicles]
FROM
  [people]
  

Results

With a document view of the data, the personal element is flattened into 4 columns and the source and vehicles elements are returned as individual columns, resulting in a table with 6 columns.

agegendername_firstname_lastsourcevehicles
20MJohnDoeinternet
  <vehicles><type>car</type><model>Honda Civic</model><insurance><company>ABC Insurance</company><policy_num>12345</policy_num></insurance><features>sunroof</features><features>rims</features><maintenance><date>07-17-2017</date><desc>oil change</desc></maintenance><maintenance><date>01-03-2018</date><desc>new tires</desc></maintenance></vehicles><vehicles><type>truck</type><model>Dodge Ram</model><insurance><company>ABC Insurance</company><policy_num>12345</policy_num></insurance><features>lift kit</features><features>tow package</features><maintenance><date>08-27-2017</date><desc>new tires</desc></maintenance><maintenance><date>01-08-2018</date><desc>oil change</desc></maintenance></vehicles>
24FJaneRobertsphone
  <vehicles><type>car</type><model>Toyota Camry</model><insurance><company>Car Insurance</company><policy_num>98765</policy_num></insurance><features>upgraded stereo</features><maintenance><date>05-11-2017</date><desc>tires rotated</desc></maintenance><maintenance><date>11-03-2017</date><desc>oil change</desc></maintenance></vehicles><vehicles><type>car</type><model>Honda Accord</model><insurance><company>Car Insurance</company><policy_num>98765</policy_num></insurance><features>custom paint</features><features>custom wheels</features><maintenance><date>10-07-2017</date><desc>new air filter</desc></maintenance><maintenance><date>01-13-2018</date><desc>new brakes</desc></maintenance></vehicles>

See Also

CData Python Connector for XML

Relational Model

The CData Python Connector for XML can be configured to create a relational model of the data in the XML file or source, treating each XPath as an individual table containing a primary key and a foreign key that links to the parent document. This is particularly useful if you need to work with your XML data in existing BI, reporting, and ETL tools that expect a relational data model.

Joining Nested Arrays as Tables

With DataModel set to "Relational", any JOINs are controlled by the query. Any time you perform a JOIN query, the XML file or source will be queried once for each table included in the query.

Example

Below is a sample query against the sample document in Raw Data, using a relational model based on the XML paths "/root/people", "/root/people/vehicles", and "/root/people/vehicles/maintenance".

Connecting String

Set the DataModel connection property to "Relational" and set the XPath connection property to "/root/people;/root/people/vehicles;/root/people/vehicles/maintenance;" to perform the following query and see the example result set.

URI=C:\people.txt;DataModel=Relational;XPath='/root/people;/root/people/vehicles;/root/people/vehicles/maintenance;'

Query

The following query explicitly JOINs the people, vehicles, and maintenance tables.

SELECT 
  [people].[personal.age] AS age, 
  [people].[personal.gender] AS gender, 
  [people].[personal.name.first] AS first_name, 
  [people].[personal.name.last] AS last_name, 
  [people].[source], 
  [vehicles].[type], 
  [vehicles].[model], 
  [vehicles].[insurance.company] AS ins_company, 
  [vehicles].[insurance.policy_num] AS ins_policy_num, 
  [maintenance].[date] AS maint_date, 
  [maintenance].[desc] AS maint_desc
FROM 
  [people]
JOIN 
  [vehicles] 
ON 
  [people].[_id] = [vehicles].[people_id]
JOIN 
  [maintenance] 
ON 
  [vehicles].[_id] = [maintenance].[vehicles_id]

Results

In the example query, each maintenance element is JOINed to its parent vehicle element, which is JOINed to its parent people element to produce a table with 8 rows (2 maintenance entries for each of 2 vehicles each for 2 people).

agegenderfirst_namelast_namesourcetypemodelins_companyins_policy_nummaint_datemaint_desc
20MJohnDoeinternetcarHonda CivicABC Insurance123452017-07-17oil change
20MJohnDoeinternetcarHonda CivicABC Insurance123452018-01-03new tires
20MJohnDoeinternettruckDodge RamABC Insurance123452017-08-27new tires
20MJohnDoeinternettruckDodge RamABC Insurance123452018-01-08oil change
24FJaneRobertsphonecarToyota CamryCar Insurance987652017-05-11tires rotated
24FJaneRobertsphonecarToyota CamryCar Insurance987652017-11-03oil change
24FJaneRobertsphonecarHonda AccordCar Insurance987652017-10-07new air filter
24FJaneRobertsphonecarHonda AccordCar Insurance987652018-01-13new brakes

See Also

CData Python Connector for XML

Automatic Schema Discovery

By default, the connector automatically infers a relational schema by inspecting a series of XML objects in an array. This section describes the connection properties available to configure these dynamic schemas.

Discovering Tables

This section shows how to fine-tune the discovered schemas by fine-tuning the row scan. The rows detected depend on the RowScanDepth, DataModel, and XPath properties.

  • RowScanDepth: This setting determines the number of object arrays to scan to find the rows and discover the columns. The process follows nested objects, counting 1 object array as 1 row.
  • DataModel: Select how you want to represent the object arrays as tables. This setting also affects the objects that are scanned: the Relational and FlattenedDocuments settings will find all object arrays (including nested ones) in RowScanDepth items. The Document setting will only find the first object array.

  • XPath: Set this to explicitly specify the object arrays you want to expose. Note that if DataModel is set to Document, you can only set one, top-level XPath. See Parsing Hierarchical Data for examples of accessing a sample document with different XPath values.

Discovering Columns

The columns identified during the discovery process depend on the FlattenArrays and FlattenObjects properties. If FlattenObjects is set (this is the default), nested objects will be flattened into a series of columns. For example, consider the following document:

<company>
  <id>12</id>
  <name>Lohia Manufacturers Inc.</name>
  <address>
    <street>Main Street</street>
    <city>Chapel Hill</city>
    <state>NC</state>
  </address>
  <office>Chapel Hill</office>
  <office>London</office>
  <office>New York</office>
  <annual_revenue>35,600,000</annual_revenue>
</company> 
With the default object flattening, this document will be represented by the following columns:

Column NameData TypeExample Value
idInteger12
nameStringLohia Manufacturers Inc.
address.streetStringMain Street
address.cityStringChapel Hill
address.stateStringNC
officeString<office>Chapel Hill</office><office>London</office><office>New York</office>
annual_revenueDouble35,600,000

If FlattenObjects is not set, then the address.street, address.city, and address.state columns will not be broken apart. The address column of type string will instead represent the entire object. Its value would be the following:

<address><street>Main Street</street><city>Chapel Hill</city><state>NC</state></address>

The FlattenArrays property can be used to flatten array values into columns of their own. This is only recommended for arrays that are expected to be short, for example the offices array below:

<office>London</office>
<office>Los Angeles</office>
The FlattenArrays property can be set to 2 to represent the array above as follows:

Column NameData TypeExample Value
office.0StringLondon
office.1StringLos Angeles

It is best to leave other unbounded arrays as they are and piece out the data for them as needed using XML Functions.

CData Python Connector for XML

Free-Form Queries

As discussed in Automatic Schema Discovery, intuited table schemas enable SQL access to unstructured XML data. Customizing Schemas enables you to define static tables and gives you more granular control over the relational view of your data; for example, you can change the data types reported. However, you are not limited to the schema's view of your data.

You can query any nested structure without flattening the data. Any relations that you can access through Automatic Schema Discovery can also be accessed with an ad hoc SQL query.

Extended Projection Syntax

In the SELECT clause, use dot notation to specify an XPath to the data, as in the following query.

SELECT [personal.name.last], [personal.name.first], [vehicles.1.type], [vehicles.1.model] FROM people WHERE [personal.name.last] = 'Roberts' AND [personal.name.first] = 'Jane'

Note that to specify the path to a specific array element, specify the element's ordinal position. Arrays have a zero-based index, so the preceding query retrieves the second vehicle.

Example

The preceding query draws the column names from the example people document in Raw Data. Below is a person object from the array of people:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <rootAttr1>rootValue1</rootAttr1>
  <people>
    <personal>
      <age>20</age>
      <gender>M</gender>
      <name>
        <first>John</first>
        <last>Doe</last>
      </name>
    </personal>
    <jobs>support</jobs>
    <jobs>coding</jobs>
    <vehicles>
      <type>car</type>
      <model>Honda Civic</model>
      <insurance>
        <company>ABC Insurance</company>
        <policy_num>12345</policy_num>
      </insurance>
      <features>sunroof</features>
      <features>rims</features>
      <maintenance>
        <date>07-17-2017</date>
        <desc>oil change</desc>
      </maintenance>
      <maintenance>
        <date>01-03-2018</date>
        <desc>new tires</desc>
      </maintenance>
    </vehicles>
    <vehicles>
      <type>truck</type>
      <model>Dodge Ram</model>
      <insurance>
        <company>ABC Insurance</company>
        <policy_num>12345</policy_num>
      </insurance>
      <features>lift kit</features>
      <features>tow package</features>
      <maintenance>
        <date>08-27-2017</date>
        <desc>new tires</desc>
      </maintenance>
      <maintenance>
        <date>01-08-2018</date>
        <desc>oil change</desc>
      </maintenance>
    </vehicles>
    <addresses>
      <type>work</type>
      <zip>12345</zip>
    </addresses>
    <addresses>
      <type>home</type>
      <zip>12357</zip>
    </addresses>
    <source>internet</source>
  </people>
</root> 

Connection String

With the following connection string, the connector will not parse nested data -- the data is processed when you execute the query. The properties of the top-level object are still flattened through the default FlattenObjects functionality. Nested data is returned as an XML aggregate.

URI=C:\people.txt;DataModel=Document;XPath='/root/people;'

Query

You can access any nested structure in the Raw Data document as a column:

SELECT [personal.name.last], [personal.name.first], [vehicles.1.type], [vehicles.1.model] FROM people WHERE [personal.name.last] = 'Roberts' AND [personal.name.first] = 'Jane'

Note that arrays have a zero-based index. The preceding query retrieves the example person's second vehicle.

Results

The preceding query returns the following results:

Column NameData TypeExample Value
personal.name.firstStringJane
personal.name.lastStringRoberts
vehicles.1.typeStringcar
vehicles.1.modelStringHonda Accord

CData Python Connector for XML

Vertical Flattening

Vertical flattening queries enable you to retrieve a nested element as if it were a separate table.

Vertical Flattening Query Syntax

In the FROM clause, you can use dot notation to drill down to a nested element.

SELECT * FROM [people.vehicles] 

Example

Consider a single array element from the Raw Data document -- a person object from an array of people:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
<people>
  <personal>
    <age>20</age>
    <gender>M</gender>
    <name>
      <first>John</first>
      <last>Doe</last>
    </name>
  </personal>
  <vehicles>
    <type>car</type>
    <model>Honda Civic</model>
    <insurance>
      <company>ABC Insurance</company>
      <policy_num>12345</policy_num>
    </insurance>
    <maintenance>
      <date>07-17-2017</date>
      <desc>oil change</desc>
    </maintenance>
    <maintenance>
      <date>01-03-2018</date>
      <desc>new tires</desc>
    </maintenance>
  </vehicles>
  <vehicles>
    <type>truck</type>
    <model>Dodge Ram</model>
    <insurance>
      <company>ABC Insurance</company>
      <policy_num>12345</policy_num>
    </insurance>
    <maintenance>
      <date>08-27-2017</date>
      <desc>new tires</desc>
    </maintenance>
    <maintenance>
      <date>01-08-2018</date>
      <desc>oil change</desc>
    </maintenance>
  </vehicles>
  <source>internet</source>
</people>
</root> 
  

Connection String

With the following connection string, the connector will not parse nested data -- the data is processed when you execute the query. Due to the default FlattenObjects functionality, the properties of the top-level element are flattened. Nested data is returned as an XML aggregate.

URI=C:\people.txt;DataModel=Document;XPath='/root/people;'

Query

Vertical flattening will allow you to retrieve the vehicles element as a separate table:

SELECT * FROM [people.vehicles]
This query returns the following data set:

featuresinsurance.companyinsurance.policy_nummaintenancemodeltype

<features>sunroof</features><features>rims</features>
ABC Insurance12345
<maintenance><date>07-17-2017</date><desc>oil change</desc></maintenance><maintenance><date>01-03-2018</date><desc>new tires</desc></maintenance>
Honda Civiccar

<features>lift kit</features><features>tow package</features>
ABC Insurance12345
<maintenance><date>08-27-2017</date><desc>new tires</desc></maintenance><maintenance><date>01-08-2018</date><desc>oil change</desc></maintenance>
Dodge Ramtruck

<features>upgraded stereo</features>
Car Insurance98765
<maintenance><date>05-11-2017</date><desc>tires rotated</desc></maintenance><maintenance><date>11-03-2017</date><desc>oil change</desc></maintenance>
Toyota Camrycar

<features>custom paint</features><features>custom wheels</features>
Car Insurance98765
<maintenance><date>10-07-2017</date><desc>new air filter</desc></maintenance><maintenance><date>01-13-2018</date><desc>new brakes</desc></maintenance>
Honda Accordcar

CData Python Connector for XML

XML Functions

The connector can return XML as column values. The connector enables you to use SQL functions to work with these column values. The following sections provide examples; for a reference, see STRING Functions. The examples in this section use the following array (see Parsing Hierarchical Data for more information on parsing XML objects and arrays):

 
<grades>
  <student>
    <grade>A</grade>
    <score>2</score>
  </student>
  <student>
    <grade>A</grade>
    <score>6</score>
  </student>
  <student>
    <grade>A</grade>
    <score>10</score>
  </student>
  <student>
    <grade>A</grade>
    <score>9</score>
  </student>
  <student>
    <grade>B</grade>
    <score>14</score>
  </student>
</grades>

XML_EXTRACT

The XML_EXTRACT function can extract individual values from an XML object. The following query returns the values shown below based on the XML path passed as the second argument to the function:
SELECT Name, XML_EXTRACT(grades,'[0].grade') AS Grade, XML_EXTRACT(grades,'[0].score') AS Score FROM Students;

Column NameExample Value
GradeA
Score2

XML_COUNT

The XML_COUNT function returns the number of elements in an XML array within an XML object. The following query returns the number of elements specified by the XML path passed as the second argument to the function:
SELECT Name, XML_COUNT(grades,'[x]') AS NumberOfGrades FROM Students;

Column NameExample Value
NumberOfGrades5

XML_SUM

The XML_SUM function returns the sum of the numeric values of an XML array within an XML object. The following query returns the total of the values specified by the XML path passed as the second argument to the function:
SELECT Name, XML_SUM(score,'[x].score') AS TotalScore FROM Students;

Column NameExample Value
TotalScore 41

XML_MIN

The XML_MIN function returns the lowest numeric value of an XML array within an XML object. The following query returns the minimum value specified by the XML path passed as the second argument to the function:
SELECT Name, XML_MIN(score,'[x].score') AS LowestScore FROM Students;

Column NameExample Value
LowestScore2

XML_MAX

The XML_MAX function returns the highest numeric value of an XML array within an XML object. The following query returns the maximum value specified by the XML path passed as the second argument to the function:
SELECT Name, XML_MAX(score,'[x].score') AS HighestScore FROM Students;

Column NameExample Value
HighestScore14

CData Python Connector for XML

Customizing Schemas

You can customize the table schemas detected through Automatic Schema Discovery to change column names and data types, enable update functionality, and more. The processing operations of the CData Python Connector for XML hide the complexity of processing data and communicating with remote data sources, but they also expose control over these layers through custom schemas.

Custom schemas are defined in configuration files. In this chapter we outline the structure of these files.

Generating Schema Files

Generating Schema Files allows you to persist and customize the dynamic schemas discovered through Automatic Schema Discovery.

Editing Schema Files

Tables and views are defined by authoring schema files in APIScript. APIScript is a simple configuration language that allows you to define the columns and the behavior of the table. It also has built-in operations that enable you to process XML. In addition to these data processing primitives, APIScript is a full-featured language with constructs for conditionals, looping, etc. However, as shown by the example schema, for most table definitions you will not need to use these features.

Example Schema

Below is a fully functional table schema that models the people document in the Raw Data example and contains all the components you will need to execute SQL to local or remote XML.

The schema reflects the following connection string, which returns a single table containing the data delineated by the specified XPaths -- see Parsing Hierarchical Data for a guide to the different DataModel settings.

DataModel=FLATTENEDDOCUMENTS;URI=C:\people.xml;XPath='/root/people;/root/people/vehicles;/root/people/vehicles/maintenance';Location=C:\myschemas;GenerateSchemaFiles=OnStart;

You can find more information on each of the components of a schema in Column Definitions, SELECT Execution, INSERT Execution, UPDATE Execution, and DELETE Execution. You can also create stored procedures to implement capabilities of your API that cannot be modeled as SELECT, INSERT, UPDATE, or DELETE statements. See Defining Stored Procedures for more information.

  <api:script>
     <api:info title="Persons" desc="Parse the OData Persons feed.">
    <!-- You can modify the name, type, and column size here. -->
    <!-- See Column Definitions to specify column behavior and use XPaths to extract column values from XML. -->
      <attr name="ID"           xs:type="int" key="true" readonly="false"   other:xPath="/feed/entry/content/properties/ID" />
      <attr name="EmployeeID"   xs:type="int"            readonly="true"    other:xPath="/feed/entry/content/properties/EmployeeID" />
      <attr name="Name"         xs:type="string"         readonly="false"   other:xPath="/feed/entry/content/properties/Name" />
      <attr name="TotalExpense" xs:type="double"         readonly="true"    other:xPath="/feed/entry/content/properties/TotalExpense" />
      <attr name="HireDate"     xs:type="datetime"       readonly="true"    other:xPath="/feed/entry/content/properties/HireDate" />
      <attr name="Salary"       xs:type="int"            readonly="true"    other:xPath="/feed/entry/content/properties/Salary" />
    </api:info>
    
    <api:set attr="uri" value="http://services.odata.org/V4/OData/(S(5cunewekdibfhpvoh21u2all))/OData.svc/Persons" /> 
  
    <!-- The XPath attribute of a schema is the path to a repeating element that defines the separation of rows -->
    <api:set attr="XPath" value="/feed/entry/" />
  
    <!-- See the xmlproviderGet page in the Operations subchapter to set any needed HTTP parameters. -->
    <api:set attr="ContentType"   value="application/atom+xml" />
  
  <!-- The GET method corresponds to SELECT. Here you can change the parameters of the request for data. The results of processing are pushed to the schema's output. See SELECT Execution for more information. -->
  <api:script method="GET">
    <api:call op="xmlproviderGet">
      <api:push/>
    </api:call>
  </api:script> 
  
  <!-- To add support for INSERTS please see the INSERT Execution page within the help for further information and examples. -->
  <api:script method="POST">
    <api:set attr="method" value="POST"/>
    <api:call op="xmlproviderGet">
      <api:throw code="500" desc="Inserts are not currently supported."/>
      <api:push/>
    </api:call>
  </api:script>

  <!-- To add support for UPDATES please see the UPDATE Execution page within the help for further information and examples. -->
  <api:script method="MERGE">
    <api:set attr="method" value="PUT"/>
    <api:call op="xmlproviderGet">
      <api:throw code="500" desc="Updates are not currently supported."/>
      <api:push/>
    </api:call>
  </api:script>

  <!-- To add support for DELETES please see the DELETE Execution page within the help for further information and examples. -->
  <api:script method="DELETE">
    <api:set attr="method" value="DELETE"/>
    <api:call op="xmlproviderGet">
      <api:throw code="500" desc="Deletes are not currently supported."/>
      <api:push/>
    </api:call>
  </api:script>

  </api:script> 

CData Python Connector for XML

Generating Schema Files

To gain more control over the schemas discovered dynamically through Automatic Schema Discovery, you can save the schema to a configuration file. The GenerateSchemaFiles property enables you to automatically generate schemas based on the data modeling settings configured in the connection string. The CreateSchema stored procedure enables you to create schemas for other XPaths after you connect.

Generating Schema Files Automatically

You can generate schemas when you connect or when you execute a query. The connector will save the schemas to the folder specified by Location.

  • Set GenerateSchemaFiles to OnStart to generate schemas for all tables detected when you connect.
  • Set GenerateSchemaFiles to OnUse to generate a schema for the referenced table when you query the table.

Using the CreateSchema Stored Procedure

You can call the CreateSchema stored procedure to generate a schema for the XPaths you specify. Below are the stored procedure's inputs and outputs.

Input

Name Type Description
TableName String The name of the table and also the name of the schema (RSD) file.
URI String The Uniform Resource Identifier (URI) of the XML resource.
XPath String The XPath of an element that repeats at the same height within the XML document. (This is used to split the document into multiple rows). You can specify multiple paths in a semicolon-separated list.
FileLocation String The folder path where the generated schema (RSD) file will be stored. When specified the TableName will be used as the schema file name.
FileName String The complete schema (RSD) file name of the generated schema. This input takes precedence over FileLocation.

Output

Name Type Description
Result String Returns Success or Failure.

Example Stored Procedure Call

With DataModel set to FLATTENDOCUMENTS in the connection string, the example stored procedure call below results in a schema that flattens all the XPath arrays into a single table.

See Flattened Documents Model for more information on this data model.

EXECUTE CreateSchema TableName='GenPeople', 
FileLocation='C:\\tests\\scripts', 
URI='C:\\tests\\people.xml', 
XPath='/root/people;/root/people/vehicles;/root/people/vehicles/maintenance'

Next Steps

  • Column Definitions: Change column names and data types or the XPath to the column value.
  • SELECT Execution: Access the HTTP request -- for example, to implement server-side searches.
  • INSERT Execution: Enable inserts by mapping inputs from the INSERT statement to an HTTP request.
  • UPDATE Execution: Enable updates by mapping the updated column values to an HTTP request.
  • DELETE Execution: Enable deletes by mapping the primary key to an HTTP request.

CData Python Connector for XML

Column Definitions

The basic attributes of a column are the name of the column, the data type, whether the column is a primary key, and the XPath. The connector uses the XPath to extract nodes from hierarchical data.

Mark up column attributes in the api:info block of the schema file. Set the XPath in the other:xPath property, as shown in the example below.

<api:info title="Persons" desc="Parse the OData Persons feed.">
    <attr name="ID"           xs:type="int" key="true" readonly="false"   other:xPath="content/properties/ID" />
    <attr name="EmployeeID"   xs:type="int"            readonly="true"    other:xPath="content/properties/EmployeeID" />
    <attr name="Name"         xs:type="string"         readonly="false"   other:xPath="content/properties/Name" />
    <attr name="TotalExpense" xs:type="double"         readonly="true"    other:xPath="content/properties/TotalExpense" />
    <attr name="HireDate"     xs:type="datetime"       readonly="true"    other:xPath="content/properties/HireDate" />
    <attr name="Salary"       xs:type="int"            readonly="true"    other:xPath="content/properties/Salary" />
  </api:info>
The following sections provide more detail on using XPaths to extract columns and rows. To see the column definitions in a complete schema, refer to Customizing Schemas.

Defining Column XPaths

The other:xPath property is used to specify the XPath that selects the column's value.

Absolute paths start with a '/' and contain the full XPath to the nested data.

<attr name="ID"           xs:type="int" key="true" other:xPath="/feed/entry/content/properties/ID" /> 

Indexed XPath values can also be used to specify an element within the XML document in the case that multiple elements with the same name are nested at the same level. The indexes are zero based.

<api:info>
  <attr name=PhoneNumber1 xs:type="string" other:xPath="Person/PhoneNumber[0]"/>
  <attr name=PhoneNumber2 xs:type="string" other:xPath="Person/PhoneNumber[1]"/>
</api:info>

Notes:

  • XPaths and column names (when used to generate the XPath) are case sensitive.
  • Any paths specified outside an XPath will only be retrieved if they are found prior to a row (XPath) being found, with the exception of the last row pushed (which will push all found paths). This is due to each row being pushed in a streaming fashion.

Defining Row XPaths

A row XPath specifies the path to an element that repeats at the same height -- an object array that the connector splits into rows. With DataModel set to FlattenedDocuments or Relational, you can specify more than one XPath in a semicolon-separated list. See Parsing Hierarchical Data for guides to these data modeling strategies.

The connection string can define the XPath property or you can define the row XPath as an attribute of an individual schema. Use the api:set keyword to define the row XPaths for a schema. With DataModel set to FlattenedDocuments or Relational, you can specify more than one XPath in a semicolon-separated list.

<api:set attr="XPath" value="/root/people;/root/people/vehicles;/root/people/vehicles/maintenance" /> 

A wildcard XPath can also be used and is helpful in the case that the XPaths are all at the same height but contain different names:

<api:set  attr="XPath" value="/feed/*" />

Defining Column Value Formats

You can set the other:valueFormat property to "aggregate" to identify a column as an aggregate.

  • The aggregate option will return the XML aggregate found at the XPath specified. For example, consider the following:
        <repeat>
        <name>TestAggregate</name>
        <myobjcol1>
          <object1>myData</object1>
          <object1>myData1</object1>
          <object2>myData2</object2>
        </myobjcol1>
        </repeat>
        
    The following example extracts the myobjcol1 element to a column named MyObjCol1:
        <api:info>
          <attr name="MyObjCol1" xs:type="string" other:xPath="myobjcol1" other:valueFormat="aggregate"/>
        </api:info>
        <api:set attr="XPath" value="/repeat"/>
        
    This column value will be the following:
        <myobjcol1>
          <object1>myData</object1>
          <object1>myData1</object1>
          <object2>myData2</object2>
        </myobjcol1>
        

Mapping SELECT criteria to query parameters

Some APIs will support filtering the results of a request by specifying a query parameter. If this parameter maps to a WHERE clause, you can use the other:filter property to program this mapping.

  • other:filter is a semicolon separated list of <parameter name>:<operator list>. <parameter name> is the name of the query parameter and <operator list> is a comma-separated list of operators used for the mapping. Valid operators are <, <=, =, >, >=, and LIKE.

The below example is for two query parameters, 'modifiedSince' and 'modifiedBefore', which filter the results based on the 'modifiedAt' column.

    <attr name="ModifiedAt"           xs:type="datetime" readonly="false"   other:xPath="content/properties/modifiedAt" other:filter="modifiedBefore:<;modifiedSince:>,>=,=" />
    

This example would take the query statement

SELECT * 
FROM <table> 
WHERE modifedAt < '<datetime>'
and generate a request that appends the query parameter '&modifiedBefore=<url encoded datetime>' to the url.

CData Python Connector for XML

SELECT Execution

When a SELECT query is issued, the connector executes the GET method of the schema, which invokes the connector's built-in operations to process XML. In the GET method you have control over the request for data. The following procedures show several ways to use this: search the remote data, server-side, with SELECT WHERE, LIMIT the results returned by the server, or implement paging.

Query Processing

By default, the connector will process the query client-side, in memory, so the XPath and URI connection properties are all you need to set to execute any SELECT statement.

The connector can also offload supported queries to the server while processing the rest of the query client side. For example, a server-side search filters the data so that a smaller dataset can be processed client-side.

Execute Selects to XML

The following steps result in a script that allows you to execute SQL-92 queries. The queries are processed client side. Before invoking a data processing operation, you will need to provide the URI and, optionally, the XPath. Use the api:set keyword to declare these attributes.

  1. Set the URI attribute to a local file or an HTTP-accessible address.

    <api:set  attr="uri"                      value="NorthwindOData.xml" /> 

  2. If needed, set the XPath attribute to the XPath of the data that constitutes an individual row. By default, the connector will scan the document to detect the rows (see Parsing Hierarchical Data).

    <api:set  attr="XPath" value="/feed/entry/" /> 

  3. Invoke the operation in the GET method. Inside the script block, use the api:push keyword to invoke the operation. Specify the operation with the op parameter. This keyword pushes the results of processing to the schema's output.

    <api:script method="GET">
      <api:set attr="method" value="GET"/>
      <api:set attr="uri" value="[uri]?$format=atom"/>
      <api:call op="xmlproviderGet">
        <api:push />
      </api:call>
    </api:script>

You can extend the resulting script to add support for processing requests server side.

Process SELECT WHERE on the Server

The following sections show how to translate a SELECT WHERE statement into a search request to XML APIs. The procedure uses the following statement:

SELECT * 
FROM <table> 
WHERE modifedAt < '2017-10-10' AND modifedAt > '2017-09-01'

If this filter is supported on the server via query parameters, you can use the other:filter property of the api:info column definition to specify the desired mapping. For the above query, we will use this property to map the modifiedAt < '<date>' filter to the query parameter that returns results that were modifed before a given date, and the modifedAt > '<date>' filter to the query parameter that filters results that were modifed after. other:filter is specified as follows:

  • other:filter is a semicolon separated list of <parameter name>:<operator list>. <parameter name> is the name of the query parameter and <operator list> is a comma-separated list of operators used for the mapping. Valid operators are <, <=, =, >, >=, and LIKE.

To perform this mapping, we would use the following markup for the modifedAt column definition:

    <attr name="modifiedAt"           xs:type="datetime" readonly="false"   other:xPath="content/properties/modifiedAt" other:filter="modifiedBefore:<;modifiedSince:>" />
    

This query results in the following request:

[url]?modifedBefore=2017-10-10&modifedSince=2017-09-01

If your API filter is not passed in a query parameter, you will need to pass it in the script. For example, consider an API that filters by name by querying the /persons/{name}/data endpoint.

SELECT *
FROM Persons 
WHERE (Name = 'Fran Wilson') 

In the GET method of the schema, use the attributes of the _input item, one of the Items in API Script, to access the search criteria and build the HTTP data retrieval request. The corresponding script below builds the request. The api:check element is useful for checking the existence of an attribute before attempting to access its value. A variety of Value Formatters are available to do transformations, like URL-encoding a string.

<api:script method="GET">
  <api:check attr="_input.Name">
    <api:set attr="uri" value="[uri]/[_input.name|urlencode]/data"/>
  </api:check>
</api:script>

Searching with Pseudo Columns

You can specify a pseudo column in the WHERE clause to build search criteria using inputs other than the columns returned in the results.

For example, in the Weather Underground API, you can return a forecast for a specified location. The Location itself is not part of the forecast data; it is specified in the request URI, as in the request below.

http://api.wunderground.com/api/{MyAPIKey}/hourly/q/{MyLocation}.xml 

Below is an example forecast query expressed in SQL:

SELECT * FROM Hourly WHERE Location="27516"

Follow the steps below to add a Location pseudo column and implement the preceding query:

  1. Add a Location input parameter to the column definitions in the api:info block. (The Location will be required; the connector should return an error if a Location is not specified.)
    <api:info>
      ...
      <input  name="Location"                 required="true"/>
    </api:info>
  2. Reference the _input item's Location attribute to build the URI:
    <api:set attr='uri' value="http://api.wunderground.com/api/[_connection.APIKey]/hourly/q/[_input.Location].xml"/>
  3. Invoke the operation to make the request and process the response:
    <api:script method="GET" >
      <api:push op="xmlproviderGet"/>
    </api:script> 

Implement Paging

To support automatic paging, add the 'Rows@Next' input to the list of columns in the api:info block.

<input name="rows@next" desc="Identifier for the next page of results. Do not set this value manually." />
Note that making this an input parameter instead of an attr parameter will prevent it from showing up in column listings. You will also need to set the 'EnablePaging' attribute to TRUE to turn off the driver's internal paging mechanism.
<api:set attr="EnablePaging" value="TRUE" />

The driver supports four types of paging implementations automatically. The first is when the URL of the next page is returned in the response. The second type involves specifying your current page offset in a query parameter. The third type is where you send the current page number in a query parameter. The fourth requires sending a page token in the query parameter of the next request. If your API utilizes one of these paging patterns, follow the below examples to implement paging:

Next Page URL

When the service returns the URL for the next page in the response body or header, set the 'pageurlpath' attribute to the location of this data. If a value is present at this location, it will be used to set the URL of the next request.

  • If the next page URL is passed in the response body, set 'pageurlpath' to the XPath of the element.
    <api:set  attr="pageurlpath"                             value="/data/nextPage" /> 
  • If the next page URL is passed in the response header with a 'Link' header, you can prefix 'pageurlpath' with header: to denote its location. If the returned 'Link' header value contains a partial URL path, you can set the 'BaseURI' attribute to the base URL that should be prepended to the url path returned in the 'Link' header.
    <api:set  attr="pageurlpath"                             value="header:Link" /> 

Paging Token

Sometimes a token is returned in the response body that should be passed to a paging parameter in the subsequent request. In this case, you can set the 'pagetokenparam' and 'pagetokenpath' attributes. 'pagetokenpath' should be set to the XPath of the element. Some services also send a variable that denotes whether or not there are more pages, if that is the case you can also set the 'hasmorepath' attribute to its XPath.

  • If the page token is passed in a query parameter, set 'pagetokenparam' to the name of the parameter.
    <api:set  attr="pagetokenpath"                        value="/data/token" /> 
    <api:set  attr="hasmorepath"                          value="/data/has_more" /> 
    <api:set  attr="pagetokenparam"                       value="nextpagetoken" /> 
    If has_more is true, this will pass the token at /data/token to the next query: ?nextpagetoken=<token>
  • Sometimes the token needs to be passed in the request body. You can do that by setting 'pagetokenparam' to its XPath.
    <api:set  attr="pagetokenpath"                        value="/request/nextpagetoken" /> 

Record Offset

If the service provides a record offset query parameter to control paging, you can implement this by setting the name of the offset query parameter, the name of the page size query parameter, and the page size to be passed. Note that the page size parameter does not need to be set if there is no parameter to control this. In this case, you must set pagesize to the default page size.


<api:set  attr="pageoffsetparam"                      value="offset" /> 
<api:set  attr="pagesizeparam"                        value="limit" /> 
<api:set  attr="pagesize"                             value="100" /> 

Page Number

Similar to record offset, if the service provides a query parameter that sets the page number, you can implement this by setting the name of the page number query parameter, the name of the page size query parameter, and the page size to be passed. Note that the page size parameter does not need to be set if there is no parameter to control this. In this case, you must set pagesize to the default page size.


<api:set  attr="pagenumberparam"                      value="page" /> 
<api:set  attr="pagesizeparam"                        value="pagesize" /> 
<api:set  attr="pagesize"                             value="100" /> 

Other Paging Types

If your API does not follow any of those paging patterns, you will need a custom paging implementation. This is done by setting the information needed from the first page in the 'Rows@Next' attribute. When the 'Rows@Next' value is set in the output, the connector will automatically call the method again with the 'Rows@Next' value in the input after it is finished returning results for this page. You can use the value of this input to modify the request on the next pass to get the next page of data. Set the Rows@Next input to any information needed to make the request for the next page of data.

For example, your API may return the next page's URL in the response. You can obtain this value by providing the XPath to the URL:

<api:set  attr="elementmappath#"  value="/next_page" />
<api:set  attr="elementmapname#"  value="rows@next" /> 
You can then modify the URL where the request is made, provided the value is set. Use the api:check element to first check if the Rows@Next input has a value. The Rows@Next input can be accessed as an attribute of the _input item:
<api:check attr="_input.rows@next">
  <api:set  attr="uri"  value="[_input.rows@next]" />
  <api:else>
    <api:set  attr="uri"  value="<first page's URL>" />
  </api:else>
<api:check> 

Process Other SELECT Statements Server Side

You can build any HTTP request in the GET method. Use the _query item to access other components of the SELECT query. In the GET method, the _query item has the following attributes that describe the query that was issued to the connector:

queryThe SQL query. For example:
SELECT Id, Name FROM Accounts WHERE City LIKE '%New%' AND COUNTRY = 'US' GROUP BY CreatedDate ORDER BY Name LIMIT 10,50;
selectcolumnsA comma-separated list containing the columns specified in the SELECT statement. For example, the Id and Name columns in the example.
tableThe table name specified in the SELECT statement. For example, Accounts in the example.
criteriaThe WHERE clause of the statement.
City LIKE '%New%' AND COUNTRY = 'US'
orderbyThe columns specified in the ORDER BY clause. For example, Name in the example.
groupbyThe GROUP BY clause in the SELECT statement. For example, CreatedDate in the example.
limitThe limit specified in the LIMIT or TOP clauses of the SELECT statement. For example, 50 in the example.
offsetThe offset specified in the LIMIT or TOP clauses of the SELECT statement. For example, 10 in the example.
isjoinWhether the query is a join.
jointableThe table to be joined.
isschemaonlyWhether the query retrieves only schema information.

Process LIMIT on the Server

If your API supports it, you can implement the LIMIT clause to restrict the number of results that need to be retrieved from the server.

Reference the value of the _query item's limit attribute when you build the API request. In the OData API, a limit can be specified with the $top query string parameter, shown below.

http://services.odata.org/V3/Northwind/Northwind.svc/Customers?$top=10

Below is the corresponding script:

<api:check attr="_query.limit">
  <api:set  attr="uri"      value="http://services.odata.org/V3/Northwind/Northwind.svc/Customers?$top=[_query.limit]" />
</api:check> 

Keyword Reference

See the API Script Reference for more information on the keywords used in this section:

CData Python Connector for XML

INSERT Execution

When an INSERT statement is executed, the connector executes the POST method of the schema, where you can build the HTTP insert request.

Execute Inserts to XML

In the POST method, the _input item, one of the Items in API Script, contains the columns to insert. For example, consider the following statement:

INSERT INTO Persons
(Name, Id)
VALUES
('Maria Anders','7') 

You can use the _input item's attributes to set these column values in the HTTP insert request. In the OData API, this is an HTTP POST. The POST data to make the preceding insert in the OData API is below:

<entry xmlns:d="http://docs.oasis-open.org/odata/ns/data" xmlns:m="http://docs.oasis-open.org/odata/ns/metadata" xmlns="http://www.w3.org/2005/Atom">
  <category scheme="http://docs.oasis-open.org/odata/ns/scheme" term="ODataDemo.Person" />
  <content type="application/xml">
    <m:properties>
      <d:Name m:type="Edm.String">Maria Anders</d:Name>
      <d:ID m:type="Edm.Int32">7</d:ID>
    </m:properties>
  </content>
</entry>
In the example schema's corresponding POST method, the required columns are first validated and then used to define the POST data. You can check that a column was provided and alert the user otherwise with the api:validate keyword.

After validating that the needed attributes exist, you can set the column values in the POST data. Set the "data" attribute to the POST data -- the body of the api:set keyword is convenient for setting long or multiline values like this.

The api:call keyword invokes the operation that will make the HTTP request. Before invoking the operation, use api:set to set the method attribute to the HTTP method you want within the scope of the api:script keyword.

<api:script method="POST">
    <api:set attr="method" value="POST"/>
    <api:validate attr="_input.Name" desc="Name and Id are required to insert." />
    <api:validate attr="_input.Id" desc="Name and Id are required to insert." />
    <api:set attr="data">
      <entry xmlns:d="http://docs.oasis-open.org/odata/ns/data" xmlns:m="http://docs.oasis-open.org/odata/ns/metadata" xmlns="http://www.w3.org/2005/Atom">
        <category scheme="http://docs.oasis-open.org/odata/ns/scheme" term="ODataDemo.Person" />
        <content type="application/xml">
          <m:properties>
            <d:Name m:type="Edm.String">[_input.Name]</d:Name>
            <d:ID m:type="Edm.Int32">[_input.Id]</d:ID>
          </m:properties>
        </content>
      </entry>
    </api:set>
    <api:call op="xmlproviderGet"/>
  </api:script>
  
Note that an INSERT statement can sometimes return data, for example, the generated Id of the new record. If you want to access values returned from an insert, use the api:push keyword instead of the api:call keyword.

Access Components of INSERT Statements

In the POST method, the _query item contains the following attributes:

queryThe SQL statement, as in the following statement:
INSERT INTO Account (account_name, account_type) VALUES ('Contoso','Company')
tableThe table in the SQL statement. For example, Account in the preceding query.

Keyword Reference

See the API Script Reference for more information on the keywords used in this section:

CData Python Connector for XML

UPDATE Execution

When an UPDATE statement is executed, the connector executes the MERGE method of the schema, where you can build the HTTP update request.

To see this method in a complete example, refer to Customizing Schemas.

Execute Updates to XML

In the MERGE method, the _input item, one of the Items in API Script, contains the columns to update. For example, consider the following statement:

UPDATE Persons 
SET Name='Ana Trujilo'
WHERE Id = '7' 

You can use the _input item's attributes to set these column values in the HTTP update request. In the OData API, this can be an HTTP PUT or PATCH. The PUT data to make the preceding update in the OData API is below:

<entry xmlns:d="http://docs.oasis-open.org/odata/ns/data" xmlns:m="http://docs.oasis-open.org/odata/ns/metadata" xmlns="http://www.w3.org/2005/Atom">
  <id>http://services.odata.org/V4/OData/%28S%28tjlj1hwyun3kt2iv0ef21c2d%29%29/OData.svc//Persons(ID=4)</id>
  <category scheme="http://docs.oasis-open.org/odata/ns/scheme" term="ODataDemo.Person" />
  <content type="application/xml">
    <m:properties>
      <d:ID m:type="Edm.Int32">4</d:ID>
        <d:Name m:type="Edm.String">Ana Trujilo</d:Name>
    </m:properties>
  </content>
</entry>
In the example schema's corresponding MERGE method, the required column, the primary key, is validated and then used in the PUT data and the URL. You can check that an input was provided and alert the user otherwise with the api:validate keyword.

After validating that the needed attributes exist, you can set the column values in the PUT data. Set the "data" attribute to the PUT data -- the body of the api:set keyword is convenient for setting long or multiline values like this.

The api:call keyword invokes the operation that will make the HTTP request. Before invoking the operation, use api:set to set the method attribute to the HTTP method you want within the scope of the api:script keyword.

<api:script method="MERGE">
  <api:set attr="method" value="PUT"/>
  <api:validate attr="_input.Id" desc="An Id is required to update." />
  <api:set attr="data">
    <entry xmlns:d="http://docs.oasis-open.org/odata/ns/data" xmlns:m="http://docs.oasis-open.org/odata/ns/metadata" xmlns="http://www.w3.org/2005/Atom">
      <api:set attr="uri" value="[uri]([_input.Id])" />
      <id>[uri]</id>
      <category scheme="http://docs.oasis-open.org/odata/ns/scheme" term="ODataDemo.Person" />
      <content type="application/xml">
        <m:properties>
          <d:ID m:type="Edm.Int32">[_input.Id]</d:ID>
          <api:check attr="_input.Name">
            <d:Name m:type="Edm.String">[_input.Name]</d:Name>
          </api:check>
        </m:properties>
      </content>
    </entry>
  </api:set>
  <api:call op="xmlproviderGet"/>
</api:script>

Access the Components of UPDATE Statements

In the MERGE method, the _query item contains the following attributes:

queryThe SQL statement, as in the following statement:
UPDATE Account SET Name='John' WHERE Id = @myId
tableThe table in the SQL statement. For example, Account in the preceding query.
criteriaThe WHERE clause of the statement. For example, the following WHERE clause in the example:
Id = @myId
nullupdatesThe columns of an UPDATE statement, separated by commas, that contain a null value or a null parameter value.

Keyword Reference

See the API Script Reference for more information on the keywords used in this section:

CData Python Connector for XML

DELETE Execution

When a DELETE statement is executed, the connector executes the DELETE method of the schema, where you can build the HTTP delete request.

To see this method in a complete example, refer to Customizing Schemas.

Execute Deletes to XML

In the DELETE method, the _input item, one of the Items in API Script, will contain the primary key of the record to delete. For example, consider the following statement:

DELETE FROM Persons WHERE Id = '7'

Below is the corresponding delete request in the OData API:

DELETE myapi.com/Persons(7)

In the corresponding DELETE method below, the required column, the primary key, is first validated and then used to modify the URI in an HTTP DELETE request:

<api:script method="DELETE">
  <api:set attr="method" value="DELETE"/>
  <api:validate attr="_input.Id" desc="An Id is required to delete." />
  <api:set attr="uri" value="[uri]([_input.Id])" />
  <api:call op="xmlproviderGet"/>
</api:script>
  

You can check that an input was provided and alert the user otherwise with the api:validate keyword. After validating that the primary key attribute exists, you can specify the primary key in the request URI. Use the api:set keyword to set the URI value.

The api:call keyword invokes the operation that will make the HTTP request. Before invoking the operation, set the method attribute to the HTTP method you want within the scope of the api:script keyword.

Access Components of DELETE Statements

In the DELETE script, the _query item contains the following attributes:

queryThe SQL statement, as in the following statement:
DELETE FROM Account WHERE Id = @myId
tableThe table in the SQL statement. For example, Account in the preceding query.
criteriaThe WHERE clause of the statement. For example, the following WHERE clause in the example:
Id = @myId

Keyword Reference

See the API Script Reference for more information on the keywords used in this section:

CData Python Connector for XML

Raw Data

Below is the structure of the Persons XML document used in the custom schema examples. This data is a simplified version of the XML response from the odata.org Northwind test service. This service is used to demonstrate data manipulation operations to XML-based REST APIs.

 
<values odata.context="http://services.odata.org/V4/OData/OData.svc/$metadata#Persons">
  <value>
    <ID>0</ID>
    <Name>Paula Wilson</Name>
  </value>
  <value>
    <ID>1</ID>
    <Name>Jose Pavarotti</Name>
  </value>
  <value>
    <ID>2</ID>
    <Name>Art Braunschweiger</Name>
  </value>
  <value odata.type="#ODataDemo.Customer">
    <ID>3</ID>
    <Name>Liz Nixon</Name>
    <TotalExpense>99.99</TotalExpense>
  </value>
  <value odata.type="#ODataDemo.Customer">
    <ID>4</ID>
    <Name>Liu Wong</Name>
    <TotalExpense>199.99</TotalExpense>
  </value>
  <value odata.type="#ODataDemo.Employee">
    <ID>5</ID>
    <Name>Jaime Yorres</Name>
    <EmployeeID>10001</EmployeeID>
    <HireDate>2000-05-30T00:00:00Z</HireDate>
    <Salary>15000</Salary>
  </value>
  <value odata.type="#ODataDemo.Employee">
    <ID>6</ID>
    <Name>Fran Wilson</Name>
    <EmployeeID>10002</EmployeeID>
    <HireDate>2001-01-02T00:00:00Z</HireDate>
    <Salary>12000</Salary>
  </value>
</values>

CData Python Connector for XML

Defining Stored Procedures

Stored procedures are function-like interfaces to the data source that can be used to search, modify, or delete data. Stored procedures model actions that typically cannot be represented as SELECT, INSERT, UPDATE, or DELETE statements. Modeling stored procedures is a similar process to modeling tables in that you can use the same built-in data processing operations to implement stored procedures.

Stored Procedure Schemas vs. Table Schemas

With minor modifications, you can follow the same process to create a stored procedure that you would follow to add support for INSERT, UDPATE, and DELETE statements: define stored procedures in .rsb files, which, like .rsd files, consist of an info block and scripts that call data processing operations.

Instead of columns, the info block defines the input and output parameters of the stored procedure. Instead of the attr element, define inputs with the input element in the info block.

As with other SQL statements, when the stored procedure is executed, the _input item contains the input parameters. You can use the _input item to map the stored procedure inputs to the operation inputs.

As with table schemas, you can use the info block to process the response. Describe the outputs of a stored procedure with the output attribute in the info block. In the output attributes, you can specify the XPaths to extract nodes of hierarchical data.

Example Stored Procedure

The following stored procedure retrieves a Person record given their Id. This fully functional schema shows how to build the request and use XPaths to parse the response.

A stored procedure executes the GET method of the schema. Build the API request in this method: check that required inputs were provided and alert the user otherwise with the api:validate keyword. Use Value Formatters to simplify working with strings, dates, and math expressions.

Invoke the operation with the api:call keyword. To return data, insert the api:push keyword in the scope of the operation call.

<api:script xmlns:api="http://www.rssbus.com/ns/rsbscript/2">

  <api:info title="GetODataPersonById" description="Retrieves the OData Person specified by Id.">
    <output name="ID"            other:xPath="/feed/entry/content/properties/ID" />
    <output name="EmployeeID"    other:xPath="/feed/entry/content/properties/EmployeeID" />
    <output name="Name"          other:xPath="/feed/entry/content/properties/Name" />
    <output name="TotalExpense"  other:xPath="/feed/entry/content/properties/TotalExpense" />
    <output name="HireDate"      other:xPath="/feed/entry/content/properties/HireDate" />
    <output name="Salary"        other:xPath="/feed/entry/content/properties/Salary" />  
  </api:info>
  
  <api:set attr="uri" value="http://services.odata.org/V4/OData/(S(5cunewekdibfhpvoh21u2all))/OData.svc/Persons" /> 
  
  <!-- The XPath attribute of the schema splits the XML into rows based on elements that repeat at the same level. -->
  <api:set attr="XPath" value="/entry/" />

  <!-- See the xmlproviderGet page in the Operations subchapter to set any needed HTTP parameters. -->
  <api:set attr="ContentType"   value="application/atom+xml" />

  <!-- The GET method corresponds to EXECUTE. Within the script block, you can see the URI modified to append a query string parameter. The results of processing are pushed to the schema's output.  -->
  <api:script method="GET">
    <api:set attr="method" value="GET"/>
    <api:set attr="uri" value="[uri]([_input.Id])?$format=atom"/>
    <api:call op="xmlproviderGet">
      <api:push />
    </api:call>
  </api:script>
	
</api:script>

Keyword Reference

See the API Script Reference for more information on the keywords used in this section:

CData Python Connector for XML

Operations

The connector has high-performance operations for processing XML data sources. These operations are platform neutral: Schema files that invoke these operations can be used in both .NET and Java. You can also extend the connector with your own operations written in .NET or Java.

The connector has the following operations:

Operation NameDescription
xmlproviderGetThe xmlproviderGet operation is an APIScript operation that is used to process XML content. It allows you to split XML content into rows.
oauthGetAccessTokenFor OAuth 1.0, exchange a request token for an access token. For OAuth 2.0, get an access token or get a new access token with the refresh token.
oauthGetUserAuthorizationURLGenerates the user authorization URL. OAuth 2.0 will not access the network in this operation.
utiladoSleepSuspends processes for a specified duration (in seconds).
utiladoPushPageTokenPushes a page token value to rows@next without pushing a row to the result set.

CData Python Connector for XML

xmlproviderGet

The xmlproviderGet operation is an APIScript operation that is used to process local and remote XML content. It allows you to split XML content into rows.

Required Parameters

  • URI: The URI parameter specifies the location of the XML content. This URI scheme can be file:// for local files or can specify a remote data source: http:// (or https://), s3://, gdrive://, box://, or ftp:// (ftps://). The URI connection property can also provide this input.
  • XPath: The XPath parameter is used to split the document into multiple rows. The connector will detect the row XPaths in the document when the DataModel property is set to FlattenedDocuments or Relational. See Parsing Hierarchical Data for a guide to configuring how the data is modeled.

    The XPath connection property can also provide the row XPaths. Specify the XPaths as absolute paths; define multiple paths in a semicolon-separated list.

    A wildcard XPath can also be used and is helpful in the case that the XPaths are all at the same height but contain different names:

    <rsb:set  attr="XPath" value="/feed/*" />

HTTP Operation

The xmlproviderGet operation can be used to make HTTP requests to XML data sources and process the results. It abstracts the complexity of connecting to XML-based REST APIs but also gives you control over the layers involved, providing the following inputs to configure authentication, the HTTP request and headers, and firewall traversal.

Column Mapping

The xmlproviderGet operation reads the Column Definitions from the api:info section of the table schema file. In the column definition, the other:xPath property maps the column value to an XML element.

Input Parameters

You can use api:set to specify the operation's input parameters, as shown below.

<rsb:set  attr="uri"                      value="NorthwindOData.xml" /> 

The connection properties also pass inputs to the operation; setting one of the following input attributes in the schema will override the connection property.

Processing

  • URI: The URI parameter specifies the location of the XML content. This URI scheme can be file:// for local files or can specify a remote data source: http:// (or https://), s3://, gdrive://, box://, or ftp:// (ftps://).
  • XPath: The XPath parameter is used to split the document into multiple rows. The connector will detect the row XPaths in the document when the DataModel property is set to FlattenedDocuments or Relational. See Parsing Hierarchical Data for a guide to configuring how the data is modeled.

    You can also set the XPath connection property to delineate the paths to the tables. Specify absolute paths and define multiple paths in a semicolon-separated list.

    A wildcard XPath can also be used and is helpful in the case that the XPaths are all at the same height but contain different names:

    <rsb:set  attr="XPath" value="/feed/*" />

HTTP

  • Method: The HTTP method that corresponds to the SQL data manipulation statement. The allowed values are GET, POST, PUT, DELETE, and MERGE. The default value is GET.
  • ContentType: The content type of the HTTP post. Relevant only if data is specified.
  • Data: Data to include in the put or the post. To post a file use a file:// URI.
  • Text: Input XML text (an alternative to URI).
  • Header:Name#: The name for each custom header to pass with the request.
  • Header:Value#: The value for each custom header to pass with the request.
  • ParamName#: The name for each parameter to pass with the request.
  • ParamValue#: The value for each parameter to pass with the request.
  • Cookie:*: Any cookies that should be added to the request.
  • Timeout: The timeout, in seconds, for the operation to complete. Zero (0) means no timeout. The default value is 60.
  • LogFile: The file where exchanged/transferred data is logged.
  • PushResponseHeader#: The response headers which should be returned from this operation. Any headers added to this list are returned as header:* parameters.
  • PushResponseCookie#: The response cookies which should be returned from this operation. Any cookies added to this list are returned as cookie:* parameters.

Authentication

  • User: The username used for authentication.
  • Password: The password used for authentication.
  • AuthScheme: The authentication method to use. Only relevant if User and Password are provided. The allowed values are BASIC, DIGEST, NONE, NTLM, NEGOTIATE. The default value is BASIC.
  • KerberosKDC: The KDC setting of Kerberos, available when AuthScheme is NEGOTIATE.
  • KerberosRealm: The Realm setting of Kerberos, available when AuthScheme is NEGOTIATE.
  • KerberosToken: The Kerberos token used for authentication.

OAuth

  • Version: The OAuth version. The allowed values are DISABLED, 1.0, 2.0. The default value is DISABLED.
  • Token: The access token for OAuth.
  • Token_Secret: The access token secret. OAuth 1.0 only.
  • Client_Id: The OAuth client Id. OAuth 1.0 only.
  • Client_Secret: The OAuth client secret. OAuth 1.0 only.
  • Sign_Method: The signature method used to calculate the signature for OAuth 1.0. The allowed values are HMAC-SHA1, PLAINTEXT. The default value is HMAC-SHA1.
  • Other_Options: Other options to control the behavior of OAuth.

Proxy

  • Proxy_Auto: Whether or not the proxy should be detected from Windows system settings. This takes precedence over other proxy settings and is not available in Java. The allowed values are TRUE, FALSE. The default value is FALSE.
  • Proxy_Server: IP address or host name of the proxy server used for the request.
  • Proxy_Port: The port number of the proxy server.
  • Proxy_User: The user Id used to authenticate with the proxy server.
  • Proxy_Password: The password used to authenticate with the proxy server.
  • Proxy_AuthScheme: The authentication scheme of the proxy server. The allowed values are BASIC, DIGEST, NONE, NTLM. The default value is BASIC.
  • Proxy_AuthToken: The proxy authentication token.
  • Proxy_SSLType: The SSL type of the proxy server. The allowed values are AUTO, ALWAYS, NEVER, TUNNEL. The default value is AUTO.

Firewall

  • Firewall_Server: The IP address or host name of the firewall.
  • Firewall_Port: The port number of the firewall.
  • Firewall_User: The user Id used to authenticate with the firewall.
  • Firewall_Password: The password used to authenticate with the firewall.
  • Firewall_Type: The type of the firewall. The allowed values are NONE, TUNNEL, SOCKS4, and SOCKS5. The default value is NONE.

Advanced Processing

  • ElementMapPath#: The XPath to the subelement that you want to specify as columns within your chosen row. This can be relative to the item (for example, title) or absolute (for example, /rss/@version).
  • ElementMapName#: The name of the chosen ElementMapPath. The ElementMapName input can be used to give a name to the XPath chosen in ElementMapPath.
  • ElementArrayMapPath#: The XPath to the element that you want to specify as an array.
  • ElementArrayMapName#: The name of the chosen ElementArrayMapPath. The ElementArrayMapName input can be used to give a name to the XPath chosen in ElementArrayMapPath.
  • AggregateFormat: The format to use with aggregate values. The allowed values are JSON, XML. The default value is XML.
  • AggregatePath#: The XPath to the element that you want to return as an aggregate.
  • AggregateName#: The name of the chosen aggregate. The AggregateName input can be used to give a name to the XPath chosen in AggregatePath.
  • ResultCodeXPath: The XPath of the result code element in the response.
  • ResultSuccessCode: The success code of the value located at ResultCodeXPath that is used to verify and identify the request as being successful.
  • ErrorMsgXPath: The XPath of the error message returned in the response.
  • IndexParentNodes: Multiple occurrences of the same element will be indexed if this is set to true. If set to false, multiple occurrences will be combined into an array. The allowed values are TRUE, FALSE. The default value is TRUE.
  • PushPrefix: The prefix to be prepended to each item attribute that is pushed.
  • EnablePaging: Specifies whether the Rows@Next input will be used for paging. The allowed values are TRUE, FALSE. The default value is FALSE.
  • OutputPrefix: Whether the prefix should be output with each pushed attribute of an item. The allowed values are TRUE, FALSE. The default value is FALSE.
  • PushOuterValueRow: Whether to generate special rows for paths outside of the repeat element when no other rows would contain them. If one of these rows is generated it will contain the values of all mapped paths outside the repeat element, along with a special attribute called @isoutervalue which is set to true. However, if there is a row in the repeat element which contains these values then the @isoutervalue is not pushed.

    The allowed values are TRUE, FALSE. The default value is FALSE.

Output Parameters

  • *: The elements and the attributes found within each item element.
  • header:*: Any headers requested from the PushResponseHeader# input (e.g. adding "Content-Type" to PushResponseHeader# will return "header:Content-Type")
  • cookie:*: Any cookies requested from the PushResponseCookie# input (e.g. adding "session" to PushResponseCookie# will return "cookie:session")
Note If you are using api:push to emit rows from within different invocations of this operation (either separate calls in the schema, or in a loop), it is recommended that you use api:map to copy all the elements from the output item produced by api:call into a temporary item that is then passed to api:push:
<api:call op="xmlproviderGet" out="output">
  <api:map from="output" to="temp" map="* = *" />
  <api:push item="temp" />
</api:call>
The items produced by this operation are required to have the same layout for performance reasons, which may not be the case if different documents are used in calls to this operation. Performing this map converts the item into a more flexible form which does not have the same layout restriction (though it may be slower to read from).

CData Python Connector for XML

oauthGetAccessToken

The oauthGetAccessToken operation is an RSBScript operation that is used to facilitate the OAuth authentication and refresh flows.

The connector includes stored procedures that invoke this operation to complete the OAuth exchange. The following example schema briefly lists some of the typically required inputs before the following sections explain them in more detail.

See Defining Stored Procedures for more information on working with custom stored procedures. For a guide to using the connector to authenticate, see the "Getting Started" chapter.

Creating a GetOAuthAccessToken Stored Procedure

Invoke the oauthGetAccessToken with the GetOAuthAccessToken stored procedure. The following inputs are required for most data sources and will provide default values for the connection properties of the same name.

<rsb:script xmlns:rsb="http://apiscript.com/ns?v1" xmlns:xs="http://www.w3.org/2001/XMLSchema"">

  <rsb:info title="GetOAuthAccessToken"   description="Obtains the OAuth access token to be used for authentication with various APIs."                                                         >
    <input  name="AuthMode"               desc="The OAuth flow. APP or WEB."                                                                                                                    />
    <input  name="CallbackURL"            desc="The URL to be used as a trusted redirect URL, where the user will return with the token that verifies that they have granted your app access. " />
    <input  name="OAuthAccessToken"       desc="The request token. OAuth 1.0 only."                                                                                                             />
    <input  name="OAuthAccessTokenSecret" desc="The request token secret. OAuth 1.0 only."                                                                                                      />
    <input  name="Verifier"               desc="The verifier code obtained when the user grants permissions to your app."                                                                       />

    <output name="OAuthAccessToken"       desc="The access token."                                                                                                                              />
    <output name="OAuthTokenSecret"       desc="The access token secret."                                                                                                                       />
    <output name="OAuthRefreshToken"      desc="A token that may be used to obtain a new access token."                                                                                         />
 </rsb:info>

  <!-- Set OAuthVersion to 1.0 or 2.0. -->
  <rsb:set attr="OAuthVersion"                                                    value="MyOAuthVersion"                 />
  <!-- Set RequestTokenURL to the URL where the request for the request token is made. OAuth 1.0 only.-->
  <rsb:set attr="OAuthRequestTokenURL"                                            value="http://MyOAuthRequestTokenURL" />
  <!-- Set OAuthAuthorizationURL to the URL where the user logs into the service and grants permissions to the application. -->
  <rsb:set attr="OAuthAuthorizationURL"                                           value="http://MyOAuthAuthorizationURL" />
  <!-- Set OAuthAccessTokenURL to the URL where the request for the access token is made. -->
  <rsb:set attr="OAuthAccessTokenURL"                                             value="http://MyOAuthAccessTokenURL"   />
  <!-- Set GrantType to the authorization grant type. OAuth 2.0 only. -->
  <rsb:set attr="GrantType"                                                       value="CODE"                           />
  <!-- Set SignMethod to the signature method used to calculate the signature of the request. OAuth 1.0 only.-->
  <rsb:set attr="SignMethod"                                                      value="HMAC-SHA1"                      />
  <rsb:call op="oauthGetAccessToken">
    <rsb:push/>
  </rsb:call>
  
</rsb:script>

Writing the RefreshOAuthAccessToken Stored Procedure

You can also use oauthGetAccessToken to refresh the access token by providing the following inputs:

<rsb:script xmlns:rsb="http://apiscript.com/ns?v1" xmlns:xs="http://www.w3.org/2001/XMLSchema"">

  <rsb:info title="RefreshOAuthAccessToken" description="Refreshes the OAuth access token used for authentication." >
    <input  name="OAuthRefreshToken"        desc="A token that may be used to obtain a new access token."           /> 
    <output name="OAuthAccessToken"         desc="The authentication token returned."                               />
    <output name="OAuthTokenSecret"         desc="The authentication token secret returned. OAuth 1.0 only."        />
    <output name="OAuthRefreshToken"        desc="A token that may be used to obtain a new access token."           />
    <output name="ExpiresIn"                desc="The remaining lifetime on the access token."                      />

  </rsb:info>

  <!-- Set OAuthVersion to 1.0 or 2.0. -->
  <rsb:set attr="OAuthVersion"                                                    value="MyOAuthVersion"                 />
    <!-- Set GrantType to REFRESH. OAuth 2.0 only. -->
    <rsb:set attr="GrantType"            value="REFRESH" />
    <!-- Set SignMethod to the signature method used to calculate the signature of the request. OAuth 1.0 only.-->
    <rsb:set attr="SignMethod"           value="HMAC-SHA1" />
    <!-- Set OAuthAccessTokenURL to the URL where the request for the access token is made. -->
    <rsb:set attr="OAuthAccessTokenURL"  value="http://MyOAuthAccessTokenURL" />
    <!-- Set AuthMode to 'WEB' when calling RefreshOAuthAccessToken -->
    <rsb:set attr="AuthMode" value="WEB"/>
  <rsb:call op="oauthGetAccessToken">
    <rsb:push/>
  </rsb:call>
  
</rsb:script>

Input Parameters

  • OAuthVersion: The OAuth version. The allowed values are 1.0, 2.0. The default value is 1.0.
  • AuthMode: The OAuth flow. OAuth 2.0 only. If you choose the App mode, this operation will launch your browser and prompt you to authenticate with your account credentials. Set this parameter to WEB to authenticate a Web app or if the connector is not allowed to open a Web browser. The default value is APP.
  • OAuthRequestTokenURL: The URL where the connector makes a request for the request token. OAuth 1.0 only. Required for OAuth 1.0.
  • OAuthAuthorizationURL: The URL where the user logs into the service and grants permissions to the application. In OAuth 1.0, if permissions are granted the request token is authorized.
  • OAuthAccessTokenURL: The URL where the request for the access token is made. In OAuth 1.0, the authorized request token is exchanged for the access token.
  • CallbackURL: The URL to be used as a trusted redirect URL, where the user will return with the token that verifies that they have granted your app access. This value must match the callback URL you specify when you register an app. Note that your data source may additionally require the port.
  • OAuthClientId: The client Id obtained when you register an app. Also called a consumer key.
  • OAuthClientSecret: The client secret obtained when you register an app. Also called a consumer secret.
  • OAuthAccessToken: The request token. OAuth 1.0 only.
  • OAuthAccessTokenSecret: The request token secret. OAuth 1.0 only.
  • OAuthRefreshToken: A token that may be used to obtain a new access token.
  • GrantType: Authorization grant type. OAuth 2.0 only. The allowed values are CODE, PASSWORD, CLIENT, REFRESH. The default value is CODE.
  • Verifier: The verifier code obtained when the user grants permissions to the connector. In the OAuth 2.0 code grant type, the verifier code is located in the code query string parameter of the callback URL. In OAuth 1.0, the verifier is located in the oauth_verifier query string parameter of the callback URL.
  • SignMethod: The signature method used to calculate the signature for OAuth 1.0. The allowed values are HMAC-SHA1, PLAINTEXT. The default value is HMAC-SHA1.
  • Cert: Path for the PFX personal certificate file. OAuth 1.0 only.
  • CertPassword: Personal certificate password. OAuth 1.0 only.
  • OtherOptions: Other options to control the behavior of OAuth.
  • OAuthParam:*: Other parameters.
  • PostData: The HTTP POST data.
  • Timeout: The timeout, in seconds, for the operation to complete. Zero (0) means no timeout. The default value is 60.
  • LogFile: Specifies a file where the request and response are logged.
  • Proxy_Auto: Whether or not the proxy should be detected from Windows system settings. This takes precedence over other proxy settings and is not available in Java. The allowed values are TRUE, FALSE. The default value is FALSE.
  • Proxy_Server: IP address or host name of the proxy server used for the request.
  • Proxy_Port: The port number of the proxy server.
  • Proxy_User: The user Id used to authenticate with the proxy server.
  • Proxy_Password: The password used to authenticate with the proxy server.
  • Proxy_AuthScheme: The authentication scheme of the proxy server. The allowed values are BASIC, DIGEST, NONE, NTLM. The default value is BASIC.
  • Proxy_AuthToken: The proxy authentication token.
  • Proxy_SSLType: The SSL type of the proxy server. The allowed values are AUTO, ALWAYS, NEVER, TUNNEL. The default value is AUTO.
  • Firewall_Type: The type of the firewall. The allowed values are NONE, TUNNEL, SOCKS4, SOCKS5. The default value is NONE.
  • Firewall_Server: The IP address or host name of the firewall.
  • Firewall_Port: The port number of the firewall.
  • Firewall_User: The user Id used to authenticate with the firewall.
  • Firewall_Password: The password used to authenticate with the firewall.

Output Parameters

  • OAuthAccessToken: The access token.
  • OAuthTokenSecret: The access token secret.
  • OAuthRefreshToken: A token that may be used to obtain a new access token.
  • ExpiresIn: The remaining lifetime on the access token.
  • OAuthParam:*: Other parameters sent from the server.

CData Python Connector for XML

oauthGetUserAuthorizationURL

The oauthGetUserAuthorizationURL is an RSBScript operation that is used to facilitate the OAuth authentication flow for Web apps, for offline apps, and in situations where the connector is not allowed to open a Web browser. To pass the needed inputs to this operation, define the GetOAuthAuthorizationURL stored procedure. The connector can call this internally.

Define stored procedures in .rsb files with the same file name as the schema's title. The example schema briefly lists some of the typically required inputs before the following sections explain them in more detail.

For a guide to authenticating in the OAuth flow, see the "Getting Started" chapter. You can find more information about stored procedures and how to write them in Defining Stored Procedures.

Writing the GetOAuthAuthorizationURL Stored Procedure

Call oauthGetUserAuthorizationURL in the GetOAuthAuthorizationURL stored procedure.

<rsb:script xmlns:rsb="http://apiscript.com/ns?v1" xmlns:xs="http://www.w3.org/2001/XMLSchema"">

  <rsb:info title="Get OAuth Authorization URL" description="Obtains the OAuth authorization URL used for authentication with various APIs."                                                          >
    <input  name="CallbackURL"                  desc="The URL to be used as a trusted redirect URL, where the user will return with the token that verifies that they have granted your app access. " />

    <output name="URL"                          desc="The URL where the user logs in and is prompted to grant permissions to the app. "                                                               />
    <output name="OAuthAccessToken"             desc="The request token. OAuth 1.0 only."                                                                                                             />
    <output name="OAuthTokenSecret"             desc="The request token secret. OAuth 1.0 only."                                                                                                      />
  </rsb:info>

  <!-- Set OAuthVersion to 1.0 or 2.0. -->
  <rsb:set attr="OAuthVersion"          value="MyOAuthVersion"                 />
  <!-- Set ResponseType to the desired authorization grant type. OAuth 2.0 only.-->
  <rsb:set attr="ResponseType"           value="code"                           />
  <!-- Set SignMethod to the signature method used to calculate the signature. OAuth 1.0 only.-->
  <rsb:set attr="SignMethod"            value="HMAC-SHA1"                      />
  <!-- Set OAuthAuthorizationURL to the URL where the user logs into the service and grants permissions to the application. -->
  <rsb:set attr="OAuthAuthorizationURL"  value="http://MyOAuthAuthorizationURL" />
  <!-- Set OAuthAccessTokenURL to the URL where the request for the access token is made. -->
  <rsb:set attr="OAuthAccessTokenURL"   value="http://MyOAuthAccessTokenURL"/>
  <!-- Set RequestTokenURL to the URL where the request for the request token is made. OAuth 1.0 only.-->
  <rsb:set attr="OAuthRequestTokenURL"   value="http://MyOAuthRequestTokenURL"       />
  <rsb:call op="oauthGetUserAuthorizationUrl">
    <rsb:push/>
  </rsb:call>
  
</rsb:script>

<p>

Input Parameters

  • OAuthVersion: The OAuth version. The allowed values are 1.0, 2.0. The default value is 1.0.
  • OAuthAuthorizationURL: The URL where the user logs into the service and grants permissions to the application. In OAuth 1.0, if permissions are granted the request token is authorized.
  • OAuthRequestTokenURL: The URL where the connector makes a request for the request token. OAuth 1.0 only. Required for OAuth 1.0.
  • CallbackURL: The URL to be used as a trusted redirect URL, where the user will return with the token that verifies that they have granted your app access. This value must match the callback URL you specify when you register an app. Note that your data source may additionally require the port. The default value is http://127.0.0.1/.
  • OAuthClientId: The client Id. Also called a consumer key.
  • OAuthClientSecret: The client secret. Also called a consumer secret.
  • ResponseType: The desired authorization grant type. OAuth 2.0 only. The allowed values are CODE, IMPLICIT. The default value is CODE.
  • SignMethod: The signature method used to calculate the signature for OAuth 1.0. The allowed values are HMAC-SHA1, RSA-SHA1, PLAINTEXT. The default value is HMAC-SHA1.
  • Cert: Path for the personal certificate PFX file. OAuth 1.0 only.
  • CertPassword: Personal certificate password. OAuth 1.0 only.
  • OtherOptions: Other options to control the behavior of OAuth.
  • OAuthParam:*: Other parameters. OAuth 1.0 only.
  • Timeout: The timeout, in seconds, for the operation to complete. Zero (0) means no timeout. The default value is 60.
  • Proxy_Auto: Whether or not the proxy should be detected from Windows system settings. This takes precedence over other proxy settings and is not available in Java. The allowed values are TRUE, FALSE. The default value is FALSE.
  • Proxy_Server: IP address or host name of the proxy server used for the request.
  • Proxy_Port: The port number of the proxy server.
  • Proxy_User: The user Id used to authenticate with the proxy server.
  • Proxy_Password: The password used to authenticate with the proxy server.
  • Proxy_AuthScheme: The authentication scheme of the proxy server. The allowed values are BASIC, DIGEST, NONE, NTLM. The default value is BASIC.
  • Proxy_AuthToken: The proxy authentication token.
  • Proxy_SSLType: The SSL type of the proxy server. The allowed values are AUTO, ALWAYS, NEVER, TUNNEL. The default value is AUTO.
  • Firewall_Type: The type of the firewall. The allowed values are NONE, TUNNEL, SOCKS4, SOCKS5. The default value is NONE.
  • Firewall_Server: The IP address or host name of the firewall.
  • Firewall_Port: The port number of the firewall.
  • Firewall_User: The user Id used to authenticate with the firewall.
  • Firewall_Password: The password used to authenticate with the firewall.

Output Parameters

  • URL: The URL where the user logs in and is prompted to grant permissions to the app. In OAuth 1.0, if permissions are granted the request token is authorized.
  • OAuthAccessToken: The request token. OAuth 1.0 only.
  • OAuthTokenSecret: The request token secret. OAuth 1.0 only.
  • OAuthParam:*: Other parameters sent from the server. OAuth 1.0 only.

CData Python Connector for XML

utiladoRefreshOAuth

The utiladoRefreshOAuth operation causes the connector to refresh any OAuth tokens that are close to expiring. This has no effect when AuthScheme is set to a non-OAuth authentication mode or when InitiateOAuth is set to OFF .

The operation takes no parameters and may be called like this:

<api:call op="utiladoRefreshOAuth" />

CData Python Connector for XML

utiladoSleep

The utiladoSleep operation causes the process that calls it to suspend execution for a specifed duration.

The required parameter is timeout. The units are in seconds. For example,

<api:call op="utiladoSleep?timeout=2" />

CData Python Connector for XML

utiladoPushPageToken

The utiladoPushPageToken operation causes the process to push a page token for rows@next without pushing a row in the result set. This is useful in some complex scenarios, such as paging the outer call while only having the nested inner call push rows.

The following list highlights examples of defining the desired page token, which can be retrieved from _input.rows@next in the next iteration:

  • Push a next page URL to rows@next:
    <api:set item="page" attr="pagetoken" value="[out1._next]" />
    <api:call op="utiladoPushPageToken" input="page" />
  • Push a paging token or cursor to rows@next:
    <api:set item="page" attr="pagetoken" value="[out1.cursor]" />
    <api:call op="utiladoPushPageToken" input="page" />
  • Push an incremented page number to rows@next:
    <api:set item="page" attr="pagetoken" value="[temp.currentpage | add(1)]" />
    <api:call op="utiladoPushPageToken" input="page" />
  • Push an incremented offset to rows@next:
    <api:set item="page" attr="pagetoken" value="[temp.offset | add([temp.pagesize])]" />
    <api:call op="utiladoPushPageToken" input="page" />

CData Python Connector for XML

System Tables

You can query the system tables described in this section to access schema information, information on data source functionality, and batch operation statistics.

Schema Tables

The following tables return database metadata for XML:

Data Source Tables

The following tables return information about how to connect to and query the data source:

  • sys_connection_props: Returns information on the available connection properties.
  • sys_sqlinfo: Describes the SELECT queries that the connector can offload to the data source.

Query Information Tables

The following table returns query statistics for data modification queries

  • sys_identity: Returns information about batch operations or single updates.

CData Python Connector for XML

sys_catalogs

Lists the available databases.

The following query retrieves all databases determined by the connection string:

SELECT * FROM sys_catalogs

Columns

Name Type Description
CatalogName String The database name.

CData Python Connector for XML

sys_schemas

Lists the available schemas.

The following query retrieves all available schemas:

          SELECT * FROM sys_schemas
          

Columns

Name Type Description
CatalogName String The database name.
SchemaName String The schema name.

CData Python Connector for XML

sys_tables

Lists the available tables.

The following query retrieves the available tables and views:

          SELECT * FROM sys_tables
          

Columns

Name Type Description
CatalogName String The database containing the table or view.
SchemaName String The schema containing the table or view.
TableName String The name of the table or view.
TableType String The table type (table or view).
Description String A description of the table or view.
IsUpdateable Boolean Whether the table can be updated.
IsInsertable Boolean Whether the table can be inserted into.
IsDeleteable Boolean Whether rows can be deleted from the table.

CData Python Connector for XML

sys_tablecolumns

Describes the columns of the available tables and views.

The following query returns the columns and data types for the NorthwindOData table:

SELECT ColumnName, DataTypeName FROM sys_tablecolumns WHERE TableName = 'NorthwindOData' 

Columns

Name Type Description
CatalogName String The name of the database containing the table or view.
SchemaName String The schema containing the table or view.
TableName String The name of the table or view containing the column.
ColumnName String The column name.
DataTypeName String The data type name.
DataType Int32 An integer indicating the data type. This value is determined at run time based on the environment.
Length Int32 The storage size of the column.
DisplaySize Int32 The designated column's normal maximum width in characters.
NumericPrecision Int32 The maximum number of digits in numeric data. The column length in characters for character and date-time data.
NumericScale Int32 The column scale or number of digits to the right of the decimal point.
IsNullable Boolean Whether the column can contain null.
Description String A brief description of the column.
Ordinal Int32 The sequence number of the column.
IsAutoIncrement String Whether the column value is assigned in fixed increments.
IsGeneratedColumn String Whether the column is generated.
IsHidden Boolean Whether the column is hidden.
IsArray Boolean Whether the column is an array.
IsReadOnly Boolean Whether the column is read-only.
IsKey Boolean Indicates whether a field returned from sys_tablecolumns is the primary key of the table.
ColumnType String The role or classification of the column in the schema. Possible values include SYSTEM, LINKEDCOLUMN, NAVIGATIONKEY, REFERENCECOLUMN, and NAVIGATIONPARENTCOLUMN.
ColumnCapabilities Int32 A bit mask denoting the column's write capabilities. The value is the sum of the following: 1 if the column is required for INSERTs, 2 if the column is allowed for INSERTs, and 4 if the column is allowed for UPDATEs. A value of 0 indicates that the write capabilities of the column are unknown or that the column is read-only.

CData Python Connector for XML

sys_procedures

Lists the available stored procedures.

The following query retrieves the available stored procedures:

          SELECT * FROM sys_procedures
          

Columns

Name Type Description
CatalogName String The database containing the stored procedure.
SchemaName String The schema containing the stored procedure.
ProcedureName String The name of the stored procedure.
Description String A description of the stored procedure.
ProcedureType String The type of the procedure, such as PROCEDURE or FUNCTION.

CData Python Connector for XML

sys_procedureparameters

Describes stored procedure parameters.

The following query returns information about all of the input parameters for the GetOAuthAccessToken stored procedure:

SELECT * FROM sys_procedureparameters WHERE ProcedureName = 'GetOAuthAccessToken' AND Direction = 1 OR Direction = 2

To include result set columns in addition to the parameters, set the IncludeResultColumns pseudo column to True:

SELECT * FROM sys_procedureparameters WHERE ProcedureName = 'GetOAuthAccessToken' AND IncludeResultColumns='True'

Columns

Name Type Description
CatalogName String The name of the database containing the stored procedure.
SchemaName String The name of the schema containing the stored procedure.
ProcedureName String The name of the stored procedure containing the parameter.
ColumnName String The name of the stored procedure parameter.
Direction Int32 An integer corresponding to the type of the parameter: input (1), input/output (2), or output(4). input/output type parameters can be both input and output parameters.
DataType Int32 An integer indicating the data type. This value is determined at run time based on the environment.
DataTypeName String The name of the data type.
NumericPrecision Int32 The maximum precision for numeric data. The column length in characters for character and date-time data.
Length Int32 The number of characters allowed for character data. The number of digits allowed for numeric data.
NumericScale Int32 The number of digits to the right of the decimal point in numeric data.
IsNullable Boolean Whether the parameter can contain null.
IsRequired Boolean Whether the parameter is required for execution of the procedure.
IsArray Boolean Whether the parameter is an array.
Description String The description of the parameter.
Ordinal Int32 The index of the parameter.
Values String The values you can set in this parameter are limited to those shown in this column. Possible values are comma-separated.
SupportsStreams Boolean Whether the parameter represents a file that you can pass as either a file path or a stream.
IsPath Boolean Whether the parameter is a target path for a schema creation operation.
Default String The value used for this parameter when no value is specified.
SpecificName String A label that, when multiple stored procedures have the same name, uniquely identifies each identically-named stored procedure. If there's only one procedure with a given name, its name is simply reflected here.
IsCDataProvided Boolean Whether the procedure is added/implemented by CData, as opposed to being a native XML procedure.

Pseudo-Columns

Name Type Description
IncludeResultColumns Boolean Whether the output should include columns from the result set in addition to parameters. Defaults to False.

CData Python Connector for XML

sys_keycolumns

Describes the primary and foreign keys.

The following query retrieves the primary key for the NorthwindOData table:

         SELECT * FROM sys_keycolumns WHERE IsKey='True' AND TableName='NorthwindOData' 
          

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
IsKey Boolean Whether the column is a primary key in the table referenced in the TableName field.
IsForeignKey Boolean Whether the column is a foreign key referenced in the TableName field.
PrimaryKeyName String The name of the primary key.
ForeignKeyName String The name of the foreign key.
ReferencedCatalogName String The database containing the primary key.
ReferencedSchemaName String The schema containing the primary key.
ReferencedTableName String The table containing the primary key.
ReferencedColumnName String The column name of the primary key.

CData Python Connector for XML

sys_foreignkeys

Describes the foreign keys.

The following query retrieves all foreign keys which refer to other tables:

         SELECT * FROM sys_foreignkeys WHERE ForeignKeyType = 'FOREIGNKEY_TYPE_IMPORT'
          

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
PrimaryKeyName String The name of the primary key.
ForeignKeyName String The name of the foreign key.
ReferencedCatalogName String The database containing the primary key.
ReferencedSchemaName String The schema containing the primary key.
ReferencedTableName String The table containing the primary key.
ReferencedColumnName String The column name of the primary key.
ForeignKeyType String Designates whether the foreign key is an import (points to other tables) or export (referenced from other tables) key.

CData Python Connector for XML

sys_primarykeys

Describes the primary keys.

The following query retrieves the primary keys from all tables and views:

         SELECT * FROM sys_primarykeys
          

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
KeySeq String The sequence number of the primary key.
KeyName String The name of the primary key.

CData Python Connector for XML

sys_indexes

Describes the available indexes. By filtering on indexes, you can write more selective queries with faster query response times.

The following query retrieves all indexes that are not primary keys:

          SELECT * FROM sys_indexes WHERE IsPrimary='false'
          

Columns

Name Type Description
CatalogName String The name of the database containing the index.
SchemaName String The name of the schema containing the index.
TableName String The name of the table containing the index.
IndexName String The index name.
ColumnName String The name of the column associated with the index.
IsUnique Boolean True if the index is unique. False otherwise.
IsPrimary Boolean True if the index is a primary key. False otherwise.
Type Int16 An integer value corresponding to the index type: statistic (0), clustered (1), hashed (2), or other (3).
SortOrder String The sort order: A for ascending or D for descending.
OrdinalPosition Int16 The sequence number of the column in the index.

CData Python Connector for XML

sys_connection_props

Returns information on the available connection properties and those set in the connection string.

The following query retrieves all connection properties that have been set in the connection string or set through a default value:

SELECT * FROM sys_connection_props WHERE Value <> ''

Columns

Name Type Description
Name String The name of the connection property.
ShortDescription String A brief description.
Type String The data type of the connection property.
Default String The default value if one is not explicitly set.
Values String A comma-separated list of possible values. A validation error is thrown if another value is specified.
Value String The value you set or a preconfigured default.
Required Boolean Whether the property is required to connect.
Category String The category of the connection property.
IsSessionProperty String Whether the property is a session property, used to save information about the current connection.
Sensitivity String The sensitivity level of the property. This informs whether the property is obfuscated in logging and authentication forms.
PropertyName String A camel-cased truncated form of the connection property name.
Ordinal Int32 The index of the parameter.
CatOrdinal Int32 The index of the parameter category.
Hierarchy String Shows dependent properties associated that need to be set alongside this one.
Visible Boolean Informs whether the property is visible in the connection UI.
ETC String Various miscellaneous information about the property.

CData Python Connector for XML

sys_sqlinfo

Describes the SELECT query processing that the connector can offload to the data source.

See SQL Compliance for SQL syntax details.

Discovering the Data Source's SELECT Capabilities

Below is an example data set of SQL capabilities. Some aspects of SELECT functionality are returned in a comma-separated list if supported; otherwise, the column contains NO.

NameDescriptionPossible Values
AGGREGATE_FUNCTIONSSupported aggregation functions.AVG, COUNT, MAX, MIN, SUM, DISTINCT
COUNTWhether COUNT function is supported.YES, NO
IDENTIFIER_QUOTE_OPEN_CHARThe opening character used to escape an identifier.[
IDENTIFIER_QUOTE_CLOSE_CHARThe closing character used to escape an identifier.]
SUPPORTED_OPERATORSA list of supported SQL operators.=, >, <, >=, <=, <>, !=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, OR
GROUP_BYWhether GROUP BY is supported, and, if so, the degree of support.NO, NO_RELATION, EQUALS_SELECT, SQL_GB_COLLATE
OJ_CAPABILITIESThe supported varieties of outer joins supported.NO, LEFT, RIGHT, FULL, INNER, NOT_ORDERED, ALL_COMPARISON_OPS
OUTER_JOINSWhether outer joins are supported.YES, NO
SUBQUERIESWhether subqueries are supported, and, if so, the degree of support.NO, COMPARISON, EXISTS, IN, CORRELATED_SUBQUERIES, QUANTIFIED
STRING_FUNCTIONSSupported string functions.LENGTH, CHAR, LOCATE, REPLACE, SUBSTRING, RTRIM, LTRIM, RIGHT, LEFT, UCASE, SPACE, SOUNDEX, LCASE, CONCAT, ASCII, REPEAT, OCTET, BIT, POSITION, INSERT, TRIM, UPPER, REGEXP, LOWER, DIFFERENCE, CHARACTER, SUBSTR, STR, REVERSE, PLAN, UUIDTOSTR, TRANSLATE, TRAILING, TO, STUFF, STRTOUUID, STRING, SPLIT, SORTKEY, SIMILAR, REPLICATE, PATINDEX, LPAD, LEN, LEADING, KEY, INSTR, INSERTSTR, HTML, GRAPHICAL, CONVERT, COLLATION, CHARINDEX, BYTE
NUMERIC_FUNCTIONSSupported numeric functions.ABS, ACOS, ASIN, ATAN, ATAN2, CEILING, COS, COT, EXP, FLOOR, LOG, MOD, SIGN, SIN, SQRT, TAN, PI, RAND, DEGREES, LOG10, POWER, RADIANS, ROUND, TRUNCATE
TIMEDATE_FUNCTIONSSupported date/time functions.NOW, CURDATE, DAYOFMONTH, DAYOFWEEK, DAYOFYEAR, MONTH, QUARTER, WEEK, YEAR, CURTIME, HOUR, MINUTE, SECOND, TIMESTAMPADD, TIMESTAMPDIFF, DAYNAME, MONTHNAME, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, EXTRACT
REPLICATION_SKIP_TABLESIndicates tables skipped during replication.
REPLICATION_TIMECHECK_COLUMNSA string array containing a list of columns which will be used to check for (in the given order) to use as a modified column during replication.
IDENTIFIER_PATTERNString value indicating what string is valid for an identifier.
SUPPORT_TRANSACTIONIndicates if the provider supports transactions such as commit and rollback.YES, NO
DIALECTIndicates the SQL dialect to use.
KEY_PROPERTIESIndicates the properties which identify the uniform database.
SUPPORTS_MULTIPLE_SCHEMASIndicates if multiple schemas may exist for the provider.YES, NO
SUPPORTS_MULTIPLE_CATALOGSIndicates if multiple catalogs may exist for the provider.YES, NO
DATASYNCVERSIONThe CData Data Sync version needed to access this driver.Standard, Starter, Professional, Enterprise
DATASYNCCATEGORYThe CData Data Sync category of this driver.Source, Destination, Cloud Destination
SUPPORTSENHANCEDSQLWhether enhanced SQL functionality beyond what is offered by the API is supported.TRUE, FALSE
SUPPORTS_BATCH_OPERATIONSWhether batch operations are supported.YES, NO
SQL_CAPAll supported SQL capabilities for this driver.SELECT, INSERT, DELETE, UPDATE, TRANSACTIONS, ORDERBY, OAUTH, ASSIGNEDID, LIMIT, LIKE, BULKINSERT, COUNT, BULKDELETE, BULKUPDATE, GROUPBY, HAVING, AGGS, OFFSET, REPLICATE, COUNTDISTINCT, JOINS, DROP, CREATE, DISTINCT, INNERJOINS, SUBQUERIES, ALTER, MULTIPLESCHEMAS, GROUPBYNORELATION, OUTERJOINS, UNIONALL, UNION, UPSERT, GETDELETED, CROSSJOINS, GROUPBYCOLLATE, MULTIPLECATS, FULLOUTERJOIN, MERGE, JSONEXTRACT, BULKUPSERT, SUM, SUBQUERIESFULL, MIN, MAX, JOINSFULL, XMLEXTRACT, AVG, MULTISTATEMENTS, FOREIGNKEYS, CASE, LEFTJOINS, COMMAJOINS, WITH, LITERALS, RENAME, NESTEDTABLES, EXECUTE, BATCH, BASIC, INDEX
PREFERRED_CACHE_OPTIONSA string value specifies the preferred cacheOptions.
ENABLE_EF_ADVANCED_QUERYIndicates if the driver directly supports advanced queries coming from Entity Framework. If not, queries will be handled client side.YES, NO
PSEUDO_COLUMNSA string array indicating the available pseudo columns.
MERGE_ALWAYSIf the value is true, The Merge Mode is forcibly executed in Data Sync.TRUE, FALSE
REPLICATION_MIN_DATE_QUERYA select query to return the replicate start datetime.
REPLICATION_MIN_FUNCTIONAllows a provider to specify the formula name to use for executing a server side min.
REPLICATION_START_DATEAllows a provider to specify a replicate startdate.
REPLICATION_MAX_DATE_QUERYA select query to return the replicate end datetime.
REPLICATION_MAX_FUNCTIONAllows a provider to specify the formula name to use for executing a server side max.
IGNORE_INTERVALS_ON_INITIAL_REPLICATEA list of tables which will skip dividing the replicate into chunks on the initial replicate.
CHECKCACHE_USE_PARENTIDIndicates whether the CheckCache statement should be done against the parent key column.TRUE, FALSE
CREATE_SCHEMA_PROCEDURESIndicates stored procedures that can be used for generating schema files.

The following query retrieves the operators that can be used in the WHERE clause:

SELECT * FROM sys_sqlinfo WHERE Name = 'SUPPORTED_OPERATORS'
Note that individual tables may have different limitations or requirements on the WHERE clause; refer to the Data Model section for more information.

Columns

Name Type Description
NAME String A component of SQL syntax, or a capability that can be processed on the server.
VALUE String Detail on the supported SQL or SQL syntax.

CData Python Connector for XML

sys_identity

Returns information about attempted modifications.

The following query retrieves the Ids of the modified rows in a batch operation:

         SELECT * FROM sys_identity
          

Columns

Name Type Description
Id String The database-generated Id returned from a data modification operation.
Batch String An identifier for the batch. 1 for a single operation.
Operation String The result of the operation in the batch: INSERTED, UPDATED, or DELETED.
Message String SUCCESS or an error message if the update in the batch failed.

CData Python Connector for XML

sys_information

Describes the available system information.

The following query retrieves all columns:

SELECT * FROM sys_information

Columns

NameTypeDescription
ProductStringThe name of the product.
VersionStringThe version number of the product.
DatasourceStringThe name of the datasource the product connects to.
NodeIdStringThe unique identifier of the machine where the product is installed.
HelpURLStringThe URL to the product's help documentation.
LicenseStringThe license information for the product. (If this information is not available, the field may be left blank or marked as 'N/A'.)
LocationStringThe file path location where the product's library is stored.
EnvironmentStringThe version of the environment or rumtine the product is currently running under.
DataSyncVersionStringThe tier of CData Sync required to use this connector.
DataSyncCategoryStringThe category of CData Sync functionality (e.g., Source, Destination).

CData Python Connector for XML

Stored Procedures

Stored procedures are function-like interfaces that extend the functionality of the connector beyond simple SELECT/INSERT/UPDATE/DELETE operations with XML.

Stored procedures accept a list of parameters, perform their intended function, and then return any relevant response data from XML, along with an indication of whether the procedure succeeded or failed.

CData Python Connector for XML Stored Procedures

Name Description
CreateSchema Generates a schema file that defines the structure of an XML collection, including element names and data types.
DeleteFile Deletes a specified XML file from local storage or a connected cloud service.
DownloadFile Downloads an XML file from a local directory or remote storage location to the specified path.
GetOAuthAccessToken Obtains the OAuth access token to be used for authentication with data sources using OAuth.
GetOAuthAuthorizationURL Obtains the OAuth authorization URL used for authentication with data sources using OAuth.
ListFiles Lists all available XML files within a specified local or cloud-based directory, including file names and paths.
RefreshOAuthAccessToken Exchanges a refresh token for a new access token.
UploadFile Uploads an XML file from a local directory to the specified destination, such as cloud or remote storage.

CData Python Connector for XML

CreateSchema

Generates a schema file that defines the structure of an XML collection, including element names and data types.

CreateSchema

Creates a local schema file (.rsd) from an existing table or view in the data model.

The schema file is created in the directory set in the Location connection property when this procedure is executed. You can edit the file to include or exclude columns, rename columns, or adjust column datatypes.

The connector checks the Location to determine if the names of any .rsd files match a table or view in the data model. If there is a duplicate, the schema file will take precedence over the default instance of this table in the data model. If a schema file is present in Location that does not match an existing table or view, a new table or view entry is added to the data model of the connector.

Input

Name Type Description
TableName String Specifies the name of the XML table for which the schema file will be created.
URI String Specifies the Uniform Resource Identifier (URI) of the XML resource from which the schema will be generated.
XPath String Specifies the XPath expression that identifies a repeating element at the same hierarchy level within the XML document. This path determines how the document is divided into multiple rows.
WriteToFile String Indicates whether the generated schema should be written directly to a file. The default value is 'true'. To write the schema to FileStream or FileData instead, set to 'false'.
FileName String Specifies the full name and path of the generated schema file.
Method String Defines the HTTP method used to retrieve the XML data, such as GET or POST.

The default value is GET.

ContentType String Specifies the Content-Type header included in the request, particularly when sending data through the PostData field.
Data String Contains the data payload to be sent in the body of the HTTP request when applicable.

Result Set Columns

Name Type Description
Result String Indicates whether or not the operation was successful.
FileData String Returns the generated schema content encoded in base64. This output is provided only when WriteToFile is set to 'false' and FileStream is not used.

CData Python Connector for XML

DeleteFile

Deletes a specified XML file from local storage or a connected cloud service.

Procedure-Specific Information

The Path input accepts paths relative to the URI provided in the connection string.

If URI is set to: gs://test-bucket/folder2 and Path='file1.txt', the file /folder2/file1.txt will be deleted.

The procedure is executed as below:

    EXEC DeleteFile Path='/hello-cdata.txt'

Input

Name Type Description
Path String Specifies the full path of the XML file to be deleted, relative to the directory defined in the Uniform Resource Identifier (URI) connection property.

Result Set Columns

Name Type Description
Success Bool Indicates whether the file deletion operation completed successfully. If the value is 'false', additional information is returned in the Details output parameter.
Details String Provides diagnostic details if the operation fails. If the deletion succeeds, this field is returned as NULL.

CData Python Connector for XML

DownloadFile

Downloads an XML file from a local directory or remote storage location to the specified path.

Procedure-Specific Information

The Path input accepts paths relative to the URI provided in the connection string.

If URI is set to: gs://test-bucket/folder2 and Path='file1.txt', the file /folder2/file1.txt will be downloaded.

The procedure is executed as below:

    EXEC DownloadFile Path='cdata.txt', LocalPath='C:/temp/test.txt'
    EXEC DownloadFile Path='/cdata.txt'

Input

Name Type Description
Path String Specifies the full path of the XML file to be downloaded, relative to the directory defined in the Uniform Resource Identifier (URI) connection property.
LocalPath String Specifies the absolute local path where the downloaded file will be saved.

Result Set Columns

Name Type Description
Success Bool Indicates whether the file download operation completed successfully. If the value is 'false', additional details are provided in the Details output parameter.
Details String Provides diagnostic information if the operation fails. When the download succeeds, this field is returned as NULL.
FileData String Returns the file content encoded in base64. This output is returned only when both LocalPath and OutputStream inputs are empty.

CData Python Connector for XML

GetOAuthAccessToken

Obtains the OAuth access token to be used for authentication with data sources using OAuth.

Input

Name Type Description
Other_Options String Other options to control behavior of OAuth.
Cert String Path for a personal certificate .pfx file. Only available for OAuth 1.0.
Cert_Password String Personal certificate password. Only available for OAuth 1.0.
AuthToken String The request token returned by GetOAuthAuthorizationUrl. Available only for OAuth 1.0.
AuthKey String The request secret key returned by GetOAuthAuthorizationUrl. Available only for OAuth 1.0.
AuthSecret String The legacy name for AuthKey, included for compatibility.
Sign_Method String The signature method used to calculate the signature for OAuth 1.0.

The allowed values are HMAC-SHA1, PLAINTEXT.

The default value is HMAC-SHA1.

GrantType String Authorization grant type. Only available for OAuth 2.0.

The allowed values are CODE, PASSWORD, CLIENT, REFRESH.

Post_Data String The post data to submit, if any.
AuthMode String The type of authentication mode to use.

The allowed values are APP, WEB.

The default value is WEB.

Verifier String The verifier code returned by the data source after permission for the app to connect has been granted. WEB AuthMode only.
Scope String The scope of access to the APIs. By default, access to all APIs used by this data provider will be specified.
CallbackURL String This field determines where the response is sent.
Prompt String This field indicates the prompt to present the user. It accepts one of the following values: NONE, CONSENT, SELECT ACCOUNT. The default is SELECT_ACCOUNT, so a given user will be prompted to select the account to connect to. If it is set to CONSENT, the user will see a consent page every time, even if they have previously given consent to the application for a given set of scopes. Lastly, if it is set to NONE, no authentication or consent screens will be displayed to the user.

The default value is SELECT_ACCOUNT.

AccessType String This field indicates if your application needs to access a Google API when the user is not present at the browser. This parameter defaults to ONLINE. If your application needs to refresh access tokens when the user is not present at the browser, then use OFFLINE. This will result in your application obtaining a refresh token the first time your application exchanges an authorization code for a user.
State String This field indicates any state that may be useful to your application upon receipt of the response. Your application receives the same value it sent, as this parameter makes a round-trip to Google authorization server and back. Uses include redirecting the user to the correct resource in your site, using nonces, and mitigating cross-site request forgery.

Result Set Columns

Name Type Description
OAuthAccessToken String The authentication token returned from Google. This can be used in subsequent calls to other operations for this particular service.
OAuthAccessTokenSecret String The OAuth access token secret.
OAuthRefreshToken String A token that may be used to obtain a new access token.
ExpiresIn String The remaining lifetime on the access token.
* String Other outputs that may be returned by the data source.

CData Python Connector for XML

GetOAuthAuthorizationURL

Obtains the OAuth authorization URL used for authentication with data sources using OAuth.

Input

Name Type Description
Cert String Path for a personal certificate .pfx file. Only available for OAuth 1.0.
Cert_Password String Personal certificate password. Only available for OAuth 1.0.
Sign_Method String The signature method used to calculate the signature for OAuth 1.0.

The allowed values are HMAC-SHA1, PLAINTEXT.

The default value is HMAC-SHA1.

Scope String The scope of access to the APIs. By default, access to all APIs used by this data provider will be specified.
CallbackURL String The URL the user will be redirected to after authorizing your application.
Prompt String This field indicates the prompt to present the user. It accepts one of the following values: NONE, CONSENT, SELECT ACCOUNT. The default is SELECT_ACCOUNT, so a given user will be prompted to select the account to connect to. If it is set to CONSENT, the user will see a consent page every time, even if they have previously given consent to the application for a given set of scopes. Lastly, if it is set to NONE, no authentication or consent screens will be displayed to the user.

The default value is SELECT_ACCOUNT.

AccessType String This field indicates if your application needs to access a Google API when the user is not present at the browser. This parameter defaults to ONLINE. If your application needs to refresh access tokens when the user is not present at the browser, then use OFFLINE. This will result in your application obtaining a refresh token the first time your application exchanges an authorization code for a user.
State String This field indicates any state that may be useful to your application upon receipt of the response. Your application receives the same value it sent, as this parameter makes a round-trip to the Google authorization server and back. Possible uses include redirecting the user to the correct resource in your site, using nonces, and mitigating cross-site request forgery.
Other_Options String Other options to control the behavior of OAuth.

Result Set Columns

Name Type Description
AuthToken String The authorization token, passed into the GetOAuthAccessToken stored procedure.
AuthKey String The authorization secret token, passed into the GetOAuthAccessToken stored procedure.
AuthSecret String A legacy name used for AuthKey, accepted for compatibility.
URL String The URL to complete user authentication.

CData Python Connector for XML

ListFiles

Lists all available XML files within a specified local or cloud-based directory, including file names and paths.

Input

Name Type Description
Mask String Specifies a filter mask to limit which files are listed. For example, use '*.xml' to include only XML files.
Path String Specifies the directory path from which files will be listed, relative to the Uniform Resource Identifier (URI) defined in the connection.

Result Set Columns

Name Type Description
FileName String Returns the name of each XML file found within the specified directory.
LastModified Long Returns the Unix timestamp representing the date and time when the file was last modified.
CreatedAt Long Returns the Unix timestamp representing when the file was originally created. A value of -1 indicates that the storage system does not support this information.
URI String Returns the URI of the listed file.

CData Python Connector for XML

RefreshOAuthAccessToken

Exchanges a refresh token for a new access token.

Input

Name Type Description
OAuthRefreshToken String The refresh token returned from the original authorization code exchange.

Result Set Columns

Name Type Description
OAuthAccessToken String The authentication token returned from the data source. This can be used in subsequent calls to other operations for this particular service.
OAuthAccessTokenSecret String The new OAuthAccessTokenSecret returned from the service.
OAuthRefreshToken String The authentication token returned from the data source. This can be used in subsequent calls to other operations for this particular service.
ExpiresIn String The remaining lifetime on the access token.

CData Python Connector for XML

UploadFile

Uploads an XML file from a local directory to the specified destination, such as cloud or remote storage.

Procedure-Specific Information

The DestinationPath input accepts paths relative to the URI provided in the connection string.

If URI is set to: gs://test-bucket/folder2 and DestinationPath='file1.txt', the file will be uploaded to /folder2/file1.txt.

The procedure is executed as below:

    EXEC UploadFile LocalPath='C:/temp/test.txt',  DestinationPath='/hello-cdata.txt'
    EXEC UploadFile InputData='eGN2eGN2eGN2eHp6IGRzZmFzZGZkZmc=',  DestinationPath='CData/hello-cdata.txt'

Input

Name Type Description
DestinationPath String Specifies the full destination path where the XML file will be uploaded. The path is relative to the directory defined in the Uniform Resource Identifier (URI) connection property.
LocalPath String Specifies the absolute path of the local file to be uploaded to the target destination.
InputData String Contains the file content as a base64-encoded string. This input is used only when neither LocalPath nor InputStream is provided.

Result Set Columns

Name Type Description
Success Bool Indicates whether or not the file upload operation completed successfully. If the value is 'false', additional details are provided in the Details output parameter.
Details String Provides diagnostic information if the upload operation fails. If the upload succeeds, this field is returned as NULL.

CData Python Connector for XML

Using the Connector

This section provides a walk-through for writing XML data access code in Python script.

For more information on the available data source entities and how to query them with SQL, see Data Model. For the SQL syntax, see SQL Compliance.

Connecting from Code

For information on how to deploy the connector and configure the connection to XML, see Package Installation and Establishing a Connection.

For information on how to connect with the xml.connector module and its related classes, see Connecting.

Executing SQL

The connection's cursor object is used to directly execute SQL queries. For information on how to execute SELECT statements and process the returned result sets, see Querying Data. For information on to modify the data in XML with INSERT, UPDATE, and DELETE statements, see Modifying Data .

Executing Stored Procedures

You can call stored procedures by using the EXECUTE statement. For further information, see Calling Stored Procedures.

CData Python Connector for XML

Connecting

Connecting with the cdata.xml Module:

The connector's module is used directly to establish a connection with the data source. It does this by using a connection string as its argument. For example:
import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")

Once the connection is created, you can use it to execute subsequent SQL queries.

CData Python Connector for XML

Querying Data

After connecting as described in Connecting, you can use the open connection to execute SQL statements.

Executing Queries

To execute SQL statements that return data, use the execute() method. Once a query is executed, the result set is fetched from the cursor. This result set can then be iterated over to process the records individually.

For example:

cur = conn.execute("SELECT Email, Username FROM NorthwindOData")
rs = cur.fetchall()
for row in rs:
	print(row)

Parameterized Queries

Various Python collections, such as arrays and tuples, can act as additional arguments for the execute() method. This enables you to parameterize the queries executed and help to prevent SQL Injection.

For example:

cmd = "SELECT Email, Username FROM NorthwindOData WHERE Email = ?"
params = ["ana.trujilo@northwind.org"]
cur = conn.execute(cmd, params)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for XML

Modifying Data

The connection is also used to issue INSERT, UPDATE, and DELETE commands to the data source. Parameters can be used with these statements if desired.

Note that the connector does not support transactions. As with normal write operations, all SQL statements executed by this connector affect the data source immediately. Call the connection's commit() method following the execution.

Insert

The following example adds a new record to the table:
cmd = "INSERT INTO NorthwindOData (Email, Username) VALUES (?, ?)"
params = ["Ana Trujilo", "Ana Trujilo"]
cur = conn.execute(cmd, params)
print("Records affected: ", cur.rowcount)

Update

The following example modifies an existing record in the table:
cmd = "UPDATE NorthwindOData SET Username = ? WHERE Id = ?"
params = ["Ana Trujilo", "1"]
cur = conn.execute(cmd, params)
print("Records affected: ", cur.rowcount)

Delete

The following example removes an existing record from the table:

cmd = "DELETE FROM NorthwindOData WHERE Id = ?"
params = ["1"]
cur = conn.execute(cmd, params)
print("Records affected: ", cur.rowcount)

CData Python Connector for XML

Calling Stored Procedures

You can execute stored procedures using either the execute() or callproc() method of the connection.

Calling Stored Procedures Using Execute()

When you call stored procedures by issuing EXECUTE commands, the stored procedure arguments are parameterized. For example:
cmd = "EXECUTE GetOAuthAccessToken CallbackURL = ?"
params = ["http://localhost"]
conn.execute(cmd, params)

Calling Stored Procedures Using Callproc()

When you call stored procedured by issuing the callproc() method, the stored procedure arguments are a procedure name and a list of parameters. For example:
cur = conn.cursor()
params = ["http://localhost"]
cur.callproc("GetOAuthAccessToken", params)

CData Python Connector for XML

Using from Tools

The connector is integrated with other tools and packages within Python.

Python Integration Guides

The following sections show how to create and use connections with the connector in common packages in Python:

Complete List of XML Integration Quickstarts

For information on connecting from other applications, see XML integration guides.

CData Python Connector for XML

From SQLAlchemy

The CData Python Connector for XML includes a Dialect class that enables integration with SQLAlchemy. Bear in mind that several aspects of connector functionality are not currently supported in SQLAlchemy 2.0 or above. If necessary, downgrade SQLAlchemy to version 1.4 or 1.3 before using this connector.

The following sections detail various aspects of this integration:

Connecting From SQLAlchemy

To construct a URL with which SQLAlchemy loads and uses the appropriate connector automatically, see Connecting

Reflecting Metadata With SQLAlchemy

To learn how to model XML tables with mapped classes, see Reflecting Metadata.

Querying Data From SQLAlchemy

To learn how to use mapped classes to query the associated tables, see Querying Data.

Modifying Data From SQLAlchemy

The connector provides INSERT/UPDATE/DELETE functionality in SQLAlchemy. To learn how to call the session's execute() method to affect the data in the data source, see Modifying Data.

CData Python Connector for XML

Connecting

Connecting With a Dialect URL

Establishing a connection using SQLAlchemy requires a specific URL format. For this connector, you can create the engine using either of the following URL formats:

Format 1


from sqlalchemy import create_engine
engine = create_engine("xml:///?DataModel=Relational;URI=C:\people.xml")

Format 2


from sqlalchemy import create_engine
engine = create_engine("xml://User:Password@/?AuthScheme=BASIC;URI=http://myapi.com/data.xml")

For SQLAlchemy 2.0, the dialect name is xml_2. To establish a connection, use the following URL format:

from sqlalchemy import create_engine
engine = create_engine("xml_2:///?DataModel=Relational;URI=C:\people.xml")

CData Python Connector for XML

Reflecting Metadata

SQLAlchemy can act as an Object-relational Map (ORM). This enables you to treat records of a database table as instantiable records. To leverage this functionality, you must reflect the underlying metadata in one of the following ways.

Note: The following examples employ SQLAlchemy 1.4.

Modeling Data Using a Mapping Class

Use "sqlalchemy.ext.declarative.declarative_base" to declare a mapping class for the table you wish to model in the ORM. A known table in the data model is modeled either partially or completely, as shown in the following example:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class NorthwindOData(Base):
	__tablename__ = "NorthwindOData"
	Id = Column(String, primary_key=True)
	Email = Column(String)
	Username = Column(String)

Automatically Reflecting Metadata

Rather than mapping tables manually, SQLAlchemy can discover the metadata for one or more tables automatically. To accomplish this across the entire data model, use automap_base:
from sqlalchemy import MetaData
from sqlalchemy.ext.automap import automap_base
meta = MetaData()
abase = automap_base(metadata=meta)
abase.prepare(autoload_with=engine)
NorthwindOData = abase.classes.NorthwindOData

You can also reflect a single table with an inspector. When reflecting this way, providing a list of specific columns to map is optional:

from sqlalchemy import MetaData, Table
from sqlalchemy import inspect
meta = MetaData()
insp = inspect(engine)
NorthwindOData_table = Table("NorthwindOData", meta)
insp.reflect_table(NorthwindOData_table, ["Id","Username"])

CData Python Connector for XML

Querying Data

After you use the steps in Connecting to connect, and use one of the methods in Reflecting Metadata to reflect some of the metadata, you can use a session object to query data.

Querying Data Using the Query Method

If the mapping class has been prepared, use it with a session object to query the data source. After binding the engine to the session, provide the mapping class to the session's query method.

For example:

engine = create_engine("xml:///?DataModel=Relational;URI=C:\people.xml")
factory = sessionmaker(bind=engine)
session = factory()
for instance in session.query(NorthwindOData).filter_by(Email="ana.trujilo@northwind.org"):
	print("Id: ", instance.Id)
	print("Email: ", instance.Email)
	print("Username: ", instance.Username)
	print("---------")

Querying Data Using the Execute Method

The session object can also run the query with the execute() method alongside the appropriate Table object. Assuming you have an active session, the following is just as viable:
NorthwindOData_table = NorthwindOData.metadata.tables["NorthwindOData"]
for instance in session.execute(NorthwindOData_table.select().where(NorthwindOData_table.c.Email == "ana.trujilo@northwind.org")):
	print("Id: ", instance.Id)
	print("FullName: ", instance.Name)
	print("City: ", instance.BillingCity)
	print("---------")

CData Python Connector for XML

Executing JOINs

Implicit Joining

If mapped classes of related XML objects have a singular foreign key relationship, the classes are implicitly joined. After importing the necessary objects, a relationship is established between your two mapped classes, as in the example below:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()
class Contact(Base):
	__tablename__ = "Contact"
	Id = Column(Integer, primary_key=True)
	Name = Column(String)
	Email = Column(String)
	BirthDate = Column(DateTime)
	AccountId = Column(String, ForeignKey("Account.Id"))
	Account_Link = relationship("Account", back_populates="Contact_Link")

class Account(Base):
	__tablename__ = "Account"
	Id = Column(String, primary_key=True)
	Name = Column(String)
	BillingCity = Column(String)
	NumberOfEmployees = Column(Integer)
	Contact_Link = relationship("Contact", order_by=Contact.Id, back_populates="Account_Link")

Once the relationship is established, the tables are queried simultaneously using the session's query() method. For example:

rs = session.query(Account, Contact).filter(Account.Id == Contact.AccountId)
for Ac, Ct in rs:
  print("AccountId: ", Ac.Id)
  print("AccountName: ", Ac.Name)
  print("ContactId: ", Ct.Id)
  print("ContactName: ", Ct.Name)

Other Join Forms

In situations where mapped classes have either no foreign keys or multiple foreign keys, you may need different forms of the JOIN query to accommodate them. Using the earlier classes as examples, the following JOIN queries are possible as well:
  • Explicit condition (necessary if there are no foreign keys in your mapped classes):
    rs = session.query(Account, Contact).join(Contact, Account.Id == Contact.AccountId)
    for Ac, Ct in rs:
  • Left-to-right relationship:
    rs = session.query(Account, Contact).join(Account.Contact_Link)
    for Ac, Ct in rs:
  • Left-to-right relationship with explicit target:
    rs = session.query(Account, Contact).join(Contact, Account.Contact_Link)
    for Ac, Ct in rs:
  • String form of a left-to-right relationship:
    rs = session.query(Account, Contact).join("Contact_Link")
    for Ac, Ct in rs:

CData Python Connector for XML

Other SQL Clauses

SQLAlchemy ORM also exposes support for other clauses in SQL, such as ORDER BY, GROUP BY, LIMIT, and OFFSET. All of these are supported by this connector:

ORDER BY

The following example sorts by a specified column using the session object's query() method:
rs = session.query(NorthwindOData).order_by(NorthwindOData.AnnualRevenue)
for instance in rs:
	print("Id: ", instance.Id)
	print("Email: ", instance.Email)
	print("Username: ", instance.Username)
	print("---------")

You can also use the session object's execute() method perform an ORDER BY. For example:

rs = session.execute(NorthwindOData_table.select().order_by(NorthwindOData_table.c.AnnualRevenue))
for instance in rs:

GROUP BY

The following example uses the session object's query() method to group records with a specified column:
rs = session.query(func.count(NorthwindOData.Id).label("CustomCount"), NorthwindOData.Email).group_by(NorthwindOData.Email)
for instance in rs:
	print("Count: ", instance.CustomCount)
	print("Email: ", instance.Email)
	print("---------")

You can also use the session object's execute() method to perform a GROUP BY:

rs = session.execute(NorthwindOData_table.select().with_only_columns([func.count(NorthwindOData_table.c.Id).label("CustomCount"), NorthwindOData_table.c.Email]).group_by(NorthwindOData_table.c.Email))
for instance in rs:

LIMIT and OFFSET

The following example uses the session object's query() method to skip the first 100 records and fetch the following 25:
rs = session.query(NorthwindOData).limit(25).offset(100)
for instance in rs:
	print("Id: ", instance.Id)
	print("Email: ", instance.Email)
	print("Username: ", instance.Username)
	print("---------")

You can also use the session object's execute() method to set a LIMIT or OFFSET:

rs = session.execute(NorthwindOData_table.select().limit(25).offset(100))
for instance in rs:

CData Python Connector for XML

Aggregate Functions

Certain aggregate functions can also be used within SQLAlchemy by using the func module.

To import this module, execute:

from sqlalchemy.sql import func

Once func is imported, the following aggregate functions are available:

COUNT

The following example counts the number of records in a set of groups using the session object's query() method.
rs = session.query(func.count(NorthwindOData.Id).label("CustomCount"), NorthwindOData.Email).group_by(NorthwindOData.Email)
for instance in rs:
	print("Count: ", instance.CustomCount)
	print("Email: ", instance.Email)
	print("---------")

You can also execute COUNT using the session object's execute() method:

rs = session.execute(NorthwindOData_table.select().with_only_columns([func.count(NorthwindOData_table.c.Id).label("CustomCount"), NorthwindOData_table.c.Email])group_by(NorthwindOData_table.c.Email))
for instance in rs:

SUM

This example calculates the cumulative amount of a numeric column in a set of groups.

rs = session.query(func.sum(NorthwindOData.AnnualRevenue).label("CustomSum"), NorthwindOData.Email).group_by(NorthwindOData.Email)
for instance in rs:
	print("Sum: ", instance.CustomSum)
	print("Email: ", instance.Email)
	print("---------")

You can also invoke SUM using the session object's execute() method.

rs = session.execute(NorthwindOData_table.select().with_only_columns([func.sum(NorthwindOData_table.c.AnnualRevenue).label("CustomSum"), NorthwindOData_table.c.Email]).group_by(NorthwindOData_table.c.Email))
for instance in rs:

AVG

This example uses the session object's query() method to calculate the average amount of a numeric column in a set of groups:
rs = session.query(func.avg(NorthwindOData.AnnualRevenue).label("CustomAvg"), NorthwindOData.Email).group_by(NorthwindOData.Email)
for instance in rs:
	print("Avg: ", instance.CustomAvg)
	print("Email: ", instance.Email)
	print("---------")

You can also use the session object's execute() method to invoke AVG:

rs = session.execute(NorthwindOData_table.select().with_only_columns([func.avg(NorthwindOData_table.c.AnnualRevenue).label("CustomAvg"), NorthwindOData_table.c.Email]).group_by(NorthwindOData_table.c.Email))
for instance in rs:

MAX and MIN

This example finds the maximum value and minimum value of a numeric column in a set of groups.
rs = session.query(func.max(NorthwindOData.AnnualRevenue).label("CustomMax"), func.min(NorthwindOData.AnnualRevenue).label("CustomMin"), NorthwindOData.Email).group_by(NorthwindOData.Email)
for instance in rs:
	print("Max: ", instance.CustomMax)
	print("Min: ", instance.CustomMin)
	print("Email: ", instance.Email)
	print("---------")

You can also use the session object's execute() method to invoke MAX and MIN:

rs = session.execute(NorthwindOData_table.select().with_only_columns([func.max(NorthwindOData_table.c.AnnualRevenue).label("CustomMax"), func.min(NorthwindOData_table.c.AnnualRevenue).label("CustomMin"), NorthwindOData_table.c.Email]).group_by(NorthwindOData_table.c.Email))
for instance in rs:

CData Python Connector for XML

Modifying Data

Commands can be executed individually by the session with a call to "execute()".

Obtaining the Table Object

The query supplied to this method is constructed using the associated Table object of a mapped class. This Table object is obtained from the mapped class's metadata field, as below:

NorthwindOData_table = NorthwindOData.metadata.tables["NorthwindOData"]

Once the table object is obtained, the write operations are executed in the following ways. The queries are executed immediately without the need for a call to "commit()":

Insert

The following example adds a new record to the table:

session.execute(NorthwindOData_table.insert(), {"Email": "Ana Trujilo", "Username": "Ana Trujilo"})

Update

The following example modifies an existing record in the table:

session.execute(NorthwindOData_table.update().where(NorthwindOData_table.c.Id == "1").values(Email="Ana Trujilo", Username="Ana Trujilo"))

Delete

The following example removes an existing record from the table:

session.execute(NorthwindOData_table.delete().where(NorthwindOData_table.c.Id == "1"))

CData Python Connector for XML

From Pandas

When combined with the connector, Pandas can be used to generate data frames that contain your XML data. Once created, a data frame can be passed to various other Python packages.

Connecting

Pandas relies on an SQLAlchemy engine to execute queries. Before you can use Pandas you must import it:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("xml:///?DataModel=Relational;URI=C:\people.xml")

Querying Data

In Pandas, SELECT queries are provided in a call to the read_sql() method, alongside a relevant connection object. Pandas executes the query on that connection, and returns the results in the form of a data frame, which can be used for a variety of purposes.
df = pd.read_sql("""
	SELECT
	   Email,
	   Username,
     $exNumericCol;
	FROM NorthwindOData;""", engine)
print(df)

Modifying Data

To insert new records into a table, create a new data frame, and define its fields accordingly. When that is done, call to_sql() on the data frame to perform the INSERT operation with the connector, as shown in the example below. You must set the "if _exists" argument to "append" to prevent Pandas from attempting building the table from scratch. To prevent Pandas from writing the data frame index as a column, set index=False.
df = pd.DataFrame({"Email": ["Ana Trujilo"], "Username": ["Ana Trujilo"]})
df.to_sql("NorthwindOData", con=engine, if_exists="append", index=False)

CData Python Connector for XML

From Matplotlib

Matplotlib contains a number of tools that can graphically model XML data after being fed a data frame From Pandas.

Using PyPlot

Before any Matplotlib tool, such as pyplot, can be used, it must be imported:
from matplotlib import pyplot as plt

Once a Pandas data frame is obtained, it can be used to create a plot visualizing XML data. For example, the following plot generates and displays a bar graph relating Email and AnnualRevenue values:

df.plot(kind="bar", x="Email", y=["AnnualRevenue"])
plt.show()

CData Python Connector for XML

From Petl

The connector can be used to create ETL applications and pipelines for CSV data in Python using Petl.

Install Required Modules

Install the Petl modules using the pip utility.
pip install petl

Connecting

After you import the modules, including the CData Python Connector for XML, you can use the connector's connect function to create a connection using a valid XML connection string. If you prefer not to use a direct connection, you can use a SQLAlchemy engine.
import petl as etl
import cdata.xml as mod
cnxn = mod.connect("DataModel=Relational;URI=C:\people.xml")

Extract, Transform, and Load the XML Data

Create a SQL query string and store the query results in a DataFrame.
sql = "SELECT	Email, Username FROM NorthwindOData "
table1 = etl.fromdb(cnxn,sql)

Loading Data

With the query results stored in a DataFrame, you can load your data into any supported Petl destination. The following example loads the data into a CSV file.
etl.tocsv(table1,'output.csv')

Modifying Data

Insert new rows into XML tables using Petl's appenddb function.
table1 = [['Email','Username'],['Ana Trujilo','Ana Trujilo']]
etl.appenddb(table1,cnxn,'NorthwindOData')

CData Python Connector for XML

Schema Discovery

The extension supports schema discovery by using SQL queries to available System Tables.

Using SQL

The following sections describe the discovery of metadata through several System Tables:

CData Python Connector for XML

Tables and Views

The connector possesses system tables that are used to discover the tables and views available in the data model. Of these system tables, "sys_tables" and "sys_views" are used to fetch information about the available tables and views respectively:

Tables


import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")
cur = conn.cursor()
cmd = "SELECT * FROM sys_tables"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

Views


import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")
cur = conn.cursor()
cmd = "SELECT * FROM sys_views"
cur.execute(cmd, params)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for XML

Columns

The available columns for any given table are fetched from a system table called "sys_tablecolumns". A specific table name is provided in the WHERE criteria to restrict the table from which the column information is fetched:

import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")
cur = conn.cursor()
cmd = "SELECT * FROM sys_tablecolumns WHERE TableName = 'NorthwindOData'"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for XML

Procedures

Procedures

A system table called "sys_procedures" is queried to obtain the available stored procedures that are executed:
import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")
cur = conn.cursor()
cmd = "SELECT * FROM sys_procedures"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

Parameters

The input parameters of any stored procedure are similarly obtained from the "sys_procedureparameters" system table:
import cdata.xml as mod
conn = mod.connect("DataModel=Relational;URI=C:\people.xml")
cur = conn.cursor()
cmd = "SELECT * FROM sys_procedureparameters WHERE ProcedureName = 'GetOAuthAccessToken'"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for XML

Advanced Features

This section details a selection of advanced features of the XML connector.

User Defined Views

The connector supports the use of user defined views, virtual tables whose contents are decided by a pre-configured user defined query. These views are useful when you cannot directly control queries being issued to the drivers. For an overview of creating and configuring custom views, see User Defined Views .

SSL Configuration

Use SSL Configuration to adjust how connector handles TLS/SSL certificate negotiations. You can choose from various certificate formats;. For further information, see the SSLServerCert property under "Connection String Options" .

Firewall and Proxy

Configure the connector for compliance with Firewall and Proxy, including Windows proxies and HTTP proxies. You can also set up tunnel connections.

Caching Data

Caching Data enables faster access to data and reduces the number of API calls, improving performance. The connector supports a simple caching model where multiple connections can also share the cache over time. When configuring the cache connection, you can specify automatic or explicit data caching.

Query Processing

The connector offloads as much of the SELECT statement processing as possible to XML and then processes the rest of the query in memory (client-side).

For further information, see Query Processing.

Logging

For an overview of configuration settings that can be used to refine CData logging, see Logging. Only two connection properties are required for basic logging, but there are numerous features that support more refined logging, which enables you to use the LogModules connection property to specify subsets of information to be logged.

Exception Handling

For an overview of how exceptions are reported and the components of an exception, see Exception Handling.

CData Python Connector for XML

User Defined Views

The CData Python Connector for XML supports the use of user defined views: user-defined virtual tables whose contents are decided by a preconfigured query. User defined views are useful in situations where you cannot directly control the query being issued to the driver; for example, when using the driver from a tool.

Use a user defined view to define predicates that are always applied. If you specify additional predicates in the query to the view, they are combined with the query already defined as part of the view.

There are two ways to create user defined views:

  • Create a JSON-formatted configuration file defining the views you want.
  • DDL statements.

Defining Views Using a Configuration File

User defined views are defined in a JSON-formatted configuration file called UserDefinedViews.json. The connector automatically detects the views specified in this file.

You can also have multiple view definitions and control them using the UserDefinedViews connection property. When you use this property, only the specified views are seen by the connector.

This user defined view configuration file is formatted so that each root element defines the name of a view, and includes a child element, called query, which contains the custom SQL query for the view.

For example:

{
	"MyView": {
		"query": "SELECT * FROM NorthwindOData WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}
Use the UserDefinedViews connection property to specify the location of your JSON configuration file. For example:
"UserDefinedViews", "C:\\Users\\yourusername\\Desktop\\tmp\\UserDefinedViews.json"

Defining Views Using DDL Statements

The connector is also capable of creating and altering the schema via DDL Statements such as CREATE LOCAL VIEW, ALTER LOCAL VIEW, and DROP LOCAL VIEW.

Create a View

To create a new view using DDL statements, provide the view name and query as follows:

CREATE LOCAL VIEW [MyViewName] AS SELECT * FROM Customers LIMIT 20;

If no JSON file exists, the above code creates one. The view is then created in the JSON configuration file and is now discoverable. The JSON file location is specified by the UserDefinedViews connection property.

Alter a View

To alter an existing view, provide the name of an existing view alongside the new query you would like to use instead:

ALTER LOCAL VIEW [MyViewName] AS SELECT * FROM Customers WHERE TimeModified > '3/1/2020';

The view is then updated in the JSON configuration file.

Drop a View

To drop an existing view, provide the name of an existing schema alongside the new query you would like to use instead.

DROP LOCAL VIEW [MyViewName]

This removes the view from the JSON configuration file. It can no longer be queried.

Schema for User Defined Views

In order to avoid a view's name clashing with an actual entity in the data model, user defined views are exposed in the UserViews schema by default. To change the name of the schema used for UserViews, reset the UserViewsSchemaName property.

Working with User Defined Views

For example, a SQL statement with a user defined view called UserViews.RCustomers only lists customers in Raleigh:
SELECT * FROM Customers WHERE City = 'Raleigh';
An example of a query to the driver:
SELECT * FROM UserViews.RCustomers WHERE Status = 'Active';
Resulting in the effective query to the source:
SELECT * FROM Customers WHERE City = 'Raleigh' AND Status = 'Active';
That is a very simple example of a query to a user defined view that is effectively a combination of the view query and the view definition. It is possible to compose these queries in much more complex patterns. All SQL operations are allowed in both queries and are combined when appropriate.

CData Python Connector for XML

SSL Configuration

Customizing the SSL Configuration

By default, the connector attempts to negotiate TLS with the server. The server certificate is validated against the default system trusted certificate store. You can override how the certificate gets validated using the SSLServerCert connection property.

To specify another certificate, see the SSLServerCert connection property.

Client SSL Certificates

The XML connector also supports setting client certificates. Set the following to connect using a client certificate.

CData Python Connector for XML

Firewall and Proxy

Connecting Through a Firewall or Proxy

HTTP Proxies

Note: The connector uses the system proxy settings by default, without further configuration needed. If you want to connect to other proxies, set ProxyAutoDetect to False and read further.

To authenticate to an HTTP proxy, set the following:

  • ProxyServer: the hostname or IP address of the proxy server that you want to route HTTP traffic through.
  • ProxyPort: the TCP port that the proxy server is running on.
  • ProxyAuthScheme: the authentication method the connector uses when authenticating to the proxy server.
  • ProxyUser: the username of a user account registered with the proxy server.
  • ProxyPassword: the password associated with the ProxyUser.

Other Proxies

Set the following properties:

CData Python Connector for XML

Caching Data

Caching Data

Caching data provides several benefits, including faster access to data and reducing the number of API calls, which improve performance. The connector supports a simple caching model where multiple connections can also share the cache over time. You can enable and configure caching features by setting the necessary connection properties.

Contents

The sections in this chapter detail the connector's caching functionality and link to the corresponding connection properties, as well as SQL statements.

Configuring the Cache Connection

Configuring the Cache Connection describes the properties that you can set when configuring the cache database.

Caching Metadata

Caching Metadata describes the CacheMetadata property. This property determines whether or not to cache the table metadata to a file store.

Automatically Caching Data

Automatically Caching Data describes how the connector automatically refreshes the cache when the AutoCache property is set.

Explicitly Caching Data

Explicitly Caching Data describes how you can decide what data is stored in the cache and when it is updated.

Data Type Mapping

Data Type Mapping shows the mappings between the data types configured in the schema and the data types in the database.

CData Python Connector for XML

Configuring the Cache Connection

Configuring the Caching Database

This section describes the properties for caching data to the persistent store of your choice.

CacheLocation

The CacheLocation property species the path to a file-system-based database. When caching is enabled, a file-system-based database is used by default. If CacheLocation is not specified, this database is stored at the path in Location. If neither of these connection properties are specified, the connector uses a platform-dependent default location.

CacheConnection

The CacheConnection property specifies a database driver and the connection string to the caching database.

CacheDriver and CacheProvider

Both the CacheDriver and CacheProvider properties are supported. Each specifies a database driver and the connection string to the caching database. CacheDriver is designed for Linux and MacOS; CacheProvider is Windows-based.

CData Python Connector for XML

Caching Metadata

This section describes how to enable caching metadata and how to update the metadata cache.

Before being able to query data, the connector requires relevant metadata to be retrieved. By default, metadata is cached in memory and shared across connections. But if you want to persist across processes, or if metadata requests are expensive, the solution is to cache the metadata to disk.

Enable Caching Metadata

To enable caching of metadata, set CacheMetadata = true and see Configuring the Cache Connection for instructions on how to configure your connection string. The connector caches the metadata the first time it is needed and uses the metadata cache for subsequent requests.

Update the Metadata Cache

Because metadata is cached, changes to metadata on the live source, for example, adding or removing a column or attribute, are not automatically reflected in the metadata cache. To get updates to the live metadata, you need to delete or drop the cached data.

CData Python Connector for XML

Automatically Caching Data

Automatically caching data is useful when you do not want to rebuild the cache for each query. When you query data for the first time, the connector automatically initializes and builds a cache in the background. When AutoCache = true, the connector uses the cache for subsequent query executions, resulting in faster response times.

Configuring Automatic Caching

Caching the NorthwindOData Table

The following example caches the NorthwindOData table in the file specified by the CacheLocation property of the connection string.

SELECT Email, Username FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'

Common Use Case

A common use for automatically caching data is to improve driver performance when making repeated requests to a live data source, such as building a report or creating a visualization. With auto caching enabled, repeated requests to the same data may be executed in a short period of time, but within an allowable tolerance (CacheTolerance) of what is considered "live" data.

CData Python Connector for XML

Explicitly Caching Data

With explicit caching (AutoCache = false), you decide exactly what data is cached and when to query the cache instead of the live data. Explicit caching gives you full control over the cache contents by using CACHE Statements. This section describes some strategies to use the caching features offered by the connector.

Creating the Cache

To load data in the cache, issue the following statement.

CACHE SELECT * FROM tableName WHERE ...

Once the statement is issued, any matching data in tableName is loaded into the corresponding table.

Updating the Cache

This section describes two ways to update the cache.

Updating with the SELECT Statement

The following example shows a statement that can update modified rows and add missing rows in the cached table. However, this statement does not delete extra rows that are already in the cache. This statement only merges the new rows or updates the existing rows.

CACHE SELECT * FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'

Updating with the TRUNCATE Statement

The following example shows a statement that can update modified rows and add missing rows in the cached table. This statement can also delete rows in the cache table that are not present in the live data source.

  CACHE WITH TRUNCATE SELECT * FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'
  

Query the Data in Online or Offline Mode

This section describes how to query the data in online or offline mode.

Online: Select Cached Tables

You can use the tableName#CACHE syntax to explicitly execute queries to the cache while still online, as shown in the following example.

SELECT * FROM NorthwindOData#CACHE

Offline: Select Cached Tables

With Offline = true, SELECT statements always execute against the local cache database, regardless of whether you explicitly specify the cached table or not. Modification of the cache is disabled in Offline mode to prevent accidentally updating only the cached data. Executing a DELETE/UPDATE/INSERT statement while in Offline mode results in an exception.

The following example selects from the local cache but not the live data source because Offline = true.

SELECT * FROM NorthwindOData WHERE Email='ana.trujilo@northwind.org' ORDER BY Username ASC

Delete Data from the Cache

You can delete data from the cache by building a direct connection to the database. Note that the connector does not support manually deleting data from the cache.

Common Use Case

A common use for caching is to have an application always query the cached data and only update the cache at set intervals, such as once every day or every two hours. There are two ways in which this can be implemented:

  • AutoCache = false and Offline = false. All queries issued by the application explicitly reference the tableName#CACHE table. When the cache needs to be updated, the application executes a tableName#CACHE ... statement to bring the cached data up to date.
  • Offline = true. Caching is transparent to the application. All queries are executed against the table as normal, so most application code does not need to be aware that caching is done. To update the cached data, simply create a separate connection with Offline = false and execute a tableName#CACHE ... statement.

CData Python Connector for XML

Data Type Mapping

The connector maps types from the data source to the corresponding data type available in the chosen cache database. The following table shows the mappings between the data types configured in the schema and the data types in the database. Some schema types have synonyms which are all listed in the Schema column.

Data Type Mapping

Note: String columns can map to different data types depending on their length.

Schema .NET JDBC SQL Server Derby MySQL Oracle SQLite Access
int, integer, int32 Int32 int int INTEGER INT NUMBER integer LONG
smallint, short, int16 Int16 short smallint SMALLINT SMALLINT NUMBER integer SHORT
double, float, real Double double float DOUBLE DOUBLE NUMBER double DOUBLE
date DateTime java.sql.Date date DATE DATE DATE date DATETIME
datetime, timestamp DateTime java.sql.Date datetime TIMESTAMP DATETIME TIMESTAMP datetime DATETIME
time, timespan TimeSpan java.sql.Time time TIME TIME TIMESTAMP datetime DATETIME
string, varchar String java.lang.String If length > 4000: nvarchar(max), Otherwise: nvarchar(length)If length > 32672: LONG VARCHAR, Otherwise VARCHAR(length)If length > 255: LONGTEXT, Otherwise: VARCHAR(length)If length > 4000: CLOB, Otherwise: VARCHAR2(length)nvarchar(length)If length > 255: LONGTEXT, Otherwise: VARCHAR(length)
long, int64, bigint Int64 long bigint BIGINT BIGINT NUMBER bigint LONG
boolean, bool Boolean boolean tinyint SMALLINT BIT NUMBER tinyint BIT
decimal, numeric Decimal java.math.BigDecimal decimal DECIMAL DECIMAL DECIMAL decimal CURRENCY
uuid Guid java.util.UUID nvarchar(length) VARCHAR(length)VARCHAR(length) VARCHAR2(length)nvarchar(length) VARCHAR(length)
binary, varbinary, longvarbinary byte[] byte[] binary(1000) or varbinary(max) after SQL Server 2000, image otherwise BLOB LONGBLOB BLOB BLOB LONGBINARY

CData Python Connector for XML

Query Processing

Query Processing

CData has a client-side SQL engine built into the connector library. This enables support for the full capabilities that SQL-92 offers, including filters, aggregations, functions, etc.

For sources that do not support SQL-92, the connector offloads as much of SQL statement processing as possible to XML and then processes the rest of the query in memory (client-side). This results in optimal performance.

For data sources with limited query capabilities, the connector handles transformations of the SQL query to make it simpler for the connector. The goal is to make smart decisions based on the query capabilities of the data source to push down as much of the computation as possible. The XML Query Evaluation component examines SQL queries and returns information indicating what parts of the query the connector is not capable of executing natively.

The XML Query Slicer component is used in more specific cases to separate a single query into multiple independent queries. The client-side Query Engine makes decisions about simplifying queries, breaking queries into multiple queries, and pushing down or computing aggregations on the client-side while minimizing the size of the result set.

There's a significant trade-off in evaluating queries, even partially, client-side. There are always queries that are impossible to execute efficiently in this model, and some can be particularly expensive to compute in this manner. CData always pushes down as much of the query as is feasible for the data source to generate the most efficient query possible and provide the most flexible query capabilities.

More Information

For a full discussion of how CData handles query processing, see CData Architecture: Query Execution.

CData Python Connector for XML

Logging

Logging

Capturing connector logging can be very helpful when diagnosing error messages or other unexpected behavior.

Basic Logging

To begin capturing connector logging, set these properties:

  • Logfile: A filepath that designates the name and location of the log file.
  • Verbosity: A numerical value (1-5) that determines the amount of detail in the log. See the page in the Connection Properties section for an explanation of the five levels.
  • MaxLogFileSize: When the limit is hit, a new log is created in the same folder with the date and time appended to the end. The default limit is 100 MB. Values lower than 100 kB will use 100 kB as the value instead.
  • MaxLogFileCount: A string specifying the maximum file count of log files. When the limit is hit, a new log is created in the same folder with the date and time appended to the end and the oldest log file will be deleted. Minimum supported value is 2. A value of 0 or a negative value indicates no limit on the count.

Once these properties are set, the connector populates the log file as it carries out various tasks, such as when authentication is performed or queries are executed. If the specified file doesn't already exist, it is created.

Log Verbosity

The verbosity level determines the amount of detail that the connector reports to the Logfile. Supported Verbosity levels range from 1 to 5.

The following list describes each level:

1Setting Verbosity to 1 logs the query, the number of rows returned by it, the start of execution and the time taken, and any errors.
2Setting Verbosity to 2 logs everything included in Verbosity 1, cache queries, and additional information about the request.
3Setting Verbosity to 3 also logs HTTP headers, as well as the body of the request and the response.
4Setting Verbosity to 4 also logs transport-level communication with the data source. This includes SSL negotiation.
5Setting Verbosity to 5 also logs communication with the data source and additional details that may be helpful in troubleshooting problems. This includes interface commands.

For normal operations, Verbosity should not be set to greater than 1. At higher verbosities you can log substantial amounts of data, which can delay execution times.

To refine the logged content further by showing/hiding specific categories of information, see LogModules.

Sensitive Data

Verbosity levels of 3 and higher may capture information that you do not want shared outside of your organization. The following lists information of concern for each level:

  • Verbosity 3: The full body of the request and the response, which includes all the data returned by the connector
  • Verbosity 4: SSL certificates
  • Verbosity 5: Any extra transfer data not included at Verbosity 3, such as non human-readable binary transfer data

Note: Although we mask sensitive values, such as passwords, in the connection string and any request in the log, it is always best practice to review the logs for any sensitive information before sharing outside your organization.

Advanced Logging

You may want to refine the exact information that is recorded to the log file. This can be accomplished using the LogModules property. This property allows you to filter the logging using a semicolon-separated list of logging modules.

Example property value:

LogModules=INFO;EXEC;SSL;SQL;META;

Note that the logfile filtering triggered by the Verbosity connection property takes precedence over the filtering imposed by this connection property. This means that operations of a higher verbosity level than the level specified in the Verbosity connection property are not printed in the logfile, even if they belong to one of the modules specified in this connection property.

The available modules and submodules are:

Module Name Module Description Submodules
INFO General Information. Includes the connection string, product version (build number), and initial connection messages.
  • Connec – Information related to creating or destroying connections.
  • Messag – Generic label for messages pertaining to connections, the connection string, and product version. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
EXEC Query Execution. Includes execution messages for user-written SQL queries, parsed SQL queries, and normalized SQL queries. Success/failure messages for queries and query pages appear here as well.
  • Messag – Messages pertaining to query execution. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Normlz – Query normalization steps. Query normalization is when the product takes the user-submitted query and rewrites the query to get the same results with optimal performance.
  • Origin – This label applies to any messages recording a user's original query (the exact, unaltered, non-normalized query executed by the user).
  • Page – Messages related to query paging.
  • Parsed – Query parsing steps. Parsing is the process of converting the user-submitted query into a standardized format for easier processing.
HTTP HTTP protocol messages. Includes HTTP requests/responses (including POST messages), as well as Kerberos related messages.
  • KERB – HTTP requests related to Kerberos.
  • Messag – Messages pertaining to HTTP protocols. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Unpack – This label applies to messages about zipped data being returned from the service API and unpacked by the product.
  • Res – Messages containing HTTP responses.
  • Req – Messages containing HTTP requests.
WSDL Messages pertaining to the generation of WSDL/XSD files.
SSL SSL certificate messages.
  • Certif – Messages pertaining to SSL certificates.
AUTH Authentication related failure/success messages.
  • Messag – Messages pertaining to authentication. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • OAuth – Messages related to OAuth authentication.
  • Krbros – Kerberos-related authentication messages.
SQL Includes SQL transactions, SQL bulk transfer messages, and SQL result set messages.
  • Bulk – Messages pertaining to bulk query execution.
  • Cache – Messages related to reading row data from and writing row data to the product's cache for better performance.
  • Messag – Messages pertaining to SQL transactions. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • ResSet – Query resultsets.
  • Transc – Messages related to handling transactions, including information about the number of jobs executed and backup table handling.
META Metadata cache and schema messages.
  • Cache – Messages related to reading from and modifying column and table definitions in the product's cache for better performance.
  • Schema – Messages related to retrieving metadata from or modifying the service schema.
  • MemSto – Messages related to writing to or reading from in-memory metadata cache.
  • Storag – Messages relating to storing metadata on disk or in an external data store, rather than in memory.
FUNC Information related to executing SQL functions.
  • Errmsg – Error messages related to executing SQL functions.
TCP Incoming and outgoing raw bytes on TCP transport layer messages.
  • Send – Raw data sent via the TCP protocol.
  • Receiv – Raw data received via the TCP protocol.
FTP Messages pertaining to the File Transfer Protocol.
  • Info – Status messages related to communication in the FTP protocol.
  • Client – Messages related to actions taken by the FTP client (the product) during FTP communication.
  • Server – Messages related to actions taken by the FTP server during FTP communication.
SFTP Messages pertaining to the Secure File Transfer Protocol.
  • Info – Status messages related to communication in the SFTP protocol.
  • To_Server – Messages related to actions taken by the SFTP client (the product) during SFTP communication.
  • From_Server – Messages related to actions taken by the SFTP server during SFTP communication.
POP Messages pertaining to data transferred via the Post Office Protocol.
  • Client – Messages related to actions taken by the POP client (the product) during POP communication.
  • Server – Messages related to actions taken by the POP server during POP communication.
  • Status – Status messages related to communication in the POP protocol.
SMTP Messages pertaining to data transferred via the Simple Mail Transfer Protocol.
  • Client – Messages related to actions taken by the SMTP client (the product) during SMTP communication.
  • Server – Messages related to actions taken by the SMTP server during SMTP communication.
  • Status – Status messages related to communication in the SMTP protocol.
CORE Messages relating to various internal product operations not covered by other modules.
DEMN Messages related to SQL remoting.
STRG Messages related to reading from and writing to raw files in formats like CSV and JSON.
CLJB Messages about bulk data uploads (cloud job).
  • Commit – Submissions for bulk data uploads.
SRCE Miscellaneous messages produced by the product that don't belong in any other module.
TRANCE Advanced messages concerning low-level product operations.

CData Python Connector for XML

Exception Handling

Exception Handling

Exceptions can be surfaced from either the API or the CData Python Connector for XML. Each exception will have an error code, an error message, and a SQL state.

Error Codes

The error code classifies the type of error.

0 NONE Used for unclassified errors and internally handled errors. This code also covers data source-specific errors that do not fit in any specific category.
65537 TCP_UNKNOWN_HOST Unable to resolve a hostname (DNS failure).
65538 TCP_CONNECTION_REFUSED Could not connect to the remote port.
65539 TCP_AUTH_FAILED Login failed when using a binary authentication protocol. Use this for auth errors when the protocol is not HTTP (LDAP, SASL, Kerberos, ...).
65540 TCP_TIMEOUT Did not receive a response after sending a request to the server.
65541 TCP_PROTOCOL For wire protocol drivers. Either the server sent a bad packet that we are unable to process, or we cannot construct a packet to send.
131073 TLS_SERVER_UNTRUSTED Could not verify SSL server certificate.
131074 TLS_CLIENT_UNTRUSTED Server did not accept the client certificate we sent.
196609 OAUTH_DECRYPT_FAILED OAuthEncryptKey did not decrypt the OAuthSettings file.
196610 OAUTH_MISSING_CLIENT_INFO OAuthClientId / OAuthClientSecret / OAuthJWTCert is missing.
196611 OAUTH_MISSING_PROP General OAuth property missing. OAUTH_MISSING_CLIENT_INFO is used for missing client ID/secret and JWT cert.
196612 OAUTH_NO_ACCESS_TOKEN Unable to retrieve access token. Only use this when getting a token in GetOAuthAccessToken / RefreshOAuthAccessToken.
196613 OAUTH_TOKEN_EXPIRED The access token expired. Normally used with a RefreshOAuth/OAuthException behavior.
196614 OAUTH_INVALID_PROP OAuth property has an invalid value. OAUTH_MISSING_CLIENT_INFO / OAUTH_MISSING_PROP is used if the value is not set.
262145 HTTP_REQUEST_TIMEOUT Did not receive a response from the HTTP server.
262146 HTTP_CLIENT_ERROR Generic HTTP 4xx error. Only use for 4xx errors not covered by other codes.
262147 HTTP_AUTH_FAILED HTTP 401 error.
262148 HTTP_LIMIT_EXCEEDED HTTP 429 error.
262149 HTTP_SERVER_ERROR HTTP 5xx error.
262150 HTTP_NOT_FOUND_ERROR HTTP 404 error.
327681 CORE_TIMEOUT General timeout. Not related to a specific network request.
327682 CORE_OP_NOT_ALLOWED Operation blocked by provider permissions.
327683 CORE_CONNECTION_CONFIG Connection configuration is not valid.
327684 CORE_SERIALIZE Failed to encode data into a specific format (XML, JSON, CSV, ...).
327685 CORE_DESERIALIZE Failed to decode data from a specific format (XML, JSON, CSV, ...).
393217 SQL_SYNTAX_ERROR Unable to parse a SQL query.
393218 SQL_MISSING_COLUMNS Query did not include required columns.
393219 SQL_MISSING_PARAMS Stored procedure call did not include required parameters.
393220 SQL_QUERY_NOT_SUPPORTED A part of the query is not allowed in the current context.
458753 SSH_SERVER_UNTRUSTED Could not verify SSH server.
524289 STORAGE_LIST_EXCEPTION Issue listing storage resources.
524290 STORAGE_RESOURCE_NOT_FOUND Issue finding storage resources.
524291 STORAGE_ROOT_RESOURCE_NOT_FOUND The root resource (bucket/share/drive) was not found; cannot create it in flat file drivers.
524292 STORAGE_RESOURCE_NOT_A_DIRECTORY Storage resource is not a directory.
524293 STORAGE_RESOURCE_NOT_A_FILE Storage resource is not a file.
524294 STORAGE_PERMISSIONS_DENIED Storage permissions denied.

SQL State

The SQL state is used when throwing generic provider errors to the wrapper and indicates the success or failure of a call.

Some of the common SQL states are listed below:

07007 REQUIRED_CLAUSE Class Code 07: Dynamic SQL Error.
08001 OPEN_CONNECTION Class Code 08: Connection Exception. The connection was unable to be established to the application server or other server.
08004 REJECT_CONNECTION The application server rejected establishment of the connection.
42501 PRIVILEGE_IDENTIFIED_OBJECT Class Code 42: Syntax Error or Access Rule Violation. The authorization ID does not have the privilege to perform the specified operation on the identified object.
42506 AUTH_FAILED Owner authorization failure occurred.
42601 SQL_SYNTAX A character, token, or clause is invalid or missing.

Error Message

The error message provides more detailed reasoning about why the error occurred. It provides an explanation of the issue, and may include steps on how to resolve it.

CData Python Connector for XML

SQL Compliance

The CData Python Connector for XML supports several operations on data, including querying, deleting, modifying, and inserting.

SELECT Statements

See SELECT Statements for a syntax reference and examples.

INSERT Statements

See INSERT Statements for a syntax reference and examples, as well as retrieving the new records' Ids.

UPDATE Statements

The primary key Id is required to update a record. See UPDATE Statements for a syntax reference and examples.

DELETE Statements

The primary key Id is required to delete a record. See DELETE Statements for a syntax reference and examples.

CACHE Statements

CACHE statements allow granular control over the connector's caching functionality. For a syntax reference and examples, see CACHE Statements.

For more information on the caching feature, see Caching Data.

EXECUTE Statements

Use EXECUTE or EXEC statements to execute stored procedures. See EXECUTE Statements for a syntax reference and examples.

Names and Quoting

  • Table and column names are considered identifier names; as such, they are restricted to the following characters: [A-Z, a-z, 0-9, _:@].
  • To use a table or column name with characters not listed above, the name must be quoted using square brackets ([name]) in any SQL statement.
  • Parameter names can optionally start with the @ symbol (e.g., @p1 or @CustomerName) and cannot be quoted.
  • Strings must be quoted using single quotes (e.g., 'John Doe').

CData Python Connector for XML

SQL Functions

The connector provides functions that are similar to those that are available with most standard databases. These functions are implemented in the CData provider engine and thus are available across all data sources with the same consistent API. Three categories of functions are available: string, date, and math.

The connector interprets all SQL function inputs as either strings or column identifiers, so you need to escape all literals as strings, with single quotes. For example, contrast the SQL Server syntax and connector syntax for the DATENAME function:

  • SQL Server:
    SELECT DATENAME(yy,GETDATE())
  • connector:
    SELECT DATENAME('yy',GETDATE())

String Functions

These functions perform string manipulations and return a string value. See STRING Functions for more details.

Date Functions

These functions perform date and date time manipulations. See DATE Functions for more details.

Math Functions

These functions provide mathematical operations. See MATH Functions for more details.

CData Python Connector for XML

STRING Functions

ASCII(character_expression)

Returns the ASCII code value of the left-most character of the character expression.

  • character_expression: The character expression.

                      SELECT ASCII('0');
                      --  Result: 48
                    

BASE64_ENCODE(input_binary)

Returns the Base64-encoded string form of a binary input.

  • input_binary: The binary value to encode.

                        SELECT BASE64_ENCODE(BinaryData);
                    -- Result: 'QmFzZTY0RW5jb2RlZA=='
                    

BASE64_DECODE(input_string)

Returns the binary result of decoding a Base64-encoded string.

  • input_string: The Base64-encoded string.

                        SELECT BASE64_DECODE('QmFzZTY0RW5jb2RlZA==');
                    -- Result: (binary output)
                    

CHAR(integer_expression)

Converts the integer ASCII code to the corresponding character.

  • integer_expression: The integer from 0 through 255.

                      SELECT CHAR(48);
                      -- Result: '0'
                    

CHARINDEX(expressionToFind ,expressionToSearch [,start_location ])

Returns the starting position of the specified expression in the character string.

  • expressionToFind: The character expression to find.
  • expressionToSearch: The character expression, typically a column, to search.
  • start_location: An optional character position to start searching for expressionToFind in expressionToSearch.

                      SELECT CHARINDEX('456', '0123456');
                      -- Result: 4

                      SELECT CHARINDEX('456', '0123456', 5);
                      -- Result: -1
                    

CHAR_LENGTH(character_expression),

Returns the number of UTF-8 characters present in the expression.

  • character_expression: The set of characters to be evaluated for length.

				 SELECT CHAR_LENGTH('sample text') FROM Account LIMIT 1
				 -- Result: 11			
				

CONCAT(string_value1, string_value2, ..., string_valueN)

Returns the string that is the concatenation of two or more string values.

  • string_value1: The first string to be concatenated.
  • string_value2: The second string to be concatenated.
  • string_valueN: (optional) Any additional strings to be concatenated.

                      SELECT CONCAT('Hello, ', 'world!');
                      -- Result: 'Hello, world!'
                    

CONTAINS(expressionToSearch, expressionToFind)

Returns 1 if expressionToFind is found within expressionToSearch; otherwise, 0.

  • expressionToSearch: The character expression, typically a column, to search.
  • expressionToFind: The character expression to find.

                      SELECT CONTAINS('0123456', '456');
                      -- Result: 1

                      SELECT CONTAINS('0123456', 'Not a number');
                      -- Result: 0
                    

ENDSWITH(character_expression, character_suffix)

Returns 1 if character_expression ends with character_suffix; otherwise, 0.

  • character_expression: The character expression.
  • character_suffix: The character suffix to search for.

                      SELECT ENDSWITH('0123456', '456');
                      -- Result: 1

                      SELECT ENDSWITH('0123456', '012');
                      -- Result: 0
                    

FILESIZE(uri)

Returns the number of bytes present in the file at the specified file path.

  • uri: The path of the file from which to read the size.

				SELECT FILESIZE('C:/Users/User1/Desktop/myfile.txt');
				-- Result: 23684
				

FORMAT(value [, parseFormat], format )

Returns the value formatted with the specified format.

  • value: The string to format.
  • format: The string specifying the output syntax of the date or numeric format.
  • parseFormat: The string specifying the input syntax of the date value. Not applicable to numeric types.

                      SELECT FORMAT(12.34, '#');
                      -- Result: 12

                      SELECT FORMAT(12.34, '#.###');
                      -- Result: 12.34

                      SELECT FORMAT(1234, '0.000E0');
                      -- Result: 1.234E3
                      
                      SELECT FORMAT('2019/01/01', 'yyyy-MM-dd');
                      -- Result: 2019-01-01
                      
                      SELECT FORMAT('20190101', 'yyyyMMdd', 'yyyy-MM-dd');
                      -- Result: '2019-01-01'
                    

HASHBYTES(algorithm, value)

Returns the hash of the input value as a byte array using the given algorithm. The supported algorithms are MD5, SHA1, SHA2_256, SHA2_512, SHA3_224, SHA3_256, SHA3_384, and SHA3_512.

  • algorithm: The algorithm to use for hashing. Must be one of MD5, SHA1, SHA2_256, SHA2_512, SHA3_224, SHA3_256, SHA3_384, or SHA3_512.
  • value: The value to hash. Must be either a string or byte array.

                      SELECT HASHBYTES('MD5', 'Test');
                      -- Result (byte array): 0x0CBC6611F5540BD0809A388DC95A615B
                    

INDEXOF(expressionToSearch, expressionToFind [,start_location ])

Returns the starting position of the specified expression in the character string.

  • expressionToSearch: The character expression, typically a column, to search.
  • expressionToFind: The character expression to find.
  • start_location: An optional character position to start searching for expressionToFind in expressionToSearch.

                      SELECT INDEXOF('0123456', '456');
                      -- Result: 4

                      SELECT INDEXOF('0123456', '456', 5);
                      -- Result: -1
                    

ISALPHABETIC(character_expression)

Returns 1 if the character expression consists only of alphabetic characters; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISALPHABETIC('Hello');
                      -- Result: 1

                      SELECT ISALPHABETIC('Hello123');
                      -- Result: 0

                      SELECT ISALPHABETIC('Hello!');
                      -- Result: 0
                    

ISALPHANUMERIC(character_expression)

Returns 1 if the character expression consists only of alphabetic and numeric characters; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISALPHANUMERIC('Hello123');
                      -- Result: 1

                      SELECT ISALPHANUMERIC('123');
                      -- Result: 1

                      SELECT ISALPHANUMERIC('Hello.123');
                      -- Result: 0
                    

ISNUMERIC(character_expression)

Returns 1 if the character expression consists only of numeric digits and up to one decimal point; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISNUMERIC('123');
                      -- Result: 1

                      SELECT ISNUMERIC('123.45');
                      -- Result: 1

                      SELECT ISNUMERIC('123.45.67');
                      -- Result: 0

                      SELECT ISNUMERIC('12a3');
                      -- Result: 0
                    

JSON_EXTRACT(json, jsonpath)

Selects any value in a JSON array or object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to extract.
  • jsonpath: The XPath used to select the nodes. The JSONPath must be a string constant. The values of the nodes selected will be returned in a token-separated list.

                      SELECT JSON_EXTRACT('{"test": {"data": 1}}', '$.test');
                      -- Result: '{"data":1}'

                      SELECT JSON_EXTRACT('{"test": {"data": 1}}', '$.test.data');
                      -- Result: 1

                      SELECT JSON_EXTRACT('{"test": {"data": [1, 2, 3]}}', '$.test.data[1]');
                      -- Result: 2
                    

LEFT ( character_expression , integer_expression )

Returns the specified number of characters counting from the left of the specified string.

  • character_expression: The character expression.
  • integer_expression: The positive integer that specifies how many characters will be returned counting from the left of character_expression.

                      SELECT LEFT('1234567890', 3);
                      -- Result: '123'
                    

LEN(string_expression)

Returns the number of characters of the specified string expression.

  • string_expression: The string expression.

                      SELECT LEN('12345');
                      -- Result: 5
                    

LOCATE(substring,string)

Returns an integer representing how many characters into the string the substring appears.

  • substring: The substring to find inside larger string.
  • string: The larger string that is searched for the substring.
  • start locations: An optional integer that sets the character position (offset) from which to start searching.

				SELECT LOCATE('sample','XXXXXsampleXXXXX');
				-- Result: 6

                SELECT LOCATE('sample', 'XXXXXsampleXXXXX', 7)
                -- Result: 0
				

LOWER ( character_expression )

Returns the character expression with the uppercase character data converted to lowercase.

  • character_expression: The character expression.

                      SELECT LOWER('MIXED case');
                      -- Result: 'mixed case'
                    

LTRIM(character_expression)

Returns the character expression with leading blanks removed.

  • character_expression: The character expression.

                      SELECT LTRIM('     trimmed');
                      -- Result: 'trimmed'
                    

MASK(string_expression, mask_character [, start_index [, end_index ]])

Replaces the characters between start_index and end_index with the mask_character within the string.

  • string_expression: The string expression to be searched.
  • mask_character: The character to mask with.
  • start_index: The optional number of characters to leave unmasked at beginning of string. Defaults to 0.
  • end_index: The optional number of characters to leave unmasked at end of string. Defaults to 0.

                        SELECT MASK('1234567890','*',);
                        -- Result: '**********'
                        SELECT MASK('1234567890','*', 4);
                        -- Result: '1234******'
                        SELECT MASK('1234567890','*', 4, 2);
                        -- Result: '1234****90'  
                    

NCHAR(integer_expression)

Returns the Unicode character with the specified integer code as defined by the Unicode standard.

  • integer_expression: The integer from 0 through 65535 (0 through xFFFF).

OCTET_LENGTH(character_expression),

Returns the number of bytes present in the expression.

  • character_expression: The set of characters to be be evaluated.

				 SELECT OCTET_LENGTH('text') FROM Account LIMIT 1
				 -- Result: 4
				

PATINDEX(pattern, expression)

Returns the starting position of the first occurrence of the pattern in the expression. Returns 0 if the pattern is not found.

  • pattern: The character expression that contains the sequence to be found. The wild-card character % can be used only at the start or end of the expression.
  • expression: The expression, typically a column, to search for the pattern.

                      SELECT PATINDEX('123%', '1234567890');
                      -- Result: 1

                      SELECT PATINDEX('%890', '1234567890');
                      -- Result: 8

                      SELECT PATINDEX('%456%', '1234567890');
                      -- Result: 4
                    

POSITION(expressionToFind IN expressionToSearch)

Returns the starting position of the specified expression in the character string.

  • expressionToFind: The character expression to find.
  • expressionToSearch: The character expression, typically a column, to search.

                      SELECT POSITION('456' IN '123456');
                      -- Result: 4

                      SELECT POSITION('x' IN '123456');
                      -- Result: 0
                    

QUOTENAME(character_string [, quote_character])

Returns a valid SQL Server-delimited identifier by adding the necessary delimiters to the specified Unicode string.

  • character_string: The string of Unicode character data. The string is limited to 128 characters. Inputs greater than 128 characters return null.
  • quote_character: An optional single character to be used as the delimiter. These include:
    • a single quotation mark (')
    • a left or right bracket ([])
    • a double quotation mark (")
    • a left or right parenthesis ( () )
    • a greater or less than sign (><)
    • a left or right brace ({})
    • a backtick (`)

    If quote_character is not specified brackets are used. If an unacceptable character is supplied, it returns NULL.


                      SELECT QUOTENAME('table_name');
                      -- Result: '[table_name]'

                      SELECT QUOTENAME('table_name', '"');
                      -- Result: '"table_name"'

                      SELECT QUOTENAME('table_name', '[');
                      -- Result: '[table_name]'
                    

REGEXP_REPLACE(expr, pattern [, replacement [, position [, occurrence [, match_type]]]])

Replaces occurrences of a regular expression pattern in the input string with a specified value and returns the resulting string.

  • expr: The string expression to be searched.
  • pattern: The regular expression pattern to match.
  • replacement: (optional) The string to replace each matched occurrence of pattern with. Supports backreferences \1 through \9 and escape sequences \n, \r, \t, and \\. By default, this argument is an empty string, meaning matched portions are removed from the output string.
  • position: (optional) The 1-based starting position used when searching for regular expression matches in expr. The default is 1. All characters prior to the starting position are included in the output string unaltered. Skipped characters are ignored when calculating regular expression matches, even if they match pattern.
  • occurrence: (optional) Specifies whether all occurrences of pattern,, or only a specific occurrence of pattern are replaced. The default is 0, which means all occurrences of pattern are replaced with replacement. Set to 1 to only replace the first instance of the pattern; 2 to replace the second; etc.
  • match_type: (optional) Modifiers used to customize matching behavior. Supported values are: 'c' (case-sensitive, default), 'i' (case-insensitive), 'm' (multiline), 'n' (dot matches newline), 'x' (extended mode). These can be freely combined by including the letters back to back. For example, 'im' applies the functionality of both 'i' and 'm'. The regular expression syntax used is that of the Extended mode ('x') ignores whitespace and allows inline comments. If the pattern needs to match a literal space, it must be explicitly escaped.

                      SELECT REGEXP_REPLACE('abc123def456', '\d+', 'NUM');
                      -- Result: 'abcNUMdefNUM'

                      SELECT REGEXP_REPLACE('Hello\nHELLO\nhello', '^hello', 'X', 1, 0, 'im');
                      -- Result: 'X\nX\nX'
                    

REPLACE(string_expression, string_pattern, string_replacement)

Replaces all occurrences of a string with another string.

  • string_expression: The string expression to be searched. This can be a character or binary data type.
  • string_pattern: The substring to be found. Cannot be an empty string.
  • string_replacement: The replacement string.

                      SELECT REPLACE('1234567890', '456', '|');
                      -- Result: '123|7890'

                      SELECT REPLACE('123123123', '123', '.');
                      -- Result: '...'

                      SELECT REPLACE('1234567890', 'a', 'b');
                      -- Result: '1234567890'
                    

REPLICATE ( string_expression ,integer_expression )

Repeats the string value the specified number of times.

  • string_expression: The string to replicate.
  • integer_expression: The repeat count.

                      SELECT REPLACE('x', 5);
                      -- Result: 'xxxxx'
                    

REVERSE ( string_expression )

Returns the reverse order of the string expression.

  • string_expression: The string.

                      SELECT REVERSE('1234567890');
                      -- Result: '0987654321'
                    

RIGHT ( character_expression , integer_expression )

Returns the right part of the string with the specified number of characters.

  • character_expression: The character expression.
  • integer_expression: The positive integer that specifies how many characters of the character expression will be returned.

                      SELECT RIGHT('1234567890', 3);
                      -- Result: '890'
                    

RTRIM(character_expression)

Returns the character expression after it removes trailing blanks.

  • character_expression: The character expression.

                      SELECT RTRIM('trimmed     ');
                      -- Result: 'trimmed'
                    

SOUNDEX(character_expression)

Returns the four-character Soundex code, based on how the string sounds when spoken.

  • character_expression: The alphanumeric expression of character data.

                      SELECT SOUNDEX('smith');
                      -- Result: 'S530'
                    

SPACE(repeatcount)

Returns the string that consists of repeated spaces.

  • repeatcount: The number of spaces.

                      SELECT SPACE(5);
                      -- Result: '     '
                    

SPLIT(string, delimiter, offset)

Returns a section of the string between to delimiters.

  • string: The string to split.
  • delimiter: The character to split the string with.
  • offset: The number of the split to return. Positive numbers are treated as offsets from the left, and negative numbers are treated as offsets from the right.

                      SELECT SPLIT('a/b/c/d', '/', 1);
                      -- Result: 'a'
                      SELECT SPLIT('a/b/c/d', '/', -2);
                      -- Result: 'c'
                    

STARTSWITH(character_expression, character_prefix)

Returns 1 if character_expression starts with character_prefix; otherwise, 0.

  • character_expression: The character expression.
  • character_prefix: The character prefix to search for.

                      SELECT STARTSWITH('0123456', '012');
                      -- Result: 1

                      SELECT STARTSWITH('0123456', '456');
                      -- Result: 0
                    

STR ( float_expression [ , integer_length [ , integer_decimal ] ] )

Returns the character data converted from the numeric data. For example, STR(123.45, 6, 1) returns 123.5.

  • float_expression: The float expression.
  • length: The optional total length to return. This includes decimal point, sign, digits, and spaces. The default is 10.
  • decimal: The optional number of places to the right of the decimal point. The decimal must be less than or equal to 16.

                      SELECT STR('123.456');
                      -- Result: '123'

                      SELECT STR('123.456', 2);
                      -- Result: '**'

                      SELECT STR('123.456', 10, 2);
                      -- Result: '123.46'
                    

STUFF(character_expression , integer_start , integer_length , replaceWith_expression)

Inserts a string into another string. It deletes the specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

  • character_expression: The string expression.
  • start: The integer value that specifies the location to start deletion and insertion. If start or length is negative, null is returned. If start is longer than the string to be modified, character_expression, null is returned.
  • length: The integer that specifies the number of characters to delete. If length is longer than character_expression, deletion occurs up to the last character in replaceWith_expression.
  • replaceWith_expression: The expression of character data that will replace length characters of character_expression beginning at the start value.

                      SELECT STUFF('1234567890', 3, 2, 'xx');
                      -- Result: '12xx567890'
                    

SUBSTRING(string_value FROM start FOR length)

Returns the part of the string with the specified length; starts at the specified index.

  • string_value: The character string.
  • start: The positive integer that specifies the start index of characters to return.
  • length: Optional. The positive integer that specifies how many characters will be returned.

                      SELECT SUBSTRING('1234567890' FROM 3 FOR 2);
                      -- Result: '34'

                      SELECT SUBSTRING('1234567890' FROM 3);
                      -- Result: '34567890'
                    
You can also drop the FROM and FOR clauses:
                    SELECT SUBSTRING('1234567890', 3, 2)
                    --Result: '34'
                    SELECT SUBSTRING('1234567890', 3)
                    --Result: '34567890'
                    

TEXT_ENCODE(input_string, charset)

Returns binary output by encoding a string using the specified character set.

  • input_string: The plain text string.
  • charset: The character set to use, such as 'UTF-8', 'ISO-8859-1'.

                    SELECT TEXT_ENCODE('Café', 'UTF-8');
                    -- Result: (binary output)
                    

TEXT_DECODE(input_binary, charset)

Returns a string decoded from binary data using the specified character set.

  • input_binary: The binary value to decode.
  • charset: The character set used for decoding.

                    SELECT TEXT_DECODE(BinaryData, 'UTF-8');
                    -- Result: 'Café'
                    

TOSTRING(string_value1)

Converts the value of this instance to its equivalent string representation.

  • string_value1: The string to be converted.

                      SELECT TOSTRING(123);
                      -- Result: '123'

                      SELECT TOSTRING(123.456);
                      -- Result: '123.456'

                      SELECT TOSTRING(null);
                      -- Result: ''
                    

TRIM(trimspec trimchar FROM string_value)

Returns the character expression with leading and/or trailing blanks removed.

  • trimspec: Optional. If included must be one of the keywords BOTH, LEADING or TRAILING.
  • trimchar: Optional. If included should be a one-character string value.
  • string_value: The string value to trim.

                      SELECT TRIM('     trimmed     ');
                      -- Result: 'trimmed'

                      SELECT TRIM(LEADING FROM '     trimmed     ');
                      -- Result: 'trimmed     '

                      SELECT TRIM('-' FROM '-----trimmed-----');
                      -- Result: 'trimmed'

                      SELECT TRIM(BOTH '-' FROM '-----trimmed-----');
                      -- Result: 'trimmed'

                      SELECT TRIM(TRAILING '-' FROM '-----trimmed-----');
                      -- Result: '-----trimmed'
                    

UNICODE(ncharacter_expression)

Returns the integer value defined by the Unicode standard of the first character of the input expression.

  • ncharacter_expression: The Unicode character expression.

UPPER ( character_expression )

Returns the character expression with lowercase character data converted to uppercase.

  • character_expression: The character expression.

                      SELECT UPPER('MIXED case');
                      -- Result: 'MIXED CASE'
                    

XML_EXTRACT(xml, xpath [, separator])

Extracts an XML document using the specified XPath to flatten the XML. A comma is used to separate the outputs by default, but this can be changed by specifying the third parameter.

  • xml: The XML document to extract.
  • xpath: The XPath used to select the nodes. The nodes selected will be returned in a token-separated list.
  • separator: The optional token used to separate the items in the flattened response. If this is not specified, the separator will be a comma.

                      SELECT XML_EXTRACT('<vowels><ch>a</ch><ch>e</ch><ch>i</ch><ch>o</ch><ch>u</ch></vowels>', '/vowels/ch');
                      -- Result: 'a,e,i,o,u'

                      SELECT XML_EXTRACT('<vowels><ch>a</ch><ch>e</ch><ch>i</ch><ch>o</ch><ch>u</ch></vowels>', '/vowels/ch', ';');
                      -- Result: 'a;e;i;o;u'
                    

CData Python Connector for XML

MATH Functions

ABS ( numeric_expression )

Returns the absolute (positive) value of the specified numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT ABS(15);
                      -- Result: 15

                      SELECT ABS(-15);
                      -- Result: 15
                    

ACOS ( float_expression )

Returns the arc cosine, the angle in radians whose cosine is the specified float expression.

  • float_expression: The float expression that specifies the cosine of the angle to be returned. Values outside the range from -1 to 1 return null.

                      SELECT ACOS(0.5);
                      -- Result: 1.0471975511966
                    

ASIN ( float_expression )

Returns the arc sine, the angle in radians whose sine is the specified float expression.

  • float_expression: The float expression that specifies the sine of the angle to be returned. Values outside the range from -1 to 1 return null.

                      SELECT ASIN(0.5);
                      -- Result: 0.523598775598299
                    

ATAN ( float_expression )

Returns the arc tangent, the angle in radians whose tangent is the specified float expression.

  • float_expression: The float expression that specifies the tangent of the angle to be returned.

                      SELECT ATAN(10);
                      -- Result: 1.47112767430373
                    

ATN2 ( float_expression1 , float_expression2 )

Returns the angle in radians between the positive x-axis and the ray from the origin to the point (y, x) where x and y are the values of the two specified float expressions.

  • float_expression1: The float expression that is the y-coordinate.
  • float_expression2: The float expression that is the x-coordinate.

                      SELECT ATN2(1, 1);
                      -- Result: 0.785398163397448
                    

CEILING ( numeric_expression ) or CEIL( numeric_expression )

Returns the smallest integer greater than or equal to the specified numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT CEILING(1.3);
                      -- Result: 2

                      SELECT CEILING(1.5);
                      -- Result: 2

                      SELECT CEILING(1.7);
                      -- Result: 2
                    

COS ( float_expression )

Returns the trigonometric cosine of the specified angle in radians in the specified expression.

  • float_expression: The float expression of the specified angle in radians.

                      SELECT COS(1);
                      -- Result: 0.54030230586814
                    

COT ( float_expression )

Returns the trigonometric cotangent of the angle in radians specified by float_expression.

  • float_expression: The float expression of the angle in radians.

                      SELECT COT(1);
                      -- Result: 0.642092615934331
                    

DEGREES ( numeric_expression )

Returns the angle in degrees for the angle specified in radians.

  • numeric_expression: The angle in radians, an expression of an indeterminate numeric data type except for the bit data type.

                      SELECT DEGREES(3.1415926);
                      -- Result: 179.999996929531
                    

EXP ( float_expression )

Returns the exponential value of the specified float expression. For example, EXP(LOG(20)) is 20.

  • float_expression: The float expression.

                      SELECT EXP(2);
                      -- Result: 7.38905609893065
                    

EXPR ( expression )

Evaluates the expression.

  • expression: The expression. Operators allowed are +, -, *, /, ==, !=, >, <, >=, and <=.

                      SELECT EXPR('1 + 2 * 3');
                      -- Result: 7

                      SELECT EXPR('1 + 2 * 3 == 7');
                      -- Result: true
                    

FLOOR ( numeric_expression )

Returns the largest integer less than or equal to the numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT FLOOR(1.3);
                      -- Result: 1

                      SELECT FLOOR(1.5);
                      -- Result: 1

                      SELECT FLOOR(1.7);
                      -- Result: 1
                    

GREATEST(int1,int2,....)

Returns the greatest of the supplied integers.

				SELECT GREATEST(3,5,8,10,1)
				-- Result: 10			
				

HEX(value)

Returns a the equivalent hex for the input value.

  • value: A string or numerical value to be converted into hex.

				SELECT HEX(866849198);
				-- Result: 33AB11AE
				
				SELECT HEX('Sample Text');
				-- Result: 53616D706C652054657874
				

JSON_AVG(json, jsonpath)

Computes the average value of a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_AVG('[1,2,3,4,5]', '$[x]');
                      -- Result: 3

                      SELECT JSON_AVG('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 3

                      SELECT JSON_AVG('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 4.5
                    

JSON_COUNT(json, jsonpath)

Returns the number of elements in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_COUNT('[1,2,3,4,5]', '$[x]');
                      -- Result: 5

                      SELECT JSON_COUNT('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 5

                      SELECT JSON_COUNT('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 2
                    

JSON_MAX(json, jsonpath)

Gets the maximum value in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_MAX('[1,2,3,4,5]', '$[x]');
                      -- Result: 5

                      SELECT JSON_MAX('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 5

                      SELECT JSON_MAX('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[..3]');
                      -- Result: 4
                    

JSON_MIN(json, jsonpath)

Gets the minimum value in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_MIN('[1,2,3,4,5]', '$[x]');
                      -- Result: 1

                      SELECT JSON_MIN('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 1

                      SELECT JSON_MIN('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 4
                    

JSON_SUM(json, jsonpath)

Computes the summary value in JSON according to the JSONPath expression. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_SUM('[1,2,3,4,5]', '$[x]');
                      -- Result: 15

                      SELECT JSON_SUM('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 15

                      SELECT JSON_SUM('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 9
                    

LEAST(int1,int2,....)

Returns the least of the supplied integers.

				SELECT LEAST(3,5,8,10,1)
				-- Result: 1			
				

LOG ( float_expression [, base ] )

Returns the natural logarithm of the specified float expression.

  • float_expression: The float expression.
  • base: The optional integer argument that sets the base for the logarithm.

                      SELECT LOG(7.3890560);
                      -- Result: 1.99999998661119
                    

LOG10 ( float_expression )

Returns the base-10 logarithm of the specified float expression.

  • float_expression: The expression of type float.

                      SELECT LOG10(10000);
                      -- Result: 4
                    

MOD(dividend,divisor)

Returns the integer value associated with the remainder when dividing the dividend by the divisor.

  • dividend: The number to take the modulus of.
  • divisor: The number to divide the dividend by when determining the modulus.

				SELECT MOD(10,3);
				-- Result: 1
				

NEGATE(real_number)

Returns the opposite to the real number input.

  • real_number: The real number to find the opposite of.

				SELECT NEGATE(10);
				-- Result: -10
				
				SELECT NEGATE(-12.4)
				--Result: 12.4
				

PI ( )

Returns the constant value of pi.

                  SELECT PI()
                  -- Result: 3.14159265358979 
                

POWER ( float_expression , y )

Returns the value of the specified expression raised to the specified power.

  • float_expression: The float expression.
  • y: The power to raise float_expression to.

                      SELECT POWER(2, 10);
                      -- Result: 1024

                      SELECT POWER(2, -2);
                      -- Result: 0.25
                    

RADIANS ( float_expression )

Returns the angle in radians of the angle in degrees.

  • float_expression: The degrees of the angle as a float expression.

                      SELECT RADIANS(180);
                      -- Result: 3.14159265358979
                    

RAND ( [ integer_seed ] )

Returns a pseudorandom float value from 0 through 1, exclusive.

  • seed: The optional integer expression that specifies the seed value. If seed is not specified, a seed value at random will be assigned.

                      SELECT RAND();
                      -- This result may be different, since the seed is randomized
                      -- Result: 0.873159630165044

                      SELECT RAND(1);
                      -- This result will always be the same, since the seed is constant
                      -- Result: 0.248668584157093
                    

ROUND ( numeric_expression [ ,integer_length] [ ,function ] )

Returns the numeric value rounded to the specified length or precision.

  • numeric_expression: The expression of a numeric data type.
  • length: The optional precision to round the numeric expression to. When this is omitted, the default behavior will be to round to the nearest whole number.
  • function: The optional type of operation to perform. When the function parameter is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

                      SELECT ROUND(1.3, 0);
                      -- Result: 1

                      SELECT ROUND(1.55, 1);
                      -- Result: 1.6

                      SELECT ROUND(1.7, 0, 0);
                      -- Result: 2

                      SELECT ROUND(1.7, 0, 1);
                      -- Result: 1
                      
                      SELECT ROUND (1.24);
                      -- Result: 1.0
                    

SIGN ( numeric_expression )

Returns the positive sign (1), 0, or negative sign (-1) of the specified expression.

  • numeric_expression: The expression of an indeterminate data type except for the bit data type.

                      SELECT SIGN(0);
                      -- Result: 0

                      SELECT SIGN(10);
                      -- Result: 1

                      SELECT SIGN(-10);
                      -- Result: -1
                    

SIN ( float_expression )

Returns the trigonometric sine of the angle in radians.

  • float_expression: The float expression specifying the angle in radians.

                     SELECT SIN(1);
                     -- Result: 0.841470984807897
                    

SQRT ( float_expression )

Returns the square root of the specified float value.

  • float_expression: The expression of type float.

                      SELECT SQRT(100);
                      -- Result: 10
                    

SQUARE ( float_expression )

Returns the square of the specified float value.

  • float_expression: The expression of type float.

                      SELECT SQUARE(10);
                      -- Result: 100

                      SELECT SQUARE(-10);
                      -- Result: 100
                    

TAN ( float_expression )

Returns the tangent of the input expression.

  • float_expression: The expression of type float.

                      SELECT TAN(1);
                      -- Result: 1.5574077246549
                    

TRUNC(decimal_number,precision)

Returns the supplied decimal number truncated to have the supplied decimal precision.

  • decimal_number: The decimal value to truncate.
  • precision: The number of decimal places to truncate the decimal number to.

				SELECT TRUNC(10.3423,2);
				-- Result: 10.34
				

_ROW_NUMBER_()

Returns a row index as an additional column.

				SELECT ColumnName, _ROW_NUMBER_() FROM TableName
				-- Result: ColumnData, 0
				ColumnData2, 1
				ColumnData3, 2
				

CData Python Connector for XML

DATE Functions

CURRENT_DATE()

Returns the current date value.

                  SELECT CURRENT_DATE();
                  -- Result: 2018-02-01
                

CURRENT_TIMESTAMP()

Returns the current time stamp of the database system as a datetime value. This value is equal to GETDATE and SYSDATETIME, and is always in the local timezone.

                  SELECT CURRENT_TIMESTAMP();
                  -- Result: 2018-02-01 03:04:05
                

DATEADD (datepart , integer_number , date [, dateformat])

Returns the datetime value that results from adding the specified number (a signed integer) to the specified date part of the date.

  • datepart: The part of the date to add the specified number to. The valid values and abbreviations are
    • year (yy, yyyy)
    • quarter (qq, q)
    • month (mm, m)
    • week (wk, ww)
    • weekday (dw)
    • dayofyear (dy, y)
    • day (dd, d)
    • hour (hh)
    • minute (mi, n)
    • second (ss, s)
    • millisecond (ms)
  • number: The number to be added.
  • date: The expression of the datetime data type.
  • dateformat: The optional output date format.

                  SELECT DATEADD('d', 5, '2018-02-01');
                  -- Result: 2018-02-06

                  SELECT DATEADD('hh', 5, '2018-02-01 00:00:00');
                  -- Result: 2018-02-01 05:00:00
                

DATEDIFF ( datepart , startdate , enddate )

Returns the difference (a signed integer) of the specified time interval between the specified start date and end date.

  • datepart: The part of the date that is the time interval of the difference between the start date and end date. The valid values and abbreviations are:
    • Year (year, yyyy, yy)
    • Quarter (quarter, qq, q)
    • Month (month, mm, m)
    • Week (week, wk, ww)
    • Weekday (weekday, dw)
    • Dayofyear (dayofyear, dy, y)
    • Day (day, dd, d)
    • Hour (hour, hh)
    • Minute (minute, mi, n)
    • Second (second, ss, s)
    • Millisecond (millisecond, ms)
  • startdate: The datetime expression of the start date.
  • enddate: The datetime expression of the end date.

                  SELECT DATEDIFF('d', '2018-02-01', '2018-02-10');
                  -- Result: 9

                  SELECT DATEDIFF('hh', '2018-02-01 00:00:00', '2018-02-01 12:00:00');
                  -- Result: 12
                

DATE_FORMAT(date,format)

Returns the date or timestamp in the format specified. This function mirrors the MySQL DATE_FORMAT function.

  • date: A date or timestamp string.
  • format: The specifier string of the desired output format. The list of supported format specifiers comes from the MySQL DATE_FORMAT function (see link to MySQL documentation above).

					SELECT DATE_FORMAT('9/4/2021 3:11:53 AM','%h')
					-- Result: 03
				  

DATEFROMPARTS(integer_year, integer_month, integer_day)

Returns the datetime value for the specified year, month, and day.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.

                    SELECT DATEFROMPARTS(2018, 2, 1);
                    -- Result: 2018-02-01
                  

DATENAME(datepart , date)

Returns the character string that represents the specified date part of the specified date.

  • datepart: The part of the date to return. The valid values and abbreviations are year (yy, yyyy), quarter (qq, q), month (mm, m), dayofyear (dy, y), day (dd, d), week (wk, ww), weekday (dw), hour (hh), minute (mi, n), second (ss, s), millisecond (ms), microsecond (mcs), and nanosecond (ns).
  • date: The datetime expression.

                     SELECT DATENAME('yy', '2018-02-01');
                     -- Result: '2018'

                     SELECT DATENAME('dw', '2018-02-01');
                     -- Result: 'Thursday'
                   

DATEPART(datepart, date [,integer_datefirst])

Returns a character string that represents the specified date part of the specified date.

  • datepart: The part of the date to return. The valid values and abbreviations are year (yy, yyyy), quarter (qq, q), month (mm, m), dayofyear (dy, y), day (dd, d), week (wk, ww), weekday (dw), hour (hh), minute (mi, n), second (ss, s), millisecond (ms), microsecond (mcs), nanosecond (ns), ISODOW, ISO_WEEK (isoweek, isowk,isoww), and ISOYEAR.
  • date: The datetime string.
  • datefirst: The optional integer representing the first day of the week. The default is 7, Sunday.

                    SELECT DATEPART('yy', '2018-02-01');
                    -- Result: 2018

                    SELECT DATEPART('dw', '2018-02-01');
                    -- Result: 5
                  

DATETIMEFROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute, integer_seconds, integer_milliseconds)

Returns the datetime value for the specified date parts.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • milliseconds: The integer expression specifying the milliseconds.

                    SELECT DATETIMEFROMPARTS(2018, 2, 1, 1, 2, 3, 456);
                    -- Result: 2018-02-01 01:02:03.456
                  

DATETIME2FROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute, integer_seconds, integer_fractions, integer_precision)

Returns the datetime value for the specified date parts.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • fractions: The integer expression specifying the fractions of the second.
  • precision: The integer expression specifying the precision of the fraction.

				    SELECT DATETIME2FROMPARTS(2018, 2, 1, 1, 2, 3, 456, 3);
                    -- Result: 2018-02-01 01:02:03.456
                  

DATE_TRUNC(date, datepart)

Truncates the date to the precision of the given date part. Modeled after the Oracle TRUNC function.

  • date: The datetime string that specifies the date.
  • datepart: Refer to the Oracle documentation for valid datepart syntax.

				    SELECT DATE_TRUNC('05-04-2005', 'YY');
                    -- Result: '1/1/2005'
					
                    SELECT DATE_TRUNC('05-04-2005', 'MM');
                    -- Result: '5/1/2005'                    
                  

DATE_TRUNC2(datepart, date, [weekday])

Truncates the date to the precision of the given date part. Modeled after the PostgreSQL date_trunc function.

  • datepart: One of 'millennium', 'century', 'decade', 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute' or 'second'.
  • date: The datetime string that specifies the date.
  • weekday: The optional day of the week to use as the first day for 'week'. One of 'sunday', 'monday', etc.

                    SELECT DATE_TRUNC2('year', '2020-02-04');
                    -- Result: '2020-01-01'

                    SELECT DATE_TRUNC2('week', '2020-02-04', 'monday');
                    -- Result: '2020-02-02', which is the previous Monday
                  

DAY(date)

Returns the integer that specifies the day component of the specified date.

  • date: The datetime string that specifies the date.

                    SELECT DAY('2018-02-01');
                    -- Result: 1
                  

DAYNAME(date)

Returns the name of the day of the week of the specified date.

  • date: The datetime string that specifies the date.

                    SELECT DAYNAME('8/18/2021');
                    -- Result: Wednesday
                  

DAYOFMONTH(date)

Returns the day of the month of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT DAYOFMONTH('04/15/2000');
				  -- Result: 15
				  

DAYOFWEEK(date)

Returns the day of the week of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT DAYOFWEEK('04/15/2000');
				  -- Result: 7
				  

DAYOFYEAR(date)

Returns the day of the year of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT DAYOFYEAR('04/15/2000');
				  -- Result: 106
				  

EOMONTH(date [, integer_month_to_add ]) or LAST_DAY(date)

Returns the last day of the month that contains the specified date with an optional offset.

  • date: The datetime expression specifying the date for which to return the last day of the month.
  • integer_month_to_add: The optional integer expression specifying the number of months to add to the date before calculating the end of the month.

                  SELECT EOMONTH('2018-02-01');
                  -- Result: 2018-02-28
                  
                  SELECT LAST_DAY('2018-02-01');
                  -- Result: 2018-02-28

                  SELECT EOMONTH('2018-02-01', 2);
                  -- Result: 2018-04-30
                

EXTRACT(date_part FROM date_column_name)

Returns the last day of the month that contains the specified date with an optional offset.

  • date_part: One of the following date components: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.
  • date_column_name: The name of a date column in a table.

                  SELECT EXTRACT(YEAR FROM DateColumn)
                  -- Result: 2021
                

FDWEEK(date)

Returns the first day of the week of the given date part.
  • date: The datetime string that specifies the date.
  • weeks to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the week.

				  SELECT FDWEEK('02-08-2018');
				  -- Result: 2/4/2018

          SELECT FDWEEK('02-08-2018', 1)
          --Result: 02/11/2018
				  

FDMONTH(date)

Returns the first day of the month of the given date part.
  • date: The datetime string that specifies the date.
  • month to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the month.

				  SELECT FDMONTH('02-08-2018');
				  -- Result: 2/1/2018

          SELECT FDMONTH('02-08-2018', 1) 
          --Result: 03/01/2018
				  

FDQUARTER(date)

Returns the first day of the quarter of the given date part.
  • date: The datetime string that specifies the date.
  • quarters to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the quarter.

				  SELECT FDQUARTER('05-08-2018');
				  -- Result: 4/1/2018

          SELECT FDQUARTER('05-08-2018',1)
          --Result: 07/01/2018
				  

FILEMODIFIEDTIME(uri)

Returns the time stamp associated with the Date Modified of the relevant file.

  • uri: An absolute path pointing to a file on the local file system.

				 SELECT FILEMODIFIEDTIME('C:/Documents/myfile.txt');
				 -- Result: 6/25/2019 10:06:58 AM
				 

FROM_DAYS(datevalue)

Returns a date derived from the number of days after 1582-10-15 (based upon the Gregorian calendar). This will be equivalent to the MYSQL FROM_DAYS function.

  • datevalue: A integer value representing the number of days since 1582-10-15.

				SELECT FROM_DAYS(736000);
				-- Result: 2/6/2015
				

FROM_UNIXTIME(time, issecond)

Returns a representation of the unix_timestamp argument as a value in YYYY-MM-DD HH:MM:SS expressed in the current time zone.

  • time: The time stamp value from epoch time. Milliseconds are accepted.
  • issecond: Indicates the time stamp value is milliseconds to epoch time.

                      SELECT FROM_UNIXTIME(1540495231, 1);
                      -- Result: 2018-10-25 19:20:31

                      SELECT FROM_UNIXTIME(1540495357385, 0);
                      -- Result: 2018-10-25 19:22:37
                    

GETDATE()

Returns the current time stamp of the database system as a datetime value. This value is equal to CURRENT_TIMESTAMP and SYSDATETIME, and is always in the local timezone.

                  SELECT GETDATE();
                  -- Result: 2018-02-01 03:04:05
                

GETUTCDATE()

Returns the current time stamp of the database system formatted as a UTC datetime value. This value is equal to SYSUTCDATETIME.

In addition, GETUTCDATE can take an optional second parameter, a date and time that are converted to UTC.

                  SELECT GETUTCDATE();
                  -- For example, if the local timezone is Eastern European Time (GMT+2)
                  -- Result: 2018-02-01 05:04:05

                  SELECT GETUTCDATE('2020/08/31 13:56:00')
                  --Result: '2020-08-31 17:56:00'
                

HOUR(date)

Returns the hour component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT HOUR('02-02-2020 11:30:00');
				-- Result: 11
				

ISDATE(date, [date_format])

Returns 1 if the value is a valid date, time, or datetime value; otherwise, 0.

  • date: The datetime string.
  • date_format: The optional datetime format.

                      SELECT ISDATE('2018-02-01', 'yyyy-MM-dd');
                      -- Result: 1

                      SELECT ISDATE('Not a date');
                      -- Result: 0
                    

LAST_WEEK()

Returns a time stamp equivalent to exactly one week before the current date.

				SELECT LAST_WEEK();	//Assume the date is 3/17/2020	
			 -- Result: 3/10/2020 00:00:00
				

LAST_MONTH()

Returns a time stamp equivalent to exactly one month before the current date.

	
				SELECT LAST_MONTH(); //Assume the date is 3/17/2020
				-- Result: 2/17/2020 00:00:00
				

LAST_YEAR()

Returns a time stamp equivalent to exactly one year before the current date.

				SELECT LAST_YEAR();	//Assume the date is 3/17/2020	
				-- Result: 3/10/2019 00:00:00
				

LDWEEK(date)

Returns the last day of the provided week.

  • date: The datetime string.
  • weeks to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the week.

				SELECT LDWEEK('02-02-2020');
				-- Result: 2/8/2020
				

LDMONTH(date)

Returns the last day of the provided month.

  • date: The datetime string.
  • months to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the month.

				SELECT LDMONTH('02-02-2020');
				-- Result: 2/29/2020

        SELECT LDMONTH('02-08-2020', 1)
        --Result: 03/31/2020
				

LDQUARTER(date)

Returns the last day of the provided quarter.

  • date: The datetime string.
  • quarters to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the quarter.

				SELECT LDQUARTER('02-02-2020');
				-- Result: 3/31/2020

        SELECT LDQUARTER('02-02-2020',1)
        --Result: 06/30/2020
				

MAKEDATE(year, days)

Returns a date value from a year and a number of days.

  • year: The year
  • days: The number of days into the year. Value must be greater than 0.

          SELECT MAKEDATE(2020, 1);
          -- Result: 2020-01-01
        

MINUTE(date)

Returns the minute component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT MINUTE('02-02-2020 11:15:00');
				-- Result: 15
				

MONTH(date)

Returns the month component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT MONTH('02-02-2020');
				-- Result: 2
				

QUARTER(date)

Returns the quarter associated with the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT QUARTER('02-02-2020');
				-- Result: 1
				

SECOND(date)

Returns the second component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT SECOND('02-02-2020 11:15:23');
				-- Result: 23
				

SMALLDATETIMEFROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute)

Returns the datetime value for the specified date and time.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.

                      SELECT SMALLDATETIMEFROMPARTS(2018, 2, 1, 1, 2);
                      -- Result: 2018-02-01 01:02:00
                    

STRTODATE(string,format)

Parses the provided string value and returns the corresponding datetime.

  • string: The string value to be converted to datetime format.
  • format: A format string which describes how to interpret the first string input. A few special formats are available as well, including UNIX, UNIXMILIS, TICKS, and FILETICKS.

				SELECT STRTODATE('03*04*2020','dd*MM*yyyy');
				-- Result: 4/3/2020
				

SYSDATETIME()

Returns the current time stamp as a datetime value of the database system. It is equal to GETDATE and CURRENT_TIMESTAMP, and is always in the local timezone.

                  SELECT SYSDATETIME();
                  -- Result: 2018-02-01 03:04:05
                

SYSUTCDATETIME()

Returns the current system date and time as a UTC datetime value. It is equal to GETUTCDATE.

                  SELECT SYSUTCDATETIME();
                  -- For example, if the local timezone is Eastern European Time (GMT+2)
                  -- Result: 2018-02-01 05:04:05
                

TIMEFROMPARTS(integer_hour, integer_minute, integer_seconds, integer_fractions, integer_precision)

Returns the time value for the specified time and with the specified precision.

  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • fractions: The integer expression specifying the fractions of the second.
  • precision : The integer expression specifying the precision of the fraction.

                      SELECT TIMEFROMPARTS(1, 2, 3, 456, 3);
                      -- Result: 01:02:03.456
                    

TO_DAYS(date)

Returns the number of days since 0000-00-01. This will only return a value for dates on or after 1582-10-15 (based upon the Gregorian calendar). This will be equivalent to the MYSQL TO_DAYS function.

  • date: The datetime string that specifies the date.

				SELECT TO_DAYS('02-06-2015');
				-- Result: 736000
				

WEEK(date)

Returns the week (of the year) associated with the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT WEEK('02-17-2020 11:15:23');
				-- Result: 8
				

YEAR(date)

Returns the integer that specifies the year of the specified date.

  • date: The datetime string.

                      SELECT YEAR('2018-02-01');
                      -- Result: 2018
                    

CData Python Connector for XML

Date Literal Functions

The following date literal functions can be used to filter date fields using relative intervals. Note that while the <, >, and = operators are supported for these functions, <= and >= are not.

L_TODAY()

The current day.

  SELECT * FROM MyTable WHERE MyDateField = L_TODAY()

L_YESTERDAY()

The previous day.

  SELECT * FROM MyTable WHERE MyDateField = L_YESTERDAY()

L_TOMORROW()

The following day.

  SELECT * FROM MyTable WHERE MyDateField = L_TOMORROW()

L_LAST_WEEK()

Every day in the preceding week.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_WEEK()

L_THIS_WEEK()

Every day in the current week.

  SELECT * FROM MyTable WHERE MyDateField = L_THIS_WEEK()

L_NEXT_WEEK()

Every day in the following week.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_WEEK()
Also available:
  • L_LAST/L_THIS/L_NEXT MONTH
  • L_LAST/L_THIS/L_NEXT QUARTER
  • L_LAST/L_THIS/L_NEXT YEAR

L_LAST_N_DAYS(n)

The previous n days, excluding the current day.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_DAYS(3)

L_NEXT_N_DAYS(n)

The following n days, including the current day.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_DAYS(3)
Also available:
  • L_LAST/L_NEXT_90_DAYS

L_LAST_N_WEEKS(n)

Every day in every week, starting n weeks before current week, and ending in the previous week.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_WEEKS(3)

L_NEXT_N_WEEKS(n)

Every day in every week, starting the following week, and ending n weeks in the future.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_WEEKS(3)
Also available:
  • L_LAST/L_NEXT_N_MONTHS(n)
  • L_LAST/L_NEXT_N_QUARTERS(n)
  • L_LAST/L_NEXT_N_YEARS(n)

CData Python Connector for XML

SELECT Statements

A SELECT statement can consist of the following basic clauses.

  • SELECT
  • INTO
  • FROM
  • JOIN
  • WHERE
  • GROUP BY
  • HAVING
  • UNION
  • ORDER BY
  • LIMIT

SELECT Syntax

The following syntax diagram outlines the syntax supported by the SQL engine of the connector:

SELECT {
  [ TOP <numeric_literal> | DISTINCT ]
  { 
    * 
    | { 
        <expression> [ [ AS ] <column_reference> ] 
        | { <table_name> | <correlation_name> } .* 
      } [ , ... ] 
  }
  { 
    FROM <table_reference> [ [ AS ] <identifier> ] 
  } [ , ... ]
  [ [  
      INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } 
    ] JOIN <table_reference> [ ON <search_condition> ] [ [ AS ] <identifier> ] 
  ] [ ... ] 
  [ WHERE <search_condition> ]
  [ GROUP BY <column_reference> [ , ... ]
  [ HAVING <search_condition> ]
  [ UNION [ ALL ] <select_statement> ]
  [ 
    ORDER BY 
    <column_reference> [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
  ]
  [ 
    LIMIT <expression>
    [ 
      { OFFSET | , }
      <expression> 
    ]
  ] 
} | SCOPE_IDENTITY() 

<expression> ::=
  | <column_reference>
  | @ <parameter> 
  | ?
  | COUNT( * | { [ DISTINCT ] <expression> } )
  | { AVG | MAX | MIN | SUM | COUNT } ( <expression> ) 
  | NULLIF ( <expression> , <expression> ) 
  | COALESCE ( <expression> , ... ) 
  | CASE <expression>
      WHEN { <expression> | <search_condition> } THEN { <expression> | NULL } [ ... ]
    [ ELSE { <expression> | NULL } ]
    END 
  | {RANK() | DENSE_RANK()} OVER ([PARTITION BY <column_reference>] {ORDER BY <column_reference>})
  | <literal>
  | <sql_function> 

<search_condition> ::= 
  {
    <expression> { = | > | < | >= | <= | <> | != | LIKE | NOT LIKE | IN | NOT IN | IS NULL | IS NOT NULL | AND | OR | CONTAINS | BETWEEN | IS DISTINCT FROM | IS NOT DISTINCT FROM } [ <expression> ]
  } [ { AND | OR } ... ] 

Examples

  1. Return all columns:
    SELECT * FROM NorthwindOData
  2. Rename a column:
    SELECT [Username] AS MY_Username FROM NorthwindOData
  3. Cast a column's data as a different data type:
    SELECT CAST(AnnualRevenue AS VARCHAR) AS Str_AnnualRevenue FROM NorthwindOData
  4. Search data:
    SELECT * FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'
  5. Return the number of items matching the query criteria:
    SELECT COUNT(*) AS MyCount FROM NorthwindOData 
  6. Return the number of unique items matching the query criteria:
    SELECT COUNT(DISTINCT Username) FROM NorthwindOData 
  7. Return the unique items matching the query criteria:
    SELECT DISTINCT Username FROM NorthwindOData 
  8. Sort a result set in ascending order:
    SELECT Email, Username FROM NorthwindOData  ORDER BY Username ASC
  9. Restrict a result set to the specified number of rows:
    SELECT Email, Username FROM NorthwindOData LIMIT 10 
  10. Parameterize a query to pass in inputs at execution time. This enables you to create prepared statements and mitigate SQL injection attacks.
    SELECT * FROM NorthwindOData WHERE Email = @param
See Explicitly Caching Data for information on using the SELECT statement in offline mode.

Pseudo Columns

Some input-only fields are available in SELECT statements. These fields, called pseudo columns, do not appear as regular columns in the results, yet may be specified as part of the WHERE clause. You can use pseudo columns to access additional features from XML.

    SELECT * FROM NorthwindOData WHERE  = '@'
    

Aggregate Functions

For SELECT examples using aggregate functions, see Aggregate Functions.

JOIN Queries

See JOIN Queries for SELECT query examples using JOINs.

Date Literal Functions

Date Literal Functions contains SELECT examples with date literal functions.

Window Functions

See Window Functions for SELECT examples containing window functions.

Table-Valued Functions

See Table-Valued Functions for SELECT examples with table-valued functions.

CData Python Connector for XML

Aggregate Functions

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'

COUNT(DISTINCT)

Returns the number of distinct, non-null field values matching the query criteria.

SELECT COUNT(DISTINCT Email) AS DistinctValues FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'

AVG

Returns the average of the column values.

SELECT Username, AVG(AnnualRevenue) FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'  GROUP BY Username

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), Username FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org' GROUP BY Username

MAX

Returns the maximum column value.

SELECT Username, MAX(AnnualRevenue) FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org' GROUP BY Username

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM NorthwindOData WHERE Email = 'ana.trujilo@northwind.org'

CData Python Connector for XML

JOIN Queries

The CData Python Connector for XML supports standard SQL joins like the following examples.

Inner Join

An inner join selects only rows from both tables that match the join condition:

SELECT 
  [people].[personal.age] AS age, 
  [people].[personal.gender] AS gender, 
  [people].[personal.name.first] AS first_name, 
  [people].[personal.name.last] AS last_name, 
  [vehicles].[model], 
FROM 
  [people], [vehicles] 
WHERE 
  [people].[_id] = [vehicles].[people_id]

Left Join

A left join selects all rows in the FROM table and only matching rows in the JOIN table:

SELECT 
  [people].[personal.age] AS age, 
  [people].[personal.gender] AS gender, 
  [people].[personal.name.first] AS first_name, 
  [people].[personal.name.last] AS last_name, 
  [vehicles].[model], 
FROM 
  [people]
LEFT OUTER JOIN 
  [vehicles] 
ON
  [people].[_id] = [vehicles].[people_id]

CData Python Connector for XML

Window Functions

Window functions allow you to create computed fields from a group of rows (a window) that return a result for each row, as opposed to one computed result for a set of rows, as is the case with aggregate functions. The connector supports the following window function syntax.

Note: Window function support is an experimental feature of the connector. This functionality extends beyond the connector's core scope of being SQL-92 compliant. As such, performance with window functions may not be optimal.

Window Function Clauses

OVER

The OVER clause defines the window over which window functions are performed.

SELECT A, B, <window function> OVER (<window frame>) FROM TableName

The <window function> refers to any supported window function clause, and the <window frame> refers to one or more clauses that specify the logic by which the window is defined.

PARTITION BY

The PARTITION BY clause subdivides a window into sub-windows called partitions. For each unique value in the column specified in the PARTITION BY clause, every record with that value collectively forms an individual partition.

SELECT A, B, <window function> OVER (PARTITION BY A ORDER BY B) From NorthwindOData

The <window function> refers to any supported window function clause.

Window Functions

The connector supports math, ranking, and analytic window functions.

Math

These window functions perform mathematical operations on the records within the window.

COUNT()

Calculates the number of records in each partition. The calculated column is of the data type "int".

In each partition, every record will display the total number of records in that partition.

SELECT Name, Role, Earnings, COUNT() OVER (PARTITION BY Role) FROM Employees

COUNT_BIG()

Calculates the number of records in each partition. The calculated column is of the data type "bigint".

In each partition, every record will display the total number of records in that partition.

SELECT Name, Role, Earnings, COUNT_BIG() OVER (PARTITION BY Role) FROM Employees

MIN(numeric_column)

Calculates the minimum value of a numerical column per partition.

In each partition, every record will display the minimum value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MIN(Earnings) OVER (PARTITION BY Role) FROM Employees

MAX(numeric_column)

Calculates the maximum value of a numerical column per partition.

In each partition, every record will display the maximum value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MAX(Earnings) OVER (PARTITION BY Role) FROM Employees

SUM(numeric_column)

Calculates the sum of a numerical column per partition.

In each partition, every record will display the sum of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, SUM(Earnings) OVER (PARTITION BY Role) FROM Employees

AVG(numeric_column)

Calculates the average value of a numerical column per partition.

In each partition, every record will display the average value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, AVG(Earnings) OVER (PARTITION BY Role) FROM Employees

MEDIAN(numeric_column)

Calculates the median value of a numerical column per partition.

In each partition, every record will display the median value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MEDIAN(Earnings) OVER (PARTITION BY Role) FROM Employees

STDEV(numeric_column)

Calculates the standard deviation of a numerical column per partition.

In each partition, every record will display the standard deviation of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, STDEV(Earnings) OVER (PARTITION BY Role) FROM Employees

STDEVP(numeric_column)

Calculates the population standard deviation of a numerical column per partition.

In each partition, every record will display the population standard deviation of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, STDEVP(Earnings) OVER (PARTITION BY Role) FROM Employees

VAR(numeric_column)

Calculates the statistical standard variance of a numerical column per partition.

In each partition, every record will display the statistical standard variance of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, VAR(Earnings) OVER (PARTITION BY Role) FROM Employees

VARP(numeric_column)

Calculates the variance population of a numerical column per partition.

In each partition, every record will display the variance population of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, VARP(Earnings) OVER (PARTITION BY Role) FROM Employees

Ranking

These window functions rank records that fall within the window and its partitions.

RANK()

Assigns a rank number to each record in a window based on the value of the column specified in the required ORDER BY clause.

If two or more records have an equal value in the in ranked column, they all receive the same rank number and the rank count increments internally, skipping ahead one rank number for each record with a duplicate value in the ORDER BY column.

SELECT Email, Username, RANK() OVER (ORDER BY Username) AS Rank FROM NorthwindOData

If you add a PARTITION BY clause, a separate set of ranks is calculated for each partition.

SELECT Email, Username, RANK() OVER (PARTITION BY Email ORDER BY Username) AS Rank FROM NorthwindOData

DENSE_RANK()

Operates like the RANK() function, but it doesn't increment the internal rank counter for each record with a duplicate value in the ranked column.

This means that, while records with identical values in the ORDER BY column still share a rank number, the function never skips a rank number.

SELECT Email, Username, DENSE_RANK() OVER (PARTITION BY Email ORDER BY Username) AS Rank FROM NorthwindOData

If you add a PARTITION BY clause, a separate set of ranks is calculated for each partition.

SELECT Email, Username, DENSE_RANK() OVER (PARTITION BY Email ORDER BY Username) AS Rank FROM NorthwindOData

ROW_NUMBER()

Calculates a row number for each record. An ORDER BY clause in the OVER clause is required.

SELECT Name, Role, Earnings, ROW_NUMBER() OVER (ORDER BY Role) FROM Employees
If you define multiple partitions with PARTITION BY, a new set of row numbers are calculated for each partition.
SELECT Name, Role, Earnings, ROW_NUMBER() OVER (PARTITION BY Role ORDER BY Earnings) FROM Employees

NTILE()

Distributes rows of an ordered partition into a specified number of approximately equal groups, or buckets. It assigns each group a bucket number starting from one. For each row in a group, the NTILE() function assigns a bucket number representing the group to which the row belongs.

The syntax of NTILE() is:

NTILE(buckets) OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)
The following are paramaters that NTILE() supports:

  • buckets: The number of buckets into which the rows are divided. The buckets can be an expression or subquery that evaluates to a positive integer. It cannot be a window function.
  • PARTITION BY: distributes rows of a result set into partitions to which the NTILE() function is applied.
  • ORDER BY is clause that specifies the logical order of rows in each partition to which the NTILE() is applied.

If the number of rows is not divisible by the buckets, the NTILE() function returns groups of two sizes with the difference by one. The larger groups always precede the smaller group in the order set by ORDER BY in the OVER() clause.

If the total of rows is divisible by the number of buckets, the function divides the rows evenly among buckets. The following statement creates a new table named ntile_demo that stores 10 integers:

CREATE TABLE sales.ntile_demo (
	v INT NOT NULL
);
	
INSERT INTO sales.ntile_demo(v) 
VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);	
	
SELECT * FROM sales.ntile_demo;
This statement uses the NTILE() function to divide ten rows into three groups:
SELECT 
	v, 
	NTILE (3) OVER (
		ORDER BY v
	) buckets
FROM 
	sales.ntile_demo;

Analytical

These window functions perform analytical operations on the records within the window.

PERCENT_RANK()

Calculates the relative rank SQL Percentile of each row. It returns values greater than zero, but the maximum value is one. It does not count any NULL values. This function is nondeterministic.

The syntax of PERCENT_RANK() is:

PERCENT_RANK() OVER (
      [PARTITION BY partition_expression, ... ]
      ORDER BY sort_expression [ASC | DESC], ...
  )
  
This syntax uses the following parameters.

  • PARTITION BY: By default, SQL Server treats the whole data set as a single set. You can specify the PARTITION BY clause to divide data into multiple sets. The Percent_Rank function performs the analytical calculations on each set. This parameter is optional.
  • ORDER BY: Sorts the data in either ascending or descending order. This parameter is required.

CData Python Connector for XML

Table-Valued Functions

Table-valued functions are functions that return a table (rowset).

Note: Table-valued function support is an experimental feature of the connector. This functionality extends beyond the connector's core scope of being SQL-92 compliant. As such, performance with these functions may not be optimal.

Table-Valued Function Clauses

CROSS APPLY

The CROSS APPLY operator is used to perform a subquery on each row of a table or resultset produced by a preceding table expression.

<table_expression_1> CROSS APPLY <table_expression_2>

The second table expression can reference results from the first table expression to create derived columns or an altered recordset via a table-valued function.

Each resulting record is an instance of the record it's splitting, with all the same column values, except for the column(s) containing the value split by the function.

WITH

The WITH clause is used alongside certain table-valued functions to match against constructs within the structure being split (keys, element names, attribute names, etc.) and/or to specify metadata for the columns generated from the function.
SELECT A.ColumnName, X.DerivedColumnName FROM TableName A CROSS APPLY <table-valued function> WITH (DerivedColumnName varchar(255)) AS X

Table-Valued Functions

STRING_SPLIT(input_text,delimiter)

Takes each record in the recordset of the preceding table expression, splits the column containing delimiters (input_text) into substrings separated by the delimiter, and returns one record per substring.

  • input_text: A column whose value you want to parse.
  • delimiter: The character used to split the value of the column specified in input_text.

Suppose there is a column called "SplitColumn" with the following content:

One-Two-Three
To unpack this value across multiple records:
SELECT A.ID, X.Value FROM [TableWithDelimitedStringField] A CROSS APPLY STRING_SPLIT(A.SplitColumn,'-') WITH (Value VARCHAR(255)) AS X

-- Results:
-----------
|ID|Value|
|1|One|
|1|Two|
|1|Three|

JSONTABLE(json_content,[jsonpath])

For each record in the recordset of the preceding table expression, returns one record for each instance of a key in a JSON array (json_content) that matches the key(s) specified in the WITH clause, at the scope specified by the "jsonpath" input.

  • json_content: A JSON "table" (array of objects). The contents can nest, but this must be a single JSON array, not any other JSON structure, at the root level.
    • The values of every instance of the key(s) provided in the WITH clause are retrievable only for substructures which are immediate children of the root-level JSON array.
  • jsonpath: An optional JSONPath query defining the scope, within the json_content array, that you want to pull content from. The JSON key(s) identified in the WITH clause must exist at the scope defined in this parameter. This defaults to the JSON root ($).

Consider a sample table with a single record, including an ID column and column with JSON content called "JSONColumn" with the following content:

[
	{
		"name": "Samuel",
		"email": "sam@gmail.com",
		"extrainfo": {
			"city": "Seattle"
		}
	},
	{
		"name": "Katherine",
		"email": "kat@gmail.com",
	},
	{
		"name": "George",
		"email": "george23@gmail.com",
	},
	{
		"name": "Carlos",
		"email": "carlos32@gmail.com",
	}
]

To extract all values for a certain key, specify the scope in the JSONTABLE function and provide the desired key(s) in the WITH clause.

SELECT A.ID, X.name FROM [TableWithJSONField] A CROSS APPLY JSONTABLE(A.JSONColumn) WITH (name VARCHAR(255)) AS X

-- Results: 
|ID|name|
---------
|1 |Samuel|
|1 |Katherine|
|1 |George|
|1 |Carlos|

XMLTABLE(xml_content,[xpath,child_type])

For each record in the resultset of the preceding table expression, returns one record for each of the elements and/or attributes in an XML structure (xml_content) that match the tag name(s) and/or attribute name(s) specified in the WITH clause, at the scope specified in the "xpath" input.

  • xml_content: A column containing an XML structure.
  • xpath: An optional XPath that specifies the scope within the XML structure at which the connector extracts content matching the tag/attribute name(s) specified in the WITH clause.
    • When extracting the content of sub-elements, the connector can retrieve all content from tags at the root level, (depth 0) immediate children of the root (depth 1), and children of those children (depth 2).
    • When extracting element attribute content, the connector can retrieve all content from tags containing the specified attribute at the root level (depth 0) and from immediate children of root-level elements (depth 1).
  • child_type: An optional parameter that specifies the part(s) of the parent element (specified in the xpath input) that the column(s) provided in the WITH clause are checked against to identify content.
    • You can supply the following values:
      • 0: The column(s) in the WITH clause are checked for matches against the parent element's attribute names and sub-element tag names.
      • 1: The column(s) in the WITH clause are checked for matches against the parent element's attribute names.
      • 2: The column(s) in the WITH clause are checked for matches against the parent element's sub-element tag names.
    • When not supplied, this defaults to 0.

Extracting Sub-Element Values

Consider a sample table with a single record, including an ID column and a column with XML content called "XMLContent" with the following content:
<shoppingList>
    <item>
        <name>Apples</name>
        <quantity>3</quantity>
        <unit>Kg</unit>
    </item>
    <item>
        <name>Bread</name>
        <quantity>2</quantity>
        <unit>Loaf</unit>
		<extrainfo>
			<Type>Whole-Grain</Type>
		</extrainfo>
    </item>
    <item>
        <name>Milk</name>
        <quantity>1</quantity>
        <unit>Carton</unit>
    </item>
    <item>
        <name>Eggs</name>
        <quantity>12</quantity>
        <unit></unit>
    </item>
</shoppingList>

To extract sub-element content, specify the scope in the XMLTABLE function and provide the desired element name(s) in the WITH clause. Note that this will not work if the XMLTABLE function's child_type input is set to 1.

SELECT A.ID, X.name FROM [TableWithXMLField] A CROSS APPLY XMLTABLE(A.XMLContent,'//*/item') WITH (name VARCHAR(255)) AS X

-- Results: 
|ID|name|
---------
|1|Apples|
|1|Bread|
|1|Milk|
|1|Eggs|

Extracting Values Using Element Tag Attributes

Suppose you have this sample table with a single record, including an ID column and a column with XML content called "XMLContent" with the following content:

<restaurant>
  <dish type="appetizer">
    <name lang="en">Caprese Salad</name>
    <chef>Chef Giovanni</chef>
    <price currency="USD">9.99</price>
  </dish>
  <dish type="main-course">
    <name lang="fr">Boeuf Bourguignon</name>
    <chef>Chef Marie</chef>
    <price currency="EUR">19.99</price>
  </dish>
  <dish type="dessert">
    <name lang="es">Tres Leches Cake</name>
    <chef>Chef Alejandro</chef>
    <price currency="MXN">89.99</price>
  </dish>
</restaurant>

To extract attribute content, specify the scope in the XMLTABLE function and provide the desired attribute name(s) in the WITH clause. Note that this will not work if the XMLTABLE function's child_type input is set to 2.

SELECT A.ID, X.type FROM [TableWithXMLField] A CROSS APPLY XMLTABLE(A.XMLContent,'//*/dish') WITH (type VARCHAR(255)) AS X

-- Results: 
|ID|type|
---------
|1|appetizer|
|1|main-course|
|1|dessert|

CSVTABLE(csv_content,[delimiter])

For each record in the resultset of the preceding table expression, reads from a column that contains a CSV table (csv_content) and for each record in that CSV table, returns one record containing the value of the CSV column(s) specified in the WITH clause.

  • csv_content: A column containing a CSV table.
  • delimiter: An optional custom delimiter (instead of a comma) which splits the CSV content contained in the csv_content input.

Consider a sample table with a single record, including an ID column and a column containing CSV table called "CSVContent" with the following content:

Name;Category;Price
Apple;Fruit;0.99
Spaghetti;Pasta;5.49
Chicken Breast;Meat;8.99
Broccoli;Vegetable;2.49

To select every value in the "Name" column and account for the custom delimiter (;):

SELECT A.ID, X.Name FROM [TableWithCSVField] A CROSS APPLY CSVTABLE(A.CSVContent,';') WITH (Name VARCHAR(255)) AS X

-- Results:
|ID|Name|
-----------
|1|Apple|
|1|Spaghetti|
|1|Chicken Breast|
|1|Broccoli|

CData Python Connector for XML

INSERT Statements

To create new records, use INSERT statements.

INSERT Syntax

The INSERT statement specifies the columns to be inserted and the new column values. You can specify the column values in a comma-separated list in the VALUES clause, as shown in the following example:

INSERT INTO <table_name> 
( <column_reference> [ , ... ] )
VALUES 
( { <expression> | NULL } [ , ... ] ) 
  

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>
The following is an example query:
INSERT INTO NorthwindOData (Username) VALUES ('Ana Trujilo')

CData Python Connector for XML

UPDATE Statements

To modify existing records, use UPDATE statements.

Update Syntax

The UPDATE statement takes as input a comma-separated list of columns and new column values as name-value pairs in the SET clause, as shown in the following example:

UPDATE <table_name> SET <select_statement> | {<column_reference> = <expression> [ , ... ]} WHERE { Id = <expression>  } [ { AND | OR } ... ] 

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>

The following is an example query:

UPDATE NorthwindOData SET Username='Ana Trujilo' WHERE Id = @myId

CData Python Connector for XML

DELETE Statements

To delete information from a table, use DELETE statements.

DELETE Syntax

The DELETE statement requires the table name in the FROM clause and the row's primary key in the WHERE clause, as shown in the following example:

<delete_statement> ::= DELETE FROM <table_name> WHERE { Id = <expression> } [ { AND | OR } ... ]

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>

The following is an example query:

DELETE FROM NorthwindOData WHERE Id = @myId

CData Python Connector for XML

CACHE Statements

When caching is enabled, CACHE statements provide complete control over the data that is cached and the table to which it is cached. The CACHE statement executes the SELECT statement specified and caches its results to a table with the same name in the cache database or to table specified in <cached_table_name>. The connector updates or inserts rows to the cache depending on whether or not they already exist in the cache, so the primary key, which is used to identify existing rows, must be included in the selected columns.

See Caching Data for more information on different caching strategies.

CACHE Statement Syntax

The cache statement may include the following options that alter its behavior:

CACHE [ <cached_table_name> ] [ WITH TRUNCATE | AUTOCOMMIT | SCHEMA ONLY | DROP EXISTING | ALTER SCHEMA ] <select_statement> 

WITH TRUNCATE

If this option is set, the connector removes existing rows in the cache table before adding the selected rows. Use this option if you want to refresh the entire cache table but keep its existing schema.

AUTOCOMMIT

If this option is set, the connector commits each row individually. Use this option if you want to ignore the rows that could not be cached due to some reason. By default, the entire result set is cached as a single transaction.

DROP EXISTING

If this option is set, the connector drops the existing cache table before caching the new results. Use this option if you want to refresh the entire cache table, including its schema.

SCHEMA ONLY

If this option is set, the connector creates the cache table based on the SELECT statement without executing the query.

ALTER SCHEMA

If this option is set, the connector alters the schema of the existing table in the cache if it does not match the schema of the SELECT statement. This option results in new columns or dropped columns, if the schema of the SELECT statement does not match the cached table.

Common Queries

Use the following cache statement to cache all rows of a table:

CACHE SELECT * FROM NorthwindOData

Use the following cache statement to cache all rows of a table into the cache table CachedNorthwindOData:

CACHE CachedNorthwindOData SELECT * FROM NorthwindOData

Use the following cache statement for incremental caching. The DateModified column may not exist in all tables. The cache statement shows how incremental caching would work if there were such a column. Also, notice that, in this case, the WITH TRUNCATE and DROP EXISTING options are specifically omitted, which would have deleted all existing rows.

CACHE CachedNorthwindOData SELECT * FROM NorthwindOData WHERE DateModified > '2013-04-04'

Use the following cache statements to create a table with all available columns that will then cache only a few of them. The sequence of statements cache only Email and Username even though the cache table CachedNorthwindOData has all the columns in NorthwindOData.

CACHE CachedNorthwindOData SCHEMA ONLY SELECT * FROM NorthwindOData
CACHE CachedNorthwindOData SELECT Email, Username FROM NorthwindOData

CData Python Connector for XML

EXECUTE Statements

To execute stored procedures, you can use EXECUTE or EXEC statements.

EXEC and EXECUTE assign stored procedure inputs, referenced by name, to values or parameter names.

Stored Procedure Syntax

To execute a stored procedure as an SQL statement, use the following syntax:

 
{ EXECUTE | EXEC } <stored_proc_name> 
{
  [ @ ] <input_name> = <expression>
} [ , ... ]

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>

Example Statements

Reference stored procedure inputs by name:

EXECUTE my_proc @second = 2, @first = 1, @third = 3;

Execute a parameterized stored procedure statement:

EXECUTE my_proc second = @p1, first = @p2, third = @p3; 

CData Python Connector for XML

PIVOT and UNPIVOT

PIVOT and UNPIVOT can be used to change a table-valued expression into another table.

PIVOT

PIVOT rotates a table-value expression by turning unique values from one column into multiple columns in the output. PIVOT can run aggregations where required on any column value.
PIVOT Synax

 
"SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, [0], [1], [2], [3], [4]
FROM
(
SELECT DaysToManufacture, StandardCost
FROM Production.Product
) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;"

UNPIVOT

UNPIVOT carries out nearly the opposite to PIVOT by rotating columns of a table-valued expressions into column values.
UNPIVOT Sytax

 
"SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;"

For further information on PIVOT and UNPIVOT, see FROM clause plus JOIN, APPLY, PIVOT (Transact-SQL)

CData Python Connector for XML

API Script Reference

The CData Python Connector for XML provides standards-based access to XML by modeling local and remote data as relational tables, views, and stored procedures. CData has its own configuration language called API Script that you can use to mark up schemas. API Script hides the complexity of crafting requests to XML and parsing the feeds returned.

However, API Script is also a high-level programming language that enables you to control almost every aspect of data access and processing. Your schema is a script interpreted by the API Script engine.

You use keywords, attributes, items, operations, and feeds to write scripts:

  • Attribute: The name part of a name-value pair, as in attribute="address", value="123 Pleasant Lane".
  • Item: A related group of attribute-value pairs that describe an input or output. For example:
    Attribute="name" value="Bob"
    Attribute="address" value="123 Pleasant Lane"
    Attribute="phone" value="123-4567"
  • Feed: A list of items: for example, a list of customers with their addresses and phone numbers.
  • Operation: A generic name for methods that accept items as input and produce feeds as output.
  • Keyword: An API Script statement, like api:set.
API Script includes many keywords that allow you to do the following:
  • Project columns over a feed and split feed items into rows.
  • Use high-level programming constructs such as if/else statements and case statements to control execution flow.
  • Call operations and define your own.
  • Create and modify items, the inputs to an operation, and feeds, the operation's result.
  • Process the feed resulting from an operation call by iterating through its items.

CData Python Connector for XML

Items in API Script

Feeds are composed of items, but in API Script items themselves are used for much more than the individual parts of a feed. They are also used to represent inputs to operations.

Declare Items

In API Script items are created, named, and given attribute values through the api:set keyword:

<api:set item="input" attr="mask" value="*.txt" />
The line above sets the "mask" attribute to the value "*.txt" on the item named "input". In this case, the input item is like a variable in API Script.

However, an item named "input" is never declared. Instead, the item is created the first time you try to set an attribute on it. In the example above, if the input item did not already exist, it would be created and the mask attribute would be set on it.

Select Attribute Values

To reference an attribute, use the syntax item.attribute (e.g., "input.mask"). To query an attribute value, surround the attribute name in square brackets ([]). This instructs the interpreter that you want to evaluate the string instead of interpreting it as a string literal.

For example, consider the following code snippet:

<api:set item="item1" attr="attr1" value="value1"/>
<api:set item="item1" attr="attr2" value="item1.attr1"/>
<api:set item="item1" attr="attr3" value="[item1.attr1]"/>

The results are the following:

  • item1.attr1 gets assigned the literal string value "value1".
  • item1.attr2 gets assigned the literal string value "item1.attr1".
  • item1.attr3 gets assigned the value "value1", because the string "[item1.attr1]" gets evaluated at run time as the attr1 attribute of item1.
Note that you can use a backslash to escape square brackets in string literals.

Default Item

In API Script there is always an implicit, unnamed item on an internal stack of items, the default item. In the following two cases, the default item is commonly used to make scripts shorter and easier to write:

  • Calling operations: The default item is the item passed by default to the operation called by your script if no other item is specified. This means that you can use api:set to write attributes to the default unnamed item and those attributes will be passed as input to the next operation called in the script. This is one way to provide an operation's required parameters.
  • Processing the current item in the output of an operation or script: If you do not specify a variable name for the result of an operation, then inside the api:call block that invokes the operation, the default item will refer to the current item produced by the operation.
Manipulate the default item by simply omitting the item attribute of an API Script keyword:
<api:set attr="path" value="." />

Named Items

In addition to items declared within the script, several built-in items are available in the scope of a script. Built-in, or special, items are available in API Script that provide an interface for accessing the connection string and the SQL query. These special items are useful for mapping inputs to data processing operations.

The following sections detail the special items.

Script Inputs (_input)

The input for a script can be read from the _input item. The SQL statement provides the input for table and stored procedure scehmas: In a SELECT statement, the _input item contains the columns or pseudo columns specified in the WHERE clause.

When you read values from the default item in a script, you are reading values from _input; likewise, attributes that you write to the default item are passed as parameters to operations along with the input to the script. Only the variables defined in the info block or in the script will be available in the _input item.

Note that inside an api:call block _input is no longer the default item and you must reference it by name if you need access to it.

Script Outputs (_out[n])

The current item in the feed produced by the api:call keyword can be accessed through the default item or a named special item, "_outX", where X is the level of nesting of api:call keywords. For example, if you are inside a single api:call keyword, the item's name will be "_out1". If you are inside three levels of nested api:call keywords, then it will be _out3.

Connection String Properties (_connection)

The _connection item has the connection properties of the connector. The connector does not perform any validation of the connection string properties. It is left to the schema author to decide which properties are required, how they are used, etc.

In addition to providing access to the connection properties, the _connection item can be used to store pieces of data in a connection. For example, it may be necessary to store session tokens that can be reused while a connection lasts. You can use the api:set keyword to store any values, as shown in the code example below:

<api:set attr="_connection._token" value="[oauth.connection_token]"/>

Note: You can set only the attributes that start with the _ symbol. This is done so that the connection properties set by the user cannot be overriden.

SQL Clauses (_query)

The _query item has the following attributes that describe the query that was issued to the connector:

queryThe SQL statement. For example:
SELECT Id, Name FROM Accounts WHERE City LIKE '%New%' AND COUNTRY = 'US' GROUP BY CreatedDate ORDER BY Name LIMIT 10,50;
selectcolumnsA comma-separated list of the columns in the SELECT clause. For example, the Id and Name columns in the example. If "*" is specified in the SELECT clause, the value of [_query.selectcolumns] is "*".
tableThe table name. For example, Accounts in the example.
isjoinWhether the query is a join.
jointableThe table in the JOIN clause.
criteriaThe WHERE clause. For example, the following WHERE clause in the example:
City LIKE '%New%' AND COUNTRY = 'US'
orderbyThe ORDER BY clause. For example, Name in the example.
groupbyThe GROUP BY clause. For example, CreatedDate in the example.
limitThe limit specified in the LIMIT or TOP clauses of the SELECT statement. For example, 50 in the example.
offsetThe offset specified in the LIMIT or TOP clauses of the SELECT statement. For example, 10 in the example.
insertselectThe SELECT statement nested in an INSERT statement.
updateselectThe SELECT statement nested in an UPDATE statement.
upsertselectThe SELECT statement nested in an UPSERT statement.
deleteselectThe SELECT statement nested in a DELETE statement.
bulkoperationcolumnsThe columns of the table the bulk operation modifies, separated by commas. For example, consider the following query:
INSERT INTO Account(account_name, account_type) SELECT customer_name, customer_type FROM Customer#TEMP
[_query.bulkoperationcolumns] returns the following:
[account_name], [account_type]
temptablecolumnsThe columns selected from the temp table in a bulk operation, separated by commas. For example, consider the following query:
DELETE FROM Account WHERE EXISTS SELECT customer_name, customer_type FROM Customer#TEMP
[_query.temptablecolumns] returns the following:
[customer_name], [customer_type]
nullupdatesThe columns of an UPDATE statement, separated by commas, that contain a null value or a null parameter value.
isschemaonlyWhether the query retrieves only schema information.

Preserve Attr Values Across API Calls (global)

The global item is useful when there are multiple different values that need to be saved and preserved in a complex multi-request flow across multiple pages, outside of just the paging value in rows@next. Any attrs that are set in this item will continue to be accessible when processing the next page of data in the query process.

CData Python Connector for XML

Value Formatters

Value formatters enable you to generate new values with specific formatting. You can use value formatters to perform string, date, and math operations on values.

The general format for invoking formatters is

[ item.attribute | formatter(parameters) | formatter (parameters) | ...]
where formatter is the name of the formatter and parameters is an optional set of parameters to control formatter output. Formatter output can be provided as input to another formatter with the pipe character ("|").

Examples

  • In the following snippet any "*" character in the myid attribute's value is replaced by "-", and the resulting value is assigned to input1.id.
    <api:set attr="input1.id" value="[myid | replace('*', '-')]"/>
  • Below, two value formatters are chained with the pipe ("|") character. In the example, only .log files are pushed from the operation.
    <api:call op="fileListDir">
      <api:check attr="name" value="[filename|tolower | endswith('.log')]">
        <api:push/>
      </api:check>
    </api:call>

CData Python Connector for XML

String Formatters

[attr | allownull()]

Returns NULL if the attribute does not exist or the value if it does.

[attr | arrayfind(substring)]

Returns the index at which the string is found in the attribute array. The index is 1 based.

  • searchstring: The string to search for in the original value.

[attr | base64decode()]

Converts the attribute value to a base 64 decoded string.

[attr | base64encode()]

Converts the attribute value to a base 64 encoded string.

[attr | capitalize()]

Returns the original attribute value with only its first character capitalized.

[attr | capitalizeall()]

Returns the original attribute value with the first character of all words capitalized.

[attr | center(integer_width[, character])]

Returns the attribute value centered in a string of width specified by the first parameter. Padding is done using the fillchar specified by the second parameter.

  • width: The total width of the output string.
  • character: The optional character used for padding. If not specified this defaults to a space.

[attr | contains(value[, ifcontains][, ifnotcontains])]

Returns true (or ifcontains) if the attribute value contains the parameter value, false (or ifnotcontains) otherwise.

  • value: The string to find from the attribute value.
  • ifcontains: The optional value returned if the attribute value contains the parameter value.
  • ifnotcontains: The optional value returned if the attribute value does not contain the parameter value.

[attr | count(substring)]

Returns the number of occurrences in the attribute value of a substring specified by the first parameter.

  • substring: The substring to search for in the attribute value.

[attr | currency([integer_count])]

Returns the numeric value formatted as currency.

  • count: The optional number specifying how many places to the right of the decimal are displayed. The default is 2.

[attr | decimal([integer_count])]

Returns the numeric value formatted as a decimal number.

  • count: The optional number that indicates how many places to the right of the decimal are displayed. Default is 2.

[attr | def([notexists][, exists])]

Checks for the existence of an attribute and returns the specified parameter value if it does not.

  • notexists: The optional value to return if the attribute value does not exist.
  • exists: The optional value to return if the original attribute exists. If not specified, the original value of the attribute is returned.

[attr | empty(value)]

Returns the specified value if the attribute value is empty, otherwise the original attribute value.

  • value: The value that will be used if the attribute is empty.

[attr | endswith(substring[, iftrue][, iffalse])]

Determines whether the attribute value ends with the specified parameter. Returns true (or iftrue) if the attribute ends with the value and false (or iffalse) if not.

  • substring: The string expected at the end.
  • iftrue: The optional value returned if the attribute value ends with the parameter value.
  • iffalse: The optional value returned if the attribute value does not end with the parameter value.

[attr | equals(value[, ifequals][, ifnotequals])]

Compares the attribute value with the first parameter value and returns true (or ifequals) if they are equal and false (or ifnotequals) if they are not.

  • value: The string to compare with the attribute value.
  • ifequals: The optional value returned if the attribute value equals the value represented by the first parameter.
  • ifnotequals: The optional value returned if the attribute value does not equal the value represented by the first parameter.

[attr | extendtabs([integer_width])]

Replaces all tab characters found in the attribute value with spaces. If the tab size specified by the parameter is not given, a default tab size of 8 characters is used.

  • width: The optional tab width, defaults to 8 if not specified.

[attr | expr(expression)]

Evaluates the mathematical expression.

  • expression: The expression.

[attr | find(substring[, integer_startindex])]

Returns the lowest zero-based index at which the substring is found in the attribute value.

  • substring: The string to search for in the attribute value.
  • startindex: The optional index at which to start the search.

[attr | getlength()]

Returns the number of characters in the attribute value.

[attr | hmacshamd5([key], [toBase64, isBase64Encoded])]

Encrypt a string with the passed-in key and HmacSHAMD5 algorithm.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.
  • isBase64Encoded: The optional boolean value that specifies whether the input is base 64 encoded. Default is false.

[attr | hmacsha1([key], [toBase64, isBase64Encoded])]

Encrypt a string with the passed-in key and HmacSHA1 algorithm.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.
  • isBase64Encoded: The optional boolean value that specifies whether the input is base 64 encoded. Default is false.

[attr | hmacsha256([key], [toBase64, isBase64Encoded])]

Encrypt a string with the passed-in key and HmacSHA256 algorithm.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.
  • isBase64Encoded: The optional boolean value that specifies whether the input is base 64 encoded. Default is false.

[attr | hmacsha512([key], [toBase64, isBase64Encoded])]

Encrypt a string with the passed-in key and HmacSHA512 algorithm.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.
  • isBase64Encoded: The optional boolean value that specifies whether the input is base 64 encoded. Default is false.

[attr | ifequal(value[, ifequals][, ifnotequals])]

Compares the attribute value with the first parameter value and returns true (or ifequals) if they are equal and false (or ifnotequals) if they are not.

  • value: The string to compare with the attribute value.
  • ifequals: The optional value returned if the attribute value equals the value represented by the first parameter.
  • ifnotequals: The optional value returned if the attribute value does not equal the value represented by the first parameter.

[attr | ifmatches(value[, ifmatch][, ifnotmatch])]

Returns true (or ifmatch) if the attribute value matches the first parameter, otherwise false (or ifnotmatch).

  • value: The value that will be compared with the attribute value.
  • ifmatch: The optional value returned if the attribute value matches the parameter value.
  • ifnotmatch: The optional value returned if the attribute value does not match the parameter value.

[attr | iftrue([iftrue][, iffalse])]

Checks the attribute value and returns true (or iftrue) if true and false (or iffalse) if false.

  • iftrue: The optional value returned if the attribute value is true.
  • iffalse: The optional value returned if the attribute value is false.

[attr | implode([separator])]

Implodes multiple values to a string separated by a separator.

  • separator: The optional separator.

[attr | insert(integer_index, string)]

Inserts the specified string at the specified index.

  • index: The zero-based index of the position in the original value where the new string should be inserted.
  • string: The string to insert into the original value.

[attr | isalpha([ifalpha][, ifnotalpha])]

Returns true (or ifalpha) if all characters in the attribute value are alphabetic and there is at least one character, false (or ifnotalpha) otherwise.

  • ifalpha: The optional value returned if the attribute value is alphabetic.
  • ifnotalpha: The optional value returned if the attribute value is not alphabetic.

[attr | isalphabetic([ifalpha][, ifnotalpha])]

Returns true (or ifalpha) if all characters in the attribute value are alphabetic and there is at least one character, false (or ifnotalpha) otherwise.

  • ifalpha: The optional value returned if the attribute value is alphabetic.
  • ifnotalpha: The optional value returned if the attribute value is not alphabetic.

[attr | isalphanum([ifalphanum][, ifnotalphanum])]

Returns true (or ifalphanum) if all characters in the attribute value are alphanumeric and there is at least one character, false (or ifnotalphanum) otherwise.

  • ifalphanum: The optional value returned if the attribute value contains only alphabetic or numeric characters.
  • ifnotalphanum: The optional value returned if the attribute value contains nonalphabetic or nonnumeric characters.

[attr | isalphanumeric([ifalphanum][, ifnotalphanum])]

Returns true (or ifalphanum) if all characters in the attribute value are alphanumeric and there is at least one character, false (or ifnotalphanum) otherwise.

  • ifalphanum: The optional value returned if the attribute value contains only alphabetic or numeric characters.
  • ifnotalphanum: The optional value returned if the attribute value contains nonalphabetic or nonnumeric characters.

[attr | isdigit([ifnum][, ifnotnum])]

Returns true (or ifnum) if all characters in the attribute value are digits and there is at least one character, false (or ifnotnum) otherwise.

  • ifnum: The optional value returned if the attribute value is numeric.
  • ifnotnum: The optional value returned if the attribute value is not numeric.

[attr | islower([iflower][, ifnotlower])]

Returns true (or iflower) if all letters in the attribute value are lowercase and there is at least one character that is a letter, false (or ifnotlower) otherwise.

  • iflower: The optional value returned if the attribute value is lowercase.
  • ifnotlower: The optional value returned if the attribute value is not lowercase.

[attr | isnumeric([ifnum][, ifnotnum])]

Returns true (or ifnum) if all characters in the attribute value are digits and there is at least one character, false (or ifnotnum) otherwise.

  • ifnum: The optional value returned if the attribute value is numeric.
  • ifnotnum: The optional value returned if the attribute value is not numeric.

[attr | isspace([ifspace][, ifnotspace])]

Return true (or ifspace) if there are only white-space characters in the attribute value and there is at least one character, false (or ifnotspace) otherwise.

  • ifspace: The optional value returned if the attribute value is a space.
  • ifnotspace: The optional value returned if the attribute value is not a space.

[attr | isupper([ifupper][, ifnotupper])]

Returns true (or ifupper) if all letters in the attribute value are uppercase and there is at least one character that is a letter, false (or ifnotupper) otherwise.

  • ifupper: The optional value returned if the attribute value is uppercase.
  • ifnotupper: The optional value returned if the attribute value is not uppercase.

[attr | join([separator])]

Implodes multiple values to a string separated by a separator.

  • separator: The optional separator.

[attr | jsonescape()]

Converts the attribute value to a JSON-escaped, single-line string.

[attr | just(integer_width[, character])]

Returns the attribute value left-justified in a string of length specified by the first parameter. Padding is done using the fillchar specified by the second parameter.

  • width: The total width of the output string.
  • character: The optional character used for padding. The default is a space.

[attr | lfind(substring[, integer_startindex])]

Returns the lowest zero-based index at which the substring is found in the attribute value.

  • substring: The string to search for in the attribute value.
  • startindex: The optional index at which to start the search.

[attr | ljust(integer_width[, character])]

Returns the attribute value left-justified in a string of length specified by the first parameter. Padding is done using the fillchar specified by the second parameter.

  • width: The total width of the output string.
  • character: The optional character used for padding. The default is a space.

[attr | lsplit(delimiter, integer_index)]

Splits the string represented by the attribute value into tokens delimited by the first parameter and returns the token at the index specified by the second parameter; counts from the left.

  • delimiter: The string used as a separator for splitting the string into tokens.
  • index: The index of the token requested where the first token is at index 1.

[attr | match(pattern[, index][, option])]

Searches the string represented by the attribute value for an occurrence of the regular expression supplied in the pattern parameter.

  • pattern: The regular expression pattern to match.
  • index: The optional numbered index of the match to return. The default is 0.
  • option: The optional comma-separated list of regular expression options. Some of the commonly used options are IgnoreCase, Multiline, Singleline, and IgnorePatternWhitespace.

[attr | md5hash([converttobase64])]

Computes the MD5 hash of the attribute value.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.

[attr | notequals(value[, notequals][, equals])]

Compares the attribute value with the first parameter value. Returns true (or notequals) if they are not equal and false (or equals) if they are.

  • value: The string to compare with the attribute value.
  • notequals: The optional value returned if the attribute value does not equal the value represented by the first parameter.
  • equals: The optional value returned if the attribute value equals the value represented by the first parameter.

[attr | nowhitespace()]

Removes the white space from the string represented by the atttribute value.

[attr | percentage([integer_count])]

Returns the numeric value formatted as a percentage.

  • count: The optional number that indicates how many places to the right of the decimal are displayed.

[attr | regex(pattern[, index][, option])]

Searches the string represented by the attribute value for an occurrence of the regular expression supplied in the pattern parameter.

  • pattern: The regular expression pattern to match.
  • index: The optional numbered index of the match to return. The default is 0.
  • option: The optional comma-separated list of regular expression options. Some of the commonly used options are IgnoreCase, Multiline, Singleline, and IgnorePatternWhitespace.

[attr | regexmatch(pattern[, index][, option])]

Searches the string represented by the attribute value for an occurrence of the regular expression supplied in the pattern parameter.

  • pattern: The regular expression pattern to match.
  • index: The optional numbered index of the match to return. The default is 0.
  • option: The optional comma-separated list of regular expression options. Some of the commonly used options are IgnoreCase, Multiline, Singleline, and IgnorePatternWhitespace.

[attr | regexreplace(search, replacewith[, integer_startat])]

Replaces all occurrences of the regular expression pattern found in the attribute value with replacewith.

  • search: The regular expression to search with.
  • replacewith: The text to replace the match with.
  • startat: The optional character index at which to start replacement. Default is 0.

[attr | remove(integer_index[, integer_count])]

Deletes characters from the attribute value; begins at the zero-based index specified by the first parameter.

  • index: The position to begin deleting the characters.
  • count: The optional number of characters to delete. If not provided all characters starting from the specified index will be deleted.

[attr | replace(oldvalue, newvalue[, ishex])]

Replaces all occurrences of the first parameter in the string represented by the attribute value with the value of the second parameter.

  • oldvalue: The string to be replaced.
  • newvalue: The string to replace all occurrences of the first parameter.
  • ishex: The optional boolean value specifying whether the first parameter is a hex representation of a character to replace. Default is false.

[attr | rfind(substring[, integer_startindex])]

Returns the highest zero-based index at which the substring is found in the attribute value.

  • substring: The string to search for in the original value.
  • startindex: The optional index at which to start the search.

[attr | rjust(integer_width[, character])]

Returns the right-justified attribute value in a string of length specified by the second parameter. Padding is done using the fillchar specified by the first parameter.

  • width: The total width of the output string.
  • character: The optional character used for padding, if not specified this defaults to a space.

[attr | rsplit(delimiter, integer_index)]

Splits the string represented by the attribute value into tokens delimited with the first parameter and returns the token at the index specified by the second parameter; counts from the right.

  • delimiter: The string used as a separator for splitting the string into tokens.
  • index: The index of the token requested where the first token is at index 1.

[attr | sha1hash([converttobase64])]

Computes the SHA-1 hash of the attribute value.

  • encodetobase64: The optional boolean value that specifies whether to convert the result into a base 64 encoded string. Default is true.

[attr | substring(integer_index[, integer_length])]

Returns a substring of the attribute value; starts at the index specified by the parameter and counts to the right.

  • index: The zero-based index at which the substring starts from the right.
  • length: The optional length of characters from the start index. The substring to the end is returned if length is not specified.

[attr | split(delimiter, integer_index)]

Splits the string represented by the attribute value into tokens delimited by the first parameter and returns the token at the index specified by the second parameter; counts from the left.

  • delimiter: The string used as a separator for splitting the string into tokens.
  • index: The index of the token requested where the first token is at index 1.

[attr | sqlescape()]

Converts the attribute value to an SQL-escaped, single-line string.

  • dbtype: The database type to encode. The allowed values are SQL or SQLite. Default is SQL.

[attr | startswith(substring[, iftrue][, iffalse])]

Returns true (or iftrue) if the attribute value starts with the specified parameter, false (or iffalse) otherwise.

  • substring: The string expected at the begining.
  • iftrue: The optional value returned if the attribute value starts with the parameter value.
  • iffalse: The optional value returned if the attribute value does not start with the parameter value.

[attr | striphtml()]

Returns the string with any HTML markup removed.

[attr | substring(integer_index[, integer_length])]

Returns a substring of the attribute value; starts at the index specified by the parameter.

  • index: The zero-based index at which the substring starts.
  • length: The optional length of characters from the start index. A substring to the end of the string is returned if length is not specified.

[attr | toalpha()]

Returns only the letters in a string.

[attr | toalphanum()]

Returns only the alphanumeric characters in a string.

[attr | tolower()]

Returns the string represented by the attribute value with all characters converted to lowercase.

[attr | toupper()]

Returns the string represented by the attribute value with all characters converted to uppercase.

[attr | trim()]

Trims leading and trailing white space from an attribute.

[attr | trimend()]

Trims trailing white space from an attribute.

[attr | trimstart()]

Trims leading white space from an attribute.

[attr | truncate(integer_count)]

Truncates the attribute value to the number of characters specified by the parameter.

  • count: The number of characters in the resulting string.

[attr | urlencode([isurlcomponent])]

Converts the attribute value to a URL encoded string.

  • isurlcomponent: The optional boolean value that specifies whether the attribute value is URL component or full URL. If set to false, it will only encode content after the first '?' character, but ignore all '=' and '&' characters. Default is true, an URL component.

[attr | urldecode()]

Converts the attribute value to a URL decoded string.

[attr | wordwrap([integer_width][, break][, cut][, wrapexp])]

Wraps a string to a given number of characters.

  • width: The optional number of characters at which the string will be wrapped.
  • break: The optional break parameter to be used to break the line.
  • cut: The optional boolean value that specifies whether to wrap the string at or before the specified width. Default is false.
  • wrapexp: The optional regex expression to be used as a breakable characters. Default is space.

[attr | print([delim])]

Returns a string with all the values of the attribute concatenated using the specified delimiter.

  • delim: The optional delimiter to separate values with. Default is a comma.

[attr | xmldecode()]

Converts the attribute value to a XML decoded string.

[attr | xmlencode()]

Converts the attribute value to a XML encoded string.

CData Python Connector for XML

Date Formatters

[attr | compare([value][, inputformat])]

Returns a signed number indicating the relative values of dates represented by the attribute value and parameter value.

  • value: The optional string representation of the date that will be compared with the attribute value. Default is now.
  • inputformat: The optional input format specifier. Default is autodetected.

[attr | date([outputformat])]

Returns the current system date and time in the format specified by the parameter if one was provided.

  • outputformat: The optional format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g (general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T long time pattern), file (Windows file time), MM/dd/yy, etc.

[attr | dateadd([interval][, integer_value][, outputformat][, inputformat])]

Returns a string value of the datetime that results from adding the specified number interval (a signed integer) to the specified date part of the date.

  • interval: The optional interval you want to add. Specify year, month, day, hour, minute, second, or millisecond.
  • value: The optional number of intervals you want to add. Can either be positive for dates in the future or negative for dates in the past.
  • outputformat: The optional output format specifier. Valid specifiers include d(short date pattern), D(long date pattern), f(long date/short time pattern), F(long date/time pattern), g(general short date/time pattern), G(general short date/long time pattern), r or R(RFC1123 pattern), s(sortable date/time pattern), t(short time pattern), T(long time pattern), file(Windows file time), MM/dd/yy, etc.
  • inputformat: The optional input format specifier. Default is autodetected.

[attr | datediff([interval][, value][, inputformat])]

Returns the difference (in units specified by the first parameter) between now and the date specified by the second parameter.

  • interval: The optional interval you want the result in. Specify day, hour, minute, second, or millisecond.
  • value: The optional string representation of the date to compare with attribute value. Default is now.
  • inputformat: The optional input format specifier. Default is autodetected.

[attr | day([inputformat])]

Returns the day component, expressed as a value between 1 and 31, of the date represented by the attribute value.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | dayofweek([inputformat])]

Returns the day of week for the date represented by the attribute value.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | dayofyear([inputformat])]

Returns the day of year expressed as a value between 1 and 366 for the date represented by the attribute value.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | filetimenow()]

Returns the date and time for the current system file time.

[attr | fromfiletime([outputformat])]

Converts a valid file time to a valid datetime value formatted as specified by the parameter if one was provided.

  • outputformat: The optional output format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g (general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T (long time pattern), file (Windows file time), MM/dd/yy, etc.

[attr | isleap([ifleap][, ifnotleap])]

Returns true (or ifleap) if the 4-digit year represented by the attribute value is a leap year, false (or ifnotleap) otherwise.

  • ifleap: The optional value returned if the attribute value is a leap year.
  • ifnotleap: The optional value returned if the attribute value is not a leap year.

[attr | month([inputformat])]

Returns the month component expressed as a value between 1 and 12 of the date represented by the attribute value.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | now([outputformat])]

Returns the current system date and time in the format specified by the parameter if one was provided.

  • outputformat: The optional format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g (general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T long time pattern), file (Windows file time), MM/dd/yy, etc.

[attr | todate([outputformat][,inputformat])]

Returns the date specified by the attribute value formatted as specified by the parameter if one was provided.

  • outputformat: The optional output format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g (general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T (long time pattern), file (Windows file time), MM/dd/yy, etc.
  • inputformat: The optional input format specifier. Default is autodetected.

[attr | tofiletime([inputformat])]

Converts a valid datetime to a valid file time value.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | tomonth()]

Returns the name of the month for the numeric value specified by the attribute value.

[attr | toutc([outputformat][, inputformat])]

Returns the date specified by the attribute value converted to UTC and formatted as specified by the outputformat parameter if one was provided.

  • outputformat: The optional format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g (general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T (long time pattern), and file (Windows file time), MM/dd/yy, etc.

[attr | utcnow([outputformat])]

Returns the current system UTC date and time.

  • outputformat: The optional format specifier. Valid specifiers include d (short date pattern), D (long date pattern), f (long date/short time pattern), F (long date/time pattern), g(general short date/time pattern), G (general short date/long time pattern), r or R (RFC1123 pattern), s (sortable date/time pattern), t (short time pattern), T (long time pattern), file (Windows file time), MM/dd/yy, etc.

[attr | weekday([inputformat])]

Returns the day of the week as an integer where Monday is 0 and Sunday is 6.

  • inputformat: The optional input format specifier. Default is autodetected.

[attr | year([inputformat])]

Returns the year component of the date represented by the attribute value.

  • inputformat: The optional input format specifier. Default is autodetected.

CData Python Connector for XML

Math Formatters

[attr | abs()]

Returns the absolute value of the numeric attribute value.

[attr | add([value])]

Returns the sum of the numeric attribute value and the value specified by the parameter.

  • value: The optional numeric value to add to the specified attribute value. Default is 1.

[attr | and(value)]

Returns the AND of two values. The values provided on each side must be 1/0, yes/no or true/false.

  • value: The boolean value to compare by.

[attr | ceiling()]

Returns the smallest integer greater than or equal to a numeric attribute value.

[attr | div([value])]

Returns the result of dividing the numeric attribute value by the specified value of the parameter.

  • value: The optional numeric value to divide the numeric attribute value by. Default is 2.

[attr | divide([value])]

Returns the result of dividing the numeric attribute value by the specified value of the parameter.

  • value: The optional numeric value to divide the numeric attribute value by. Default is 2.

[attr | floor()]

Returns the largest integer less than or equal to the numeric attribute value.

[attr | greaterthan(value[, ifgreater][, ifnotgreater])]

Returns true (or ifgreater) if the attribute value is greater than the parameter value, false (or ifnotgreater) otherwise.

  • value: The numeric value to compare with the attribute value.
  • ifgreater: The optional value returned if the attribute value is greater than the parameter value.
  • ifnotgreater: The optional value returned if the attribute value is not greater than the parameter value.

[attr | isbetween(integer_lowvalue, integer_highvalue[, ifbetween][, ifnotbetween])]

Returns true (or ifbetween) if the attribute value is greater than or equal to the first parameter value and less than or equal to the second parameter value, false (or ifnotbetween) otherwise.

  • lowvalue: The lower bound of the range to check.
  • highvalue: The higher bound of the range to check.
  • ifbetween: The optional value returned if the attribute value is greater than or equal to the first parameter value and less than or equal to the second parameter value.
  • ifnotbetween: The optional value returned if the attribute value is less than the first parameter value or greater than the second parameter value.

[attr | isequal(value[, ifequal][, ifnotequal])]

Returns true (or ifequal) if the attribute value is equal to the parameter value, false (or ifnotequal) otherwise.

  • value: The numeric value to compare with the attribute value.
  • ifequal: The optional value returned if the attribute value is equal to the parameter value.
  • ifnotequal: The optional value returned if the attribute value is not equal to the parameter value.

[attr | isgreater(value[, ifgreater][, ifnotgreater])]

Returns true (or ifgreater) if the attribute value is greater than the parameter value, false (or ifnotgreater) otherwise.

  • value: The numeric value to compare with the attribute value.
  • ifgreater: The optional value returned if the attribute value is greater than the parameter value.
  • ifnotgreater: The optional value returned if the attribute value is not greater than the parameter value.

[attr | isless(value[, ifless][, ifnotless])]

Returns true (or ifless) if the attribute value is less than the parameter value, false (or ifnotless) otherwise.

  • value: The numeric value to compare with the attribute value.
  • ifless: The optional value returned if the attribute value is less than the parameter value.
  • ifnotless: The optional value returned if the attribute value is not less than the parameter value.

[attr | lessthan(value[, ifless][, ifnotless])]

Returns true (or ifless) if the attribute value is less than the parameter value, false (or ifnotless) otherwise.

  • value: The numeric value to compare with the attribute value.
  • ifless: The optional value returned if the attribute value is less than the parameter value.
  • ifnotless: The optional value returned if the attribute value is not less than the parameter value.

[attr | mathadd([value])]

Returns the sum of the numeric attribute value and the value specified by the parameter.

  • value: The optional numeric value to add to the specified attribute value. Default is 1.

[attr | mathmod(value)]

Returns the modulus of the numeric attribute value divided by the specified parameter value.

  • value: The number to divide the attribute value by.

[attr | mathpow([value])]

Returns the numeric attribute value raised to the power specified by the parameter value.

  • value: The optional power to raise the attribute value to. Default is 2.

[attr | mathround([integer_value])]

Returns the numeric attribute value rounded to the number of decimal places specified by the parameter.

  • value: The optional number of decimal places. Default is 2.

[attr | mathsub([value])]

Returns the difference between the numeric attribute value and the value specified by the parameter.

  • value: The optional numeric value to subtract the attribute value by.

[attr | modulus(value)]

Returns the modulus of the numeric attribute value divided by the specified parameter value.

  • value: The number to divide the attribute value by.

[attr | multiply([value])]

Returns the result of multiplying the numeric attribute value with the specified value of the parameter.

  • value: The optional numeric value to multiply the numeric attribute value by. Default is 2.

[attr | or(value)]

Returns the OR of two values. The values provided on each side must be 1/0, yes/no or true/false.

  • value: The boolean value to compare by.

[attr | pow([value])]

Returns the numeric attribute value raised to the power specified by the parameter value.

  • value: The optional power to raise the attribute value to. Default is 2.

[attr | rand([integer_value])]

Returns a random integer between 0 and the parameter value.

  • value: The optional value that limits the highest possible random integer. Default is 100.

[attr | random([integer_value])]

Returns a random integer between 0 and the parameter value.

  • value: The optional value that limits the highest possible random integer. Default is 100.

[attr | round([integer_value])]

Returns the numeric attribute value rounded to the number of decimal places specified by the parameter.

  • value: The optional number of decimal places. Default is 2.

[attr | sqrt()]

Returns the square root of the numeric attribute value.

[attr | subtract([value])]

Returns the difference between the numeric attribute value and the value specified by the parameter.

  • value: The optional numeric value to subtract the attribute value by.

CData Python Connector for XML

Operations

While Value Formatters handle simple data manipulation and formatting, Operations are used for more complex work within API Script.

CData Python Connector for XML

httpPost

Post data to a URL using the HTTP POST method.

Required Parameters

  • url: The destination URL

Optional Parameters

  • timeout: The timeout, in seconds, for the operation to complete. Zero (0) means no timeout. Default is 60
  • proxy_server: The IP address or host name of the proxy server
  • proxy_auto: Whether the proxy should be detected from Windows system settings. Allowed values: TRUE, FALSE. Default is FALSE
  • proxy_port: The port number of the proxy server
  • proxy_user: The user ID for the proxy server
  • proxy_password: The password for the proxy server
  • proxy_authscheme: Authentication scheme of the proxy server. Allowed values: BASIC, DIGEST, PROPRIETARY, NONE, NTLM. Default is BASIC
  • proxy_authtoken: Proxy authentication token
  • proxy_ssltype: SSL/TLS type of the proxy. Allowed values: AUTO, ALWAYS, NEVER, TUNNEL. Default is AUTO
  • firewall_server: IP or host name of the firewall
  • firewall_port: Port of the firewall
  • firewall_user: Username for the firewall
  • firewall_password: Password for the firewall
  • firewall_type: Type of firewall. Allowed values: NONE, TUNNEL, SOCKS4, SOCKS5. Default is NONE
  • kerberoskdc: Kerberos KDC setting, used when authscheme is Negotiate
  • kerberosrealm: Kerberos realm setting, used when authscheme is Negotiate
  • internalconfig#: Sets an internal configuration setting
  • charset: Charset of exchanged data. Default is UTF-8
  • httpversion: HTTP version. Allowed values: 1.0, 1.1. Default is 1.1
  • cookie:*: Any cookies to add to the request
  • followredirects: Whether to follow HTTP redirects. Allowed values: TRUE, FALSE. Default is TRUE
  • sslcert: SSL/TLS certificate to accept. Can be PEM, file path, public key, thumbprint, or TRUSTED
  • sslclientcert: Name of the client certificate store
  • sslclientcerttype: Store type for the client certificate. Allowed values: USER, MACHINE, PFXFILE, etc
  • sslclientcertpassword: Password for the client certificate
  • sslclientcertsubject: Subject of the client certificate. An asterisk finds the first in the store
  • user: Username for authentication
  • password: Password for authentication
  • authscheme: Authorization mechanism. Allowed values: BASIC, DIGEST, NTLM. Default is BASIC
  • version: OAuth version. Allowed values: Disabled, 1.0, 2.0. Default is Disabled
  • token: OAuth request token
  • token_secret: OAuth request token secret (1.0 only)
  • sign_method: Signature method for OAuth 1.0. Allowed values: HMAC-SHA1, PLAINTEXT. Default is HMAC-SHA1
  • client_id: Client ID (OAuth 1.0 only)
  • client_secret: Client secret (OAuth 1.0 only)
  • header:name#: Name of a custom header
  • header:value#: Value of a custom header
  • paramname#: Name of a parameter to include
  • paramvalue#: Value of a parameter to include
  • formencoding: Encoding for parameters. Allowed values: URLENCODED, FORMDATA. Default is URLENCODED
  • postdata: Raw data to include in the POST. Use file://path to include a file
  • contenttype: Content type of the POST. Default is application/x-www-form-urlencoded
  • logfile: Full path to log file for request/response data (requires verbosity)
  • verbosity: Log verbosity, 1-5

Output Attributes

  • ssl:issuer: Issuer of the SSL/TLS certificate
  • ssl:subject: Subject of the SSL/TLS certificate
  • http:statuscode: HTTP status code returned
  • http:content: Content of the HTTP response
  • cookie:*: Cookies returned with the response
  • http:allcookies: All response cookies as a single string
  • header:*: Headers returned with the response

Example


<api:set item="http" attr="URL" value="http://example.com/people"/>
<api:set item="http" attr="paramname#1" value="name"/>
<api:set item="http" attr="paramvalue#1" value="Charlie"/>
<api:set item="http" attr="paramname#2" value="age"/>
<api:set item="http" attr="paramvalue#2" value="28"/>

<api:call op="httpPost" in="http">
  <api:set attr="output.data" value="[http:content]"/>
</api:call>

<api:set attr="output.filename" value="httpContent.txt"/>
<api:push item="output"/>

CData Python Connector for XML

httpGet

Get a document from the Web using the HTTP GET method

Required Parameters

  • url: The URL to retrieve

Optional Parameters

  • timeout: The timeout, in seconds, for the operation to complete. Zero (0) means no timeout. Default is 60
  • proxy_server: The IP address or host name of the proxy server
  • proxy_auto: Whether the proxy should be detected from Windows system settings. Allowed values: TRUE, FALSE. Default is FALSE
  • proxy_port: The port number of the proxy server
  • proxy_user: The user ID for the proxy server
  • proxy_password: The password for the proxy server
  • proxy_authscheme: Authentication scheme of the proxy server. Allowed values: BASIC, DIGEST, PROPRIETARY, NONE, NTLM. Default is BASIC
  • proxy_authtoken: Proxy authentication token
  • proxy_ssltype: SSL/TLS type of the proxy. Allowed values: AUTO, ALWAYS, NEVER, TUNNEL. Default is AUTO
  • firewall_server: IP or host name of the firewall
  • firewall_port: Port of the firewall
  • firewall_user: Username for the firewall
  • firewall_password: Password for the firewall
  • firewall_type: Type of firewall. Allowed values: NONE, TUNNEL, SOCKS4, SOCKS5. Default is NONE
  • kerberoskdc: Kerberos KDC setting, used when authscheme is Negotiate
  • kerberosrealm: Kerberos realm setting, used when authscheme is Negotiate
  • internalconfig#: Sets an internal configuration setting
  • charset: Charset of exchanged data. Default is UTF-8
  • httpversion: HTTP version. Allowed values: 1.0, 1.1. Default is 1.1
  • cookie:*: Any cookies to add to the request
  • followredirects: Whether to follow HTTP redirects. Allowed values: TRUE, FALSE. Default is TRUE
  • sslcert: SSL/TLS certificate to accept. Can be PEM, file path, public key, thumbprint, or TRUSTED
  • sslclientcert: Name of the client certificate store
  • sslclientcerttype: Store type for the client certificate. Allowed values: USER, MACHINE, PFXFILE, JKSFILE, JKSBLOB, PEMKEY_FILE, PEMKEY_BLOB, PUBLIC_KEY_FILE, PUBLIC_KEY_BLOB, SSHPUBLIC_KEY_BLOB, P7BFILE, P7BBLOB, SSHPUBLIC_KEY_FILE, PPKFILE, PPKBLOB, XMLFILE, XMLBLOB
  • sslclientcertpassword: Password for the client certificate
  • sslclientcertsubject: Subject of the client certificate. An asterisk finds the first in the store
  • user: Username for authentication
  • password: Password for authentication
  • authscheme: Authorization mechanism. Allowed values: BASIC, DIGEST, NTLM. Default is BASIC
  • version: OAuth version. Allowed values: Disabled, 1.0, 2.0. Default is Disabled
  • token: OAuth request token
  • token_secret: OAuth request token secret (1.0 only)
  • sign_method: Signature method for OAuth 1.0. Allowed values: HMAC-SHA1, PLAINTEXT. Default is HMAC-SHA1
  • client_id: Client ID (OAuth 1.0 only)
  • client_secret: Client secret (OAuth 1.0 only)
  • header:name#: Name of a custom header
  • header:value#: Value of a custom header
  • ifmodifiedsince: If-Modified-Since value (for example: Sat, 25 Feb 2006 04:11:47 GMT)
  • localfile: If specified, write the results of the GET to this file
  • logfile: Full path to log file for request/response data (requires verbosity)
  • verbosity: Log verbosity, 1-5

Output Attributes

  • ssl:issuer: Issuer of the SSL/TLS certificate
  • ssl:subject: Subject of the SSL/TLS certificate
  • http:statuscode: HTTP status code returned
  • http:content: Content of the HTTP response
  • cookie:*: Cookies returned with the response
  • http:allcookies: All response cookies as a single string
  • header:*: Headers returned with the response

CData Python Connector for XML

Keyword Reference

Statements in API Script are defined using keywords, XML elements prefixed with "api:". Keywords include the usual features of a programming or scripting language, such as conditionals, loops, and flow control. However, API Script also includes special keywords tailored specifically for feed manipulation and generation; for example, api:call, api:enum, and api:set.

Most keywords take parameters that define or affect their behavior. Parameters are specified as XML attributes of the keyword element. The required and optional parameters, along with code examples, for each keyword are explained in this section.

Keyword Scope

In API Script, some keywords introduce scope; that is, some keywords can be nested inside the bodies of other keywords, and how they are nested is meaningful to the language:

  • You can define instructions for an iteration within a keyword's scope: For example, the body of an api:call keyword is executed for each item in the feed produced by the operation invoked by api:call. Because of this, keywords nested inside api:call are executed for each iteration to produce each item in the feed.
  • Scope associates matching pairs of keywords; for example, the api:else keyword defines an alternate execution path for a conditional keyword like api:equals or api:check. In API Script, a certain api:else keyword is associated with a conditional statement when it is nested as a direct child of the conditional statement. Thus, the api:else keyword must not be defined outside of the scope introduced by a conditional keyword.
  • Keywords can introduce new items (variables) within their scope. For example, the api:call keyword will introduce a default output item representing the item being iterated over in the feed being generated.
  • Keywords can inject additional attributes into the default item that provide more information within their scope. These attributes are called Control Attributes when described in this document. They are easily recognized because they start with the _ character; for example, _attr, _index, _value, etc.

CData Python Connector for XML

api:break

The api:break keyword can be used to break out of iterations of api:call or api:enum. It can also be used to break out of the entire script if it is used outside the scope of any other API Script keywords.

Parameters

None

Control Attributes

None

Examples

Break out of api:enum. The example below lists the first two attributes of the item foo:

<api:set attr="foo.attr1" value="value1"/>
<api:set attr="foo.attr2" value="value2"/>
<api:set attr="foo.attr3" value="value3"/>

<api:enum item="foo">
[_index]: [_attr] has the value [_value]. 
<api:equals attr="_index" value="2"> 
<api:break/>
</api:equals>
</api:enum>

See Also

  • api:continue: Continue to the next item.
  • api:enum: Loop over the values of an item, list, range, or multivalued attribute.
  • api:call: Loop over items returned by an operation.

CData Python Connector for XML

api:call

The api:call keyword is used to call operations. Valid operations are the following:

  • Built-in operations installed along with connector assemblies located in the bin subfolder of the application
  • Operations you write yourself in .NET or Java and place in the bin subfolder of the application

Operations take items as input and return feeds as output. The scope of api:call is executed for every item in the feed returned from the call. Within the scope of api:call, you can inspect and modify the attributes in the item returned. You can then provide these attributes as inputs to another operation, thus forming an operation pipeline. Or, you can push out the item to the output.

The Output Item Stack and the Default Item

Each time an api:call is encountered, a new item is pushed onto an internal stack of items. The item on the top of this stack is the default item. This is the item that provides input to api:call when an item name is not explicitly specified in the input to the call.

The called operation writes attributes to the default item, and api:push pushes the default item to the output. When you push an item, only the attributes from the default item, at the top of the stack, are pushed.

The default item is swept clean after an item has been iterated over, and the api:call then works on the next item. This means that you will not be able to read a value set in a previous iteration of an api:call in the next iteration. To retain values across an iteration, copy them to a named item with api:set.

You can refer to the default item as _ or explicitly as _out1, _out2, _out[n], where N is the depth of the stack. This enables you to read all the values available at this point in the execution process; the lookup process starts from the default item and continues through the stack until a value is found.

In the example below, you can see how items are pushed to the top of the stack with each call and how the default item changes within the scope of each call.

<api:call op="operation1"> 
The default item here is _out1 
A push here would push the attributes from _out1 
The input item used to call operation2 is also _out1 
<api:call op="operation2"> 
The default item here is _out2 
A push here will push the attributes from _out2 
If there was another api:call here the input item used would be _out2 
_out2 is swept clean here for the next iteration 
</api:call> 
The default item here is again _out1 
A push here would again push the attributes from _out1 
The input item at this level is again _out1 
_out1 is swept clean here for the next iteration 
</api:call> 

Specify Input to an Operation

There are 3 ways to provide input to a call:

  • The default item: If an input item is not specified, the called operation reads input values from the default item. You can use the api:set keyword to set values in the default item so that they are processed by the called operation.
    <api:set attr="mask" value="*.txt"/>
    <api:set attr="path" value="C:\\"/>
    <api:call op="fileListDir">
    ... 
    </api:call>
  • An explicit input item: Instead of using the default item, you can use the in parameter to explicitly specify the items you want to use as input to the operation. If you choose to do so the default item is no longer used and the input values are read from the input items specified and, as shown below, the query string passed to the operation.
    <api:set attr="mask" value="*.* -- Will be ignored --"/>
    <api:set attr="myinput.mask" value="*.txt"/>
    <api:set attr="myinput.path" value="C:\\"/>
    <api:call op="fileListDir" in="myinput">
    ... 
    </api:call>
  • Query string parameters: You can also use query string notation to specify input to an operation. The attributes specified as part of the query string are given precedence. Thus, if there is a name clash between attributes specified in the query string and those in the input item, the ones in the query string are preferred. However, the other attributes of the input item are still accessible. The example below shows the syntax to specify input in the query string:
    <api:set attr="myinput.mask" value="*.txt -- will be overridden --"/> 
    <api:set attr="myinput.path" value="C:\\"/> 
    <api:call op="fileListDir?mask=*.rsb" in="myinput">
    ...
    </api:call>

Parameters

  • op: The name of the operation to be called.
  • in[put]: A list of items used as input when invoking the operation. Attributes are looked up from left to right in the input items specified.
  • out[put]: The item where the output attributes are placed. Within the api:call scope, the current output item can be retrieved using the item name specified here. You can also use _out[n] or _pipe to refer to the call's results.

    Note: Attributes set within a call are not available outside the scope of the call. This is because each iteration of the call deletes the attributes from the previous iteration; at the end of the call nothing is left. To access an attribute outside the scope of a call, use api:set to explicitly copy the attribute to the item you want to use outside the call.

  • item: The name of the item to be used for both input and output.
  • sep[arator]: The separator used to separate multiple input items. The default is a comma.
  • ignoreprefix: A comma-separated list of prefixes that are ignored when found. Some operations return attributes with names of the form "prefix:name" (e.g., api:operation and sql:company). In some situations, you may want to treat both prefix:name and name as the same attribute.
  • page and pagesize: The subset of items that will be iterated through. Used to enable paging of the operation or feed results. For example, if you specify page="2" and pagesize="5", the api:call keyword iterates only through items 6 to 10 of the resulting feed.

Control Attributes

  • _index: The index of the item currently being iterated over by api:call.
  • _op: The name of the operation being called. This is helpful when the operation name is not known until execution.
  • _separator: The separator used to separate multiple input items.

Examples

Call an operation using the default item as input:

<api:set attr="path" value="C:\myfiles"/>
<api:call op="fileListDir">
  <api:push/>
</api:call>

See Also

  • api:first: Write elements to be executed only for the first iteration of the call.
  • api:catch: Catch errors within a call.
  • api:continue: Continue to the next iteration.

CData Python Connector for XML

api:case

The api:case keyword is used with the api:select keyword. The api:case keyword consists of a block of API Script that is executed if the value in api:select matches the value in api:case.

Parameters

  • value: The pattern or value to compare against the value specified in api:select.
  • match: The type of matches to find to determine whether the case statement should be executed. The default value is "exact", which requires an exact match of the value. Other supported types are "regex", for regular expression matching, and "glob", which supports a simple expression model similar to the one used in file-name patterns (e.g., *.txt). The .NET edition of the connector uses the .NET Framework version of regular expression matching. The Java edition uses Java regular expression constructs.

Control Attributes

None

Examples

Display an icon based on the condition. The api:case elements match "CompanyA" and "CompanyB" in the company_name attribute and if any occurrences are found take the action associated with that case.

<api:select value="[company_name]">
  <api:case value="CompanyA">
    <img src="http://www.companya.com/favicon.ico" />
  </api:case>
  <api:case value="CompanyB">
    <img src="http://www.companyb.com/favicon.ico" />
  </api:case>
  <api:default>
    <img src="http://www.myhosting.com/generic.ico"/>
  </api:default>
</api:select>

See Also

CData Python Connector for XML

api:catch

The api:catch keyword is used to create an exception-handling block in a script. In addition to api:try, you can contain an api:catch block within any of the following keywords, the scope of which serves as an implicit api:try section:

Parameters

  • code: The code parameter allows you to selectively catch exceptions. To catch all exceptions, use the character *.

Control Attributes

  • _code: The code of the caught exception.
  • _desc: A short description of the caught exception.
  • _details: More information about the exception, if available.

Examples

Throw and catch an exception. Inside an api:call, an APIException is thrown and caught. Inside the scope of the keyword, the api:ecode and api:emessage attributes are added to the current item and pushed out.

<api:call op="...">
  <api:throw code="myerror" description="thedescription" details="Other Details."/>
  <api:catch code="myerror">
    <api:set attr="api:ecode" value="[_code]"/>
    <api:set attr="api:emessage" value="[_description]: [_details]"/>
    <api:push/>
  </api:catch>
</api:call>
Catch all exceptions:
<api:catch code="*">
  An exception occurred. Code: [_code], Message: [_desc]
</api:catch>

See Also

CData Python Connector for XML

api:check

The api:check keyword can be used with or without a value parameter. Without a value parameter, it is used to ensure that an attribute is present in an item and that it is not a null string before the body of the api:check is executed.

If a value parameter is specified, the api:check body executes only if the expression evaluates to true. Other values are considered false. The evaluation is case insensitive.

Like other simple conditionals in API Script, it can be paired with an api:else keyword. Note that, unlike api:equals, api:check does not throw an exception if the attribute does not exist in the item.

Parameters

  • item: The item in which to check the attribute. Specifying an item is not required. If no item is specified, the default output item is used instead.
  • attr: The name of the attribute to check. This parameter is required.
  • value: An expression that evaluates to true or false. For example, the result of a formatter that returns true or false.
  • action: The action to execute if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Examples

Check whether an attribute was set before using it:
<api:check attr="_input.In_Stock">
...
</api:check>

See Also

CData Python Connector for XML

api:continue

The api:continue keyword can be used to move to the next iterations of api:call or api:enum.

Parameters

None

Control Attributes

None

Examples

Produce a feed that lists only the files in a directory. The api:continue keyword is used to skip over items representing a directory.

<api:call op="fileListDir">
  <api:equals attr="file:isdir" value="true">
    <api:continue/>
  </api:equals>
  <api:push/>
</api:call>

List the values of single-valued attributes. All multivalued attributes are skipped by using api:continue.

<api:set attr="foo.multiattr#" value="value1"/>
<api:set attr="foo.multiattr#" value="value2"/>
<api:set attr="foo.attr2"      value="value3"/>
<api:enum item="foo">
  <api:notequals attr="_count" value="1">
    <api:continue/>
  </api:notequals>
  [_index]: [_attr] has the value [_value] <!-- only evaluated for attr2 -->
</api:enum>

See Also

CData Python Connector for XML

api:default

The api:default keyword is used with the api:select keyword. The api:default keyword consists of a block of API Script that is executed if the value in api:select does not match any of the values in api:case.

Parameters

None

Control Attributes

None

Examples

Display an icon based on the condition. The api:case elements match "CompanyA" and "CompanyB" in the company_name attribute, and, if any occurrences are found, take the action associated with that case.
<api:select value="[company_name]">
  <api:case value="CompanyA">
    <img src="http://www.companya.com/favicon.ico" />
  </api:case>
  <api:case value="CompanyB">
    <img src="http://www.companyb.com/favicon.ico" />
  </api:case>
  <api:default>
    <img src="http://www.myhosting.com/generic.ico"/>
  </api:default>
</api:select>

<p>

See Also

CData Python Connector for XML

api:else

The api:else keyword is used to execute an alternate block of code when a test like api:exists or api:match fails. It can also be used to execute an alternate block of code within an api:call when the call fails to produce any output items.

Unlike other languages API Script requires the api:else statement to be within the scope of the test it belongs to.

Parameters

None

Control Attributes

None

Examples

Return a placeholder title if the file does not have a name:
<api:call op="fileListDir" out="out">
  <api:null attr="filename">
    <api:set attr="title" value="Unnamed File"/>
    <api:else>
      <api:set attr="title" value="[filename]"/>
    </api:else>
  </api:null>
  <api:push title="[title]">
  [out.*]
  </api:push>
</api:call> 

See Also

CData Python Connector for XML

api:enum

The api:enum keyword can be used to enumerate over the attributes within an item, a delimited list, a supplied range of values, and the values of a multivalued attribute. The body of api:enum is executed for each element of the set that is being iterated upon.

Parameters

  • item: The name of the item whose attributes you want to iterate over.
  • attr: The expression to match that specifies which attributes are iterated over. For example, "api:*". You can also provide this parameter to iterate over the values of a multivalued attribute.
  • prefix: The prefix based on which the item is enumerated.
  • expand: The boolean value that specifies how api:enum behaves when multivalued attributes are encountered. If expand is set to true, the body of api:enum will be executed once for each value of the attribute. If false, all values will be concatenated in a single string value, and only a single iteration will be performed. By default, api:enum will not expand all values.
  • sep[arator]: The separator to be used to concatenate values of a multivalued attribute if the expand parameter is false. Additionally, separator is used to tokenize the values in a list if listseparator is not defined. The default value is the new-line character "\n".
  • list: The list of separated values to enumerate over. For example, if the list of values is "violet, indigo, blue, green, yellow, orange, red" and the separator is a ',' the scope of api:enum is executed for each color in the rainbow.
  • range: The range of numbers or characters to enumerate over in ascending or descending order; for example, "a..z", "Z..A".
  • recurse: Whether to enumerate over nested attributes. The default is true.
Note: You can specify either the range attribute or the item attribute, but not both. Additionally, attributes are enumerated in alphabetical order.

Control Attributes

  • _attr: The name of the attribute being iterated over. When you are iterating over the values of a multivalued attribute, the attribute name will be the same except that it will also have the index as part of the name. The index is separated from the name by the hash symbol (#). For example, name#1, name#2, etc.
  • _index: The index at which the attribute appears within an item or the position of the list element currently being enumerated over.
  • _value: The value of the attribute being iterated over. For a multivalued attribute, the expand and separator parameter settings determine whether _value is a reference to one attribute value or a reference to all attribute values.
  • _count: The number of values in an attribute or in a list.
  • _separator: The separator used to separate the values in a list.

Examples

Display the attribute names and attribute values of the item named "input":

<api:set item="input" attr="Greeting" value="Hello" />
<api:set item="input" attr="Goodbye" value="See ya" />
<api:enum item="input">
  [_attr] is [_value]
  <br/>
</api:enum> 

goodbye is See ya greeting is Hello
To enumerate over a list of values use the list and separator parameters of api:enum. For example, the code below lists the colors specified in the colors attribute:
<api:set attr="colors" value="violet, indigo, blue, green, yellow, orange, red"/>
<api:enum list="[colors]" separator=",">
  [_value] 
</api:enum>
To enumerate over a range of values, use the range attribute. For example, the code below lists the character set from a to z, from Z to A, and the numbers from 1 to 25:
<api:enum range="a..z">
  [_value] 
</api:enum>
<api:enum range="Z..A">
  [_value] 
</api:enum>
<api:enum range="1..25">
  [_value] 
</api:enum>
To enumerate over all the values of a multivalued attribute, use the attr argument to specify a multivalued attribute and set expand to true:
<api:set attr="foo.email#1" value="joe@mycompany.com"/>
<api:set attr="foo.email#2" value="john@mycompany.com"/>
<api:enum attr="foo.email" expand="true">
    ([_index]) [_attr] -> [_value]
</api:enum>
The example above results in the following output:
(1) email#1 -> joe@mycompany.com (2) email#2 -> john@mycompany.com

See Also

CData Python Connector for XML

api:equals

The api:equals keyword compares the value of an attribute to a reference value. Unlike api:check, the api:equals keyword will throw an exception if the specified item does not contain the specified attribute. If the specified attribute exists and its value matches, then the comparison will succeed.

Note: Both api:equals and api:check expect the name of the attribute whose value will be compared with a given value. If you need to compare two values, you can use api:select instead. For example:

<api:select value="[company_name]">
  <api:case value="CompanyA">
    <img src="http://www.companya.com/favicon.ico" />
  </api:case>
  <api:case value="CompanyB">
    <img src="http://www.companyb.com/favicon.ico" />
  </api:case>
  <api:default>
    <img src="http://www.myhosting.com/generic.ico"/>
  </api:default>
</api:select>

Parameters

  • item: The item in which to compare the attribute. Specifying an item is not required. If no item is specified, the default output item is used instead.
  • attr: The name of the attribute to compare.
  • case: Whether to use case-sensitive or case-insensitive comparison. This defaults to case-sensitive comparison; to use case-insensitive comparison, set the case parameter to "ignore".
  • value: The value to compare the attribute with.
  • action: The action to perform if equality is met. Allowed values: break, continue.

Control Attributes

None

Example

Like other conditional keywords, the body of api:equals may also contain an api:else keyword, which will be executed if the values do not match. The following lists all files except .err files:

<api:call op="fileListDir">
  <api:equals attr="file:extension" value=".err">
  <api:else>
    <api:push/>
  </api:else>
  </api:equals>
</api:call>

See Also

  • api:select: Choose between more than one alternative.
  • api:notequals: Create a block that is executed when equality is not met.

CData Python Connector for XML

api:exists

The api:exists keyword checks that an attribute has a value in the specified item. The api:notnull keyword is a synonym for api:exists.

Parameters

  • item: The item to check. If not specified, the default output item is used.
  • attr: The name of the attribute to check.
  • action: The action to perform if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Example

Define missing title attributes for a feed of files:
<api:call op="fileListDir" output="out">
  <api:exists attr="filename">
    <api:set attr="title" value="[filename]"/>
    <api:else>
      <api:set attr="title" value="Unnamed File"/>
    </api:else>
  </api:exists>
  <api:push title="[title]">
  [out.file:*] 
  </api:push>
</api:call> 

See Also

  • api:else: Create a block which is executed if the condition is not satisfied.

CData Python Connector for XML

api:first

The api:first keyword is used to execute a section of a script for only the first iteration of an api:call or api:enum keyword. It is a convenient way to generate headings or to inspect the first item of a feed before going through the rest of the feed.

During the first iteration, the api:first body executes before any other code within the api:call or api:enum, regardless of where the api:first is located within the api:call or api:enum body. As a reminder of this, it is recommended to locate the api:first at the top of the api:call or api:enum body.

If the scope has no items, then neither api:first nor api:last are executed.

Parameters

None

Control Attributes

None

Examples

Create an HTML table from a feed where each item is represented as a row:

<api:call op="listCustomers">
  <api:first>
    <table>
    <thead>
      <api:enum item="customer">
        <td>[_attr]</td>
      </api:enum>
    </thead>
  </api:first>
    <tr>
      <api:enum item="customer">
        <td>[_value]</td>
      </api:enum>
    </tr>
  <api:last>
    </table>
  </api:last>
</api:call>

See Also

  • api:last: Execute a code block only for the last iteration.

CData Python Connector for XML

api:finally

The api:finally keyword is used to execute a section of a script after control leaves an api:call, api:try, or api:script statement. It is a convenient way to clean up the formatting of generated documents.

Parameters

None

Control Attributes

None

Examples

The api:finally block is executed when an unhandled exception occurs. This can be used to ensure that tags are closed:

<table>
<api:call op="listCustomers" out="customer">
  <api:first>
    <thead>
        <api:enum item="customer">
          <td>[_attr]</td>
        </api:enum>
    </thead>
  </api:first>
  <tr>
      <api:enum item="customer">
        <td>[_value]</td>
      </api:enum>
  </tr>
  <api:finally>
  </table> <!-- ensure tags are still closed -->
  </api:finally>
</api:call>

See Also

  • api:try: Define a scope to catch exceptions.
  • api:call: Loop over items returned by an operation.
  • api:script: Create a script block.

CData Python Connector for XML

api:if

You can use the api:if keyword to evaluate expressions that can contain items, attributes, and values. The scope of the keyword is executed if the specified expression evaluates to true.

Parameters

  • exp: The expression to evaluate. You can make string, date, and numeric comparisons.
  • attr: The name of the attribute to compare the value of. The value of an attribute can be checked for a matching value or for the values null or notnull.
  • value: The value to compare with the value of the attribute specified by attr.
  • item: The item that contains the attribute being compared.
  • operator: The name of the operator to compare the operands specified by attr and value. Allowed values: null, notnull, hasvalue, equals, equalsignorecase, notequals, lessthan, and greaterthan. Default: notnull.
  • action: The action to perform if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Examples

Evaluate a simple comparison of two values:

<api:if exp="[attr] == 10">
Evaluate the equality of a given value and the value of a given attribute:
<api:set attr="attr1" value="value1"/>
<api:set attr="attr2" value="value2"/>
<api:if attr="attr1" value="[attr2]" operator="notequals"> <!-- Evaluates to true -->
<api:else>
False
</api:else>
True
</api:if>
Evaluate whether an attribute exists:
<api:set attr="exists" value="true"/>
<api:if attr="exists"> <!-- Evaluates to true -->
[exists]
</api:if>

See Also

  • api:exists: Check that an attribute has a value in the specified item.
  • api:equals: Create a block that is executed when equality is met.

CData Python Connector for XML

api:include

The api:include keyword is used to include API Script from other files. Like traditional includes in other programming languages, api:include is replaced by the contents of the file specified in the file parameter.

Parameters

  • file | document: The name of the file to be included.

Control Attributes

None

Examples

Import certain attributes (companyname, copyright) in each script without duplication:

<api:include file="globals.rsb"/> 
[companyname] 
[copyright] 
<api:call ...>

CData Python Connector for XML

api:info

The api:info keyword is used to describe the metadata for scripts. This information is used by the connector to implement basic error checking on user input and to set default values. The api:info keyword can contain the following:

  • Column definitions
  • Input parameters the script expects
  • Output the script produces

Table Parameters

The following parameters can be defined for the table itself:

  • desc[ription]: The description for the table. If a description is not provided, the name of the script is used.
  • title: The title of the script. If a title is not provided, the name of the script is used.
  • methods: The HTTP methods that can be executed against this script. SELECT, INSERT, UPDATE, and DELETE correspond to HTTP GET, POST, PUT/PATCH/MERGE, and DELETE, respectively.
  • url: The URL of the script author.
  • keywords: The keywords that describe the script.

Input, Output, and Column Parameters

The api:info keyword has additional parameters contained within its scope that define columns as well as script inputs and outputs. Note these parameters are not API Script keywords, but additional information for api:info.

attr

The attr parameter describes a table column and includes at least two attributes: name and data type. The name must be an alphanumeric string.

Other optional attributes provide more information about the column and enable the connector to represent these columns correctly in various tools.

<attr 
  name="Name"
  xs:type="string"
  other:xPath="name/full"
  readonly="true"    
  columnsize="100"
  desc="The name of the person." 
/> 

  • name: The alphanumeric string that defines the name of the column.
  • xs:type: The data type of the column. The string, int, double, datetime, and boolean types are supported.
  • other: Attributes prefixed with 'other:' that provide extra information. These other properties can be operation specific. For example, other:xPath specifies the XPath to a node in a local or remote resource. The XPath can be relative to a RepeatElement.
  • desc[ription]: A short description of the column.
  • key: Whether the column is part of the primary key in the table.
  • readonly: Whether the column can be updated. Allowed values are true and false.
  • req[uired]: Whether the column must be specified in an insert. Allowed values are true and false.
  • def[ault]: The default value for the column if none is specified.
  • values: A comma-separated list of the valid values for the column. If specified, the engine will throw an error if the specified column value does not match one of the allowed values.
  • reference[s]: The foreign key to the primary key of another table. The foreign key is specified with the following syntax: table.key. For example: "Employees.EmployeeId".
  • columnsize: The maximum character length of a string or the precision of a numeric column. The precision of a numeric column is the number of digits.
  • scale | decimaldigits: The scale of a decimal column. The scale is the number of digits to the right of the decimal point.
  • isnullable: Indicates whether the column accepts null values. Note that this does not prevent sending or receiving a null value.

input

Input parameters are used to describe inputs to the script.

Input elements can be used in schemas for both tables and stored procedures.

The attributes of this parameter provide users with more information about the input and allow the engine to perform rudimentary checks.

In stored procedure schemas, one or more input elements are used to describe the inputs of the stored procedure. In table schemas an input element defines a pseudo column, a column that can only be used in the WHERE clause.

For XML data sources, pseudo columns cannot contain an XPath.

<input
  name="name"
  desc="Example of an input parameter"
  default="defValue"
  req="true"
  values="value1, value2, value3"
  xs:type="string" 
/>
  • name: The name of the input. An alphanumeric string that may additionally contain the following: "#" denotes that the input can have multiple values, "myprefix:*" denotes a set of inputs with the same prefix, and a value of "*" denotes arbitrary input parameters.
  • desc[ription]: A short description of the input.
  • xs:type: The data type of the input. The string, int, double, datetime, and boolean types are supported.
  • def[ault]: The default value to be used when no input value is supplied in the script call.
  • key: Whether the input is a primary key.
  • req[uired]: Whether the input is required. The engine will throw an error if the required input is not supplied and there is no default value defined. Allowed values are true and false.
  • values: A comma-separated list of the allowed values for the input. If specified, the engine will throw an error if the specified input does not match one of the allowed values.
  • alias: The alias of the input.
  • other: Attributes prefixed with "other:" that provide extra information. These other properties can be operation specific.

output

Output parameters describe the output of the operation. However, they are ignored by the connector. Thus, the output of the operation can be entirely independent of what is defined in the info block.

<output  name="Id" 
         desc="The unique identifier of the record."
         xs:type="string"
         other:xPath="content/properties/Id" 
/>
  • name: The name of the output. "myprefix:*" denotes a set of outputs with the same prefix, and a value of "*" denotes arbitrary output parameters.
  • xs:type: The data type of the output. The string, int, double, datetime, and boolean types are supported.
  • desc[ription]: A short description of the output.
  • columnsize: The maximum character length of a string or the precision of a numeric output. The precision is the number of digits.
  • other: Attributes prefixed with 'other:' that provide extra information about the output. For example, other:xPath specifies the XPath to a node in a local or remote resource. The XPath can be relative to a RepeatElement.

Examples

Describes the metadata for a typical table with columns of different data types:
<api:info title="NorthwindOData" desc="Parse an XML document (NorthwindOdata.xml) into rows.">
  <attr name="ID"           xs:type="int" key="true" other:xPath="content/properties/ID" />
  <attr name="EmployeeID"   xs:type="int"            other:xPath="content/properties/EmployeeID" />
  <attr name="Name"         xs:type="string"         other:xPath="content/properties/Name" />
  <attr name="TotalExpense" xs:type="double"         other:xPath="content/properties/TotalExpense" />
  <attr name="HireDate"     xs:type="datetime"       other:xPath="content/properties/HireDate" />
  <attr name="Salary"       xs:type="int"            other:xPath="content/properties/Salary" />
</api:info> 

The following describes the metadata for a stored procedure that searches the Web using the Bing Search API:

<api:info title="SearchWeb"    desc="Use Bing to search the Web."> 
  <output name="Id"          xs:type="string"    other:xPath="content/properties/ID"          />
  <output name="URL"         xs:type="string"    other:xPath="content/properties/Url"         />
  <output name="Title"       xs:type="string"    other:xPath="content/properties/Title"       />
  <output name="Description" xs:type="string"    other:xPath="content/properties/Description" />
  <output name="DisplayURL"  xs:type="datetime"  other:xPath="content/properties/DisplayUrl"  />

  <input name="SearchTerms"    />
</api:info>

See Also

CData Python Connector for XML

api:last

API Script keywords within the scope of the api:last keyword will only be executed after the last item is encountered and only if there were items returned by api:call or api:enum.

An api:last statement is executed only after the last item is processed; it maintains access to the last item in the feed. If the scope has no items, then neither api:first nor api:last are executed.

Parameters

None

Control Attributes

None

Examples

Create an HTML table from a feed where each item is represented as a row:

<api:call op="listCustomers">
  <api:first>
    <table>
    <thead>
      <api:enum item="customer">
        <td>[_attr]</td>
      </api:enum>
    </thead>
  </api:first>
  <tr>
    <api:enum item="customer">
      <td>[_value]</td>
    </api:enum>
  </tr>
  <api:last>
    </table>
  </api:last>
</api:call>

See Also

  • api:first: Execute a code block only for the first iteration.

CData Python Connector for XML

api:map

The api:map keyword is used to map attributes in one item to attributes in another item. Attributes are read from one item and written to another with the new names specified in the map string. The api:map keyword does not clear the destination item: It simply adds new attributes to it. Or, if an attribute exists in the destination item, it is overwritten, and other attributes remain as they were.

Parameters

  • to: The name of the item into which attributes are to be written.
  • from: The name of the item from which attributes are to be read.
  • map: A list of attribute names that specify the attribute names in the destination item, followed by the attribute names in the source item. For example, you can map attributes with one prefix to attributes with another prefix by using the syntax below:
    customer:* = soap:*
    Any characters that are not valid attribute names are ignored and are used to demarcate the end of a name.

Control Attributes

  • This keyword does not have any control attributes.

Examples

Map three attributes: The map is a succession of the "to" attribute name followed by the "from" attribute name.

<api:set item="item1" attr="var1" value="x"/>
<api:set item="item1" attr="var2" value="y"/>
<api:set item="item2" attr="attr1" value="z"/>
<api:map to="item2" from="item1" map="attr1=var1, attr2=var2"/>
In this example, the var1 and var2 attributes of item1 are mapped respectively to the attr1 and attr2 attributes of item2. The attr1 attribute, which is set in item2 with the value z, is overwritten with x, the value of var1 from item1. The attr2 attribute, which does not exist in item2, is created and set with y, the value of var2 in item1.

You can map multiple attributes from items with one prefix to items with a different prefix. This is useful in changing the prefix from connector prefixes (for example, soap:*) to business domain prefixes (for example, customer:*). The following example creates a mapping from all soap:* attributes in the item soapout to attributes prefixed with customer:* in the item customer:

<api:map from="soapout" to="customer" map="customer:* = soap:*"/>
Copy all attributes from one item to another item:
<api:map from="copyfrom" to="copyto" map="* = *"/>

See Also

  • api:set: Set the attributes of an item.

CData Python Connector for XML

api:match

The api:match keyword is similar to the api:equals keyword; however, it permits complex matching rules.

Parameters

  • pattern: The pattern to match.
  • type: The type of matches to find. The default value is "exact", which requires an exact match of the value. In this case api:match is identical to api:equals. Other supported types are "regex", for regular expression matching, and "glob", which supports a simple expression model similar to the one used in file-name patterns, for example, *.txt.

    The .NET edition of the connector uses the .NET Framework version of regular expression matching. The Java edition uses Java regular expression constructs.

  • value: The value to match.

Control Attributes

None

Examples

Check for floating point numbers using a regex pattern. If the pattern is matched then the item will be pushed out.

<api:match pattern="\[-+\]?\[0-9\]*\.?\[0-9\]*" type="regex" value="-3.14">
  <api:push/>
</api:match>

See Also

CData Python Connector for XML

api:notequals

The api:notequals keyword verifies that the attribute does not match the specified value. It has a similar behavior to the api:equals keyword.

Parameters

  • item: The item in which to compare the attribute. Specifying an item is not required; if no item is specified, the default output item is used instead.
  • attr: The name of the attribute to compare.
  • value: The reference value to compare the attribute with.
  • action: The action to perform if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Example

List all files except .err files:
<api:call op="fileListDir">
  <api:notequals attr="file:extension" value=".err">
    <api:push/>
  </api:notequals>
</api:call>

See Also

  • api:equals: Check for equality.
  • api:else: Create a block which is executed if the condition is not satisfied.

CData Python Connector for XML

api:null

The api:null keyword checks that an attribute does not exist in the specified item.

Parameters

  • item: The item to check. If not specified, the default output item is used.
  • attr: The name of the attribute to check.
  • action: The action to perform if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Example

Define missing title attributes.
<api:call op="fileListDir" output="out">
  <api:null attr="filename">
    <api:set attr="title" value="Unnamed File"/>
    <api:else>
      <api:set attr="title" value="[filename]"/>
    </api:else>
  </api:null>
  <api:push title="[title]">
  [out.file:*] 
  </api:push>
</api:call>

See Also

  • api:else: Create a block which is executed if the condition is not satisfied.

CData Python Connector for XML

api:notnull

The api:notnull keyword checks that an attribute has a value in the specified item. The api:exists keyword is a synonym for api:notnull.

Parameters

  • item: The item to check. If not specified, the default output item is used.
  • attr: The name of the attribute to check.
  • action: The action to perform if the expression evaluates to true. Allowed values: break, continue.

Control Attributes

None

Example

Define missing title attributes.
<api:call op="fileListDir" output="out">
  <api:notnull attr="filename">
      <api:set attr="[title]" value="[filename]"/>
    <api:else>
      <api:set attr="[title]" value="Unnamed file"/>
    </api:else>
  </api:notnull> 
  <api:push title="[title]">
  [out.file:*]
  </api:push>
</api:call>

See Also

  • api:else: Create a block which is executed if the condition is not satisfied.

CData Python Connector for XML

api:push

The api:push keyword pushes an item into the output feed of the script. If there are no api:push elements in your script, no output items will result from it.

Parameters

  • item: The item to push into the feed. If not present, the item at the top of the stack will be pushed.
  • title: The title for the feed item.
  • desc[ription]: The description for the feed item. If none is provided, the scope of the api:push keyword will be used as the value of this attribute. The scope of the api:push keyword may contain other keywords, HTML tags, etc. Everything is evaluated as a template and is used to set the description.
  • op: The name of the operation to call and then push the resulting items. For example:
      <api:push op="myOp"/>    
      

    This is a shorthand for the following:

    <api:call op="myOp">
      <api:push/>
    </api:call>

  • enc[oding]: The encoding of the description. By default, the connector pushes the description as escaped XML. You can choose to encode the description as CDATA to include unescaped XML by setting this parameter to "cdata".

Control Attributes

None

Example

Create a description for each item pushed out. The description is the text within the scope of the api:push keyword, shown below:
<api:call op="fileListDir?mask=*.log">
  <api:push>
    The .log file contains details about the transmission, including any error messages.
  </api:push>
</api:call>

CData Python Connector for XML

api:script

The api:script keyword can be used to create script blocks that respond to SQL statements.

Parameters

  • method: The HTTP method (GET, POST, PUT/PATCH/MERGE, or and DELETE) used to invoke the script. Specify multiple methods in a comma-separated list. These methods correspond to SELECT, INSERT, UPDATE, and DELETE queries, respectively.

Control Attributes

None

Examples

Call two operations that manipulate remote XML. This example uses an OData API, the odata.org Northwind reference service. In the example below, the first block will be executed only when the script is accessed using the POST method (an INSERT statement is executed), while the second block will be executed only when the script is accessed using the GET method (a SELECT statement is executed).

<api:script method="POST">
  <api:set attr="sql.rec:name" value="[_input.name]"/>
  <api:set attr="sql.rec:address" value="[_input.address]"/>
  <api:call op="sqliteInsert" in="sql">
    <api:push/>
  </api:call>
</api:script>
<api:script method="GET">
  <api:set attr="sql.query" value="SELECT * FROM [sql.table];"/>
  <api:call op="sqliteQuery" in="sql">
    <api:push/>
  </api:call>
</api:script>

CData Python Connector for XML

api:select

The api:select keyword is similar to a switch-case block in other programming languages and can be used to create complex conditional statements. The body of api:select can contain one or more api:case keywords and one api:default keyword.

The value in api:select is matched with those specified in api:case. The body of the api:case statement contains the keywords and statements to be executed if the value specified matches the value in the api:select keyword.

The body of the api:default statement will be executed only if none of the api:case statements result in a match. The api:default keyword has no parameters and can appear only once in an api:select.

Parameters

  • value: The value to compare with those specified in api:case statements.
  • attr: The attribute whose value is compared with values specified in api:case statements.

Control Attributes

None

Examples

Set the icon depending on the company name. The api:case elements match "CompanyA" and "CompanyB" in the company_name attribute, and, if any occurrences are found, take the action associated with that case.

<api:select value="[company_name]">
  <api:case value="CompanyA">
    <img src="http://www.companya.com/favicon.ico" />
  </api:case>
  <api:case value="CompanyB">
    <img src="http://www.companyb.com/favicon.ico" />
  </api:case>
  <api:default>
    <img src="http://www.myhosting.com/generic.ico"/>
  </api:default>
</api:select>

<p>

See Also

CData Python Connector for XML

api:set

The api:set keyword sets a value in an attribute. If an attribute is set in an item that does not exist, the item is automatically created.

There are two ways to set a value using api:set. You can set the value parameter or, for large values that are multiline and complex, you can set the value using the scope of the keyword itself.

Parameters

  • item: The item parameter is used to specify the item in which the attribute is set. Specifying an item is not required. If an item is not specified, the default item is used.
  • attr: The name of the attribute. You can also specify the item using the dot notation (e.g., item.prefix:attr). Note that a complete attribute name has both a prefix and an attribute name, but the prefix is not required.
  • value: The value to be assigned to the attribute. If this parameter is not provided, the entire body of the api:set keyword is used as the value. This is convenient for setting long or multiline values.
  • copyfrom: The attributes from the item specified in this parameter are copied to the item specified by the item parameter.

Control Attributes

None

Examples

Use the scope of the keyword to set a value to the message attribute of the item named "input":

<api:set item="input" attr="message">
  Dear [name],
  You have won a cruise trip to Hawaii.
  Please confirm your acceptance by [date].
  Thanks, [sales]
</api:set>

See Also

  • api:unset: Remove an attribute from an item.
  • api:setm: Set multiple attributes with only one keyword.

CData Python Connector for XML

api:setc

The api:setc keyword enables you to add static text without escaping the special characters in API Script, such as square brackets. While special characters can be escaped with a backslash, this keyword provides a shortcut. For example, this keyword can be used to easily set an XPath.

Parameters

  • item: The item in which to set the attribute.
  • attr: The name of the attribute.
  • value: The value to be assigned to the attribute. If this parameter is not provided, the entire body of the api:setc keyword is used as the value. This is convenient for setting long or multiline values.
  • copyfrom: The attributes from the item specified in this parameter are copied to the item specified by the item parameter.

Control Attributes

None

Examples

Set an unescaped XPath:

<api:setc attr="xpath" value="/root/book[1]/@name" />

CData Python Connector for XML

api:setm

The api:setm keyword is a shorthand for api:set that can be used to perform multiple sets with just one keyword.

Each line, separated by \r\n, is a separate set operation. Multiline values can be specified with three single quotes ('''), as in Python.

The first equals sign ("=") separates the attribute name from the value. This means that attribute values can contain spaces. However, leading and trailing spaces are ignored. Quotes can be used to include leading or trailing spaces, as shown in the examples.

Parameters

  • item: The item in which the attributes are set. Specifying an item is not required. If an item is not specified, the default item is used.

Control Attributes

None

Examples

Use the scope of the keyword to set contact attributes:

<api:setm>
name = ContactName 
company = ContactCompany
address = 600 Market Street
includespace = " This string has a leading space"
</api:setm>

See Also

  • api:set: Set attributes in an item.

CData Python Connector for XML

api:throw

The api:throw keyword is used to raise an error (exception) from within a script.

Parameters

  • code: A string value used to identify the source or meaning of the exception. This parameter is required.
  • desc[ription]: An optional parameter that specifies a short message describing the error condition.
  • details: An optional parameter that can specify additional data useful to diagnose the error condition.

Control Attributes

None

Example

The example below explicitly defines both the error code and description:

<api:throw code="myerror" desc="thedescription" />

See Also

  • api:try: Define a scope for catching exceptions.
  • api:catch: Catch thrown exceptions and define exception processing.

CData Python Connector for XML

api:try

The api:try and api:catch keywords are used to create an exception-handling block in a script. If any keyword inside the api:try body throws an APIException, the connector will look for a matching api:catch keyword inside the same scope and will execute the catch body.

Parameters

None

Control Attributes

None

Example

Throw and catch an exception. Inside the scope of the keyword, api:ecode and api:emessage attributes are added to the current item and pushed out.

<api:call op="...">
  <api:try>
    <api:throw code="myerror" description="thedescription" details="Other Details."/>
    <api:catch code="myerror">
      <api:set attr="api:ecode" value="[_code]"/>
      <api:set attr="api:emessage" value="[_description]: [_details]"/>
      <api:push/>
    </api:catch>
  </api:try>
</api:call>

See Also

CData Python Connector for XML

api:unset

The api:unset keyword is used to delete attributes from an item or delete the item itself.

Parameters

  • item: The item from which the attribute is to be removed. If you do not specify an item, the default output item is used. This parameter can also be used to remove an item.
  • attr: The attributes to delete from the item. You can use a glob mask to delete more than one parameter, for example, "*.foo".

Control Attributes

None

Examples

Remove an attribute from an item before it is pushed out:

<api:call op="fileListDir">
  <api:unset attr="file:size"/>
  <api:push/>
</api:call>

See Also

  • api:set: Set attributes in an item.

CData Python Connector for XML

api:validate

You can use api:validate to throw an error if a required value is not provided.

Parameters

  • item: The item that contains the attribute to be validated.
  • attr: The attribute to be validated. If the attribute does not exist, an error is thrown.
  • code: The error code to be thrown if validation fails. Default: "api:validate".
  • desc: The error description to be thrown if validation fails. By default a message is thrown that the specified attribute is required.

Examples

Throw a more specific message if the _query item does not contain the Id attribute:

<api:validate attr="_query.Id"   desc="The Id is required to delete."/>

See Also

  • api:throw: Raise an error (exception) from within a script.

CData Python Connector for XML

Connection String Options

The connection string properties are the various options that can be used to establish a connection. This section provides a complete list of the options you can configure in the connection string for this provider. Click the links for further details.

For more information on establishing a connection, see Establishing a Connection.

Authentication


PropertyDescription
AuthSchemeThe type of authentication to use when connecting to remote services.
AccessKeyThe access key used to authenticate to XML. This value is accessible from your security credentials page.
SecretKeyYour account secret key. This value is accessible from your security credentials page.
ApiKeyThe API Key used to identify the user to IBM Cloud.
UserSpecifies the username or account ID used to authenticate the user.
PasswordSpecifies the password used to authenticate the user.
SharePointEditionThe edition of SharePoint being used. Set either SharePointOnline or SharePointOnPremise.
ImpersonateUserModeSpecify the type of the user impersonation. It should be whether the User mode or the Admin mode.

Connection


PropertyDescription
ConnectionTypeSpecifies the file storage service, server, or file access protocol through which your XML files are stored and retreived.
URIThe Uniform Resource Identifier (URI) for the XML resource location.
XPathSpecifies the XPath of an element that repeats at the same height within the XML document, which the provider uses to to split the document into multiple rows.
DataModelSpecifies the data model to use when parsing XML documents and generating the database metadata.
XMLFormatSpecifies the format of the XML document.
RegionThe hosting region for your S3-like Web Services.
OracleNamespaceThe Oracle Cloud Object Storage namespace to use.
StorageBaseURLSpecifies the URL of a cloud storage service provider.
SimpleUploadLimitThis setting specifies the threshold, in bytes, above which the provider will choose to perform a multipart upload rather than uploading everything in one request.
UseVirtualHostingIf true (default), buckets will be referenced in the request using the hosted-style request: http://yourbucket.s3.amazonaws.com/yourobject. If set to false, the bean will use the path-style request: http://s3.amazonaws.com/yourbucket/yourobject. Note that this property will be set to false, in case of an S3 based custom service when the CustomURL is specified.
TestConnectionBehaviorSpecifies the behavior of the test connection operation.
UseLakeFormationWhen this property is set to true, AWSLakeFormation service will be used to retrieve temporary credentials, which enforce access policies against the user based on the configured IAM role. The service can be used when authenticating through OKTA, ADFS, AzureAD, PingFederate, while providing a SAML assertion.

AWS Authentication


PropertyDescription
AWSAccessKeySpecifies your AWS account access key. This value is accessible from your AWS security credentials page.
AWSSecretKeyYour AWS account secret key. This value is accessible from your AWS security credentials page.
AWSRoleARNThe Amazon Resource Name of the role to use when authenticating. Multiple roles can be specified separated by semicolons for role chaining.
AWSPrincipalARNThe ARN of the SAML Identity provider in your AWS account.
AWSRegionThe hosting region for your Amazon Web Services.
AWSCredentialsFileThe path to the AWS Credentials File to be used for authentication.
AWSCredentialsFileProfileThe name of the profile to be used from the supplied AWSCredentialsFile.
AWSSessionTokenYour AWS session token.
AWSExternalIdA unique identifier that might be required when you assume a role in another account.
MFASerialNumberThe serial number of the MFA device if one is being used.
MFATokenThe temporary token available from your MFA device.
CredentialsLocationThe location of the settings file where MFA credentials are saved.
TemporaryTokenDurationThe amount of time (in seconds) a temporary token will last.
AWSWebIdentityTokenThe OAuth 2.0 access token or OpenID Connect ID token that is provided by an identity provider.
ServerSideEncryptionWhen activated, file uploads into Amazon S3 buckets will be server-side encrypted.
AWSContainerCredentialsFullURIThe full URI of the container credential provider endpoint used by EKS Pod Identity.
AWSContainerAuthorizationTokenFileThe path to a file containing the authorization token for the EKS Pod Identity credential provider.
SSEContextA BASE64-encoded UTF-8 string holding JSON which represents a string-string (key-value) map.
SSEEnableS3BucketKeysConfiguration to use an S3 Bucket Key at the object level when encrypting data with AWS KMS. Enabling this will reduce the cost of server-side encryption by lowering calls to AWS KMS.
SSEKeyA symmetric encryption KeyManagementService key, that is used to protect the data when using ServerSideEncryption.

Azure Authentication


PropertyDescription
AzureStorageAccountThe name of your Azure storage account.
AzureAccessKeyThe storage key associated with your Azure account.
AzureSharedAccessSignatureA shared access key signature that may be used for authentication.
AzureTenantIdentifies the XML tenant being used to access data. Accepts either the tenant's domain name (for example, contoso.onmicrosoft.com ) or its directory (tenant) ID.
AzureEnvironmentSpecifies the Azure network environment to which you will connect. Must be the same network to which your Azure account was added.

Keycloak Authentication


PropertyDescription
KeycloakRealmURLSpecifies the full URL to the Keycloak server including the specific realm used for authentication and authorization.

SSO


PropertyDescription
SSOLoginURLThe identity provider's login URL.
SSOPropertiesAdditional properties required to connect to the identity provider, formatted as a semicolon-separated list.
SSOExchangeURLThe URL used for consuming the SAML response and exchanging it for service specific credentials.

JWT OAuth


PropertyDescription
OAuthJWTCertSupplies the name of the client certificate's JWT Certificate store.
OAuthJWTCertTypeIdentifies the type of key store containing the JWT Certificate.
OAuthJWTCertPasswordProvides the password for the OAuth JWT certificate used to access a password-protected certificate store. If the certificate store does not require a password, leave this property blank.
OAuthJWTCertSubjectIdentifies the subject of the OAuth JWT certificate used to locate a matching certificate in the store. Supports partial matches and the wildcard '*' to select the first certificate.
OAuthJWTSubjectThe user subject for which the application is requesting delegated access.
OAuthJWTSubjectTypeThe SubType for the JWT authentication.
OAuthJWTPublicKeyIdThe Id of the public key for JWT.
OAuthJWTAudienceA space-separated list of entities that may use the JWT.
OAuthJWTValidityTimeHow long the JWT should remain valid, in seconds.

Kerberos


PropertyDescription
KerberosKDCIdentifies the Kerberos Key Distribution Center (KDC) service used to authenticate the user. (SPNEGO or Windows authentication only).
KerberosRealmIdentifies the Kerberos Realm used to authenticate the user.
KerberosSPNIdentifies the service principal name (SPN) for the Kerberos Domain Controller.
KerberosUserConfirms the principal name for the Kerberos Domain Controller, which uses the format host/user@realm.
KerberosKeytabFileIdentifies the Keytab file containing your pairs of Kerberos principals and encrypted keys.
KerberosServiceRealmIdentifies the service's Kerberos realm. (Cross-realm authentication only).
KerberosServiceKDCIdentifies the service's Kerberos Key Distribution Center (KDC).
KerberosTicketCacheSpecifies the full file path to an MIT Kerberos credential cache file.

OAuth


PropertyDescription
InitiateOAuthSpecifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.
OAuthVersionIdentifies the version of OAuth being used.
OAuthClientIdSpecifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.
OAuthClientSecretSpecifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).
OAuthAccessTokenSpecifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.
OAuthAccessTokenSecretThe OAuth access token secret for connecting using OAuth.
SubjectIdThe user subject for which the application is requesting delegated access.
SubjectTypeThe Subject Type for the Client Credentials authentication.
OAuthSettingsLocationSpecifies the location of the settings file where OAuth values are saved.
CallbackURLIdentifies the URL users return to after authenticating to XML via OAuth (Custom OAuth applications only).
ScopeSpecifies the scope of the authenticating user's access to the application, to ensure they get appropriate access to data. If a custom OAuth application is needed, this is generally specified at the time the application is created.
OAuthPasswordGrantModeSpecifies how the OAuth Client ID and Client Secret are sent to the authorization server.
OAuthIncludeCallbackURLWhether to include the callback URL in an access token request.
OAuthAuthorizationURLThe authorization URL for the OAuth service.
OAuthAccessTokenURLThe URL from which the OAuth access token is retrieved.
OAuthRefreshTokenURLThe URL to refresh the OAuth token from.
OAuthRequestTokenURLThe URL the service provides to retrieve request tokens from. This is required in OAuth 1.0.
OAuthVerifierSpecifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.
AuthTokenThe authentication token used to request and obtain the OAuth Access Token.
AuthKeyThe authentication secret used to request and obtain the OAuth Access Token.
OAuthParamsA comma-separated list of other parameters to submit in the request for the OAuth access token in the format paramname=value.
OAuthRefreshTokenSpecifies the OAuth refresh token used to request a new access token after the original has expired.
OAuthExpiresInSpecifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.
OAuthTokenTimestampDisplays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.

SSL


PropertyDescription
SSLClientCertSpecifies the TLS/SSL client certificate store for SSL Client Authentication (2-way SSL). This property works in conjunction with other SSL-related properties to establish a secure connection.
SSLClientCertTypeSpecifies the type of key store containing the TLS/SSL client certificate for SSL Client Authentication. Choose from a variety of key store formats depending on your platform and certificate source.
SSLClientCertPasswordSpecifes the password required to access the TLS/SSL client certificate store. Use this property if the selected certificate store type requires a password for access.
SSLClientCertSubjectSpecifes the subject of the TLS/SSL client certificate to locate it in the certificate store. Use a comma-separated list of distinguished name fields, such as CN=www.server.com, C=US. The wildcard * selects the first certificate in the store.
SSLModeThe authentication mechanism to be used when connecting to the FTP or FTPS server.
SSLServerCertSpecifies the certificate to be accepted from the server when connecting using TLS/SSL.

SSH


PropertyDescription
SSHAuthModeThe authentication method used when establishing an SSH Tunnel to the service.
SSHClientCertA certificate to be used for authenticating the SSHUser.
SSHClientCertPasswordThe password of the SSHClientCert key if it has one.
SSHClientCertSubjectThe subject of the SSH client certificate.
SSHClientCertTypeThe type of SSHClientCert private key.
SSHUserThe SSH user.
SSHPasswordThe SSH password.

Firewall


PropertyDescription
FirewallTypeSpecifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.
FirewallServerIdentifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.
FirewallPortSpecifies the TCP port to be used for a proxy-based firewall.
FirewallUserIdentifies the user ID of the account authenticating to a proxy-based firewall.
FirewallPasswordSpecifies the password of the user account authenticating to a proxy-based firewall.

Proxy


PropertyDescription
ProxyAutoDetectSpecifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.
ProxyServerIdentifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.
ProxyPortIdentifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.
ProxyAuthSchemeSpecifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.
ProxyUserProvides the username of a user account registered with the proxy server specified in the ProxyServer connection property.
ProxyPasswordSpecifies the password of the user specified in the ProxyUser connection property.
ProxySSLTypeSpecifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.
ProxyExceptionsSpecifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.

Logging


PropertyDescription
LogfileSpecifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.
VerbositySpecifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.
LogModulesSpecifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.
MaxLogFileSizeSpecifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.
MaxLogFileCountSpecifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.

Schema


PropertyDescription
LocationSpecifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.
BrowsableSchemasOptional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .
TablesOptional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .
ViewsOptional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .
PushAttributesSpecifies whether to push any identified attributes as columns.
FlattenArraysSpecifies how many elements of nested XML arrays are flattened into individual columns.
FlattenObjectsSpecifies whether object properties are flattened into individual columns.
QualifyColumnsSpecifies how column names are qualified to ensure uniqueness in the generated schema.

Caching


PropertyDescription
AutoCacheSpecifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.
CacheProviderThe namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.
CacheDriverThe driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.
CacheConnectionSpecifies the connection string for the specified cache database.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceNotes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.
OfflineGets the data from the specified cache database instead of live XML data.
CacheMetadataDetermines whether the provider caches table metadata to a file-based cache database.

Miscellaneous


PropertyDescription
AWSCertificateThe absolute path to the certificate file or the certificate content in PEM format encoded in base64.
AWSCertificatePasswordThe password for the certificate if applicable, otherwise leave blank.
AWSCertificateTypeThe type of AWSCertificate .
AWSPrivateKeyThe absolute path to the private key file or the private key content in PEM format encoded in base64.
AWSPrivateKeyPasswordThe password for the private key if it is encrypted, otherwise leave blank.
AWSPrivateKeyTypeThe type of AWSPrivateKey .
AWSProfileARNProfile to pull policies from.
AWSSessionDurationDuration, in seconds, for the resulting session.
AWSTrustAnchorARNTrust anchor to use for authentication.
BackwardsCompatibilityModeSpecifies whether the provider operates in XML compatibility mode using the behavior and feature set from the 2017 release.
CharsetSpecifies the session character set for encoding and decoding character data transferred to and from the XML file. The default value is UTF-8.
ClientCultureThis property can be used to specify the format of data (e.g., currency values) that is accepted by the client application. This property can be used when the client application does not support the machine's culture settings. For example, Microsoft Access requires 'en-US'.
CultureThis setting can be used to specify culture settings that determine how the provider interprets certain data types that are passed into the provider. For example, setting Culture='de-DE' will output German formats even on an American machine.
CustomHeadersSpecifies additional HTTP headers to append to the request headers created from other properties, such as ContentType and From. Use this property to customize requests for specialized or nonstandard APIs.
CustomURLParamsA string of custom URL parameters to be included with the HTTP request, in the form field1=value1&field2=value2&field3=value3.
ExcludeFilesComma-separated list of file extensions to exclude from the set of the files modeled as tables.
ExcludeStorageClassesA comma seperated list of storage classes to ignore.
FlattenRowLimitSpecifies the maximum number of rows that can be generated from a single flattened element.
FolderIdThe ID of a folder in Google Drive. If set, the resource location specified by the URI is relative to the Folder ID for all operations.
GenerateSchemaFilesIndicates the user preference as to when schemas should be generated and saved.
IncludeDropboxTeamResourcesIndicates if you want to include Dropbox team files and folders.
IncludeFilesComma-separated list of file extensions to include into the set of the files modeled as tables.
IncludeItemsFromAllDrivesWhether Google Drive shared drive items should be included in results. If not present or set to false, then shared drive items are not returned.
MaxRowsSpecifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.
MetadataDiscoveryURIIdentifies a file to read when aggregating multiple files into a single table, to specify the schema of the aggregated table.
OtherSpecifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.
PagesizeSpecifies the maximum number of records per page the provider returns when requesting data from XML.
PathSeparatorDetermines the character used to replace file path separators when generating table names.
PseudoColumnsSpecifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.
ReadonlyToggles read-only access to XML from the provider.
RowScanDepthSpecifies the number of rows the provider scans when dynamically determining table columns.
RTKSpecifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.
TimeoutSpecifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.
TypeDetectionSchemeSpecifies how the provider determines the data types of columns in the generated schema.
URISeparatorSpecifies the delimiter used to separate multiple values in the URI property.
UserDefinedViewsSpecifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.
CData Python Connector for XML

Authentication

This section provides a complete list of the Authentication properties you can configure in the connection string for this provider.


PropertyDescription
AuthSchemeThe type of authentication to use when connecting to remote services.
AccessKeyThe access key used to authenticate to XML. This value is accessible from your security credentials page.
SecretKeyYour account secret key. This value is accessible from your security credentials page.
ApiKeyThe API Key used to identify the user to IBM Cloud.
UserSpecifies the username or account ID used to authenticate the user.
PasswordSpecifies the password used to authenticate the user.
SharePointEditionThe edition of SharePoint being used. Set either SharePointOnline or SharePointOnPremise.
ImpersonateUserModeSpecify the type of the user impersonation. It should be whether the User mode or the Admin mode.
CData Python Connector for XML

AuthScheme

The type of authentication to use when connecting to remote services.

Possible Values

AwsRootKeys, AwsEC2Roles, AwsIAMRoles, ADFS, Okta, PingFederate, AwsTempCredentials, AwsCredentialsFile, AzureAD, Keycloak, EKSPodIdentity, AzureMSI, AzureServicePrincipal, AzureServicePrincipalCert, AccessKey, AzureStorageSAS, IAMSecretKey, OAuth, Basic, OneLogin, NTLM, SFTP, None, Negotiate, OAuthClient, OAuthJWT, OAuthPKCE, GCPInstanceAccount, Digest, OAuthPassword, NONE

Data Type

string

Default Value

"NONE"

Remarks

Amazon S3

The following options are available when ConnectionType is set to Amazon S3:

  • AwsRootKeys: Set this to use the root user access key and secret. Useful for quickly testing, but production use cases are encouraged to use something with narrowed permissions.
  • AwsEC2Roles: Set this to automatically use IAM Roles assigned to the EC2 machine the CData Python Connector for XML is currently running on.
  • AwsIAMRoles: Set to use IAM Roles for the connection.
  • ADFS: Set to use a single sign on connection with ADFS as the identify provider.
  • OKTA: Set to use a single sign on connection with OKTA as the identify provider.
  • PingFederate: Set to use a single sign on connection with PingFederate as the identify provider.
  • AwsTempCredentials: Set this to leverage temporary security credentials alongside a session token to connect.
  • AwsCredentialsFile: Set to use a credential file for authentication.
  • AzureAD: Set to use a single sign on connection with AzureAD as the identify provider.
  • Keycloak: Set to use a single sign on connection with Keycloak as the identify provider.
  • EKSPodIdentity: Set to use EKS Pod Identity for authentication. Automatically retrieves temporary credentials from the EKS Pod Identity Agent running on the node.

Azure Services

The following options are available when ConnectionType is set to Azure Blob Storage, Azure Data Lake Storage Gen1, Azure Data Lake Storage Gen2, Azure Data Lake Storage Gen2 SSL, or OneDrive:

  • AzureAD: Set this to perform Azure Active Directory OAuth authentication.
  • AzureMSI: Set this to automatically obtain Managed Service Identity credentials when running on an Azure VM.
  • AzureServicePrincipal: Set this to authenticate as an Azure Service Principal.
  • AzureServicePrincipalCert: Set this to authenticate as an Azure Service Principal using a Certificate.
  • AccessKey: Set this to authenticate with the storage key associated with your XML account.
  • AzureStorageSAS: Set this to authenticate with Shared Access Signature (SAS).

OneLake

The following options are available when ConnectionType is set to OneLake:

  • AzureAD: Set this to perform Azure Active Directory OAuth authentication.
  • AzureMSI: Set this to automatically obtain Managed Service Identity credentials when running on an Azure VM.
  • AzureServicePrincipal: Set this to authenticate as an Azure Service Principal.
  • AzureServicePrincipalCert: Set this to authenticate as an Azure Service Principal using a Certificate.

Azure Files

Only the following option is available when ConnectionType is set to Azure Files:

  • AccessKey: Set this to authenticate with the storage key associated with your XML account.
  • AzureStorageSAS: Set this to authenticate with Shared Access Signature (SAS).

Box

The following options are available when ConnectionType is set to Box:

Dropbox

Only the following option is available when ConnectionType is set to Dropbox:

OAuth: Uses OAuth2 with the authorization code grant type. OAuthVersion must be set to 2.0.

FTP(S)

Only the following option is available when ConnectionType is set to FTP or FTPS:

Basic: Basic user credentials (user/password).

Various Google Services

The following options are available when ConnectionType points Google Cloud Storage or Google Drive:

  • OAuth: Uses OAuth2 using a standard user account. OAuthVersion must be set to 2.0.
  • OAuthPKCE: Uses OAuth2 with the authorization code grant type and PKCE extension. OAuthVersion must be set to 2.0.
  • OAuthJWT: Uses OAuth2 with the JWT bearer grant type. OAuthJWTCertType and OAuthJWTCert determine what certificate the JWT is signed with. OAuthVersion must be set to 2.0.
  • GCPInstanceAccount: When running on a GCP virtual machine, the provider can authenticate using a service account tied to the virtual machine.

HDFS

The following options are available when ConnectionType is set to HDFS or HDFS Secure:

  • None: No authentication is used.
  • Negotiate: Kerberos authentication.

HTTP

The following options are available when ConnectionType is set to HTTP or HTTPS:

  • None: No authentication is used.
  • Basic: Basic user/password authentication.
  • Digest: Uses HTTP Digest authentication with User and Password.
  • OAuth: Uses either OAuth1 or OAuth2. OAuthVersion must be set to determine what version of OAuth is used.
  • OAuthJWT: Uses OAuth2 with the JWT bearer grant type. OAuthJWTCertType and OAuthJWTCert determine what certificate the JWT is signed with. OAuthVersion must be set to 2.0.
  • OAuthPassword: Uses OAuth2 with the password grant type. User and Password are the credentials. OAuthVersion must be set to 2.0.
  • OAuthClient: Uses OAuth2 with the client credentials grant type. OAuthClientId and OAuthClientSecret are the credentials. OAuthVersion must be set to 2.0.
  • OAuthPKCE: Uses OAuth2 with the authorization code grant type and PKCE extension. OAuthClientId is the credential. OAuthVersion must be set to 2.0.

IBM Cloud Object Storage

The following options are also available when ConnectionType is set to IBM Object Storage Source:

  • OAuth: Uses OAuth with the specific flow being determined by the InitiateOAuth. ApiKey must be set to successfully complete this flow.
  • IAMSecretKey: Uses AccessKey and SecretKey to authenticate to IBM Cloud Object Storage.

Oracle Cloud Storage

Only the following option is available when ConnectionType is set to Oracle Cloud Storage:

IAMSecretKey: Uses AccessKey and SecretKey to authenticate to the Oracle Cloud Storage.

SFTP

When ConnectionType is set to SFTP, the connector sets AuthScheme to SFTP. When AuthScheme is set to SFTP, the precise authentication method is controlled using the SSHAuthMode property. See this property's documentation for further information.

SharePoint GRAPH

The following options are also available when ConnectionType is set to SharePoint GRAPH:

  • AzureAD: Set this to perform Azure Active Directory OAuth authentication.
  • AzureMSI: Set this to automatically obtain Managed Service Identity credentials when running on an Azure VM.
  • AzureServicePrincipal: Set this to authenticate as an Azure Service Principal.
  • AzureServicePrincipalCert: Set this to authenticate as an Azure Service Principal using a Certificate.

SharePoint SOAP

The following options are also available when ConnectionType is set to SharePoint SOAP:

  • Basic: Use basic user/password credentials to authenticate.
  • ADFS: Set to use a single sign on connection with ADFS as the identify provider.
  • Okta: Set to use a single sign on connection with OKTA as the identify provider.
  • OneLogin: Set to use a single sign on connection with OneLogin as the identify provider.
  • NTLM: Set this to use your Windows credentials for authentication.

SharePoint REST V1

The following options are also available when ConnectionType is set to SharePoint REST V1. SharePoint REST V1 supports both on-premise and SharePoint Online environments:

  • Basic: Use basic user/password credentials to authenticate. On-premise only.
  • NTLM: Set this to use your Windows credentials for authentication. On-premise only.
  • ADFS: Set to use a single sign on connection with ADFS as the identify provider. SharePoint Online only.
  • Okta: Set to use a single sign on connection with OKTA as the identify provider. SharePoint Online only.
  • OneLogin: Set to use a single sign on connection with OneLogin as the identify provider. SharePoint Online only.
  • PingFederate: Set to use a single sign on connection with PingFederate as the identify provider. SharePoint Online only.
  • AzureAD: Set this to perform Azure Active Directory (Entra ID) OAuth authentication. On-premise and SharePoint Online.

CData Python Connector for XML

AccessKey

The access key used to authenticate to XML. This value is accessible from your security credentials page.

Data Type

string

Default Value

""

Remarks

User is used with AccessKey to authenticate the user against the XML server.

CData Python Connector for XML

SecretKey

Your account secret key. This value is accessible from your security credentials page.

Data Type

string

Default Value

""

Remarks

Your account secret key. This value is accessible from your security credentials page depending on the service you are using.

CData Python Connector for XML

ApiKey

The API Key used to identify the user to IBM Cloud.

Data Type

string

Default Value

""

Remarks

Access to resources in the XML REST API is governed by an API key in order to retrieve token. An API Key can be created by navigating to Manage --> Access (IAM) --> Users and clicking 'Create'.

CData Python Connector for XML

User

Specifies the username or account ID used to authenticate the user.

Data Type

string

Default Value

""

Remarks

The User and Password properties are used together to authenticate with the target service or server.

This property is useful for authenticating user accounts across supported connection types and authentication schemes.

CData Python Connector for XML

Password

Specifies the password used to authenticate the user.

Data Type

string

Default Value

""

Remarks

The User and Password properties are used together to authenticate with the target service or server.

This property is useful for authenticating user accounts across supported connection types and authentication schemes.

CData Python Connector for XML

SharePointEdition

The edition of SharePoint being used. Set either SharePointOnline or SharePointOnPremise.

Possible Values

SharePointOnline, SharePointOnPremise

Data Type

string

Default Value

"SharePointOnline"

Remarks

The edition of SharePoint being used. Set either SharePointOnline or SharePointOnPremise.

CData Python Connector for XML

ImpersonateUserMode

Specify the type of the user impersonation. It should be whether the User mode or the Admin mode.

Possible Values

User, Admin

Data Type

string

Default Value

"User"

Remarks

Specify the type of the user impersonation. It should be whether the User mode or the Admin mode. The Admin mode is available only for Enterprise with Governance accounts and will be upon request. It will not work for any other accounts.

CData Python Connector for XML

Connection

This section provides a complete list of the Connection properties you can configure in the connection string for this provider.


PropertyDescription
ConnectionTypeSpecifies the file storage service, server, or file access protocol through which your XML files are stored and retreived.
URIThe Uniform Resource Identifier (URI) for the XML resource location.
XPathSpecifies the XPath of an element that repeats at the same height within the XML document, which the provider uses to to split the document into multiple rows.
DataModelSpecifies the data model to use when parsing XML documents and generating the database metadata.
XMLFormatSpecifies the format of the XML document.
RegionThe hosting region for your S3-like Web Services.
OracleNamespaceThe Oracle Cloud Object Storage namespace to use.
StorageBaseURLSpecifies the URL of a cloud storage service provider.
SimpleUploadLimitThis setting specifies the threshold, in bytes, above which the provider will choose to perform a multipart upload rather than uploading everything in one request.
UseVirtualHostingIf true (default), buckets will be referenced in the request using the hosted-style request: http://yourbucket.s3.amazonaws.com/yourobject. If set to false, the bean will use the path-style request: http://s3.amazonaws.com/yourbucket/yourobject. Note that this property will be set to false, in case of an S3 based custom service when the CustomURL is specified.
TestConnectionBehaviorSpecifies the behavior of the test connection operation.
UseLakeFormationWhen this property is set to true, AWSLakeFormation service will be used to retrieve temporary credentials, which enforce access policies against the user based on the configured IAM role. The service can be used when authenticating through OKTA, ADFS, AzureAD, PingFederate, while providing a SAML assertion.
CData Python Connector for XML

ConnectionType

Specifies the file storage service, server, or file access protocol through which your XML files are stored and retreived.

Possible Values

Local, Amazon S3, Azure Blob Storage, Azure Data Lake Storage Gen2, Azure Data Lake Storage Gen2 SSL, Azure Files, Box, Dropbox, FTP, FTPS, Google Cloud Storage, Google Drive, HDFS, HDFS Secure, HTTP, HTTPS, IBM Object Storage Source, OneDrive, OneLake, Oracle Cloud Storage, SFTP, SharePoint GRAPH, SharePoint SOAP, SharePoint REST V1

Data Type

string

Default Value

"Local"

Remarks

Set the ConnectionType to one of the following:

  • Local: XML files stored on your local machine.
  • Amazon S3
  • Azure Blob Storage
  • Azure Data Lake Storage Gen2
  • Azure Data Lake Storage Gen2 SSL
  • Azure Files
  • Box
  • Dropbox
  • FTP
  • FTPS
  • Google Cloud Storage
  • Google Drive
  • HDFS
  • HDFS Secure
  • HTTP: Connects to XML files hosted on HTTP streams.
  • HTTPS: Connects to XML files hosted on HTTPS streams.
  • IBM Object Storage Source
  • OneDrive
  • OneLake
  • Oracle Cloud Storage
  • SFTP
  • SharePoint GRAPH
  • SharePoint SOAP
  • SharePoint REST V1

Set the ConnectionType to one of the following:

  • Local: XML files stored on your local machine.
  • Amazon S3
  • Azure Blob Storage
  • Azure Data Lake Storage Gen2
  • Azure Data Lake Storage Gen2 SSL
  • Azure Files
  • Box
  • Dropbox
  • FTP
  • FTPS
  • Google Cloud Storage
  • Google Drive
  • HDFS
  • HDFS Secure
  • HTTP: Connects to XML files hosted on HTTP streams.
  • HTTPS: Connects to XML files hosted on HTTPS streams.
  • IBM Object Storage Source
  • OneDrive
  • OneLake
  • Oracle Cloud Storage
  • SFTP
  • SharePoint GRAPH
  • SharePoint SOAP
  • SharePoint REST V1

CData Python Connector for XML

URI

The Uniform Resource Identifier (URI) for the XML resource location.

Data Type

string

Default Value

""

Remarks

Set the URI property to specify a path to a file or stream.

NOTE:

  • This connection property requires that you set ConnectionType.
  • If specifying a directory path, it is generally recommended to end the URI with a trailing path separator character, as an example 'folder1/' instead of 'folder1'.

See Fine-Tuning Data Access for more advanced features available for parsing and merging multiple files.

Below are examples of the URI formats for the available data sources:

Service provider URI formats
Local Single File Path One table

localPath/file.xml

file://localPath/file.xml

Directory Path (One aggregated table from all files)

localPath

file://localPath

HTTP or HTTPS http://remoteStream

https://remoteStream

Amazon S3 Single File Path One table

s3://remotePath/file.xml

Directory Path (One aggregated table from all files)

s3://remotePath

Azure Blob Storage Single File Path One table

azureblob://mycontainer/myblob//file.xml

Directory Path (One aggregated table from all files)

azureblob://mycontainer/myblob/

OneDrive Single File Path One table

onedrive://remotePath/file.xml

Directory Path (One aggregated table from all files)

onedrive://remotePath

Google Cloud Storage Single File Path One table

gs://bucket/remotePath/file.xml

Directory Path (One aggregated table from all files)

gs://bucket/remotePath

Google Drive Single File Path One table

gdrive://remotePath/file.xml

Directory Path (One aggregated table from all files)

gdrive://remotePath

Box Single File Path One table

box://remotePath/file.xml

Directory Path (One aggregated table from all files)

box://remotePath

FTP or FTPS Single File Path One table

ftp://server:port/remotePath/file.xml

Directory Path (One aggregated table from all files)

ftp://server:port/remotePath

SFTP Single File Path One table

sftp://server:port/remotePath/file.xml

Directory Path (One aggregated table from all files)

sftp://server:port/remotePath

SharePoint SOAP Single File Path One table

sp://library/folder/file.xml

Directory Path (One aggregated table from all files)

sp://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

SharePoint GRAPH Single File Path One table

spgraph://library/folder/file.xml

Directory Path (One aggregated table from all files)

spgraph://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

SharePoint REST V1 Single File Path One table

sprestv1://library/folder/file.xml

Directory Path (One aggregated table from all files)

sprestv1://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

Example Connection Strings and Queries

Below are example connection strings to XML files or streams.

Service provider URI formats Connection example
Local Single File Path One table

localPath

file://localPath/file.xml

Directory Path (One aggregated table from all files)

localPath

file://localPath

URI=C:\folder1/file.xml
Amazon S3 Single File Path One table

s3://bucket1/folder1/file.xml

Directory Path (One aggregated table from all files)

s3://bucket1/folder1

URI=s3://bucket1/folder1/file.xml; AWSAccessKey=token1; AWSSecretKey=secret1; AWSRegion=OHIO;
Azure Blob Storage Single File Path One table

azureblob://mycontainer/myblob//file.xml

Directory Path (One aggregated table from all files)

azureblob://mycontainer/myblob/

URI=azureblob://mycontainer/myblob/; AzureStorageAccount=myAccount; AzureAccessKey=myKey;

URI=azureblob://mycontainer/myblob/; AzureStorageAccount=myAccount; InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth;

OneDrive Single File Path One table

onedrive://remotePath/file.xml

Directory Path (One aggregated table from all files)

onedrive://remotePath

URI=onedrive://folder1/file.xml;InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth;

URI=onedrive://SharedWithMe/folder1/file.xml;InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth;

Google Cloud Storage Single File Path One table

gs://bucket/remotePath/file.xml

Directory Path (One aggregated table from all files)

gs://bucket/remotePath

URI=gs://bucket/folder1/file.xml; InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth; ProjectId=test;
Google Drive Single File Path One table

gdrive://remotePath/file.xml

Directory Path (One aggregated table from all files)

gdrive://remotePath

URI=gdrive://folder1/file.xml;InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth;
Box Single File Path One table

box://remotePath/file.xml

Directory Path (One aggregated table from all files)

box://remotePath

URI=box://folder1/file.xml; InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth; OAuthClientId=oauthclientid1; OAuthClientSecret=oauthcliensecret1; CallbackUrl=http://localhost:12345;
FTP or FTPS Single File Path One table

ftp://server:port/remotePath/file.xml

Directory Path (One aggregated table from all files)

ftp://server:port/remotePath

URI=ftps://localhost:990/folder1/file.xml; User=user1; Password=password1;
SFTP sftp://server:port/remotePath URI=sftp://127.0.0.1:22/remotePath/file.xml; User=user1; Password=password1;
SharePoint SOAP Single File Path One table

sp://library/folder/file.xml

Directory Path (One aggregated table from all files)

sp://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

URI=sp://Shared Documents/folder1/file.xml; User=user1; Password=password1; StorageBaseURL=https://subdomain.sharepoint.com;
SharePoint GRAPH Single File Path One table

spgraph://library/folder/file.xml

Directory Path (One aggregated table from all files)

spgraph://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

URI=spgraph://Shared Documents/folder1/file.xml; InitiateOAuth=GETANDREFRESH; AuthScheme=OAuth; StorageBaseURL=https://subdomain.sharepoint.com;
SharePoint REST V1 Single File Path One table

sprestv1://library/folder/file.xml

Directory Path (One aggregated table from all files)

sprestv1://library/folder/

Use the Sharepoint URL as the remote path. Not the display name.

URI=sprestv1://Shared Documents/folder1/file.xml; AuthScheme=NTLM; User=user1; Password=password1; StorageBaseURL=http://sharepointserver/sites/mysite;

CData Python Connector for XML

XPath

Specifies the XPath of an element that repeats at the same height within the XML document, which the provider uses to to split the document into multiple rows.

Data Type

string

Default Value

""

Remarks

The value of this option depends on the current XMLFormat. By default, connector automatically finds the object arrays in the document and models them as rows. This parameter allows you to explicitly define the object arrays using XPaths.

Multiple paths can be specified using a semicolon-separated list. The DataModel property governs how the nested object arrays are modeled as tables.

When using the XMLTable XMLFormat, this option uses a special format so that both column and row paths may be provided. Refer to the XMLFormat documentation for more details.

Automatically Detecting Object Arrays

When XPath is left empty, the connector determines the XPaths by parsing the XML document and identifying the object arrays. The DataModel and RowScanDepth properties configure the row scan; see Automatic Schema Discovery for more information.

This property is used to generate the schema definition when a schema file is not present (see Customizing Schemas).

XPath Examples

For the people example in Raw Data, an example XPath is $.people.vehicles.maintenance

A wildcard XPath can also be used and is helpful in the case that the XPaths are all at the same height but contain different names:

<rsb:set  attr="XPath" value="/feed/*" />

CData Python Connector for XML

DataModel

Specifies the data model to use when parsing XML documents and generating the database metadata.

Possible Values

Document, FlattenedDocuments, Relational

Data Type

string

Default Value

"Document"

Remarks

The connector splits XML documents into rows based on elements that repeat at the same level.

Flattening Nested XML

By default, the connector projects columns over the properties of objects and returns arrays as XML aggregates.

  • Object: Any parent element that does not repeat at the same height.
  • Array: Any element that repeats at the same height.

In the following example, jobs is a primitive array:

<jobs>sales</jobs>
<jobs>marketing</jobs>

In the following example, maintenance is an object array, since each maintenance node has child elements.

<maintenance>
  <date>07-17-2017</date>
  <desc>oil change</desc>
</maintenance>
<maintenance>
  <date>01-03-2018</date>
  <desc>new tires</desc>
</maintenance> 

Selecting a Data Modeling Strategy

The following DataModel configurations are available. See Parsing Hierarchical Data for examples of querying the data in the different configurations.

  • Document

    Returns a single table representing a row for each top-level object. In this data model, any nested object arrays will not be flattened and will be returned as aggregates. Unless an XPath value is explicitly specified, the connector will identify and use the top-most object array found as the XPath.

  • FlattenedDocuments

    Returns a single table representing a JOIN of the available documents in the file. In this data model, nested XPath values will act in the same manner as a SQL JOIN. Additionally, nested sibling XPath values (child paths at the same height), will be treated as a SQL CROSS JOIN. Unless explicitly specified, the connector will identify the XPath values available by parsing the file and identifying the available documents, including nested documents.

  • Relational

    Returns multiple tables, one for each XPath value specified. In this data model, any nested documents (object arrays) will be returned as relational tables that contain a primary key and a foreign key that links to the parent table. Unless explicitly specified, the connector will identify the XPath values available by parsing the file and identifying the available documents (including nested documents).

See Also

  • XPath: Explicitly set the paths to the documents you want to include.
  • FlattenArrays and FlattenObjects: Use these properties to horizontally flatten the data. This enables customization of the columns that will be identified for each of these data models.
  • Parsing Hierarchical Data: Shows how to query data using each of the DataModel configurations.
  • Modeling XML Data: Provides a map to the different data modeling strategies.
  • Connecting to XML Data Sources: Follow this configuration guide for an overview of the properties you need to connect.

CData Python Connector for XML

XMLFormat

Specifies the format of the XML document.

Possible Values

XML, XMLTABLE

Data Type

string

Default Value

"XML"

Remarks

The following XMLFormat configurations are available.

  • XML

    This is the default format and should be used in the majority of cases. The element or attribute name containing each value is used as the column name for that value.

  • XMLTable

    This format is for when the column name is separate from the data contained in that column. This is useful when the element or attribute containing the data has a generic name (like "Value") instead of being specific to each column.

    Note: DataModel does not apply when using this XMLFormat.

    Example:

        <Report>
          <Table>
              <Row>
                  <Value label="Customer">Mark Rodgers</Value>
                  <Value label="SupportCost">89.28</Value>
                  <Value label="ContractValue">299.99</Value>
              </Row>
              <Row>
                  <Value label="Customer">Hank Howards</Value>
                  <Value label="SupportCost">225.63</Value>
                  <Value label="ContractValue">0.00</Value>
              </Row>
          </Table>
        </Report>
      

    The XPath property requires special syntax to identify the column and row paths. Each path is given with a prefix depending on the type of path. All of the following are required:

    • row: This is the XPath of the element that contains each row's data. In the above example, this is: row:/Report/Table/Row
    • name: This is the XPath of the element containing the column name. In the above example, this is: column:/Report/Table/Row/Value@label
    • value: This is the XPath of the element that contains each column's data inside the row. In the above example, this is: value:/Report/Table/Row/Value

    Each of these paths is separated by a semicolon, so the complete XPath for the above example is: row:/Report/Table/Row;name:/Report/Table/Row/Value@label;value:/Report/Table/Row/Value

CData Python Connector for XML

Region

The hosting region for your S3-like Web Services.

Data Type

string

Default Value

""

Remarks

The hosting region for your S3-like Web Services.

Oracle Cloud Object Storage Regions

Value Region
Commercial Cloud Regions
ap-hyderabad-1 India South (Hyderabad)
ap-melbourne-1 Australia Southeast (Melbourne)
ap-mumbai-1 India West (Mumbai)
ap-osaka-1 Japan Central (Osaka)
ap-seoul-1 South Korea Central (Seoul)
ap-sydney-1 Australia East (Sydney)
ap-tokyo-1 Japan East (Tokyo)
ca-montreal-1 Canada Southeast (Montreal)
ca-toronto-1 Canada Southeast (Toronto)
eu-amsterdam-1 Netherlands Northwest (Amsterdam)
eu-frankfurt-1 Germany Central (Frankfurt)
eu-zurich-1 Switzerland North (Zurich)
me-jeddah-1 Saudi Arabia West (Jeddah)
sa-saopaulo-1 Brazil East (Sao Paulo)
uk-london-1 UK South (London)
us-ashburn-1 (default) US East (Ashburn, VA)
us-phoenix-1 US West (Phoenix, AZ)
US Gov FedRAMP High Regions
us-langley-1 US Gov East (Ashburn, VA)
us-luke-1 US Gov West (Phoenix, AZ)
US Gov DISA IL5 Regions
us-gov-ashburn-1 US DoD East (Ashburn, VA)
us-gov-chicago-1 US DoD North (Chicago, IL)
us-gov-phoenix-1 US DoD West (Phoenix, AZ)

Wasabi Regions

Value Region
eu-central-1 Europe (Amsterdam)
us-east-1 (Default) US East (Ashburn, VA)
us-east-2 US East (Manassas, VA)
us-west-1 US West (Hillsboro, OR)

CData Python Connector for XML

OracleNamespace

The Oracle Cloud Object Storage namespace to use.

Data Type

string

Default Value

""

Remarks

The Oracle Cloud Object Storage namespace to use. This setting must be set to the Oracle Cloud Object Storage namespace associated with the Oracle Cloud account before any requests can be made. Refer to the Understanding Object Storage Namespaces page of the Oracle Cloud documentation for instructions on how to find your account's Object Storage namespace.

CData Python Connector for XML

StorageBaseURL

Specifies the URL of a cloud storage service provider.

Data Type

string

Default Value

""

Remarks

This connection property is used to specify:

  • The URL of a custom S3 service.
  • The URL required for the SharePoint SOAP/REST cloud storage service provider.

    If the domain for this option ends in -my (for example, https://bigcorp-my.sharepoint.com) then you may need to use the onedrive:// scheme instead of the sp:// or spgraph:// scheme.

When connecting to files in a non–root-level SharePoint Online site (for example, under /sites/<your site>/), set this property to the full site path. For example: StorageBaseURL=https://<your domain>.sharepoint.com/sites/<your site>/

Using the full SharePoint site URL ensures the connector can locate files stored in subsites or other non-root-level site structures.

CData Python Connector for XML

SimpleUploadLimit

This setting specifies the threshold, in bytes, above which the provider will choose to perform a multipart upload rather than uploading everything in one request.

Data Type

string

Default Value

""

Remarks

This setting specifies the threshold, in bytes, above which the connector will choose to perform a multipart upload rather than uploading everything in one request.

CData Python Connector for XML

UseVirtualHosting

If true (default), buckets will be referenced in the request using the hosted-style request: http://yourbucket.s3.amazonaws.com/yourobject. If set to false, the bean will use the path-style request: http://s3.amazonaws.com/yourbucket/yourobject. Note that this property will be set to false, in case of an S3 based custom service when the CustomURL is specified.

Data Type

bool

Default Value

true

Remarks

If true (default), buckets will be referenced in the request using the hosted-style request: http://yourbucket.s3.amazonaws.com/yourobject. If set to false, the bean will use the path-style request: http://s3.amazonaws.com/yourbucket/yourobject. Note that this property will be set to false, in case of an S3 based custom service when the CustomURL is specified.

CData Python Connector for XML

TestConnectionBehavior

Specifies the behavior of the test connection operation.

Possible Values

READ_FILE, LIST_FILES, NO_OPERATION, AUTHENTICATE, LIST_OR_READ_FILES

Data Type

string

Default Value

"LIST_OR_READ_FILES"

Remarks

Changes how the connector responds to a test connection operation based on the integration scenario.

LIST_OR_READ_FILES

List and read files from the storage source until at least one is parsed. Fails if none of the files can be parsed (are invalid). Fails if the directory contains no XML files. Note: this mode will not read files in sub-directories. This is the most flexible option and works with both directory and file URIs.

READ_FILE

Validates that the URI points to a readable XML file. The URI must point to an existing XML file, not a directory. This behavior will fail if the file does not exist or contains invalid XML content.

LIST_FILES

Validates that the URI points to a directory and lists its contents. Fails if the directory contains no XML files.

NO_OPERATION

Performs basic URI validation without accessing files or verifying their existence. This is useful for quickly validating configuration without network or file system operations.

AUTHENTICATE

Validates connection credentials and URI accessibility. For cloud storage, this verifies authentication. For local files, this checks URI format and basic accessibility.

Notes

  • The connector is read-only. Unlike write-capable drivers, empty directories will cause failures for LIST_FILES and LIST_OR_READ_FILES behaviors since a connection with no readable files is unusable.
  • The MetadataDiscoveryURI property specifies a representative XML file for schema detection. When set, this file is validated during connection testing with READ_FILE and LIST_OR_READ_FILES behaviors.
  • You can omit the URI entirely if you provide customized RSD schema files in the driver's Location directory. In this case, the driver validates that at least one .rsd file is valid.
  • When using NO_OPERATION, only basic URI syntax validation is performed. The connection test will succeed even if files don't exist, but will fail if no URI is provided and no RSD schemas are available.

Behavior by URI examples

URI NO_OPERATION READ_FILE LIST_FILES LIST_OR_READ_FILES AUTHENTICATE
Directory with XML files Success Failure: URI must point to an existing file Success Success Success
Empty directory Success Failure: URI must point to an existing file Failure: URI must point to a non-empty directory Failure: Unable to find any valid XML resource for supplied URI Success
Non-existing directory Success Failure: URI must point to an existing file Failure: URI must point to an existing directory Failure: URI must point to an existing file or directory Success
Valid XML file Success Success Failure: URI must point to an existing directory Success Success
Non-existing file Success Failure: URI must point to an existing file Failure: URI must point to an existing directory Failure: URI must point to an existing file or directory Success
Invalid XML format Success Failure: Parsing error Failure: URI must point to an existing directory Failure: Parsing error Success
Cloud storage, invalid credentials Success Failure: Authentication error Failure: Authentication error Failure: Authentication error Failure: Authentication error

CData Python Connector for XML

UseLakeFormation

When this property is set to true, AWSLakeFormation service will be used to retrieve temporary credentials, which enforce access policies against the user based on the configured IAM role. The service can be used when authenticating through OKTA, ADFS, AzureAD, PingFederate, while providing a SAML assertion.

Data Type

bool

Default Value

false

Remarks

When this property is set to true, AWSLakeFormation service will be used to retrieve temporary credentials, which enforce access policies against the user based on the configured IAM role. The service can be used when authenticating through OKTA, ADFS, AzureAD, PingFederate, while providing a SAML assertion.

CData Python Connector for XML

AWS Authentication

This section provides a complete list of the AWS Authentication properties you can configure in the connection string for this provider.


PropertyDescription
AWSAccessKeySpecifies your AWS account access key. This value is accessible from your AWS security credentials page.
AWSSecretKeyYour AWS account secret key. This value is accessible from your AWS security credentials page.
AWSRoleARNThe Amazon Resource Name of the role to use when authenticating. Multiple roles can be specified separated by semicolons for role chaining.
AWSPrincipalARNThe ARN of the SAML Identity provider in your AWS account.
AWSRegionThe hosting region for your Amazon Web Services.
AWSCredentialsFileThe path to the AWS Credentials File to be used for authentication.
AWSCredentialsFileProfileThe name of the profile to be used from the supplied AWSCredentialsFile.
AWSSessionTokenYour AWS session token.
AWSExternalIdA unique identifier that might be required when you assume a role in another account.
MFASerialNumberThe serial number of the MFA device if one is being used.
MFATokenThe temporary token available from your MFA device.
CredentialsLocationThe location of the settings file where MFA credentials are saved.
TemporaryTokenDurationThe amount of time (in seconds) a temporary token will last.
AWSWebIdentityTokenThe OAuth 2.0 access token or OpenID Connect ID token that is provided by an identity provider.
ServerSideEncryptionWhen activated, file uploads into Amazon S3 buckets will be server-side encrypted.
AWSContainerCredentialsFullURIThe full URI of the container credential provider endpoint used by EKS Pod Identity.
AWSContainerAuthorizationTokenFileThe path to a file containing the authorization token for the EKS Pod Identity credential provider.
SSEContextA BASE64-encoded UTF-8 string holding JSON which represents a string-string (key-value) map.
SSEEnableS3BucketKeysConfiguration to use an S3 Bucket Key at the object level when encrypting data with AWS KMS. Enabling this will reduce the cost of server-side encryption by lowering calls to AWS KMS.
SSEKeyA symmetric encryption KeyManagementService key, that is used to protect the data when using ServerSideEncryption.
CData Python Connector for XML

AWSAccessKey

Specifies your AWS account access key. This value is accessible from your AWS security credentials page.

Data Type

string

Default Value

""

Remarks

To find your AWS account access key:

  1. Sign into the AWS Management console with the credentials for your root account.
  2. Select your account name or number.
  3. Select My Security Credentials in the menu.
  4. Click Continue to Security Credentials.
  5. To view or manage root account access keys, expand the Access Keys section.

CData Python Connector for XML

AWSSecretKey

Your AWS account secret key. This value is accessible from your AWS security credentials page.

Data Type

string

Default Value

""

Remarks

Your AWS account secret key. This value is accessible from your AWS security credentials page:

  1. Sign into the AWS Management console with the credentials for your root account.
  2. Select your account name or number and select My Security Credentials in the menu that is displayed.
  3. Click Continue to Security Credentials and expand the Access Keys section to manage or create root account access keys.

CData Python Connector for XML

AWSRoleARN

The Amazon Resource Name of the role to use when authenticating. Multiple roles can be specified separated by semicolons for role chaining.

Data Type

string

Default Value

""

Remarks

When authenticating outside of AWS, it is common to use a Role for authentication instead of your direct AWS account credentials. Entering the AWSRoleARN will cause the CData Python Connector for XML to perform a role based authentication instead of using the AWSAccessKey and AWSSecretKey directly. The AWSAccessKey and AWSSecretKey must still be specified to perform this authentication. You cannot use the credentials of an AWS root user when setting RoleARN. The AWSAccessKey and AWSSecretKey must be those of an IAM user.

Role Chaining

To perform role chaining, specify multiple role ARNs separated by semicolons. The roles will be assumed in sequence, with each subsequent role being assumed using the temporary credentials from the previous role. For example:
arn:aws:iam::111111111111:role/RoleA;arn:aws:iam::222222222222:role/RoleB
This will first assume RoleA using the IAM user credentials, then assume RoleB using RoleA's temporary credentials.

CData Python Connector for XML

AWSPrincipalARN

The ARN of the SAML Identity provider in your AWS account.

Data Type

string

Default Value

""

Remarks

The ARN of the SAML Identity provider in your AWS account.

CData Python Connector for XML

AWSRegion

The hosting region for your Amazon Web Services.

Possible Values

OHIO, NORTHERNVIRGINIA, NORTHERNCALIFORNIA, OREGON, CAPETOWN, HONGKONG, TAIPEI, HYDERABAD, JAKARTA, MALAYSIA, MELBOURNE, MUMBAI, OSAKA, SEOUL, SINGAPORE, SYDNEY, THAILAND, TOKYO, CENTRAL, CALGARY, BEIJING, NINGXIA, FRANKFURT, IRELAND, LONDON, MILAN, PARIS, SPAIN, STOCKHOLM, ZURICH, TELAVIV, MEXICOCENTRAL, BAHRAIN, UAE, SAOPAULO, GOVCLOUDEAST, GOVCLOUDWEST, ISOLATEDUSEAST, ISOLATEDUSEASTB, ISOLATEDUSEASTF, ISOLATEDUSSOUTHF, ISOLATEDUSWEST, ISOLATEDEUWEST

Data Type

string

Default Value

"NORTHERNVIRGINIA"

Remarks

The hosting region for your Amazon Web Services. Available values are OHIO, NORTHERNVIRGINIA, NORTHERNCALIFORNIA, OREGON, CAPETOWN, HONGKONG, TAIPEI, HYDERABAD, JAKARTA, MALAYSIA, MELBOURNE, MUMBAI, OSAKA, SEOUL, SINGAPORE, SYDNEY, THAILAND, TOKYO, CENTRAL, CALGARY, BEIJING, NINGXIA, FRANKFURT, IRELAND, LONDON, MILAN, PARIS, SPAIN, STOCKHOLM, ZURICH, TELAVIV, MEXICOCENTRAL, BAHRAIN, UAE, SAOPAULO, GOVCLOUDEAST, GOVCLOUDWEST, ISOLATEDUSEAST, ISOLATEDUSEASTB, ISOLATEDUSEASTF, ISOLATEDUSSOUTHF, ISOLATEDUSWEST and ISOLATEDEUWEST.

CData Python Connector for XML

AWSCredentialsFile

The path to the AWS Credentials File to be used for authentication.

Data Type

string

Default Value

""

Remarks

The path to the AWS Credentials File to be used for authentication. See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html for more information.

CData Python Connector for XML

AWSCredentialsFileProfile

The name of the profile to be used from the supplied AWSCredentialsFile.

Data Type

string

Default Value

"default"

Remarks

The name of the profile to be used from the supplied AWSCredentialsFile. See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html for more information.

CData Python Connector for XML

AWSSessionToken

Your AWS session token.

Data Type

string

Default Value

""

Remarks

Your AWS session token. This value can be retrieved in different ways. See this link for more info.

CData Python Connector for XML

AWSExternalId

A unique identifier that might be required when you assume a role in another account.

Data Type

string

Default Value

""

Remarks

A unique identifier that might be required when you assume a role in another account.

CData Python Connector for XML

MFASerialNumber

The serial number of the MFA device if one is being used.

Data Type

string

Default Value

""

Remarks

You can find the device for an IAM user by going to the AWS Management Console and viewing the user's security credentials. For virtual devices, this is actually an Amazon Resource Name (such as arn:aws:iam::123456789012:mfa/user).

CData Python Connector for XML

MFAToken

The temporary token available from your MFA device.

Data Type

string

Default Value

""

Remarks

If MFA is required, this value will be used along with the MFASerialNumber to retrieve temporary credentials to login. The temporary credentials available from AWS will only last up to 1 hour by default (see TemporaryTokenDuration). Once the time is up, the connection must be updated to specify a new MFA token so that new credentials may be obtained. %AWSpSecurityToken; %AWSpTemporaryTokenDuration;

CData Python Connector for XML

CredentialsLocation

The location of the settings file where MFA credentials are saved.

Data Type

string

Default Value

"%APPDATA%\\CData\\XML Data Provider\\CredentialsFile.txt"

Remarks

MFA credentials are short-lived and typically expire after an hour. At that point, you must specify a different MFAToken to continue connecting. MFA tokens only work once, so in the case of multi-threaded or multi-process applications, the credentials must be centrally located and shared to avoid problems. When MFAToken is not specified, this property does nothing.

If left unspecified, the default location is "%APPDATA%\\CData\\XML Data Provider\\CredentialsFile.txt" with %APPDATA% being set to the user's configuration directory:

Platform %APPDATA%
Windows The value of the APPDATA environment variable
Linux ~/.config

CData Python Connector for XML

TemporaryTokenDuration

The amount of time (in seconds) a temporary token will last.

Data Type

string

Default Value

"3600"

Remarks

Temporary tokens are used with both MFA and Role based authentication. Temporary tokens will eventually time out, at which time a new temporary token must be obtained. For situations where MFA is not used, this is not a big deal. The CData Python Connector for XML will internally request a new temporary token once the temporary token has expired.

However, for MFA required connection, a new MFAToken must be specified in the connection to retrieve a new temporary token. This is a more intrusive issue since it requires an update to the connection by the user. The maximum and minimum that can be specified will depend largely on the connection being used.

For Role based authentication, the minimum duration is 900 seconds (15 minutes) while the maximum if 3600 (1 hour). Even if MFA is used with role based authentication, 3600 is still the maximum.

For MFA authentication by itself (using an IAM User or root user), the minimum is 900 seconds (15 minutes), the maximum is 129600 (36 hours).

CData Python Connector for XML

AWSWebIdentityToken

The OAuth 2.0 access token or OpenID Connect ID token that is provided by an identity provider.

Data Type

string

Default Value

""

Remarks

The OAuth 2.0 access token or OpenID Connect ID token that is provided by an identity provider. An application can get this token by authenticating a user with a web identity provider. If not specified, the value for this connection property is automatically obtained from the value of the 'AWS_WEB_IDENTITY_TOKEN_FILE' environment variable.

CData Python Connector for XML

ServerSideEncryption

When activated, file uploads into Amazon S3 buckets will be server-side encrypted.

Possible Values

OFF, S3-Managed Keys, Key Management Service Keys

Data Type

string

Default Value

"OFF"

Remarks

Server-side encryption is the encryption of data at its destination by the application or service that receives it. Amazon S3 encrypts your data at the object level as it writes it to disks in its data centers and decrypts it for you when you access it. Learn more: https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html

CData Python Connector for XML

AWSContainerCredentialsFullURI

The full URI of the container credential provider endpoint used by EKS Pod Identity.

Data Type

string

Default Value

""

Remarks

This property is typically set automatically via the AWS_CONTAINER_CREDENTIALS_FULL_URI environment variable by the EKS Pod Identity Agent. If the environment variable is not available, specify the endpoint URI using this property.

CData Python Connector for XML

AWSContainerAuthorizationTokenFile

The path to a file containing the authorization token for the EKS Pod Identity credential provider.

Data Type

string

Default Value

""

Remarks

This property is typically set automatically via the AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variable by the EKS Pod Identity Agent. If the environment variable is not available, specify the token file path using this property.

CData Python Connector for XML

SSEContext

A BASE64-encoded UTF-8 string holding JSON which represents a string-string (key-value) map.

Data Type

string

Default Value

""

Remarks

Example of what the JSON may look decoded: {"aws:s3:arn": "arn:aws:s3:::_bucket_/_object_"}.

CData Python Connector for XML

SSEEnableS3BucketKeys

Configuration to use an S3 Bucket Key at the object level when encrypting data with AWS KMS. Enabling this will reduce the cost of server-side encryption by lowering calls to AWS KMS.

Data Type

bool

Default Value

false

Remarks

Configuration to use an S3 Bucket Key at the object level when encrypting data with AWS KMS. Enabling this will reduce the cost of server-side encryption by lowering calls to AWS KMS.

CData Python Connector for XML

SSEKey

A symmetric encryption KeyManagementService key, that is used to protect the data when using ServerSideEncryption.

Data Type

string

Default Value

""

Remarks

A symmetric encryption KeyManagementService key, that is used to protect the data when using ServerSideEncryption.

CData Python Connector for XML

Azure Authentication

This section provides a complete list of the Azure Authentication properties you can configure in the connection string for this provider.


PropertyDescription
AzureStorageAccountThe name of your Azure storage account.
AzureAccessKeyThe storage key associated with your Azure account.
AzureSharedAccessSignatureA shared access key signature that may be used for authentication.
AzureTenantIdentifies the XML tenant being used to access data. Accepts either the tenant's domain name (for example, contoso.onmicrosoft.com ) or its directory (tenant) ID.
AzureEnvironmentSpecifies the Azure network environment to which you will connect. Must be the same network to which your Azure account was added.
CData Python Connector for XML

AzureStorageAccount

The name of your Azure storage account.

Data Type

string

Default Value

""

Remarks

The name of your Azure storage account.

CData Python Connector for XML

AzureAccessKey

The storage key associated with your Azure account.

Data Type

string

Default Value

""

Remarks

The storage key associated with your XML account. You can retrieve it as follows:

  1. Sign into the azure portal with the credentials for your root account. (https://portal.azure.com/)
  2. Click on storage accounts and select the storage account you want to use.
  3. Under settings, click Access keys.
  4. Your storage account name and key will be displayed on that page.

CData Python Connector for XML

AzureSharedAccessSignature

A shared access key signature that may be used for authentication.

Data Type

string

Default Value

""

Remarks

A shared access signature. You can create one by following these steps:

  1. Sign into the azure portal with the credentials for your root account. (https://portal.azure.com/)
  2. Click on storage accounts and select the storage account you want to use.
  3. Under settings, click Shared Access Signature.
  4. Set the permissions and when the token will expire
  5. Click Generate SAS can copy the token.

CData Python Connector for XML

AzureTenant

Identifies the XML tenant being used to access data. Accepts either the tenant's domain name (for example, contoso.onmicrosoft.com ) or its directory (tenant) ID.

Data Type

string

Default Value

""

Remarks

A tenant is a digital container for your organization's users and resources, managed through Microsoft Entra ID (formerly Azure AD). Each tenant is associated with a unique directory ID, and often with a custom domain (for example, microsoft.com or contoso.onmicrosoft.com).

To find the directory (tenant) ID in the Microsoft Entra Admin Center, navigate to Microsoft Entra ID > Properties and copy the value labeled "Directory (tenant) ID".

This property is required in the following cases:

  • When AuthScheme is set to AzureServicePrincipal or AzureServicePrincipalCert
  • When AuthScheme is AzureAD and the user account belongs to multiple tenants

You can provide the tenant value in one of two formats:

  • A domain name (for example, contoso.onmicrosoft.com)
  • A directory (tenant) ID in GUID format (for example, c9d7b8e4-1234-4f90-bc1a-2a28e0f9e9e0)

Specifying the tenant explicitly ensures that the authentication request is routed to the correct directory, which is especially important when a user belongs to multiple tenants or when using service principal–based authentication.

If this value is omitted when required, authentication may fail or connect to the wrong tenant. This can result in errors such as unauthorized or resource not found.

CData Python Connector for XML

AzureEnvironment

Specifies the Azure network environment to which you will connect. Must be the same network to which your Azure account was added.

Possible Values

GLOBAL, CHINA, USGOVT, USGOVTDOD

Data Type

string

Default Value

"GLOBAL"

Remarks

Required if your Azure account is part of a different network than the Global network, such as China, USGOVT, or USGOVTDOD.

CData Python Connector for XML

Keycloak Authentication

This section provides a complete list of the Keycloak Authentication properties you can configure in the connection string for this provider.


PropertyDescription
KeycloakRealmURLSpecifies the full URL to the Keycloak server including the specific realm used for authentication and authorization.
CData Python Connector for XML

KeycloakRealmURL

Specifies the full URL to the Keycloak server including the specific realm used for authentication and authorization.

Data Type

string

Default Value

""

Remarks

The URL must be in the format: http(s)://{server-url}:{port}/realms/{realm-name}.

A realm in Keycloak is a logical namespace that manages a set of users, roles, clients, and configurations. It isolates authentication and authorization for different applications or services, allowing each realm to have its own user base and security settings. Multiple realms can exist within a single Keycloak instance, providing separation between different environments or groups.

Specifying KeycloakRealmURL is required when AuthScheme = Keycloak.

CData Python Connector for XML

SSO

This section provides a complete list of the SSO properties you can configure in the connection string for this provider.


PropertyDescription
SSOLoginURLThe identity provider's login URL.
SSOPropertiesAdditional properties required to connect to the identity provider, formatted as a semicolon-separated list.
SSOExchangeURLThe URL used for consuming the SAML response and exchanging it for service specific credentials.
CData Python Connector for XML

SSOLoginURL

The identity provider's login URL.

Data Type

string

Default Value

""

Remarks

The identity provider's login URL.

CData Python Connector for XML

SSOProperties

Additional properties required to connect to the identity provider, formatted as a semicolon-separated list.

Data Type

string

Default Value

""

Remarks

Additional properties required to connect to the identity provider, formatted as a semicolon-separated list.

This is used with the SSOLoginURL.

SSO configuration is discussed further in Establishing a Connection.

CData Python Connector for XML

SSOExchangeURL

The URL used for consuming the SAML response and exchanging it for service specific credentials.

Data Type

string

Default Value

""

Remarks

The CData Python Connector for XML will use the URL specified here to consume a SAML response and exchange it for service specific credentials. The retrieved credentials are the final piece during the SSO connection that are used to communicate with XML.

CData Python Connector for XML

JWT OAuth

This section provides a complete list of the JWT OAuth properties you can configure in the connection string for this provider.


PropertyDescription
OAuthJWTCertSupplies the name of the client certificate's JWT Certificate store.
OAuthJWTCertTypeIdentifies the type of key store containing the JWT Certificate.
OAuthJWTCertPasswordProvides the password for the OAuth JWT certificate used to access a password-protected certificate store. If the certificate store does not require a password, leave this property blank.
OAuthJWTCertSubjectIdentifies the subject of the OAuth JWT certificate used to locate a matching certificate in the store. Supports partial matches and the wildcard '*' to select the first certificate.
OAuthJWTSubjectThe user subject for which the application is requesting delegated access.
OAuthJWTSubjectTypeThe SubType for the JWT authentication.
OAuthJWTPublicKeyIdThe Id of the public key for JWT.
OAuthJWTAudienceA space-separated list of entities that may use the JWT.
OAuthJWTValidityTimeHow long the JWT should remain valid, in seconds.
CData Python Connector for XML

OAuthJWTCert

Supplies the name of the client certificate's JWT Certificate store.

Data Type

string

Default Value

""

Remarks

The OAuthJWTCertType field specifies the type of the certificate store specified in OAuthJWTCert. If the store is password-protected, use OAuthJWTCertPassword to supply the password..

OAuthJWTCert is used in conjunction with the OAuthJWTCertSubject field in order to specify client certificates. If OAuthJWTCert has a value, and OAuthJWTCertSubject is set, the CData Python Connector for XML initiates a search for a certificate. For further information, see OAuthJWTCertSubject.

Designations of certificate stores are platform-dependent.

Notes

  • The most common User and Machine certificate stores in Windows include:
    • MY: A certificate store holding personal certificates with their associated private keys.
    • CA: Certifying authority certificates.
    • ROOT: Root certificates.
    • SPC: Software publisher certificates.
  • In Java, the certificate store normally is a file containing certificates and optional private keys.
  • When the certificate store type is PFXFile, this property must be set to the name of the file.
  • When the type is PFXBlob, the property must be set to the binary contents of a PFX file (i.e. PKCS12 certificate store).

CData Python Connector for XML

OAuthJWTCertType

Identifies the type of key store containing the JWT Certificate.

Possible Values

USER, MACHINE, PFXFILE, PFXBLOB, JKSFILE, JKSBLOB, PEMKEY_FILE, PEMKEY_BLOB, PUBLIC_KEY_FILE, PUBLIC_KEY_BLOB, SSHPUBLIC_KEY_FILE, SSHPUBLIC_KEY_BLOB, P7BFILE, PPKFILE, XMLFILE, XMLBLOB, BCFKSFILE, BCFKSBLOB, GOOGLEJSON, GOOGLEJSONBLOB, BOXJSON, BOXJSONBLOB

Data Type

string

Default Value

"USER"

Remarks

ValueDescriptionNotes
USERA certificate store owned by the current user. Only available in Windows.
MACHINEA machine store.Not available in Java or other non-Windows environments.
PFXFILEA PFX (PKCS12) file containing certificates.
PFXBLOBA string (base-64-encoded) representing a certificate store in PFX (PKCS12) format.
JKSFILEA Java key store (JKS) file containing certificates.Only available in Java.
JKSBLOBA string (base-64-encoded) representing a certificate store in Java key store (JKS) format. Only available in Java.
PEMKEY_FILEA PEM-encoded file that contains a private key and an optional certificate.
PEMKEY_BLOBA string (base64-encoded) that contains a private key and an optional certificate.
PUBLIC_KEY_FILEA file that contains a PEM- or DER-encoded public key certificate.
PUBLIC_KEY_BLOBA string (base-64-encoded) that contains a PEM- or DER-encoded public key certificate.
SSHPUBLIC_KEY_FILEA file that contains an SSH-style public key.
SSHPUBLIC_KEY_BLOBA string (base-64-encoded) that contains an SSH-style public key.
P7BFILEA PKCS7 file containing certificates.
PPKFILEA file that contains a PPK (PuTTY Private Key).
XMLFILEA file that contains a certificate in XML format.
XMLBLOBAstring that contains a certificate in XML format.
BCFKSFILEA file that contains an Bouncy Castle keystore.
BCFKSBLOBA string (base-64-encoded) that contains a Bouncy Castle keystore.
GOOGLEJSONA JSON file containing the service account information. Only valid when connecting to a Google service.
GOOGLEJSONBLOBA string that contains the service account JSON. Only valid when connecting to a Google service.
BOXJSONA JSON file containing the service account credentials. Only valid when connecting to Box.
BOXJSONBLOBThe certificate store is a string that contains the service account JSON. Only valid when connecting to Box.

CData Python Connector for XML

OAuthJWTCertPassword

Provides the password for the OAuth JWT certificate used to access a password-protected certificate store. If the certificate store does not require a password, leave this property blank.

Data Type

string

Default Value

""

Remarks

This property specifies the password needed to open a password-protected certificate store. To determine if a password is necessary, refer to the documentation or configuration for your specific certificate store.

This is not required when using the GOOGLEJSON OAuthJWTCertType. Google JSON keys are not encrypted.

CData Python Connector for XML

OAuthJWTCertSubject

Identifies the subject of the OAuth JWT certificate used to locate a matching certificate in the store. Supports partial matches and the wildcard '*' to select the first certificate.

Data Type

string

Default Value

"*"

Remarks

The value of this property is used to locate a matching certificate in the store. The search process works as follows:

  • If an exact match for the subject is found, the corresponding certificate is selected.
  • If no exact match is found, the store is searched for certificates whose subjects contain the property value.
  • If no match is found, no certificate is selected.

You can set the value to '*' to automatically select the first certificate in the store. The certificate subject is a comma-separated list of distinguished name fields and values. For example: CN=www.server.com, OU=test, C=US, E=support@cdata.com.

Common fields include:

FieldMeaning
CNCommon Name. This is commonly a host name like www.server.com.
OOrganization
OUOrganizational Unit
LLocality
SState
CCountry
EEmail Address

If a field value contains a comma, enclose it in quotes. For example: "O=ACME, Inc.".

CData Python Connector for XML

OAuthJWTSubject

The user subject for which the application is requesting delegated access.

Data Type

string

Default Value

""

Remarks

The user subject for which the application is requesting delegated access. Typically, the user account name or email address.

CData Python Connector for XML

OAuthJWTSubjectType

The SubType for the JWT authentication.

Possible Values

enterprise, user

Data Type

string

Default Value

"enterprise"

Remarks

The SubType for the JWT authentication. Set this to "enterprise" or "user" depending on the type of token being requested.

CData Python Connector for XML

OAuthJWTPublicKeyId

The Id of the public key for JWT.

Data Type

string

Default Value

""

Remarks

The Id of the public key for JWT. Set this to the value of your Public Key Id in your app settings.

CData Python Connector for XML

OAuthJWTAudience

A space-separated list of entities that may use the JWT.

Data Type

string

Default Value

""

Remarks

This corresponds to the aud field in the JWT. The entries in this list are typically URLs, but the exact values depend on the API being used.

CData Python Connector for XML

OAuthJWTValidityTime

How long the JWT should remain valid, in seconds.

Data Type

int

Default Value

3600

Remarks

This is used to calculate the exp field in the JWT. By default this is set to 3600 which means the JWT is valid for 1 hour after it is generated. Some APIs may require lower values than this.

CData Python Connector for XML

Kerberos

This section provides a complete list of the Kerberos properties you can configure in the connection string for this provider.


PropertyDescription
KerberosKDCIdentifies the Kerberos Key Distribution Center (KDC) service used to authenticate the user. (SPNEGO or Windows authentication only).
KerberosRealmIdentifies the Kerberos Realm used to authenticate the user.
KerberosSPNIdentifies the service principal name (SPN) for the Kerberos Domain Controller.
KerberosUserConfirms the principal name for the Kerberos Domain Controller, which uses the format host/user@realm.
KerberosKeytabFileIdentifies the Keytab file containing your pairs of Kerberos principals and encrypted keys.
KerberosServiceRealmIdentifies the service's Kerberos realm. (Cross-realm authentication only).
KerberosServiceKDCIdentifies the service's Kerberos Key Distribution Center (KDC).
KerberosTicketCacheSpecifies the full file path to an MIT Kerberos credential cache file.
CData Python Connector for XML

KerberosKDC

Identifies the Kerberos Key Distribution Center (KDC) service used to authenticate the user. (SPNEGO or Windows authentication only).

Data Type

string

Default Value

""

Remarks

The Kerberos properties are used when using SPNEGO or Windows Authentication. The connector requests session tickets and temporary session keys from the Kerberos KDC service, which is usually co-located with the domain controller.

If KerberosKDC is not specified, the connector tries to detect these properties automatically from the following locations:

  • KRB5 Config File (krb5.ini/krb5.conf): If the KRB5_CONFIG environment variable is set and the file exists, the connector obtains the KDC from the specified file. If it is not found there, the connector tries to read from the default MIT location based on the OS: C:\ProgramData\MIT\Kerberos5\krb5.ini (Windows) or /etc/krb5.conf (Linux).
  • Domain Name and Host: If the Kerberos Realm and Kerberos KDC cannot be inferred from another location, the connector infers them from the configured domain name and host.

CData Python Connector for XML

KerberosRealm

Identifies the Kerberos Realm used to authenticate the user.

Data Type

string

Default Value

""

Remarks

A realm is a logical network, similar to a domain, that defines a group of systems under the same master KDC. Some realms are hierarchical, where one realm is a superset of the other realm, but usually realms are nonhierarchical (or “direct”) and the mapping between the two realms must be defined. Kerberos cross-realm authentication enables authentication across realms. Each realm only needs to have a principal entry for the other realm in its KDC.

The Kerberos properties are used when using SPNEGO or Windows Authentication. The connector requests session tickets and temporary session keys from the Kerberos KDC service, which is usually co-located with the domain controller. The Kerberos Realm can be configured by an administrator to be any string, but it is usually based on the domain name.

If Kerberos Realm is not specified, the connector will attempt to detect these properties automatically from the following locations:

  • KRB5 Config File (krb5.ini/krb5.conf): If the KRB5_CONFIG environment variable is set and the file exists, the connector will obtain the default realm from the specified file. Otherwise, it will attempt to read from the default MIT location based on the OS: C:\ProgramData\MIT\Kerberos5\krb5.ini (Windows) or /etc/krb5.conf (Linux)
  • Domain Name and Host: If the Kerberos Realm and Kerberos KDC could not be inferred from another location, the connector will infer them from the user-configured domain name and host. This might work in some Windows environments.

CData Python Connector for XML

KerberosSPN

Identifies the service principal name (SPN) for the Kerberos Domain Controller.

Data Type

string

Default Value

""

Remarks

If the SPN on the Kerberos Domain Controller is not the same as the URL that you are authenticating to, use this property to set the SPN to the KDC's URL.

CData Python Connector for XML

KerberosUser

Confirms the principal name for the Kerberos Domain Controller, which uses the format host/user@realm.

Data Type

string

Default Value

""

Remarks

If there is a Kerberos principal, that Kerberos principal name should always be used to authenticate to the database.

CData Python Connector for XML

KerberosKeytabFile

Identifies the Keytab file containing your pairs of Kerberos principals and encrypted keys.

Data Type

string

Default Value

""

Remarks

A keytab (short for “key table”) stores long-term keys for one or more principals. In most cases, end users authenticate to the KDC using their client secret (password). However, in situations where authentication or re-authentication happen using automated scripts and applications, it may be more efficient to use a keytab, which sends passwords to the KDC in encrypted form, automatically.

Keytabs are normally represented by files in a standard format, and named using the format type:value. Usually type is FILE and value is the absolute pathname of the file. The other possible value for type is MEMORY, which indicates a temporary keytab stored in the memory of the current process.

A keytab contains one or more entries, where each entry consists of a timestamp (indicating when the entry was written to the keytab), a principal name, a key version number, an encryption type, and the encryption key itself. They can be generated using kutil.

For example:

[admin@myhost]# ktutil

ktutil: addent -password -p starlord/myhost.galaxy.com@GALAXY.COM -k 1 -e aes256-cts-hmac-sha1-96
Password for starlord/myhost.galaxy.com:

ktutil: addent -password -p starlord/myhost.galaxy.com@GALAXY.COM -k 1 -e aes128-cts-hmac-sha1-96
Password for starlord/myhost.galaxy.com:

ktutil: addent -password -p starlord/myhost.galaxy.com@GALAXY.COM -k 1 -e des3-cbc-sha1
Password for starlord/myhost.galaxy.com:

ktutil: wkt /path/to/starlord.keytab

Note: You must create principals for all authentication methods (encryption types) you want to support.

To display a keytab, use klist -k.

CData Python Connector for XML

KerberosServiceRealm

Identifies the service's Kerberos realm. (Cross-realm authentication only).

Data Type

string

Default Value

""

Remarks

The KerberosServiceRealm is used to specify a service's KerberosRealm when using cross-realm Kerberos authentication.

In most cases, a single realm and KDC machine are used to perform the Kerberos authentication, which means that this property would not be required. However, the property is available for complex setups where a different realm and KDC machine are used to obtain an authentication ticket (AS request) and a service ticket (TGS request).

CData Python Connector for XML

KerberosServiceKDC

Identifies the service's Kerberos Key Distribution Center (KDC).

Data Type

string

Default Value

""

Remarks

The KerberosServiceKDC is used to specify the service Kerberos KDC when using cross-realm Kerberos authentication.

In most cases, a single realm and KDC machine are used to perform the Kerberos authentication, which means that this property would not be required. However, the property is available for complex setups where a different realm and KDC machine are used to obtain an authentication ticket (AS request) and a service ticket (TGS request).

CData Python Connector for XML

KerberosTicketCache

Specifies the full file path to an MIT Kerberos credential cache file.

Data Type

string

Default Value

""

Remarks

Set this property if you want to use a credential cache file that was created using the MIT Kerberos Ticket Manager or kinit command.

CData Python Connector for XML

OAuth

This section provides a complete list of the OAuth properties you can configure in the connection string for this provider.


PropertyDescription
InitiateOAuthSpecifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.
OAuthVersionIdentifies the version of OAuth being used.
OAuthClientIdSpecifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.
OAuthClientSecretSpecifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).
OAuthAccessTokenSpecifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.
OAuthAccessTokenSecretThe OAuth access token secret for connecting using OAuth.
SubjectIdThe user subject for which the application is requesting delegated access.
SubjectTypeThe Subject Type for the Client Credentials authentication.
OAuthSettingsLocationSpecifies the location of the settings file where OAuth values are saved.
CallbackURLIdentifies the URL users return to after authenticating to XML via OAuth (Custom OAuth applications only).
ScopeSpecifies the scope of the authenticating user's access to the application, to ensure they get appropriate access to data. If a custom OAuth application is needed, this is generally specified at the time the application is created.
OAuthPasswordGrantModeSpecifies how the OAuth Client ID and Client Secret are sent to the authorization server.
OAuthIncludeCallbackURLWhether to include the callback URL in an access token request.
OAuthAuthorizationURLThe authorization URL for the OAuth service.
OAuthAccessTokenURLThe URL from which the OAuth access token is retrieved.
OAuthRefreshTokenURLThe URL to refresh the OAuth token from.
OAuthRequestTokenURLThe URL the service provides to retrieve request tokens from. This is required in OAuth 1.0.
OAuthVerifierSpecifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.
AuthTokenThe authentication token used to request and obtain the OAuth Access Token.
AuthKeyThe authentication secret used to request and obtain the OAuth Access Token.
OAuthParamsA comma-separated list of other parameters to submit in the request for the OAuth access token in the format paramname=value.
OAuthRefreshTokenSpecifies the OAuth refresh token used to request a new access token after the original has expired.
OAuthExpiresInSpecifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.
OAuthTokenTimestampDisplays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.
CData Python Connector for XML

InitiateOAuth

Specifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.

Possible Values

OFF, REFRESH, GETANDREFRESH

Data Type

string

Default Value

"OFF"

Remarks

OAuth is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. The OAuth flow defines the method to be used for:

  • Logging in users.
  • Exchanging user credentials for an OAuth access token to be used for authentication.
  • Providing limited access to applications.

The options for initiating and maintaining OAuth access are named for the parts of that flow that the connector handles:

OFF The connector provides no automatic OAuth flow initiation. The OAuth flow is handled entirely by the user.
This means that the user must refresh the token manually, and reconnect with an updated OAuthAccessToken property when the current token expires.
GETANDREFRESH The connector handles the entire OAuth flow (both GET and REFRESH). This means that if a token already exists, the connector refreshes it when necessary; if no token currently exists, the connector obtains it by prompting the user to login.
REFRESH The user obtains the OAuth Access Token and sets up the sequence for refreshing the OAuth Access Token. (The user is never prompted to log in to authenticate.) After the user logs in, the connector handles the refresh of the OAuth Access Token.

For more information on how to set up OAuth and use this property when configuring a connection, see Establishing a Connection.

CData Python Connector for XML

OAuthVersion

Identifies the version of OAuth being used.

Possible Values

1.0, 2.0

Data Type

string

Default Value

"2.0"

Remarks

Accepted entries are: 1.0,2.0

CData Python Connector for XML

OAuthClientId

Specifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.

Data Type

string

Default Value

""

Remarks

This property is required in two cases:

  • When using a custom OAuth application, such as in web-based authentication flows, service-based authentication, or certificate-based flows that require application registration.
  • If the driver does not provide embedded OAuth credentials.

(When the driver provides embedded OAuth credentials, this value may already be provided by the connector and thus not require manual entry.)

OAuthClientId is generally used alongside other OAuth-related properties such as OAuthClientSecret and OAuthSettingsLocation when configuring an authenticated connection.

OAuthClientId is one of the key connection parameters that need to be set before users can authenticate via OAuth. You can usually find this value in your identity provider’s application registration settings. Look for a field labeled Client ID, Application ID, or Consumer Key.

While the client ID is not considered a confidential value like a client secret, it is still part of your application's identity and should be handled carefully. Avoid exposing it in public repositories or shared configuration files.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for XML

OAuthClientSecret

Specifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).

Data Type

string

Default Value

""

Remarks

This property (sometimes called the application secret or consumer secret) is required when using a custom OAuth application in any flow that requires secure client authentication, such as web-based OAuth, service-based connections, or certificate-based authorization flows. It is not required when using an embedded OAuth application.

The client secret is used during the token exchange step of the OAuth flow, when the driver requests an access token from the authorization server. If this value is missing or incorrect, authentication fails with either an invalid_client or an unauthorized_client error.

OAuthClientSecret is one of the key connection parameters that need to be set before users can authenticate via OAuth. You can obtain this value from your identity provider when registering the OAuth application.

Notes:

  • This value should be stored securely and never exposed in public repositories, scripts, or unsecured environments.
  • Client secrets may also expire after a set period. Be sure to monitor expiration dates and rotate secrets as needed to maintain uninterrupted access.

For more information on how this property is used when configuring a connection, see Establishing a Connection

CData Python Connector for XML

OAuthAccessToken

Specifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.

Data Type

string

Default Value

""

Remarks

OAuthAccessToken is a temporary credential that authorizes access to protected resources. It is typically returned by the identity provider after the user or client application completes an OAuth authentication flow. This property is most commonly used in automated workflows or custom OAuth implementations where you want to manage token handling outside of the driver.

The OAuth access token has a server-dependent timeout, limiting user access. The timeout is set using the OAuthExpiresIn property. However, it can be reissued between requests to keep access alive as long as the user keeps working.

If InitiateOAuth is set to REFRESH, we recommend that you also set both OAuthExpiresIn and OAuthTokenTimestamp. The connector uses these properties to determine when the token expires so it can refresh most efficiently. If OAuthExpiresIn and OAuthTokenTimestamp are not specified, the connector refreshes the token immediately.

Note: Access tokens should be treated as sensitive credentials and stored securely. Avoid exposing them in logs, scripts, or configuration files that are not access-controlled.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for XML

OAuthAccessTokenSecret

The OAuth access token secret for connecting using OAuth.

Data Type

string

Default Value

""

Remarks

The OAuthAccessTokenSecret property is used to connect and authenticate using OAuth. The OAuthAccessTokenSecret is retrieved from the OAuth server as part of the authentication process. It is used with the OAuthAccessToken and can be used for multiple requests until it times out.

CData Python Connector for XML

SubjectId

The user subject for which the application is requesting delegated access.

Data Type

string

Default Value

""

Remarks

Id of the user or enterprise, based on the configuration set in SubjectType.

CData Python Connector for XML

SubjectType

The Subject Type for the Client Credentials authentication.

Possible Values

enterprise, user

Data Type

string

Default Value

"enterprise"

Remarks

The Subject Type for the Client Credentials authentication. Set this to "enterprise" or "user" depending on the type of token being requested.

CData Python Connector for XML

OAuthSettingsLocation

Specifies the location of the settings file where OAuth values are saved.

Data Type

string

Default Value

"%APPDATA%\\CData\\XML Data Provider\\OAuthSettings.txt"

Remarks

Storing OAuth settings in a central location avoids the need for users to enter OAuth connection properties manually each time they log in. It also enables credentials to be shared across connections or processes.

You can store OAuth values in a central file for shared access to those values, in either of the following ways:

  • Set InitiateOAuth to either GETANDREFRESH or REFRESH and specify a filepath to the OAuth settings file.
  • Use memory storage to load the credentials into static memory.

The following sections provide more detail on each of these methods.

Specifying the OAuthSettingsLocation Filepath

The default OAuth setting location is %APPDATA%\\CData\\XML Data Provider\\OAuthSettings.txt, with %APPDATA% set to the user's configuration directory. Default values vary, depending on the user's operating system.

  • Windows (ODBC and Power BI): registry://%DSN%
  • Windows: %APPDATA%CDataXML Data Provider\OAuthSettings.txt
  • Mac: %APPDATA%/CData/XML Data Provider/OAuthSettings.txt
  • Linux: %APPDATA%/CData/XML Data Provider/OAuthSettings.txt

Loading Credentials Via Memory Storage

Memory locations are specified by using a value starting with memory://, followed by a unique identifier for that set of credentials (for example, memory://user1). The identifier can be anything you choose, but it should be unique to the user.

Unlike file-based storage, where credentials persist across connections, memory storage loads the credentials into static memory and the credentials are shared between connections using the same identifier for the life of the process. To persist credentials outside the current process, you must manually store the credentials prior to closing the connection. This enables you to set them in the connection when the process is started again.

To retrieve OAuth property values, query the sys_connection_props system table. If there are multiple connections using the same credentials, the properties are read from the previously closed connection.

Supported Storage Types

  • memory://: Stores OAuth tokens in-memory (unique identifier, shared within same process, etc.)
  • registry://: Only supported in the Windows ODBC and Power BI editions. Stores OAuth tokens in the registry under the DSN settings. Must end in a DSN name like registry://CData Python Connector for XML Data Source, or registry://%DSN%.
  • %DSN%: The name of the DSN you are connecting with.
  • Default (no prefix): Stores OAuth tokens within files. The value can be either an absolute path, or a path starting with %APPDATA% or %PROGRAMFILES%.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for XML

CallbackURL

Identifies the URL users return to after authenticating to XML via OAuth (Custom OAuth applications only).

Data Type

string

Default Value

""

Remarks

If you created a custom OAuth application, the OAuth authorization server redirects the user to this URL during the authentication process. This value must match the callback URL you specified when you configured the custom OAuth application.

CData Python Connector for XML

Scope

Specifies the scope of the authenticating user's access to the application, to ensure they get appropriate access to data. If a custom OAuth application is needed, this is generally specified at the time the application is created.

Data Type

string

Default Value

""

Remarks

Scopes are set to define what kind of access the authenticating user will have; for example, read, read and write, restricted access to sensitive information. System administrators can use scopes to selectively enable access by functionality or security clearance.

When InitiateOAuth is set to GETANDREFRESH, you must use this property if you want to change which scopes are requested.

When InitiateOAuth is set to either REFRESH or OFF, you can change which scopes are requested using either this property or the Scope input.

Scopes are set to define what kind of access the authenticating user will have; for example, read, read and write, restricted access to sensitive information. System administrators can use scopes to selectively enable access by functionality or security clearance.

When InitiateOAuth is set to GETANDREFRESH, you must use this property if you want to change which scopes are requested.

When InitiateOAuth is set to either REFRESH or OFF, you can change which scopes are requested using either this property or the Scope input.

CData Python Connector for XML

OAuthPasswordGrantMode

Specifies how the OAuth Client ID and Client Secret are sent to the authorization server.

Possible Values

Post, Basic

Data Type

string

Default Value

"Post"

Remarks

The OAuth RFC provides two methods of passing the OAuthClientId and OAuthClientSecret:

  • POST: Sends the OAuthClientId and OAuthClientSecret in the POST body of the token request. This is the most commonly supported method and works with most OAuth flows.
  • BASIC: Sends the OAuthClientId and OAuthClientSecret in the HTTP Authorization header using Basic authentication. Some OAuth servers require this method for added compliance or security.

CData Python Connector for XML

OAuthIncludeCallbackURL

Whether to include the callback URL in an access token request.

Data Type

bool

Default Value

true

Remarks

This defaults to true since standards-compliant OAuth services will ignore the redirect_uri parameter for grant types like CLIENT or PASSWORD that do not require it.

This option should only be enabled for OAuth services that report errors when redirect_uri is included.

CData Python Connector for XML

OAuthAuthorizationURL

The authorization URL for the OAuth service.

Data Type

string

Default Value

""

Remarks

The authorization URL for the OAuth service. At this URL, the user logs into the server and grants permissions to the application. In OAuth 1.0, if permissions are granted, the request token is authorized.

CData Python Connector for XML

OAuthAccessTokenURL

The URL from which the OAuth access token is retrieved.

Data Type

string

Default Value

""

Remarks

In OAuth 1.0, the authorized request token is exchanged for the access token at this URL.

CData Python Connector for XML

OAuthRefreshTokenURL

The URL to refresh the OAuth token from.

Data Type

string

Default Value

""

Remarks

The URL to refresh the OAuth token from. In OAuth 2.0, this URL is where the refresh token is exchanged for a new access token when the old access token expires.

CData Python Connector for XML

OAuthRequestTokenURL

The URL the service provides to retrieve request tokens from. This is required in OAuth 1.0.

Data Type

string

Default Value

""

Remarks

The URL the service provides to retrieve request tokens from. This is required in OAuth 1.0. In OAuth 1.0, this is the URL where the app makes a request for the request token.

CData Python Connector for XML

OAuthVerifier

Specifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.

Data Type

string

Default Value

""

Remarks

For detailed instructions about how to obtain the OAuthVerifier value, see Establishing a Connection.

CData Python Connector for XML

AuthToken

The authentication token used to request and obtain the OAuth Access Token.

Data Type

string

Default Value

""

Remarks

This property is required only when performing headless authentication in OAuth 1.0. It can be obtained from the GetOAuthAuthorizationUrl stored procedure.

It can be supplied alongside the AuthKey in the GetOAuthAccessToken stored procedure to obtain the OAuthAccessToken.

CData Python Connector for XML

AuthKey

The authentication secret used to request and obtain the OAuth Access Token.

Data Type

string

Default Value

""

Remarks

This property is required only when performing headless authentication in OAuth 1.0. It can be obtained from the GetOAuthAuthorizationUrl stored procedure.

It can be supplied alongside the AuthToken in the GetOAuthAccessToken stored procedure to obtain the OAuthAccessToken.

CData Python Connector for XML

OAuthParams

A comma-separated list of other parameters to submit in the request for the OAuth access token in the format paramname=value.

Data Type

string

Default Value

""

Remarks

A comma-separated list of other parameters to submit in the request for the OAuth access token in the format paramname=value.

CData Python Connector for XML

OAuthRefreshToken

Specifies the OAuth refresh token used to request a new access token after the original has expired.

Data Type

string

Default Value

""

Remarks

The refresh token is used to obtain a new access token when the current one expires. It enables seamless authentication for long-running or automated workflows without requiring the user to log in again. This property is especially important in headless, CI/CD, or server-based environments where interactive authentication is not possible.

The refresh token is typically obtained during the initial OAuth exchange by calling the GetOAuthAccessToken stored procedure. After that, it can be set using this property to enable automatic token refresh, or passed to the RefreshOAuthAccessTokenproc; stored procedure if you prefer to manage the refresh manually.

When InitiateOAuth is set to REFRESH, the driver uses this token to retrieve a new access token automatically. After the first refresh, the driver saves updated tokens in the location defined by OAuthSettingsLocation, and uses those values for subsequent connections.

Note: The OAuthRefreshToken should be handled securely and stored in a trusted location. Like access tokens, refresh tokens can expire or be revoked depending on the identity provider’s policies.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for XML

OAuthExpiresIn

Specifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.

Data Type

string

Default Value

""

Remarks

The OAuth Access Token is assigned to an authenticated user, granting that user access to the network for a specified period of time. The access token is used in place of the user's login ID and password, which stay on the server.

An access token created by the server is only valid for a limited time. OAuthExpiresIn is the number of seconds the token is valid from when it was created. For example, a token generated at 2024-01-29 20:00:00 UTC that expires at 2024-01-29 21:00:00 UTC (an hour later) would have an OAuthExpiresIn value of 3600, no matter what the current time is.

To determine how long the user has before the Access Token will expire, check OAuthTokenTimestamp.

CData Python Connector for XML

OAuthTokenTimestamp

Displays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.

Data Type

string

Default Value

""

Remarks

The OAuth access token is assigned to an authenticated user, granting that user access to the network for a specified period of time. The access token is used in place of the user's login ID and password, which stay on the server.

An access token created by the server is only valid for a limited time. OAuthTokenTimestamp is the Unix timestamp when the server created the token. For example, OAuthTokenTimestamp=1706558400 indicates the OAuthAccessToken was generated by the server at 2024-01-29 20:00:00 UTC.

CData Python Connector for XML

SSL

This section provides a complete list of the SSL properties you can configure in the connection string for this provider.


PropertyDescription
SSLClientCertSpecifies the TLS/SSL client certificate store for SSL Client Authentication (2-way SSL). This property works in conjunction with other SSL-related properties to establish a secure connection.
SSLClientCertTypeSpecifies the type of key store containing the TLS/SSL client certificate for SSL Client Authentication. Choose from a variety of key store formats depending on your platform and certificate source.
SSLClientCertPasswordSpecifes the password required to access the TLS/SSL client certificate store. Use this property if the selected certificate store type requires a password for access.
SSLClientCertSubjectSpecifes the subject of the TLS/SSL client certificate to locate it in the certificate store. Use a comma-separated list of distinguished name fields, such as CN=www.server.com, C=US. The wildcard * selects the first certificate in the store.
SSLModeThe authentication mechanism to be used when connecting to the FTP or FTPS server.
SSLServerCertSpecifies the certificate to be accepted from the server when connecting using TLS/SSL.
CData Python Connector for XML

SSLClientCert

Specifies the TLS/SSL client certificate store for SSL Client Authentication (2-way SSL). This property works in conjunction with other SSL-related properties to establish a secure connection.

Data Type

string

Default Value

""

Remarks

This property specifies the client certificate store for SSL Client Authentication. Use this property alongside SSLClientCertType, which defines the type of the certificate store, and SSLClientCertPassword, which specifies the password for password-protected stores. When SSLClientCert is set and SSLClientCertSubject is configured, the driver searches for a certificate matching the specified subject.

Certificate store designations vary by platform. On Windows, certificate stores are identified by names such as MY (personal certificates), while in Java, the certificate store is typically a file containing certificates and optional private keys.

The following are designations of the most common User and Machine certificate stores in Windows:

MYA certificate store holding personal certificates with their associated private keys.
CACertifying authority certificates.
ROOTRoot certificates.
SPCSoftware publisher certificates.

For PFXFile types, set this property to the filename. For PFXBlob types, set this property to the binary contents of the file in PKCS12 format.

CData Python Connector for XML

SSLClientCertType

Specifies the type of key store containing the TLS/SSL client certificate for SSL Client Authentication. Choose from a variety of key store formats depending on your platform and certificate source.

Possible Values

USER, MACHINE, PFXFILE, PFXBLOB, JKSFILE, JKSBLOB, PEMKEY_FILE, PEMKEY_BLOB, PUBLIC_KEY_FILE, PUBLIC_KEY_BLOB, SSHPUBLIC_KEY_FILE, SSHPUBLIC_KEY_BLOB, P7BFILE, PPKFILE, XMLFILE, XMLBLOB, BCFKSFILE, BCFKSBLOB

Data Type

string

Default Value

"USER"

Remarks

This property determines the format and location of the key store used to provide the client certificate. Supported values include platform-specific and universal key store formats. The available values and their usage are:

USER - defaultFor Windows, this specifies that the certificate store is a certificate store owned by the current user. Note that this store type is not available in Java.
MACHINEFor Windows, this specifies that the certificate store is a machine store. Note that this store type is not available in Java.
PFXFILEThe certificate store is the name of a PFX (PKCS12) file containing certificates.
PFXBLOBThe certificate store is a string (base-64-encoded) representing a certificate store in PFX (PKCS12) format.
JKSFILEThe certificate store is the name of a Java key store (JKS) file containing certificates. Note that this store type is only available in Java.
JKSBLOBThe certificate store is a string (base-64-encoded) representing a certificate store in JKS format. Note that this store type is only available in Java.
PEMKEY_FILEThe certificate store is the name of a PEM-encoded file that contains a private key and an optional certificate.
PEMKEY_BLOBThe certificate store is a string (base64-encoded) that contains a private key and an optional certificate.
PUBLIC_KEY_FILEThe certificate store is the name of a file that contains a PEM- or DER-encoded public key certificate.
PUBLIC_KEY_BLOBThe certificate store is a string (base-64-encoded) that contains a PEM- or DER-encoded public key certificate.
SSHPUBLIC_KEY_FILEThe certificate store is the name of a file that contains an SSH-style public key.
SSHPUBLIC_KEY_BLOBThe certificate store is a string (base-64-encoded) that contains an SSH-style public key.
P7BFILEThe certificate store is the name of a PKCS7 file containing certificates.
PPKFILEThe certificate store is the name of a file that contains a PuTTY Private Key (PPK).
XMLFILEThe certificate store is the name of a file that contains a certificate in XML format.
XMLBLOBThe certificate store is a string that contains a certificate in XML format.
BCFKSFILEThe certificate store is the name of a file that contains an Bouncy Castle keystore.
BCFKSBLOBThe certificate store is a string (base-64-encoded) that contains a Bouncy Castle keystore.

CData Python Connector for XML

SSLClientCertPassword

Specifes the password required to access the TLS/SSL client certificate store. Use this property if the selected certificate store type requires a password for access.

Data Type

string

Default Value

""

Remarks

This property provides the password needed to open a password-protected certificate store. This property is necessary when using certificate stores that require a password for decryption, as is often recommended for PFX or JKS type stores.

If the certificate store type does not require a password, for example USER or MACHINE on Windows, this property can be left blank. Ensure that the password matches the one associated with the specified certificate store to avoid authentication errors.

CData Python Connector for XML

SSLClientCertSubject

Specifes the subject of the TLS/SSL client certificate to locate it in the certificate store. Use a comma-separated list of distinguished name fields, such as CN=www.server.com, C=US. The wildcard * selects the first certificate in the store.

Data Type

string

Default Value

"*"

Remarks

This property determines which client certificate to load based on its subject. The connector searches for a certificate that exactly matches the specified subject. If no exact match is found, the connector looks for certificates containing the value of the subject. If no match is found, no certificate is selected.

The subject should follow the standard format of a comma-separated list of distinguished name fields and values. For example, CN=www.server.com, OU=Test, C=US. Common fields include the following:

FieldMeaning
CNCommon Name. This is commonly a host name like www.server.com.
OOrganization
OUOrganizational Unit
LLocality
SState
CCountry
EEmail Address

Note: If any field contains special characters, such as commas, the value must be quoted. For example: CN="Example, Inc.", C=US.

CData Python Connector for XML

SSLMode

The authentication mechanism to be used when connecting to the FTP or FTPS server.

Possible Values

AUTOMATIC, NONE, IMPLICIT, EXPLICIT

Data Type

string

Default Value

"AUTOMATIC"

Remarks

If SSLMode is set to NONE, default plaintext authentication is used to log in to the server. If SSLMode is set to IMPLICIT, the SSL negotiation will start immediately after the connection is established. If SSLMode is set to EXPLICIT, the connector will first connect in plaintext, and then explicitly start SSL negotiation through a protocol command such as STARTTLS. If SSLMode is set to AUTOMATIC, if the remote port is set to the standard plaintext port of the protocol (where applicable), the component will behave the same as if SSLMode is set to EXPLICIT. In all other cases, SSL negotiation will be IMPLICIT.

  • AUTOMATIC
  • NONE
  • IMPLICIT
  • EXPLICIT

CData Python Connector for XML

SSLServerCert

Specifies the certificate to be accepted from the server when connecting using TLS/SSL.

Data Type

string

Default Value

""

Remarks

If you are using a TLS/SSL connection, use this property to specify the TLS/SSL certificate to be accepted from the server. If you specify a value for this property, all other certificates that are not trusted by the machine are rejected.

This property can take the following forms:

Description Example
A full PEM Certificate (example shortened for brevity) -----BEGIN CERTIFICATE-----
MIIChTCCAe4CAQAwDQYJKoZIhv......Qw==
-----END CERTIFICATE-----
A path to a local file containing the certificate C:\cert.cer
The public key (example shortened for brevity) -----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSq......AQAB
-----END RSA PUBLIC KEY-----
The MD5 Thumbprint (hex values can also be either space- or colon-separated) ecadbdda5a1529c58a1e9e09828d70e4
The SHA1 Thumbprint (hex values can also be either space- or colon-separated) 34a929226ae0819f2ec14b4a3d904f801cbb150d

Note: It is possible to use '*' to signify that all certificates should be accepted, but due to security concerns this is not recommended.

CData Python Connector for XML

SSH

This section provides a complete list of the SSH properties you can configure in the connection string for this provider.


PropertyDescription
SSHAuthModeThe authentication method used when establishing an SSH Tunnel to the service.
SSHClientCertA certificate to be used for authenticating the SSHUser.
SSHClientCertPasswordThe password of the SSHClientCert key if it has one.
SSHClientCertSubjectThe subject of the SSH client certificate.
SSHClientCertTypeThe type of SSHClientCert private key.
SSHUserThe SSH user.
SSHPasswordThe SSH password.
CData Python Connector for XML

SSHAuthMode

The authentication method used when establishing an SSH Tunnel to the service.

Possible Values

None, Password, Public_Key

Data Type

string

Default Value

"Password"

Remarks

  • None: No authentication is performed. The current SSHUser value is ignored, and the connection is logged in as anonymous.
  • Password: The connector uses the values of SSHUser and SSHPassword to authenticate the user.
  • Public_Key: The connector uses the values of SSHUser and SSHClientCert to authenticate the user. SSHClientCert must have a private key available for this authentication method to succeed.

CData Python Connector for XML

SSHClientCert

A certificate to be used for authenticating the SSHUser.

Data Type

string

Default Value

""

Remarks

SSHClientCert must contain a valid private key in order to use public key authentication. A public key is optional, if one is not included then the connector generates it from the private key. The connector sends the public key to the server and the connection is allowed if the user has authorized the public key.

The SSHClientCertType field specifies the type of the key store specified by SSHClientCert. If the store is password protected, specify the password in SSHClientCertPassword.

Some types of key stores are containers which may include multiple keys. By default the connector will select the first key in the store, but you can specify a specific key using SSHClientCertSubject.

CData Python Connector for XML

SSHClientCertPassword

The password of the SSHClientCert key if it has one.

Data Type

string

Default Value

""

Remarks

This property is required for SSH tunneling when using certificate-based authentication. If the SSH certificate is in a password-protected key store, provide the password using this property to access the certificate.

CData Python Connector for XML

SSHClientCertSubject

The subject of the SSH client certificate.

Data Type

string

Default Value

"*"

Remarks

When loading a certificate the subject is used to locate the certificate in the store.

If an exact match is not found, the store is searched for subjects containing the value of the property.

If a match is still not found, the property is set to an empty string, and no certificate is selected.

The special value "*" picks the first certificate in the certificate store.

The certificate subject is a comma separated list of distinguished name fields and values. For instance "CN=www.server.com, OU=test, C=US, E=support@cdata.com". Common fields and their meanings are displayed below.

FieldMeaning
CNCommon Name. This is commonly a host name like www.server.com.
OOrganization
OUOrganizational Unit
LLocality
SState
CCountry
EEmail Address

If a field value contains a comma it must be quoted.

CData Python Connector for XML

SSHClientCertType

The type of SSHClientCert private key.

Possible Values

USER, MACHINE, PFXFILE, PFXBLOB, JKSFILE, JKSBLOB, PEMKEY_FILE, PEMKEY_BLOB, PPKFILE, PPKBLOB, XMLFILE, XMLBLOB

Data Type

string

Default Value

"PEMKEY_FILE"

Remarks

This property can take one of the following values:

TypesDescriptionAllowed Blob Values
MACHINE/USER Blob values are not supported.
JKSFILE/JKSBLOB base64-only
PFXFILE/PFXBLOBA PKCS12-format (.pfx) file. Must contain both a certificate and a private key.base64-only
PEMKEY_FILE/PEMKEY_BLOBA PEM-format file. Must contain an RSA, DSA, or OPENSSH private key. Can optionally contain a certificate matching the private key.base64 or plain text.
PPKFILE/PPKBLOBA PuTTY-format private key created using the puttygen tool.base64-only
XMLFILE/XMLBLOBAn XML key in the format generated by the .NET RSA class: RSA.ToXmlString(true).base64 or plain text.

CData Python Connector for XML

SSHUser

The SSH user.

Data Type

string

Default Value

""

Remarks

The SSH user.

CData Python Connector for XML

SSHPassword

The SSH password.

Data Type

string

Default Value

""

Remarks

The SSH password.

CData Python Connector for XML

Firewall

This section provides a complete list of the Firewall properties you can configure in the connection string for this provider.


PropertyDescription
FirewallTypeSpecifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.
FirewallServerIdentifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.
FirewallPortSpecifies the TCP port to be used for a proxy-based firewall.
FirewallUserIdentifies the user ID of the account authenticating to a proxy-based firewall.
FirewallPasswordSpecifies the password of the user account authenticating to a proxy-based firewall.
CData Python Connector for XML

FirewallType

Specifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.

Possible Values

NONE, TUNNEL, SOCKS4, SOCKS5

Data Type

string

Default Value

"NONE"

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

Note: By default, the connector connects to the system proxy. To disable this behavior and connect to one of the following proxy types, set ProxyAutoDetect to false.

The following table provides port number information for each of the supported protocols.

Protocol Default Port Description
TUNNEL 80 The port where the connector opens a connection to XML. Traffic flows back and forth via the proxy at this location.
SOCKS4 1080 The port where the connector opens a connection to XML. SOCKS 4 then passes theFirewallUser value to the proxy, which determines whether the connection request should be granted.
SOCKS5 1080 The port where the connector sends data to XML. If the SOCKS 5 proxy requires authentication, set FirewallUser and FirewallPassword to credentials the proxy recognizes.

To connect to HTTP proxies, use ProxyServer and ProxyPort. To authenticate to HTTP proxies, use ProxyAuthScheme, ProxyUser, and ProxyPassword.

CData Python Connector for XML

FirewallServer

Identifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for XML

FirewallPort

Specifies the TCP port to be used for a proxy-based firewall.

Data Type

int

Default Value

0

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for XML

FirewallUser

Identifies the user ID of the account authenticating to a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for XML

FirewallPassword

Specifies the password of the user account authenticating to a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for XML

Proxy

This section provides a complete list of the Proxy properties you can configure in the connection string for this provider.


PropertyDescription
ProxyAutoDetectSpecifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.
ProxyServerIdentifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.
ProxyPortIdentifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.
ProxyAuthSchemeSpecifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.
ProxyUserProvides the username of a user account registered with the proxy server specified in the ProxyServer connection property.
ProxyPasswordSpecifies the password of the user specified in the ProxyUser connection property.
ProxySSLTypeSpecifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.
ProxyExceptionsSpecifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.
CData Python Connector for XML

ProxyAutoDetect

Specifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.

Data Type

bool

Default Value

true

Remarks

When this connection property is set to True, the connector checks your system proxy settings for existing proxy server configurations (no need to manually supply proxy server details).

This connection property takes precedence over other proxy settings. If you want to configure the connector to connect to a specific proxy server, set ProxyAutoDetect to False.

On Windows, the connector reads the proxy settings from the Internet Options in the registry, specifically the registry key HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\. On Windows 10 and later, this corresponds to the Proxy Settings found in the Windows Settings.

Note that these settings apply only to the current user of the machine. If you're running an application as a service, the connector does not read your own user's settings. You must instead manually supply the proxy settings in the connector's connection properties.

On Mac, the connector reads proxy settings from the system-configured CFNetwork settings.

On Linux, this property is unsupported, and is set to False by default.

To connect to an HTTP proxy, see ProxyServer. For other proxies, such as SOCKS or tunneling, see FirewallType.

CData Python Connector for XML

ProxyServer

Identifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.

Data Type

string

Default Value

""

Remarks

The connector only routes HTTP traffic through the proxy server specified in this connection property when ProxyAutoDetect is set to False.

If ProxyAutoDetect is set to True (the default), the connector instead routes HTTP traffic through the proxy server specified in your system proxy settings.

CData Python Connector for XML

ProxyPort

Identifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.

Data Type

int

Default Value

80

Remarks

The connector only routes HTTP traffic through the ProxyServer port specified in this connection property when ProxyAutoDetect is set to False.

If ProxyAutoDetect is set to True (the default), the connector instead routes HTTP traffic through the proxy server port specified in your system proxy settings.

For other proxy types, see FirewallType.

CData Python Connector for XML

ProxyAuthScheme

Specifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.

Possible Values

BASIC, DIGEST, NONE, NEGOTIATE, NTLM

Data Type

string

Default Value

"BASIC"

Remarks

Note: The connector only uses this ProxyAuthScheme when ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the authentication method specified in your system proxy settings.

Supported authentication types :

  • BASIC: The connector performs HTTP basic authentication.
  • DIGEST: The connector performs HTTP digest authentication.
  • NTLM: The connector retrieves an NTLM token.
  • NEGOTIATE: The connector retrieves an NTLM or Kerberos token based on the applicable protocol for authentication.
  • NONE: Signifies that the ProxyServer does not require authentication.

For all values other than NONE, you must also set the ProxyUser and ProxyPassword connection properties.

If you need to use another authentication type, such as SOCKS 5 authentication, see FirewallType.

CData Python Connector for XML

ProxyUser

Provides the username of a user account registered with the proxy server specified in the ProxyServer connection property.

Data Type

string

Default Value

""

Remarks

The ProxyUser and ProxyPassword connection properties are used to connect and authenticate against the HTTP proxy specified in ProxyServer.

After selecting one of the available authentication types in ProxyAuthScheme, set this property as follows:

ProxyAuthScheme Value Value to set for ProxyUser
BASIC The username of a user registered with the proxy server.
DIGEST The username of a user registered with the proxy server.
NEGOTIATE The username of a Windows user who is a valid user in the domain or trusted domain that the proxy server is part of, in the format user@domain or domain\user.
NTLM The username of a Windows user who is a valid user in the domain or trusted domain that the proxy server is part of, in the format user@domain or domain\user.
NONE Do not set the ProxyPassword connection property.

Note: The connector only uses this username if ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the username specified in your system proxy settings.

CData Python Connector for XML

ProxyPassword

Specifies the password of the user specified in the ProxyUser connection property.

Data Type

string

Default Value

""

Remarks

The ProxyUser and ProxyPassword connection properties are used to connect and authenticate against the HTTP proxy specified in ProxyServer.

After selecting one of the available authentication types in ProxyAuthScheme, set this property as follows:

ProxyAuthScheme Value Value to set for ProxyPassword
BASIC The password associated with the proxy server user specified in ProxyUser.
DIGEST The password associated with the proxy server user specified in ProxyUser.
NEGOTIATE The password associated with the Windows user account specified in ProxyUser.
NTLM The password associated with the Windows user account specified in ProxyUser.
NONE Do not set the ProxyPassword connection property.

For SOCKS 5 authentication or tunneling, see FirewallType.

Note: The connector only uses this password if ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the password specified in your system proxy settings.

CData Python Connector for XML

ProxySSLType

Specifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.

Possible Values

AUTO, ALWAYS, NEVER, TUNNEL

Data Type

string

Default Value

"AUTO"

Remarks

This property determines when to use SSL for the connection to the HTTP proxy specified by ProxyServer. You can set this connection property to the following values :

AUTODefault setting. If ProxyServer is set to an HTTPS URL, the connector uses the TUNNEL option. If ProxyServer is set to an HTTP URL, the component uses the NEVER option.
ALWAYSThe connection is always SSL enabled.
NEVERThe connection is not SSL enabled.
TUNNELThe connection is made through a tunneling proxy. The proxy server opens a connection to the remote host and traffic flows back and forth through the proxy.

CData Python Connector for XML

ProxyExceptions

Specifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.

Data Type

string

Default Value

""

Remarks

The ProxyServer is used for all addresses, except for addresses defined in this property. Use semicolons to separate entries.

Note: The connector uses the system proxy settings by default, without further configuration needed. If you want to explicitly configure proxy exceptions for this connection, set ProxyAutoDetect to False.

CData Python Connector for XML

Logging

This section provides a complete list of the Logging properties you can configure in the connection string for this provider.


PropertyDescription
LogfileSpecifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.
VerbositySpecifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.
LogModulesSpecifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.
MaxLogFileSizeSpecifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.
MaxLogFileCountSpecifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.
CData Python Connector for XML

Logfile

Specifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.

Data Type

string

Default Value

""

Remarks

This property specifies the location and name of the log file where the connector records its operations, including authentication events, query execution, and connection details. If the specified file does not exist, the connector creates it. Ensure that the user or the service running the connector has write access to the specified path or file. Without sufficient permissions, the log file is not created.

Sensitive information from the connection string, such as passwords and tokens, is automatically masked in the logs. However, sensitive information present in the data itself may not be masked.

If you specify a relative path for Logfile, and if the Location property is set, that directory is used as the base path for the log file.

Additional properties allow you to customize logging behavior:

CData Python Connector for XML

Verbosity

Specifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.

Data Type

string

Default Value

"1"

Remarks

This property defines the level of detail the connector includes in the log file. Higher verbosity levels increase the detail of the logged information, but may also result in larger log files and slower performance due to the additional data being captured.

The default verbosity level is 1, which is recommended for regular operation. Higher verbosity levels are primarily intended for debugging purposes. For more information on each level, refer to Logging.

When combined with the LogModules property, Verbosity can refine logging to specific categories of information.

CData Python Connector for XML

LogModules

Specifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.

Data Type

string

Default Value

""

Remarks

The connector writes details about each operation it performs into the logfile specified by the Logfile connection property.

Each of these logged operations are assigned to a themed category called a module, and each module has a corresponding short code used to labels individual connector operations as belonging to that module.

When this connection property is set to a semicolon-separated list of module codes, only operations belonging to the specified modules are written to the logfile. Note that this only affects which operations are logged moving forward and doesn't retroactively alter the existing contents of the logfile. For example: INFO;EXEC;SSL;META;

By default, logged operations from all modules are included.

You can explicitly exclude a module by prefixing it with a "-". For example: -HTTP

To apply filters to submodules, identify them with the syntax <module name>.<submodule name>. For example, the following value causes the connector to only log actions belonging to the HTTP module, and further refines it to exclude actions belonging to the Res submodule of the HTTP module: HTTP;-HTTP.Res

Note that the logfile filtering triggered by the Verbosity connection property takes precedence over the filtering imposed by this connection property. This means that operations of a higher verbosity level than the level specified in the Verbosity connection property are not printed in the logfile, even if they belong to one of the modules specified in this connection property.

The available modules and submodules are:

Module Name Module Description Submodules
INFO General Information. Includes the connection string, product version (build number), and initial connection messages.
  • Connec – Information related to creating or destroying connections.
  • Messag – Generic label for messages pertaining to connections, the connection string, and product version. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
EXEC Query Execution. Includes execution messages for user-written SQL queries, parsed SQL queries, and normalized SQL queries. Success/failure messages for queries and query pages appear here as well.
  • Messag – Messages pertaining to query execution. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Normlz – Query normalization steps. Query normalization is when the product takes the user-submitted query and rewrites the query to get the same results with optimal performance.
  • Origin – This label applies to any messages recording a user's original query (the exact, unaltered, non-normalized query executed by the user).
  • Page – Messages related to query paging.
  • Parsed – Query parsing steps. Parsing is the process of converting the user-submitted query into a standardized format for easier processing.
HTTP HTTP protocol messages. Includes HTTP requests/responses (including POST messages), as well as Kerberos related messages.
  • KERB – HTTP requests related to Kerberos.
  • Messag – Messages pertaining to HTTP protocols. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Unpack – This label applies to messages about zipped data being returned from the service API and unpacked by the product.
  • Res – Messages containing HTTP responses.
  • Req – Messages containing HTTP requests.
WSDL Messages pertaining to the generation of WSDL/XSD files.
SSL SSL certificate messages.
  • Certif – Messages pertaining to SSL certificates.
AUTH Authentication related failure/success messages.
  • Messag – Messages pertaining to authentication. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • OAuth – Messages related to OAuth authentication.
  • Krbros – Kerberos-related authentication messages.
SQL Includes SQL transactions, SQL bulk transfer messages, and SQL result set messages.
  • Bulk – Messages pertaining to bulk query execution.
  • Cache – Messages related to reading row data from and writing row data to the product's cache for better performance.
  • Messag – Messages pertaining to SQL transactions. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • ResSet – Query resultsets.
  • Transc – Messages related to handling transactions, including information about the number of jobs executed and backup table handling.
META Metadata cache and schema messages.
  • Cache – Messages related to reading from and modifying column and table definitions in the product's cache for better performance.
  • Schema – Messages related to retrieving metadata from or modifying the service schema.
  • MemSto – Messages related to writing to or reading from in-memory metadata cache.
  • Storag – Messages relating to storing metadata on disk or in an external data store, rather than in memory.
FUNC Information related to executing SQL functions.
  • Errmsg – Error messages related to executing SQL functions.
TCP Incoming and outgoing raw bytes on TCP transport layer messages.
  • Send – Raw data sent via the TCP protocol.
  • Receiv – Raw data received via the TCP protocol.
FTP Messages pertaining to the File Transfer Protocol.
  • Info – Status messages related to communication in the FTP protocol.
  • Client – Messages related to actions taken by the FTP client (the product) during FTP communication.
  • Server – Messages related to actions taken by the FTP server during FTP communication.
SFTP Messages pertaining to the Secure File Transfer Protocol.
  • Info – Status messages related to communication in the SFTP protocol.
  • To_Server – Messages related to actions taken by the SFTP client (the product) during SFTP communication.
  • From_Server – Messages related to actions taken by the SFTP server during SFTP communication.
POP Messages pertaining to data transferred via the Post Office Protocol.
  • Client – Messages related to actions taken by the POP client (the product) during POP communication.
  • Server – Messages related to actions taken by the POP server during POP communication.
  • Status – Status messages related to communication in the POP protocol.
SMTP Messages pertaining to data transferred via the Simple Mail Transfer Protocol.
  • Client – Messages related to actions taken by the SMTP client (the product) during SMTP communication.
  • Server – Messages related to actions taken by the SMTP server during SMTP communication.
  • Status – Status messages related to communication in the SMTP protocol.
CORE Messages relating to various internal product operations not covered by other modules.
DEMN Messages related to SQL remoting.
STRG Messages related to reading from and writing to raw files in formats like CSV and JSON.
CLJB Messages about bulk data uploads (cloud job).
  • Commit – Submissions for bulk data uploads.
SRCE Miscellaneous messages produced by the product that don't belong in any other module.
TRANCE Advanced messages concerning low-level product operations.

CData Python Connector for XML

MaxLogFileSize

Specifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.

Data Type

string

Default Value

"100MB"

Remarks

For values lower than 100 KB, the connector uses 100 KB as the minimum allowable size.

To control the total number of log files retained, use the MaxLogFileCount property in conjunction with this property. Together, these properties allow you to manage the size and retention of log files effectively.

CData Python Connector for XML

MaxLogFileCount

Specifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.

Data Type

int

Default Value

-1

Remarks

Each log file name includes the date and time for easier identification.

This property accepts the following values:

  • A value of 2 or higher sets the maximum number of log files retained.
  • A value of 1 retains only one log file. When it reaches the maximum size, the file is deleted and replaced by a new one, leaving no history beyond the current log.
  • A value of 0 or negative indicates no limit on the number of log files, and logging continues indefinitely.

To manage log file size, use the MaxLogFileSize property. The two properties work together to control the size and retention of log files in the logging folder.

CData Python Connector for XML

Schema

This section provides a complete list of the Schema properties you can configure in the connection string for this provider.


PropertyDescription
LocationSpecifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.
BrowsableSchemasOptional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .
TablesOptional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .
ViewsOptional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .
PushAttributesSpecifies whether to push any identified attributes as columns.
FlattenArraysSpecifies how many elements of nested XML arrays are flattened into individual columns.
FlattenObjectsSpecifies whether object properties are flattened into individual columns.
QualifyColumnsSpecifies how column names are qualified to ensure uniqueness in the generated schema.
CData Python Connector for XML

Location

Specifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.

Data Type

string

Default Value

"%APPDATA%\\CData\\XML Data Provider\\Schema"

Remarks

The Location property is only needed if you want to either customize definitions (for example, change a column name, ignore a column, etc.) or extend the data model with new tables, views, or stored procedures.

If left unspecified, the default location is %APPDATA%\\CData\\XML Data Provider\\Schema, where %APPDATA% is set to the user's configuration directory:

Platform %APPDATA%
Windows The value of the APPDATA environment variable
Linux ~/.config

CData Python Connector for XML

BrowsableSchemas

Optional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .

Data Type

string

Default Value

""

Remarks

Listing all available database schemas can take extra time, thus degrading performance. Providing a list of schemas in the connection string saves time and improves performance.

CData Python Connector for XML

Tables

Optional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .

Data Type

string

Default Value

""

Remarks

Listing all available tables from some databases can take extra time, thus degrading performance. Providing a list of tables in the connection string saves time and improves performance.

If there are lots of tables available and you already know which ones you want to work with, you can use this property to restrict your viewing to only those tables. To do this, specify the tables you want in a comma-separated list. Each table should be a valid SQL identifier with any special characters escaped using square brackets, double-quotes or backticks. For example, Tables=TableA,[TableB/WithSlash],WithCatalog.WithSchema.`TableC With Space`.

Note: If you are connecting to a data source with multiple schemas or catalogs, you must specify each table you want to view by its fully qualified name. This avoids ambiguity between tables that may exist in multiple catalogs or schemas.

CData Python Connector for XML

Views

Optional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .

Data Type

string

Default Value

""

Remarks

Listing all available views from some databases can take extra time, thus degrading performance. Providing a list of views in the connection string saves time and improves performance.

If there are lots of views available and you already know which ones you want to work with, you can use this property to restrict your viewing to only those views. To do this, specify the views you want in a comma-separated list. Each view should be a valid SQL identifier with any special characters escaped using square brackets, double-quotes or backticks. For example, Views=ViewA,[ViewB/WithSlash],WithCatalog.WithSchema.`ViewC With Space`.

Note: If you are connecting to a data source with multiple schemas or catalogs, you must specify each view you want to examine by its fully qualified name. This avoids ambiguity between views that may exist in multiple catalogs or schemas.

CData Python Connector for XML

PushAttributes

Specifies whether to push any identified attributes as columns.

Data Type

bool

Default Value

true

Remarks

When this property is set to true (default), the connector pushes XML attributes as individual columns and included in any aggregate values.

When this property is set to false, attributes are not pushed as columns or in aggregates (for example the connector strips them from the output).

CData Python Connector for XML

FlattenArrays

Specifies how many elements of nested XML arrays are flattened into individual columns.

Data Type

string

Default Value

""

Remarks

When this property is not set, nested arrays are returned as XML strings.

When this property is set to a numeric value, the connector flattens nested XML arrays by returning the specified number of elements as separate columns. The element index is appended to each column name.

The following example shows how a nested array is flattened:

<languages>FLOW-MATIC</languages>
<languages>LISP</languages>
<languages>COBOL</languages>
When FlattenArrays is set to -1, all elements in nested arrays are flattened into individual columns.

Column NameColumn Value
languages.0FLOW-MATIC

Flattening is recommended only for arrays that are expected to be short, as large arrays can significantly increase the number of columns and reduce performance.

This property is useful for converting nested XML arrays into individual columns.

CData Python Connector for XML

FlattenObjects

Specifies whether object properties are flattened into individual columns.

Data Type

bool

Default Value

true

Remarks

When FlattenObjects is set to true, the connector flattens object properties into separate columns. An element is considered an object if it appears only once at its level in the XML structure. If an element repeats at the same level, it is considered an array.

When this property is set to false, objects nested within arrays are returned as XML strings instead of flattened columns.

The following example shows how nested objects are flattened at connection time:

<grades>
  <grade>A</grade>
  <score>2</score>
</grades>
<grades>
  <grade>A</grade>
  <score>6</score>
</grades>
<grades>
  <grade>A</grade>
  <score>10</score>
</grades>
<grades>
  <grade>A</grade>
  <score>9</score>
</grades>
<grades>
  <grade>B</grade>
  <score>14</score>
</grades>
To generate the column name, the connector concatenates the property name onto the object name with a dot. When FlattenObjects is set to true and FlattenArrays is set to 1, the preceding array is flattened into the following table:

Column NameColumn Value
grades.0.gradeA
grades.0.score2

Flattening objects simplifies querying nested data but can increase the number of columns when applied to deeply nested structures.

This property is useful for controlling how nested objects are represented in flattened XML data models.

CData Python Connector for XML

QualifyColumns

Specifies how column names are qualified to ensure uniqueness in the generated schema.

Possible Values

None, Parent, Full

Data Type

string

Default Value

"None"

Remarks

By default the connector qualifies column names only as much as necessary to make them unique. For example, given the following XML document, the connector produces the columns id referring to the company id and employee.id.

<company>
  <id>Smith Holdings</id>
  <employees>
    <employee>
      <id>George Smith</id>
    </employee>
    <employee>
      <id>Mike Johnson</id>
    </employee>
  </employees>
</company>

When this option is set to Parent, the connector uses a similar procedure to the one above. However, the connector will always qualify columns by one level so that their table name is included, even if the column name is unique. For example, the above document would generate the columns company.id and employee.id because both are unique when including their parent.

When this option is set to Full, the connector will qualify all column names with their full XPath. This generates longer column names but ensures that it is clear where each column name comes from within the document. For the example above, the connector generates the columns company.id and company.employees.employee.id.

CData Python Connector for XML

Caching

This section provides a complete list of the Caching properties you can configure in the connection string for this provider.


PropertyDescription
AutoCacheSpecifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.
CacheProviderThe namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.
CacheDriverThe driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.
CacheConnectionSpecifies the connection string for the specified cache database.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceNotes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.
OfflineGets the data from the specified cache database instead of live XML data.
CacheMetadataDetermines whether the provider caches table metadata to a file-based cache database.
CData Python Connector for XML

AutoCache

Specifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, the connector automatically caches the contents of tables targeted by SELECT queries. The content of these tables is cached to the cache database specified by the CacheConnection and CacheProvider connection properties.

See Also

For additional information, see:

  • CacheMetadata: With CacheMetadata enabled, all retrieved metadata is mirrored in the cache database. This means that any subsequent attempts by the connector to discover metadata are much faster, as this metadata is then read directly from the cache database, without needing to spend time requesting metadata from XML.
  • Explicitly Caching Data: This topic provides examples for using AutoCache in Offline mode.
  • CACHE Statements: You can use the CACHE statement to explicitly cache the content of any table targeted by a SELECT query.

CData Python Connector for XML

CacheProvider

The namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.

Data Type

string

Default Value

""

Remarks

You can cache to ADO.NET providers saved in your ADO.NET global assembly cache (GAC).

CData ADO.NET providers automatically register themselves with the GAC during installation, so you don't need to do so manually.

Third-party ADO.NET providers may or may not automatically register themselves with the GAC during installation. If you want to cache to a third-party ADO.NET provider, consult the documentation for that provider to determine what steps (if any) you must take to register them with the GAC. Once they have been registered, you can supply their namespace in this connection property.

You must also set the CacheConnection connection property to provide a connection string for the specified ADO.NET provider.

The following sections show connection examples and address other requirements for several popular database providers. Refer to CacheConnection for more information on typical connection properties.

SQLite

You can use the Microsoft ADO.NET Provider for SQLite to cache to SQLite databases.

CacheProvider=Microsoft.Data.Sqlite;CacheConnection='DataSource=C:\\Users\\Public\\cache.db;'DataModel=Relational;URI=C:\people.xml

MySQL

To cache to MySQL, you can use the CData ADO.NET Provider for MySQL:
Cache Provider=System.Data.CData.MySQL;Cache Connection='Server=localhost;Port=3306;Database=cache;User=root;Password=123456';User=myUser;Password=myPassword;Security Token=myToken;

SQL Server

You can use the Microsoft .NET Framework Provider for SQL Server, included in the .NET Framework, to cache to SQL Server:

Cache Provider=System.Data.SqlClient;Cache Connection="Server=MyMACHINE\MyInstance;Database=SQLCACHE;User Id=root;Password=admin";DataModel=Relational;URI=C:\people.xml

Oracle

To cache to Oracle, you can use the Oracle Data Provider for .NET, as shown in the following example:

Cache Provider=Oracle.DataAccess.Client;Cache Connection='User Id=scott;Password=tiger;Data Source=ORCL';DataModel=Relational;URI=C:\people.xml

The Oracle Data Provider for .NET also requires the Oracle Database Client. When you download the Oracle Database Client, ensure that its bitness matches the bitness of your machine. When you install, select either the Runtime or Administrator installation type. The Instant Client is not sufficient.

PostgreSQL

To cache to PostgreSQL, you can use the CData ADO.NET Provider for PostgreSQL:
Cache Provider=System.Data.CData.PostgreSQL;Cache Connection='Server=localhost;Port=5432;Database=cache;User=postgres;Password=123456';User=myUser;Password=myPassword;Security Token=myToken;

CData Python Connector for XML

CacheDriver

The driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.

Data Type

string

Default Value

""

Remarks

You can cache to any database for which you have a JDBC driver, including CData JDBC drivers.

Note: You must add the JAR file of the specified JDBC driver to the classpath. For CData JDBC drivers, you can find this JAR file in the "lib" subfolder of that driver's installation directory.

You must also set the CacheConnection connection property to provide a connection string for the specified JDBC driver.

For Linux systems and macOS, you need to create a config.ini file on the installation path of the driver (site-packages/cdata). The config.ini file has the following format (the driver and the path of the JDBC driver):

[salesforce.cpython-38-x86_64-linux-gnu.so]
CLASSPATH = /home/usrname/Downloads/lib/cdata.jdbc.postgresql.jar

Examples

The following examples show how to cache to several major databases. For more information on the JDBC URL syntax and typical connection properties, see CacheConnection.

Derby and Java DB

Java DB is the Oracle distribution of Derby. You must add the Derby JDBC driver's JAR file, derbytools.jar, to your classpath to cache to Java DB.

The Derby JDBC driver's JAR file is bundled in db-derby-10.17.1.0-bin.zip, which you can download from this page. You can find derbytools.jar in the "lib" subfolder of this zip file.

After adding derbytools.jar to the classpath, you can cache to a Java DB database as follows:

jdbc:xml:CacheDriver=org.apache.derby.jdbc.EmbeddedDriver;CacheConnection='jdbc:derby:sample';DataModel=Relational;URI=C:\people.xml
To cache to an in-memory database, use a JDBC URL like the following:
jdbc:xml:CacheDriver=org.apache.derby.jdbc.EmbeddedDriver;CacheConnection='jdbc:derby:memory';DataModel=Relational;URI=C:\people.xml

SQLite

The following is a JDBC URL for the SQLite JDBC driver:

jdbc:xml:CacheDriver=org.sqlite.JDBC;CacheConnection='jdbc:sqlite:C:/Temp/sqlite.db';DataModel=Relational;URI=C:\people.xml

MySQL

The following is a JDBC URL for the CData JDBC Driver for MySQL:

  jdbc:xml:Cache Driver=cdata.jdbc.mysql.MySQLDriver;Cache Connection='jdbc:mysql:Server=localhost;Port=3306;Database=cache;User=root;Password=123456';DataModel=Relational;URI=C:\people.xml
  

SQL Server

The following JDBC URL uses the Microsoft JDBC Driver for SQL Server:

jdbc:xml:Cache Driver=com.microsoft.sqlserver.jdbc.SQLServerDriver;Cache Connection='jdbc:sqlserver://localhost\sqlexpress:7437;user=sa;password=123456;databaseName=Cache';DataModel=Relational;URI=C:\people.xml

Oracle

The following is a JDBC URL for the Oracle Thin Client:

jdbc:xml:Cache Driver=oracle.jdbc.OracleDriver;CacheConnection='jdbc:oracle:thin:scott/tiger@localhost:1521:orcldb';DataModel=Relational;URI=C:\people.xml
NOTE: If using a version of Oracle older than 9i, the cache driver will instead be oracle.jdbc.driver.OracleDriver .

PostgreSQL

The following JDBC URL uses the official PostgreSQL JDBC driver:

jdbc:xml:CacheDriver=cdata.jdbc.postgresql.PostgreSQLDriver;CacheConnection='jdbc:postgresql:User=postgres;Password=admin;Database=postgres;Server=localhost;Port=5432;';DataModel=Relational;URI=C:\people.xml

CData Python Connector for XML

CacheConnection

Specifies the connection string for the specified cache database.

Data Type

string

Default Value

""

Remarks

The target cache database is determined by a combination of this connection property and the CacheProvider connection property. Both properties are required to use the specified cache database.

The connection string specified in this connection property is passed directly to the specified in the CacheProvider connection property. Consult the documentation for the specified for more information on its available connection properties.

Examples of common cache database settings can be found below.

SQLite

MySQL

The following are typical connection properties:

  • Server: The IP address or domain name of the server hosting the MySQL database that you want to cache to.
  • Port: The port on the specified server where your MySQL instance is running.
  • Database: The name of the MySQL database that you want to cache to. Must match the name of a MySQL database hosted on the specified server.
  • User: The username of a user registered with the selected MySQL database.
  • Password: The password associated with the specified MySQL user.

SQL Server

The following are typical SQL Server connection properties:

  • Server: The name or network address of the computer running SQL Server. To connect to a named instance instead of the default instance, specify the host name and the instance name, separated by a backslash.
  • Port: The port on the specified server where your SQL Server instance is running.
  • Database: The name of the SQL Server database you want to cache to. Must match the name of a SQL Server database hosted on the specified server.
  • Integrated Security: To use the current Windows account for authentication, set this option to True. To authenticate with User and Password instead, set this option to False.
  • User Id: The username of a user registered with the selected SQL Server database. This property is only needed if you are not using integrated security.
  • Password: The password associated with the specified SQL Server user. This property is only needed if you are not using integrated security.

Oracle

The following are typical connection properties:

  • Data Source: The connect descriptor that identifies the Oracle database. This can be a TNS connect descriptor, an Oracle Net Services name that resolves to a connect descriptor, or, after version 11g, an Easy Connect naming (the host name of the Oracle server with an optional port and service name).

  • User Id: The username of a user registered with the selected Oracle database.
  • Password: The password associated with the specified Oracle user.

PostgreSQL

The following are typical connection properties:

  • Host: The address of the server hosting the PostgreSQL database.
  • Port: The port on the specified host server where your PostgreSQL database is hosted.
  • Database: The name of the PostgreSQL database you want to cache to. Must match the name of a PostgreSQL database hosted on the specified server.
  • User name: The username of a user registered with the selected PostgreSQL database.
  • Password: The password associated with the specified user.

CData Python Connector for XML

CacheLocation

Specifies the path to the cache when caching to a file.

Data Type

string

Default Value

"%APPDATA%\\CData\\XML Data Provider"

Remarks

The CacheLocation is a simple, file-based cache.

If left unspecified, the default location is %APPDATA%\\CData\\XML Data Provider, where %APPDATA% is set to the user's configuration directory:

Platform %APPDATA%
Windows The value of the APPDATA environment variable
Linux ~/.config

See Also

  • AutoCache: Set to implicitly create and maintain a cache for later offline use.
  • CacheMetadata: Set to persist the XML catalog in CacheLocation.

CData Python Connector for XML

CacheTolerance

Notes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.

Data Type

int

Default Value

600

Remarks

When you execute a query for tables in the cache, the connector checks the time elapsed since the last update to the cache.

If the last update to the cache is older than the value of this connection property (measured in seconds), the connector refreshes the cache.

Otherwise, the connector returns data directly from the cache.

CData Python Connector for XML

Offline

Gets the data from the specified cache database instead of live XML data.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, all queries execute against the cache database instead of the live XML data.

In this mode, some SQL operations like INSERT, UPDATE, DELETE, and CACHE are disabled.

CData Python Connector for XML

CacheMetadata

Determines whether the provider caches table metadata to a file-based cache database.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, as you execute queries, table metadata in the XML catalog is cached to the cache database specified by CacheConnection and CacheProvider, or, if those connection properties are not set, to the user's home directory.

The location of your home directory varies by platform:

PlatformHome Directory
Windows %APPDATA%\\CData\\XML Data Provider
Mac ~/Library/Application Support/CData/XML Data Provider
Unix ~/.config/CData/XML Data Provider

A table's metadata is retrieved only once, when the table is queried for the first time.

When to Use CacheMetadata

When there are a large number of XML tables and columns for the connector to retrieve during metadata discovery, the connector may take a while to list all table metadata.

You may experience slow metadata retrieval when:

  • Your XML instance naturally has a large table count.
  • The connector has been configured, via its connection properties, to discover more tables than it would under its default configuration.
  • You make many short-lived connections to the connector.
With CacheMetadata enabled, all retrieved metadata is mirrored in the cache database. This means that any subsequent attempts by the connector to discover metadata are much faster, as this metadata is then read directly from the cache database, without needing to spend time requesting metadata from XML.

When Not to Use CacheMetadata

The connector automatically persists metadata in memory for up to an hour when you first discover the metadata for a table or view, so CacheMetadata is generally not necessary.

CacheMetadata is not ideal in scenarios where you are working with volatile metadata. The first time you query a table, the connector caches its metadata to the cache database file. This cache is not dynamically updated to reflect updates to the table schema, so you must delete and rebuild the cache database file to pick up new, changed, or deleted columns.

CData Python Connector for XML

Miscellaneous

This section provides a complete list of the Miscellaneous properties you can configure in the connection string for this provider.


PropertyDescription
AWSCertificateThe absolute path to the certificate file or the certificate content in PEM format encoded in base64.
AWSCertificatePasswordThe password for the certificate if applicable, otherwise leave blank.
AWSCertificateTypeThe type of AWSCertificate .
AWSPrivateKeyThe absolute path to the private key file or the private key content in PEM format encoded in base64.
AWSPrivateKeyPasswordThe password for the private key if it is encrypted, otherwise leave blank.
AWSPrivateKeyTypeThe type of AWSPrivateKey .
AWSProfileARNProfile to pull policies from.
AWSSessionDurationDuration, in seconds, for the resulting session.
AWSTrustAnchorARNTrust anchor to use for authentication.
BackwardsCompatibilityModeSpecifies whether the provider operates in XML compatibility mode using the behavior and feature set from the 2017 release.
CharsetSpecifies the session character set for encoding and decoding character data transferred to and from the XML file. The default value is UTF-8.
ClientCultureThis property can be used to specify the format of data (e.g., currency values) that is accepted by the client application. This property can be used when the client application does not support the machine's culture settings. For example, Microsoft Access requires 'en-US'.
CultureThis setting can be used to specify culture settings that determine how the provider interprets certain data types that are passed into the provider. For example, setting Culture='de-DE' will output German formats even on an American machine.
CustomHeadersSpecifies additional HTTP headers to append to the request headers created from other properties, such as ContentType and From. Use this property to customize requests for specialized or nonstandard APIs.
CustomURLParamsA string of custom URL parameters to be included with the HTTP request, in the form field1=value1&field2=value2&field3=value3.
ExcludeFilesComma-separated list of file extensions to exclude from the set of the files modeled as tables.
ExcludeStorageClassesA comma seperated list of storage classes to ignore.
FlattenRowLimitSpecifies the maximum number of rows that can be generated from a single flattened element.
FolderIdThe ID of a folder in Google Drive. If set, the resource location specified by the URI is relative to the Folder ID for all operations.
GenerateSchemaFilesIndicates the user preference as to when schemas should be generated and saved.
IncludeDropboxTeamResourcesIndicates if you want to include Dropbox team files and folders.
IncludeFilesComma-separated list of file extensions to include into the set of the files modeled as tables.
IncludeItemsFromAllDrivesWhether Google Drive shared drive items should be included in results. If not present or set to false, then shared drive items are not returned.
MaxRowsSpecifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.
MetadataDiscoveryURIIdentifies a file to read when aggregating multiple files into a single table, to specify the schema of the aggregated table.
OtherSpecifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.
PagesizeSpecifies the maximum number of records per page the provider returns when requesting data from XML.
PathSeparatorDetermines the character used to replace file path separators when generating table names.
PseudoColumnsSpecifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.
ReadonlyToggles read-only access to XML from the provider.
RowScanDepthSpecifies the number of rows the provider scans when dynamically determining table columns.
RTKSpecifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.
TimeoutSpecifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.
TypeDetectionSchemeSpecifies how the provider determines the data types of columns in the generated schema.
URISeparatorSpecifies the delimiter used to separate multiple values in the URI property.
UserDefinedViewsSpecifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.
CData Python Connector for XML

AWSCertificate

The absolute path to the certificate file or the certificate content in PEM format encoded in base64.

Data Type

string

Default Value

""

Remarks

The absolute path to the certificate file or the certificate file content in PEM format encoded in base64, depending on the value of AWSCertificateType.

CData Python Connector for XML

AWSCertificatePassword

The password for the certificate if applicable, otherwise leave blank.

Data Type

string

Default Value

""

Remarks

The password for the certificate if applicable, otherwise leave blank.

CData Python Connector for XML

AWSCertificateType

The type of AWSCertificate .

Possible Values

PEM_FILE, PEM_BLOB

Data Type

string

Default Value

"PEM_FILE"

Remarks

This property can take one of the following values:

PEM_FILEAbsolute path to a certificate file in PEM format.
PEM_BLOBA string (base64-encoded) representing a PEM-encoded certificate.

CData Python Connector for XML

AWSPrivateKey

The absolute path to the private key file or the private key content in PEM format encoded in base64.

Data Type

string

Default Value

""

Remarks

The absolute path to the private key file or the private key file content in PEM format encoded in base64, depending on the value of AWSPrivateKeyType.

CData Python Connector for XML

AWSPrivateKeyPassword

The password for the private key if it is encrypted, otherwise leave blank.

Data Type

string

Default Value

""

Remarks

The password for the private key if it is encrypted, otherwise leave blank.

CData Python Connector for XML

AWSPrivateKeyType

The type of AWSPrivateKey .

Possible Values

PEM_FILE, PEM_BLOB

Data Type

string

Default Value

"PEM_FILE"

Remarks

This property can take one of the following values:

PEM_FILEAbsolute path to a private key file in PEM format.
PEM_BLOBA string (base64-encoded) representing a PEM-encoded private key.

CData Python Connector for XML

AWSProfileARN

Profile to pull policies from.

Data Type

string

Default Value

""

Remarks

Profile to pull policies from.

CData Python Connector for XML

AWSSessionDuration

Duration, in seconds, for the resulting session.

Data Type

int

Default Value

3600

Remarks

Duration, in seconds, for the resulting session. Default: 3600 seconds.

CData Python Connector for XML

AWSTrustAnchorARN

Trust anchor to use for authentication.

Data Type

string

Default Value

""

Remarks

Trust anchor to use for authentication.

CData Python Connector for XML

BackwardsCompatibilityMode

Specifies whether the provider operates in XML compatibility mode using the behavior and feature set from the 2017 release.

Data Type

bool

Default Value

false

Remarks

When this property is set to true, the connector uses the XML parsing behavior and feature set available in the 2017 version.

When this property is set to false (default), the connector enables the enhanced flattening features introduced in later versions. These includes DataModel, FlattenArrays, and FlattenObjects as well as the dynamic flattening of tables and columns via a SQL query.

This property is useful for maintaining compatibility with legacy integrations that rely on the original XML schema behavior.

CData Python Connector for XML

Charset

Specifies the session character set for encoding and decoding character data transferred to and from the XML file. The default value is UTF-8.

Data Type

string

Default Value

"UTF-8"

Remarks

Specifies the session character set for encoding and decoding character data transferred to and from the XML file. The default value is UTF-8.

CData Python Connector for XML

ClientCulture

This property can be used to specify the format of data (e.g., currency values) that is accepted by the client application. This property can be used when the client application does not support the machine's culture settings. For example, Microsoft Access requires 'en-US'.

Data Type

string

Default Value

""

Remarks

This option affects the format of connector output. To specify the format that defines how input should be interpreted, use the Culture option. By default the connector uses the current locale settings of the machine to interpret input and format output.

CData Python Connector for XML

Culture

This setting can be used to specify culture settings that determine how the provider interprets certain data types that are passed into the provider. For example, setting Culture='de-DE' will output German formats even on an American machine.

Data Type

string

Default Value

""

Remarks

This property affects the connector input. To interpret values in a different cultural format, use the Client Culture property. By default the connector uses the current locale settings of the machine to interpret input and format output.

CData Python Connector for XML

CustomHeaders

Specifies additional HTTP headers to append to the request headers created from other properties, such as ContentType and From. Use this property to customize requests for specialized or nonstandard APIs.

Data Type

string

Default Value

""

Remarks

Use this property to add custom headers to HTTP requests sent by the connector.

This property is useful when fine-tuning requests to interact with APIs that require additional or nonstandard headers. Headers must follow the format "header: value" as described in the HTTP specifications and each header line must be separated by the carriage return and line feed (CRLF) characters. Important: Use caution when setting this property. Supplying invalid headers may cause HTTP requests to fail.

CData Python Connector for XML

CustomURLParams

A string of custom URL parameters to be included with the HTTP request, in the form field1=value1&field2=value2&field3=value3.

Data Type

string

Default Value

""

Remarks

This property enables you to specify custom query string parameters that are included with the HTTP request. The parameters must be encoded as a query string in the form field1=value1&field2=value2&field3=value3, where each value is URL encoded. URL encoding converts the characters in the string that can be transmitted over the internet as follows:

  • Non-ASCII characters are replaced with their equivalent in the form of a "%" followed by two hexadecimal digits.
  • Spaces are replaced with either a plus sign (+) or %20.

CData Python Connector for XML

ExcludeFiles

Comma-separated list of file extensions to exclude from the set of the files modeled as tables.

Data Type

string

Default Value

""

Remarks

It is also possible to specify datetime filters. We currently support CreatedDate and ModifiedDate. All extension filters are evaluated in disjunction (using OR operator), and then the resulting filter is evaluated in conjunction (using AND operator) with the datetime filters.

Examples:

ExcludeFiles="TXT,CreatedDate<='2020-11-26T07:39:34-05:00'"
ExcludeFiles="TXT,ModifiedDate<=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 50, 000)"
ExcludeFiles="ModifiedDate>=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 49, 000),ModifiedDate<=CURRENT_TIMESTAMP()"

CData Python Connector for XML

ExcludeStorageClasses

A comma seperated list of storage classes to ignore.

Data Type

string

Default Value

""

Remarks

This can be used to refine the type of Files to be retrieved from Amazon S3. For example setting this property to GLACIER will ignore all files of storage class GLACIER. Possible values are:

  • STANDARD
  • STANDARD_IA
  • ONEZONE_IA
  • INTELLIGENT_TIERING
  • REDUCED_REDUNDANCY
  • GLACIER_IR
  • GLACIER
  • DEEP_ARCHIVE

CData Python Connector for XML

FlattenRowLimit

Specifies the maximum number of rows that can be generated from a single flattened element.

Data Type

int

Default Value

250000

Remarks

When flattening large or deeply nested XML data, the connector must generate multiple rows for each flattened element. If the number of rows grows excessively, it can cause high memory usage or query failures.

When this property is set, the connector verifies that the number of rows produced by a single flattened element does not exceed the specified limit. If the expected output exceeds this limit, the query fails and an error is reported instead of attempting to generate all rows.

This property is useful for preventing excessive memory consumption and ensuring predictable performance when flattening complex XML documents.

CData Python Connector for XML

FolderId

The ID of a folder in Google Drive. If set, the resource location specified by the URI is relative to the Folder ID for all operations.

Data Type

string

Default Value

""

Remarks

The ID of a folder in Google Drive. If set, the resource location specified by the URI is relative to the Folder ID for all operations.

CData Python Connector for XML

GenerateSchemaFiles

Indicates the user preference as to when schemas should be generated and saved.

Possible Values

Never, OnUse, OnStart, OnCreate

Data Type

string

Default Value

"Never"

Remarks

This property outputs schemas to .rsd files in the path specified by Location.

Available settings are the following:

  • Never: A schema file will never be generated.
  • OnUse: A schema file will be generated the first time a table is referenced, provided the schema file for the table does not already exist.
  • OnStart: A schema file will be generated at connection time for any tables that do not currently have a schema file.
  • OnCreate: A schema file will be generated by when running a CREATE TABLE SQL query.
Note that if you want to regenerate a file, you will first need to delete it.

Generate Schemas with SQL

When you set GenerateSchemaFiles to OnUse, the connector generates schemas as you execute SELECT queries. Schemas are generated for each table referenced in the query.

When you set GenerateSchemaFiles to OnCreate, schemas are only generated when a CREATE TABLE query is executed.

Generate Schemas on Connection

Another way to use this property is to obtain schemas for every table in your database when you connect. To do so, set GenerateSchemaFiles to OnStart and connect.

CData Python Connector for XML

IncludeDropboxTeamResources

Indicates if you want to include Dropbox team files and folders.

Data Type

bool

Default Value

false

Remarks

In order to access Dropbox team folders and files, please set this connection property to True.

CData Python Connector for XML

IncludeFiles

Comma-separated list of file extensions to include into the set of the files modeled as tables.

Data Type

string

Default Value

"XML,TXT"

Remarks

Comma-separated list of file extensions to include into the set of the files modeled as tables. For example, IncludeFiles=XML,TXT. The default is XML,TXT.

The following archive types are also supported: ZIP, TAR, and GZ. Files of these types are modeled as an aggregated table.

A '*' value can be specified to include all files. A 'NOEXT' value can be specified to include files without an extension.

It is also possible to specify datetime filters. We currently support CreatedDate and ModifiedDate. All extension filters are evaluated in disjunction (using OR operator), and then the resulting filter is evaluated in conjunction (using AND operator) with the datetime filters.

Examples:

IncludeFiles="TXT,CreatedDate<='2020-11-26T07:39:34-05:00'"
IncludeFiles="TXT,ModifiedDate<=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 50, 000)"
IncludeFiles="ModifiedDate>=DATETIMEFROMPARTS(2020, 11, 26, 7, 40, 49, 000),ModifiedDate<=CURRENT_TIMESTAMP()"

CData Python Connector for XML

IncludeItemsFromAllDrives

Whether Google Drive shared drive items should be included in results. If not present or set to false, then shared drive items are not returned.

Data Type

bool

Default Value

false

Remarks

If this property is set to 'True', files will be retrieved from all drives, including shared drives. The file retrieval can be limited a specific shared drive or a specific folder in that shared drive by setting the start of the URI to the path of the shared drive and optionally any folder within, for example: 'gdrive://SharedDriveA/FolderA/...'. Additionally, the FolderId property can be used to limit the search to an exact subdirectory.

CData Python Connector for XML

MaxRows

Specifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.

Data Type

int

Default Value

-1

Remarks

The default value for this property, -1, means that no row limit is enforced unless the query explicitly includes a LIMIT clause. (When a query includes a LIMIT clause, the value specified in the query takes precedence over the MaxRows setting.)

Setting MaxRows to a whole number greater than 0 ensures that queries do not return excessively large result sets by default.

This property is useful for optimizing performance and preventing excessive resource consumption when executing queries that could otherwise return very large datasets.

CData Python Connector for XML

MetadataDiscoveryURI

Identifies a file to read when aggregating multiple files into a single table, to specify the schema of the aggregated table.

Data Type

string

Default Value

""

Remarks

Identifies a file to read when aggregating multiple files into a single table, to specify the schema of the aggregated table.

CData Python Connector for XML

Other

Specifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.

Data Type

string

Default Value

""

Remarks

This property allows advanced users to configure hidden properties for specialized situations, with the advice of our Support team. These settings are not required for normal use cases but can address unique requirements or provide additional functionality. To define multiple properties, use a semicolon-separated list.

Note: It is strongly recommended to set these properties only when advised by the Support team to address specific scenarios or issues.

Caching Configuration

PropertyDescription
CachePartial=TrueCaches only a subset of columns, which you can specify in your query.
QueryPassthrough=TruePasses the specified query to the cache database instead of using the SQL parser of the connector.

Integration and Formatting

PropertyDescription
DefaultColumnSizeSets the default length of string fields when the data source does not provide column length in the metadata. The default value is 2000.
ConvertDateTimeToGMT=TrueConverts date-time values to GMT, instead of the local time of the machine. The default value is False (use local time).
RecordToFile=filenameRecords the underlying socket data transfer to the specified file.

CData Python Connector for XML

Pagesize

Specifies the maximum number of records per page the provider returns when requesting data from XML.

Data Type

int

Default Value

1000

Remarks

When processing a query, instead of requesting all of the queried data at once from XML, the connector can request the queried data in pieces called pages.

This connection property determines the maximum number of results that the connector requests per page.

Note: Setting large page sizes may improve overall query execution time, but doing so causes the connector to use more memory when executing queries and risks triggering a timeout.

CData Python Connector for XML

PathSeparator

Determines the character used to replace file path separators when generating table names.

Data Type

string

Default Value

"_"

Remarks

When this property is set, the connector replaces the default path separator used in XML element paths with the specified character when generating table names.

For example, if an XML file is located at Test/Files/Test.xml and PathSeparator is set to _, the resulting table name is Test_Files_Test.xml.

This property is useful for ensuring consistent and valid table names when reading XML files from nested directories.

CData Python Connector for XML

PseudoColumns

Specifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.

Data Type

string

Default Value

""

Remarks

This property allows you to define which pseudocolumns the connector exposes as table columns.

To specify individual pseudocolumns, use the following format:

Table1=Column1;Table1=Column2;Table2=Column3

To include all pseudocolumns for all tables use:

*=*

CData Python Connector for XML

Readonly

Toggles read-only access to XML from the provider.

Data Type

bool

Default Value

false

Remarks

When set to True, the connector allows only SELECT queries. Attempting an INSERT, UPDATE, DELETE, or stored procedure query fails with an error message.

CData Python Connector for XML

RowScanDepth

Specifies the number of rows the provider scans when dynamically determining table columns.

Data Type

string

Default Value

"100"

Remarks

When this property is set, the connector scans the specified number of rows (objects) in the XML document to detect columns and datatypes. The scans follow nested objects, counting each object array as a single row.

If no schema (RSD) is available for the table, columns are determined dynamically using this scan. The behavior applies when using GenerateSchemaFiles or when a schema file is not present.

Higher values improve detection accuracy but may increase request time. Setting this property to 0 causes the connector to parse the entire XML document.

This property is useful for controlling the trade-off between schema detection accuracy and query performance when parsing XML data.

See Also

CData Python Connector for XML

RTK

Specifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.

Data Type

string

Default Value

""

Remarks

This property is typically unnecessary, as most configurations support a standard licensing mechanism.

Warning: The value of this property takes precedence over all existing licensing information. To avoid licensing errors, ensure the provided runtime key is correct.

CData Python Connector for XML

Timeout

Specifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.

Data Type

int

Default Value

60

Remarks

The timeout applies to each individual communication with the server rather than the entire query or operation. For example, a query could continue running beyond 60 seconds if each paging call completes within the timeout limit.

Timeout is set to 60 seconds by default. To disable timeouts, set this property to 0.

Disabling the timeout allows operations to run indefinitely until they succeed or fail due to other conditions such as server-side timeouts, network interruptions, or resource limits on the server.

Note: Use this property cautiously to avoid long-running operations that could degrade performance or result in unresponsive behavior.

CData Python Connector for XML

TypeDetectionScheme

Specifies how the provider determines the data types of columns in the generated schema.

Possible Values

None, RowScan

Data Type

string

Default Value

"RowScan"

Remarks

When this property is set to None, all columns are returned as string values without data type inference.

When this property is set to RowScan, the connector scans a sample of rows to heuristically infer column data types. The number of rows scanned is determined by the RowScanDepth property.

This property is useful for controlling the method of type inference during schema discovery.

CData Python Connector for XML

URISeparator

Specifies the delimiter used to separate multiple values in the URI property.

Data Type

string

Default Value

","

Remarks

When this property is set, the connector uses the specified delimiter to separate multiple URIs in a single connection string.

By default, the delimiter is a comma (,), allowing you to join multiple file paths or endpoints, for example:

URI=c:/data/data1.xml,c:/data/data2.xml,c:/data/data3.xml

This property is useful for connecting to multiple JSON files or resources in a single query.

CData Python Connector for XML

UserDefinedViews

Specifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.

Data Type

string

Default Value

""

Remarks

UserDefinedViews allows you to define and manage custom views through a JSON-formatted configuration file called UserDefinedViews.json. These views are automatically recognized by the connector and enable you to execute custom SQL queries as if they were standard database views. The JSON file defines each view as a root element with a child element called "query", which contains the SQL query for the view.

For example:

{
	"MyView": {
		"query": "SELECT * FROM NorthwindOData WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}

You can use this property to define multiple views in a single file and specify the filepath. For example:

UserDefinedViews=C:\Path\To\UserDefinedViews.json
When you specify a view in UserDefinedViews, the connector only sees that view.

For further information, see User Defined Views.

CData Python Connector for XML

Third Party Copyrights

LZMA from 7Zip LZMA SDK

LZMA SDK is placed in the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

LZMA2 from XZ SDK

Version 1.9 and older are in the public domain.

Xamarin.Forms

Xamarin SDK

The MIT License (MIT)

Copyright (c) .NET Foundation Contributors

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NSIS 3.10

Copyright (C) 1999-2025 Contributors THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS

"Contribution" means:

a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor:

i) changes to the Program, and

ii) additions to the Program;

where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.

"Contributor" means any person or entity that distributes the Program.

"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.

2. GRANT OF RIGHTS

a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.

b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.

c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.

d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.

3. REQUIREMENTS

A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;

ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and

iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the Program.

Contributors may not remove or alter any copyright notices contained within the Program.

Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.

4. COMMERCIAL DISTRIBUTION

Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL

If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against a Contributor with respect to a patent applicable to software (including a cross-claim or counterclaim in a lawsuit), then any patent licenses granted by that Contributor to such Recipient under this Agreement shall terminate as of the date such litigation is filed. In addition, if Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. IBM is the initial Agreement Steward. IBM may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.

This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

AdoptOpenJDK / Adoptium Temurin JRE 17.0.18_8

Copyright (c) Eclipse Foundation AISBL. All Rights Reserved.

Apache License, Version 2.0

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

  1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
  2. You must cause any modified files to carry prominent notices stating that You changed the files; and
  3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
  4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

Eclipse Distribution License - v 1.0

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Eclipse Public License - v 2.0

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS "Contribution" means:

  • a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and
  • b) in the case of each subsequent Contributor:
    • i) changes to the Program, and
    • ii) additions to the Program;
    where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution "originates" from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works.
"Contributor" means any person or entity that Distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions Distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors.

"Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship.

"Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof.

"Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy.

"Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor.

2. GRANT OF RIGHTS

  • a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works.
  • b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
  • c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
  • d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
  • e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3).

3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then:

  • a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and
  • b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license:
    • i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
    • ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
    • iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and
    • iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3.
3.2 When the Program is Distributed as Source Code:
  • a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and
  • b) a copy of this Agreement must be included with each copy of the Program.
3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability (‘notices') contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices.

4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version.

Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement.

Exhibit A – Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}."

Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses.

If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.

You may add additional accurate notices of copyright ownership.

GNU Classpath

Classpath is distributed under the terms of the GNU General Public License with the following clarification and special exception.

Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination.

As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.

As such, it can be used to run, create and distribute a large class of applications and applets. When GNU Classpath is used unmodified as the core class library for a virtual machine, compiler for the java languge, or for a program written in the java programming language it does not affect the licensing for distributing those programs directly.

OpenJDK Assembly Exception

The OpenJDK source code made available by Oracle America, Inc. (Oracle) at openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2 only ("GPL2"), with the following clarification and special exception.

Linking this OpenJDK Code statically or dynamically with other code is making a combined work based on this library. Thus, the terms and conditions of GPL2 cover the whole combination.

As a special exception, Oracle gives you permission to link this OpenJDK Code with certain code licensed by Oracle as indicated at http://openjdk.java.net/legal/exception-modules-2007-05-08.html ("Designated Exception Modules") to produce an executable, regardless of the license terms of the Designated Exception Modules, and to copy and distribute the resulting executable under GPL2, provided that the Designated Exception Modules continue to be governed by the licenses under which they were offered by Oracle.

As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code to build an executable that includes those portions of necessary code that Oracle could not provide under GPL2 (or that Oracle has provided under GPL2 with the Classpath exception). If you modify or add to the OpenJDK code, that new GPL2 code may still be combined with Designated Exception Modules if the new code is made subject to this exception by its copyright holder.

Copyright (c) 2026 CData Software, Inc. - All rights reserved.
Build 26.0.9655