ODBC Driver for Anzo

Build 21.0.8171

CData ODBC Driver for Anzo

Overview

The CData ODBC Driver for Anzo enables real-time access to Anzo data, directly from any applications that support ODBC connectivity, the most widely supported interface for connecting applications with data.

The driver wraps the complexity of accessing Anzo data in a standard ODBC driver compliant with ODBC 3.8. Applications can then access Anzo as a traditional database. The driver hides the complexity of accessing data and provides additional powerful security features, smart caching, batching, socket management, and more.

Key Features

  • Bidirectional access.
  • Access, analyze, and report on data with your SQL-based tool of choice.
  • Supports 32-bit and 64-bit applications.
  • Supports the Unicode ODBC APIs and ODBC 3.8.
  • Drivers for Windows, Linux, and macOS/OS X.

Getting Started

See Getting Started to create an ODBC data source name (DSN) and connect to Anzo from your platform.

Using the ODBC Driver/Using from Tools

See Using ODBC to connect to Anzo from the following programming languages and for information on the supported interfaces:

See Using from Tools for information on using the ODBC driver in some of the popular applications and programming languages that connect via ODBC.

See the Anzo integration guides for information on connecting from other applications.

Linked Server

You can use SQL Linked Server to connect to the CData SQL Gateway. SQL Server treats the CData SQL Gateway as a linked SQL Server instance, so you can write full SQL queries to query your Anzo data without losing performance as would happen connecting to an ODBC data source directly. The connection can be made locally or to the Gateway located on a separate machine.

See Create a Linked Server for more information.

SQL Gateway

See SQL Gateway to configure MySQL or SQL Server entry points for Anzo on your server, using the included CData SQL Gateway application. The SQL Gateway listens for incoming MySQL and SQL Server connections and brokers the SQL request to the ODBC data source. This enables any MySQL or SQL Server client to connect, from PHP applications, SQL Server linked servers, and so on.

Advanced Features

Advanced Features details additional features supported by the driver, 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.

Data Model

See Data Model for the available database objects. This section also provides more detailed information on querying specific Anzo entities.

Connection Properties

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

CData ODBC Driver for Anzo

Getting Started

The CData ODBC Driver for Anzo is a standards-based ODBC driver with editions for Windows and Unix-based operating systems, like macOS and Linux. The following sections show how to create an ODBC data source and query data.

Creating a DSN on Your Platform

The following guides show how to use the standard tools to configure data source names (DSN).

Anzo Version Support

The driver models Anzo entities as a relational database, dynamically discovering the schemas to allow access to all of your Anzo sources.

See Also

See the following sections to connect to the DSN from tools and from code:

CData ODBC Driver for Anzo

Windows DSN Configuration

Using the Microsoft ODBC Data Source Administrator

You can use the Microsoft ODBC Data Source Administrator to edit the DSN configuration. Note that the DSN is created during the installation process.

Complete the following steps to edit the DSN configuration:

  1. Select Start > Search, and enter ODBC Data Sources in the Search box.
  2. Choose the version of the ODBC Administrator that corresponds to the bitness of your application (32-bit or 64-bit).
  3. Click the System DSN tab.
  4. Select the system data source and click Configure.
  5. Edit the information on the Connection tab and click OK.

Note: For .NET Framework 4.0, the driver distributes Microsoft Visual C++ 2017 Redistributable. For .NET Framework 3.5, the driver distributes Microsoft Visual C++ 2008 Redistributable.

To authenticate to Anzo, you must provide the User and Password properties.

To connect to data, specify Url. This is the Url to your Anzo data.

CData ODBC Driver for Anzo

macOS DSN Configuration

This section shows how to set up ODBC connectivity and configure DSNs on macOS.

Minimum macOS Version

The CData ODBC Driver for Anzo driver requires macOS Sierra (10.12) or above.

Licensing the Driver

In a terminal, run the following commands to license the driver. To activate a trial, omit the <key> input.

cd "/Applications/CData ODBC Driver for Anzo/bin"
sudo ./install-license.sh <key>

You'll be prompted for a name and password. These refer to your name and your machine's password.

To authenticate to Anzo, you must provide the User and Password properties.

To connect to data, specify Url. This is the Url to your Anzo data.

Uninstalling the Driver

The easiest way to uninstall the driver is to open a terminal and run the included uninstall.sh script, located in the installation directory. For example:

cd "/Applications/CData ODBC Driver for Anzo"
sudo ./uninstall.sh

Note: The script needs to be run from the installation directory.

CData ODBC Driver for Anzo

Using the iODBC Driver Manager

Connecting through a Driver Manager

On macOS, the CData ODBC Driver for Anzo is preconfigured for use with the iODBC driver manager, as are many other products like Filemaker Pro, Microsoft Excel, and Tableau. You can find the latest version of iODBC on the iODBC site.

The driver installation registers the driver with iODBC and creates a system DSN, which you can use in any tools or applications that support ODBC connectivity.

The driver manager loads the driver and passes function calls from the application to the driver. The driver must be registered with the driver manager and DSNs are defined in the driver manager's configuration files.

Configuring DSNs

To configure a DSN, you can use the iODBC Administrator 64-bit, the GUI installed with iODBC. Note that the ODBC Manager must match the bitness of the ODBC driver. The most recent version of the CData ODBC Driver for Anzo is 64-bit only. Alternatively, you can edit the iODBC configuration files.

You can configure User or System DSNs. User data sources are restricted to a user account. System data sources can be accessed by all users.

Configuring a DSN with the iODBC Administrator

You can create user DSNs by opening the iODBC Administrator 64-bit from Launchpad.

To modify the system DSN installed by the driver or create a system DSN, open the iODBC Administrator 64-bit with elevated permissions. To do so, enter the following command into a terminal:

sudo /Applications/iODBC/iODBC\ Administrator64.app/Contents/MacOS/iODBC\ Administrator64
After opening the iODBC Administrator 64-bit, you will see the CData Anzo Source listed under the System tab. Select the DSN and click the Configure button to set connection properties as name-value pairs.

To create your own DSN, instead click Add on the User or System tab and then select the CData ODBC Driver for Anzo option.

Configuring a DSN in the iODBC INI Files

Configure DSNs in odbc.ini. Register ODBC drivers in odbcinst.ini.

odbc.ini

Define ODBC data sources in sections in the odbc.ini file. User data sources can only be accessed by the user account whose home folder the odbc.ini is located in. System data sources can be accessed by all users.

PrivilegesPath
User/Users/myuser/Library/ODBC/odbc.ini
System/Library/ODBC/odbc.ini

Modifying iODBC's system-wide settings requires elevated permissions; to do so, you can use the sudo command to open a text editor from the terminal. For example:

sudo nano /Library/ODBC/odbc.ini

In addition to the connection properties required to connect to your data source, the Driver property specifies either a driver definition in the odbcinst.ini file or the path to the driver library.

[CData Anzo Source]
Driver = CData ODBC Driver for Anzo
User=username
Password=password
URL=http://35.184.41.230:8080/dataondemand/MyData

Additionally, in the ODBC Data Sources section, the DSN must be set to a driver defined in the odbcinst.ini file. For example, below is the entry for the DSN created during the driver install:

[ODBC Data Sources]
CData Anzo Source = CData ODBC Driver for Anzo

odbcinst.ini

You may need to modify the installed driver definition if you change the path to the driver library.

To register an ODBC driver, modify the odbcinst.ini file. With iODBC, drivers can be available to only one user account or drivers can be available system wide.

PrivilegesPath
User/Users/myuser/Library/ODBC/odbcinst.ini
System/Library/ODBC/odbcinst.ini

Drivers are defined in sections in the odbcinst.ini file. The section name specifies the name of the driver. In this section, the Driver property specifies the path to the driver library. The driver library is the .dylib file located in the lib subfolder of the installation directory, by default in /Applications/CData ODBC Driver for Anzo.

[CData ODBC Driver for Anzo]
Driver = /Applications/CData ODBC Driver for Anzo/lib/libanzoodbc.dylib

The ODBC Drivers section must also contain a property with the driver name, set to "Installed". For example:

[ODBC Drivers]
CData ODBC Driver for Anzo = Installed

Testing the Connection

You can use the iODBC Demo, available in most iODBC installations, to connect to Anzo and execute SQL queries.

iODBC Demo

Complete the following steps to connect from the iODBC Demo:

  • Open Launchpad and search for "iODBC".
  • If you need to connect to Anzo from an application that can use only the ANSI ODBC API, click iODBC Demo Ansi. Otherwise, click iODBC Demo Unicode.
  • In the Environment menu, click Open Connection.
  • Select the DSN on the corresponding tab and test the connection.
You can now execute SQL statements to Anzo by clicking Execute SQL in the SQL menu.

Set the Driver Encoding

The ODBC drivers need to specify which encoding to use with the ODBC Driver Manager. By default, the CData ODBC Drivers for Mac are configured to use UTF-32 which is compatible with iODBC, but other Driver Managers may require alternative encoding.

Alternatively, if you are using the ODBC driver from an application that uses the ANSI ODBC API it may be necessary to set the ANSI code page. For example, to import Japanese characters in an ANSI application, you can specify the code page in the config file '/Applications/CData ODBC Driver for Anzo/lib/cdata.odbc.anzo.ini':

[Driver]
AnsiCodePage = 932

CData ODBC Driver for Anzo

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 driver leverages the JNI for improved performance.

Configure the INI File

The Mac edition of the Anzo ODBC driver is shipped with a configuration file. This file is used to several parameters, including JNI behavior. By default, this is found in:

/Applications/CData ODBC Driver for Anzo/lib/cdata.odbc.anzo.ini

Configure the JNI driver's behavior by editing the properties in the driver's INI file. The driver can be configured as follows:

  • DriverManagerEncoding: Can be either UTF-8, UTF-16, or UTF-32. This will typically need to be specified when using the Unicode ODBC API.
  • AnsiCodePage: Set this to the name of the encoding used for the ANSI ODBC API. Acceptable values are: Shift_JIS, GB2312, and all Java charset names. This will need to be configured if the application is using the ANSI ODBC API.
  • LibODBCINST: Set this to be the path to the libodbcinst library that is used to read/write the ODBC DSN. Configure this when the target machine has installed too many intances of ODBCINST.
  • JVM: Configure the JVM library location used to launch the JVM. Users usually need to configure it when the application is a Java program.
  • ClassPath: Configure the paths to the third-party jar libraries, separated by colon characters.

Ensure that these properties are placed in the .ini file, one per line, under the Drivers section name:

[Drivers]
DriverManagerEncoding = UTF-16

Configure Environment Variables

Additionally, set the following environment variables:

  • CDATA_JVM: This is the path to the JVM.
  • CDATA_JVM_OPTIONS: Place JVM options here.
  • CDATA_ODBC_LOG: Set this in the following scheme: <SCHEME>://<TAG>[|<LEVEL>]

    • SCHEME: The options are SYSLOG, STDOUT, FILE
      • SYSLOG: The native ODBC wrapper (cdata.odbc.anzo.so) logs into syslogs.
      • STDOUT: Both the native ODBC wrapper and odbc core(cdata.odbcm.anzo.jar) logs into stdout. The Logfile and Verbosity properties can override the behavior of ODBC core.
      • FILE: The native odbc 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
      • The ident for SYSLOG. For STDOUT, this will be N/A. If it is FILE, the it is the filename.
    • LEVEL
      • Set to one of: FATAL | ERROR | WARNING | INFO | DEBUG

The following are some examples of this syntax:

  • STDOUT://1|DEBUG
  • SYSLOG://[CData Anzo ODBC]|DEBUG
  • FILE:///var/my_odbc.log|DEBUG

CData ODBC Driver for Anzo

Linux DSN Configuration

This section describes how to set up ODBC connectivity and configure DSNs on several Linux distributions: Debian-based systems, like Ubuntu, and Red Hat Linux platforms, like Red Hat Enterprise Linux (RHEL), CentOS, and Fedora.

Minimum Linux Versions

Here are the minimum supported versions for Red Hat-based and Debian-based systems:

OSMin. Version
Ubuntu11.04
Debian7
RHEL6.9
CentOS6.9
Fedora13
SUSE12.1

Installing the Driver Dependencies

Run the following commands as root or with sudo to install the necessary dependencies:

  • Debian/Ubuntu:
    apt-get install libc6 libstdc++6 zlib1g libgcc1
  • RHEL/CentOS/Fedora:
    yum install glibc libstdc++ zlib libgcc

Here are the corresponding libraries required by the driver:

Debian/Ubuntu PackageRHEL/CentOS/Fedora PackageFile
libc6glibclinux-vdso.1
libc6glibclibm.so.6
libc6glibclibrt.so.1
libc6glibclibdl.so.2
libc6glibclibpthread.so.0
libc6glibclibc.so.6
libc6glibcld-linux-x86-64.so.2
libstdc++6libstdc++libstdc++.so.6
zlib1gzliblibz.so.1
libgcc1libgcclibgcc_s.so.1

Installing the Driver

You can use standard package management systems to install the driver.

On Debian-based systems, like Ubuntu, run the following command with root or sudo:

dpkg -i /path/to/driver/setup/AnzoODBCDriverforUnix.deb 

On systems that support the RPM package format, run the following command with root or sudo:

rpm -ivh /path/to/driver/AnzoODBCDriverforUnix.rpm 

Licensing the Driver

Run the following commands to license the driver. To activate a trial, omit the <key> input.

cd /opt/cdata/cdata-odbc-driver-for-anzo/bin/
sudo ./install-license.sh <key>

Connecting through the Driver Manager

The driver manager loads the driver and passes function calls from the application to the driver. You need to register the driver with the driver manager and you define DSNs in the driver manager's configuration files.

The driver installation registers the driver with the unixODBC driver manager and creates a system DSN. The unixODBC driver manager can be used from Python and from many other applications. Your application may embed another driver manager.

Creating the DSN

See Using unixODBC to install unixODBC and configure DSNs. See Using the DataDirect Driver Manager to create a DSN to connect to OBIEE, Informatica, and SAS.

To authenticate to Anzo, you must provide the User and Password properties.

To connect to data, specify Url. This is the Url to your Anzo data.

Set the Driver Encoding

The ODBC drivers need to specify which encoding to use with the ODBC Driver Manager. By default, the CData ODBC Drivers for Unix are configured to use UTF-16 which is compatible with unixODBC, but other Driver Managers may require alternative encoding.

Alternatively, if you are using the ODBC driver from an application that uses the ANSI ODBC API it may be necessary to set the ANSI code page. For example, to import Japanese characters in an ANSI application, you can specify the code page in the config file '/opt/cdata/cdata-odbc-driver-for-anzo/lib/cdata.odbc.anzo.ini':

[Driver]
AnsiCodePage = 932

CData ODBC Driver for Anzo

Using unixODBC

In the following sections, you can find how-tos on installing the unixODBC driver manager, setting up the driver for unixODBC, and creating DSNs.

Installing unixODBC

Precompiled binaries for the unixODBC driver manager are available for many operating systems.

On Debian-based systems like Ubuntu, you can install unixODBC by running the following command as root or with sudo:

apt-get install unixodbc unixodbc-dev
On Red Hat Enterprise Linux, CentOS, and Fedora, you can install unixODBC with YUM or DNF. For example, run the following command as root or with sudo:
yum install unixODBC unixODBC-devel
If binaries are not available for your operating system, you will need to compile unixODBC yourself. Please refer to the unixODBC website for more information about obtaining binaries or compiling unixODBC on your operating system.

Using unixODBC Configuration Files

If your unixODBC installation does not include a graphical tool, you can set up connectivity to Anzo by editing the configuration files.

You can determine the location of the configuration files on your system by entering the following command into a terminal:

odbcinst -j
Below is an example of the output of this command:
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/myuser/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
Note: Modifying system-wide settings requires elevated permissions; to do so, you can use root or the sudo command.

Set the Driver Encoding

unixODBC communicates with applications using UTF-16 encoding. This is the default encoding in CData ODBC drivers, but this can be set to alternative options if necessary, in the config file '/opt/cdata/cdata-odbc-driver-for-anzo/lib/cdata.odbc.anzo.ini'.

Register the Driver

Register the driver by adding a section to the odbcinst.ini file. You may need to modify the installed driver definition if you change the path to the driver library.

The sections of the odbcinst.ini file map a driver name to the driver library. The section begins with the driver name; the Driver property points to the path to the driver library. The driver library is the .so file located by default in /opt/cdata/cdata-odbc-driver-for-anzo/lib. A Description property can also be provided.

[CData ODBC Driver for Anzo]
Driver=/opt/cdata/cdata-odbc-driver-for-anzo/lib/libanzoodbc.x64.so
Description=CData ODBC Driver for Anzo

To check that the driver is registered, list the drivers installed on the system with the following command:

odbcinst -q -d

Define a DSN

Create a DSN by adding an entry to odbc.ini. Below is an example DSN entry in odbc.ini:

[CData Anzo Source]
Driver=/opt/cdata/cdata-odbc-driver-for-anzo/lib/libanzoodbc.x64.so
User=username
Password=password
URL=http://35.184.41.230:8080/dataondemand/MyData

Test the Connection

You can use the unixODBC test tool, isql, to execute SQL queries to Anzo from the command line. When testing the connection, use the -v flag to output any messages from the driver manager and the driver.

isql -v "CData Anzo Source" 

CData ODBC Driver for Anzo

Using the DataDirect Driver Manager

Some ODBC client programs ship with their own ODBC driver managers, as opposed to the open-source unixODBC. For example, Informatica, OBIEE, and SAS use the DataDirect driver manager. See Using from Tools for application-specific configuration.

To avoid incompatibilities between unixODBC and your ODBC client application's ODBC driver manager, we would recommend uninstalling unixODBC before configuring the driver.

Set the Driver Encoding

The CData ODBC driver also supports the ODBC environment attributes SQL_ATTR_APP_UNICODE_TYPE and SQL_ATTR_DRIVER_UNICODE_TYPE, which the DataDirect ODBC Driver Manager uses to automatically set the encoding depending on what the client applications expects. If those attributes are supported by the client application, character encoding is defined automatically. If those attribute aren't specified, the encoding can be set manually, in '/opt/cdata/cdata-odbc-driver-for-anzo/lib/cdata.odbc.anzo.ini'. By default, the DataDirect Driver Manager uses UTF-8:

[Driver]
DriverManagerEncoding=UTF-8

Register the Driver

In the driver configuration file, "odbcinst.ini", register the driver name. Note that this step is not required for SAS and Informatica.

The location of this file may depend on your installation. Some applications search environment variables for the ODBC configuration files, such as $ODBCHOME.

[CData ODBC Driver for Anzo]
Driver=/opt/cdata/cdata-odbc-driver-for-anzo/lib/libanzoodbc.x64.so
Description=CData ODBC Driver for Anzo 2021

Configure the DSN

In the DSN configuration file, "odbc.ini", make sure to specify the driver library by its full path, as opposed to the driver name like with unixODBC. You can then enter the other connection properties required by the specific data source.

The location of this file may depend on your installation. Some applications search environment variables for the ODBC configuration files, such as $ODBCHOME.

[CData Anzo Source]
Driver=/opt/cdata/cdata-odbc-driver-for-anzo/lib/libanzoodbc.x64.so
User=username
Password=password
URL=http://35.184.41.230:8080/dataondemand/MyData
See Linux DSN Configuration for a guide to connecting to Anzo.

CData ODBC Driver for Anzo

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 driver leverages the JNI for improved performance.

Configure the INI File

The Linux edition of the Anzo ODBC driver is shipped with a configuration file. This file is used to several parameters, including JNI behavior. By default, this is found in:

/opt/cdata/cdata-odbc-driver-for-anzo/lib/cdata.odbc.anzo.ini

Configure the JNI driver's behavior by editing the properties in the driver's INI file. The driver can be configured as follows:

  • DriverManagerEncoding: Can be either UTF-8, UTF-16, or UTF-32. This will typically need to be specified when using the Unicode ODBC API.
  • AnsiCodePage: Set this to the name of the encoding used for the ANSI ODBC API. Acceptable values are: Shift_JIS, GB2312, and all Java charset names. This will need to be configured if the application is using the ANSI ODBC API.
  • LibODBCINST: Set this to be the path to the libodbcinst library that is used to read/write the ODBC DSN. Configure this when the target machine has installed too many intances of ODBCINST.
  • JVM: Configure the JVM library location used to launch the JVM. Users usually need to configure it when the application is a Java program.
  • ClassPath: Configure the paths to the third-party jar libraries, separated by colon characters.

Ensure that these properties are placed in the .ini file, one per line, under the Drivers section name:

[Drivers]
DriverManagerEncoding = UTF-16

Configure Environment Variables

Additionally, set the following environment variables:

  • CDATA_JVM: This is the path to the JVM.
  • CDATA_JVM_OPTIONS: Place JVM options here.
  • CDATA_ODBC_LOG: Set this in the following scheme: <SCHEME>://<TAG>[|<LEVEL>]

    • SCHEME: The options are SYSLOG, STDOUT, FILE
      • SYSLOG: The native ODBC wrapper (cdata.odbc.anzo.so) logs into syslogs.
      • STDOUT: Both the native ODBC wrapper and odbc core(cdata.odbcm.anzo.jar) logs into stdout. The Logfile and Verbosity properties can override the behavior of ODBC core.
      • FILE: The native odbc 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
      • The ident for SYSLOG. For STDOUT, this will be N/A. If it is FILE, the it is the filename.
    • LEVEL
      • Set to one of: FATAL | ERROR | WARNING | INFO | DEBUG

The following are some examples of this syntax:

  • STDOUT://1|DEBUG
  • SYSLOG://[CData Anzo ODBC]|DEBUG
  • FILE:///var/my_odbc.log|DEBUG

CData ODBC Driver for Anzo

Changelog

General Changes

[7915] - 2021-09-02

Added
  • Added support for the STRING_SPLIT table-valued function in the CROSS APPLY clause.

[7889] - 2021-08-07

Changed
  • Add the KeySeq column to the sys_foreignkeys table.

[7888] - 2021-08-06

Changed
  • Add the new sys_primarykeys system table.

[7874] - 2021-07-23

Changed
  • 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 vs te predicate. Ie: 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. Ie: WHERE col > L_LAST_MONTH(). This will continue to resolve to the same values that previously were calculated in the criteria. Note that the "L_" prefix will only work in the predicate - it not available for the projection.

[7859] - 2021-07-08

Added
  • Added the TCP Logging Module for the logging information happening on the TCP wire protocol. The transport bytes that are incoming and ongoing will be logged at verbosity=5.

[7785] - 2021-04-23

Added
  • Added support for handling client side formulas during insert / update. For example: UPDATE Table SET Col1 = Concat(Col1, " - ", Col2) WHERE Col2 LIKE 'A%'

[7783] - 2021-04-23

Changed
  • Updated how display sizes are determined for varchar primary key and foreign key columns so they will match the reported length of the column.

[7776] - 2021-04-16

Added
  • Non-conditional updates between two columns is now available to all drivers. For example: UPDATE Table SET Col1=Col2
Changed
  • Reduced the length to 255 for varchar primary key and foreign key columns.
  • Updated implicit and metadata caching to improve performance and support for multiple connections. Old metadata caches are not compatible - you would need to generate new metadata caches if you are currently using CacheMetadata.
  • Updated index naming convention to avoid duplicates
  • Updated and standardized Getting Started connection help.
  • Added the Advanced Features section to the help of all drivers.
  • Categorized connection property listings in the help for all editions.

ODBC Changes

[8026] - 2021-12-22

Added
  • Added support for transactions.

[7880] - 2021-07-29

Added
  • Added support for the Array data type for the input parameters in stored procedures.

[7819] - 2021-05-29

Added
  • Exposed the InitiateOAuth connection property.

[7818] - 2021-05-28

Changed
  • Add new hidden property SupportNativeDataType support.

[7816] - 2021-05-26

Added
  • Support JAVA_HOME setting in confirgure file.

[7789] - 2021-04-29

Added
  • Adding the SqlMaxColumnNameLen connection property.

[7776] - 2021-04-16

Changed
  • ODBC Drivers on the Linux and Mac now depend on the JRE, which brings improved stability and performance.

CData ODBC Driver for Anzo

Using ODBC

This section provides a reference for connecting to the driver using the ODBC libraries available in various languages.

ODBC Compliance

The driver is compliant with ODBC 3.8. The following sections list the supported ODBC APIs:

Language-Specific Help

The following sections describe using specific programming languages with the driver:

CData ODBC Driver for Anzo

Supported Functions

Supported Functions

The CData ODBC Driver for Anzo supports the following ODBC API functions:

Function Conformance Level Status
SQLAllocConnect (Core) Supported
SQLAllocEnv (Core) Supported
SQLAllocStmt (Core) Supported
SQLBindCol (Core) Supported
SQLCancel (Core) Supported
SQLColAttributes (Core) Supported
SQLConnect (Core) Supported
SQLDescribeCol (Core) Supported
SQLDisconnect (Core) Supported
SQLError (Core) Supported
SQLExecDirect (Core) Supported
SQLExecute (Core) Supported
SQLFetch (Core) Supported
SQLFreeConnect (Core) Supported
SQLFreeEnv (Core) Supported
SQLFreeStmt (Core) Supported
SQLGetCursorName (Core) Not Supported
SQLNumResultCols (Core) Supported
SQLPrepare (Core) Supported
SQLRowCount (Core) Supported
SQLSetCursorName (Core) Not Supported
SQLSetParam (Core) Supported
SQLTransact (Core) Not Supported
SQLColumns (Core) Supported
SQLDriverConnect (Core) Supported
SQLGetConnectOption (Core) Supported
SQLGetData (Core) Supported
SQLGetFunctions (Core) Supported
SQLGetInfo (Core) Supported
SQLGetStmtOption (Core) Supported
SQLGetTypeInfo (Core) Supported
SQLParamData (Core) Supported
SQLPutData (Core) Supported
SQLSetConnectOption (Core) Supported
SQLSetStmtOption (Core) Supported
SQLSpecialColumns (Core) Supported
SQLStatistics (Core) Supported
SQLTables (Core) Supported
SQLBrowseConnect (Level 1) Supported
SQLColumnPrivileges (Level 2) Not Supported
SQLDataSources (Core) Supported
SQLDescribeParam (Level 2) Supported
SQLExtendedFetch (Level 2) Supported
SQLForeignKeys (Level 2) Supported
SQLMoreResults (Level 1) Not Supported
SQLNativeSql (Core) Supported
SQLNumParams (Core) Supported
SQLParamOptions (Core) Supported
SQLPrimaryKeys (Level 1) Supported
SQLProcedureColumns (Level 1) Supported
SQLProcedures (Level 1) Supported
SQLSetPos (Level 2) Not Supported
SQLSetScrollOptions (Level 2) Not Supported
SQLTablePrivileges (Level 2) Not Supported
SQLDrivers (Level 2) Supported
SQLBindParameter (Core) Supported
SQLAllocHandle (Core) Supported
SQLBindParam (Core) Supported
SQLCloseCursor (Core) Supported
SQLColAttribute (Core) Supported
SQLCopyDesc (Core) Supported
SQLEndTran (Core) Not Supported
SQLFetchScroll (Core) Supported
SQLFreeHandle (Core) Supported
SQLGetConnectAttr (Core) Supported
SQLGetDescField (Core) Supported
SQLGetDescRec (Core) Supported
SQLGetDiagField (Core) Supported
SQLGetDiagRec (Core) Supported
SQLGetEnvAttr (Core) Supported
SQLGetStmtAttr (Core) Supported
SQLSetConnectAttr (Core) Supported
SQLSetDescField (Core) Supported
SQLSetDescRec (Core) Supported
SQLSetEnvAttr (Core) Supported
SQLSetStmtAttr (Core) Supported
SQLBulkOperations (Level 1) Supported

CData ODBC Driver for Anzo

Supported Data Types

Supported Types

The CData ODBC Driver for Anzo supports the following data types as column values:

CData SchemaODBC Data Type
stringSQL_CHAR
stringSQL_VARCHAR
stringSQL_LONGVARCHAR
shortSQL_SMALLINT
intSQL_INTEGER
longSQL_BIGINT
floatSQL_REAL
doubleSQL_DOUBLE
decimalSQL_DECIMAL
booleanSQL_BIT
datetimeSQL_TYPE_TIMESTAMP
datetimeSQL_TIMESTAMP
timeSQL_TYPE_TIME
timeSQL_TIME

CData ODBC Driver for Anzo

From C/C++

This section provides a reference to ODBC compliance and a walk-through to writing ODBC data access code to Anzo in C/C++.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from C/C++

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo. Connecting shows how to connect with ODBC functions.

Executing SQL

Use ODBC functions to execute SQL to Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.
  • See Discovering Schemas to obtain schema information, such as the available tables, columns, keys, and types. See Data Model to obtain the driver metadata by querying the available system tables.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Connecting

To create a connection, create an environment handle and a connection handle using SQLAllocHandle. You can then use SQLDriverConnect to provide a DSN or an ODBC connection string.

Connect to a DSN


  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
  SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
  SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
  SQLDriverConnect(hdbc, 0, (SQLCHAR*)"Dsn=CData Anzo Source;", SQL_NTS, 0, 0, 0, 0);

Provide a Driver Connection String


  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
  SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
  SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
  SQLDriverConnect(hdbc, 0, (SQLCHAR*)"DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;", SQL_NTS, 0, 0, 0, 0);

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can allocate a statement handle and execute the statement.

SELECT Procedure

Use SQLExecDirect to execute the statement and SQLFetch to fetch the records. You can use SQLBindCol to bind variables to columns in the result set. The numbering of the result set columns starts at 1.

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
SQLDriverConnect(hdbc, 0, (SQLCHAR*)"Dsn=CData Anzo Source", SQL_NTS, 0, 0, 0, 0);
SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
SQLExecDirect(hstmt, (SQLCHAR*)"SELECT location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", SQL_NTS);  
SQLCHAR slocation_displayName[20] = {0};
SQLLEN cblocation_displayName = 0;
SQLBindCol(hstmt, 1, SQL_C_CHAR, slocation_displayName, 20, &cblocation_displayName);
SQLRETURN retcode = SQLFetch(hstmt);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
 ...
}

Iterating over the Results

You can use SQLGetData to get values while iterating through a cursor. To iterate over the results, use SQLFetch to fetch rows and SQLGetData to retrieve the column values.

  SQLHENV henv;
  SQLHDBC hdbc;
  SQLHSTMT hstmt;
  char sId[255] = {0};
  SQLLEN cbId = 0;
  if (SQLAllocHandle(SQL_HANDLE_ENV, 0 ,&henv) == SQL_SUCCESS) {
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
    if (SQLAllocHandle(SQL_HANDLE_DBC, henv ,&hdbc) == SQL_SUCCESS) {
      if (SQLConnect(hdbc, "CData Anzo Source", SQL_NTS, 0, 0, 0, 0) == SQL_SUCCESS) {
        if (SQLAllocHandle(SQL_HANDLE_STMT, hdbc ,&hstmt) == SQL_SUCCESS) {
          if (SQLExecDirect(hstmt, "SELECT Id FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", SQL_NTS) == SQL_SUCCESS) {
            while(SQLFetch(hstmt) == SQL_SUCCESS) {
              if (SQLGetData(hstmt, 1, SQL_C_CHAR, (SQLPOINTER)sId, 255, &cbId) == SQL_SUCCESS) {
                printf("Id: %s\n", sId);
              }
            }
          }
          SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
        }
        SQLDisconnect(hdbc);
      }
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    }
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
  }

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

Use SQLExecDirect to execute data manipulation statements and use the SQLRowCount function to obtain the affected rows.

INSERT

To insert updates:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
SQLDriverConnect(hdbc, 0, (SQLCHAR*)"Dsn=CData Anzo Source;", SQL_NTS, 0, 0, 0, 0);
SQLExecDirect(hstmt, (SQLCHAR*)"INSERT INTO [Anzo].[ExpandData].Events (location_displayName) VALUES ('Town Hall Grille')", SQL_NTS);  
SQLINTEGER  rowCount = 0;
SQLRowCount(hstmt, &rowCount);

UPDATE

To retrieve updates:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
SQLDriverConnect(hdbc, 0, (SQLCHAR*)"Dsn=CData Anzo Source;", SQL_NTS, 0, 0, 0, 0);
SQLExecDirect(hstmt, (SQLCHAR*)"UPDATE [Anzo].[ExpandData].Events SET location_displayName='Town Hall Grille' WHERE Id='Jq74mCczmFXk1tC10GB')", SQL_NTS);  
SQLINTEGER  rowCount = 0;
SQLRowCount(hstmt, &rowCount); 

DELETE

To delete updates:

SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); 
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); 
SQLDriverConnect(hdbc, 0, (SQLCHAR*)"Dsn=CData Anzo Source;", SQL_NTS, 0, 0, 0, 0);
SQLExecDirect(hstmt, (SQLCHAR*)"DELETE FROM [Anzo].[ExpandData].Events WHERE Id='Jq74mCczmFXk1tC10GB')", SQL_NTS);  
SQLINTEGER  rowCount = 0;
SQLRowCount(hstmt, &rowCount); 

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Binding Parameters

Use the SQLBindParameter function to bind the specified parameter position to the specified variable. Note that the parameter order starts at 1.

Example

The following example executes a parameterized SELECT and iterates over the results. You can use SQLExecDirect to execute any parameterized statement.

  SQLHENV henv;
  SQLHDBC hdbc;
  SQLHSTMT hstmt;
  char sId[30] = {0};
  SQLLEN cbsId = 0;
  char param[30] = {0};
  strcpy(param, "Jq74mCczmFXk1tC10GB");
  SQLLEN cbParam = SQL_NTS;
  if (SQLAllocHandle(SQL_HANDLE_ENV, 0 ,&henv) == SQL_SUCCESS) {
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
    if (SQLAllocHandle(SQL_HANDLE_DBC, henv ,&hdbc) == SQL_SUCCESS) {
      if (SQLConnect(hdbc, "CData Anzo Source", SQL_NTS, 0, 0, 0, 0) == SQL_SUCCESS) {
        if (SQLAllocHandle(SQL_HANDLE_STMT, hdbc ,&hstmt) == SQL_SUCCESS) {
          SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 100, 0, (SQLPOINTER)param, 30, &cbParam);
          if (SQLExecDirect(hstmt, "SELECT Id FROM [Anzo].[ExpandData].Events WHERE Id = ?", SQL_NTS) == SQL_SUCCESS) {
            while(SQLFetch(hstmt) == SQL_SUCCESS) {
              if (SQLGetData(hstmt, 1, SQL_C_CHAR, (SQLPOINTER)sId, 255, &cbsId) == SQL_SUCCESS) {
                printf("Id: %s\n", sId);
              }
            }
          }
          SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
        }
        SQLDisconnect(hdbc);
      }
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    }
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
  }

CData ODBC Driver for Anzo

Executing Stored Procedures

Procedure for Calling Stored Procedures

Use SQLExecDirect to call a stored procedure and SQLFetch and SQLGetData to iterate through its results. The following example shows the CALL syntax; you can also use the EXECUTE syntax, detailed in EXECUTE Statements.

Example


  SQLHENV henv;
  SQLHDBC hdbc;
  SQLLEN cbObjectName = SQL_NTS;
  if (SQLAllocHandle(SQL_HANDLE_ENV, 0 ,&henv) == SQL_SUCCESS) {
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
    if (SQLAllocHandle(SQL_HANDLE_DBC, henv ,&hdbc) == SQL_SUCCESS) {
      if (SQLConnect(hdbc, "CData Anzo Source", SQL_NTS, 0, 0, 0, 0) == SQL_SUCCESS) {
        SQLHSTMT hstmt;
        SQLAllocHandle(SQL_HANDLE_STMT, hdbc ,&hstmt); 
        if (SQLExecDirect(hstmt, (SQLCHAR*)"{?=call CreateJob('Account', 'Insert')}", SQL_NTS) == SQL_SUCCESS) {
        if (SQLExecDirect(hstmt, "{?=call SendMail('abc123')}", SQL_NTS) == SQL_SUCCESS) {
          char sCreatedById[255] = {0};
          SQLLEN cbsCreatedById = 0;
          while(SQLFetch(hstmt) == SQL_SUCCESS) {
            SQLGetData(hstmt, 2, SQL_C_CHAR, (SQLPOINTER)sCreatedById, 255, &cbsCreatedById);
            printf("CreatedById: %s\n", sCreatedById);
          }
        }
        SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
        SQLDisconnect(hdbc);
      }
      SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    }
    SQLFreeHandle(SQL_HANDLE_ENV, henv);
  }

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information in the ODBC API. See Data Model to obtain the driver metadata by querying the available system tables.

List Tables and Views

You can use the SQLTables function to list all available tables or views. The TableType parameter can be 'TABLE', 'VIEW', or both, and it is used to decide if tables or views are listed. After calling SQLTables, you can use SQLFetch and SQLBindCol to read the table listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLTables(hstmt, 0, 0, 0, 0, 0, 0, (SQLCHAR*)"'TABLE','VIEW'", SQL_NTS);

List Table Columns

You can use the SQLColumns function to list all columns of a specified table. After calling SQLColumns, you can use SQLFetch and SQLBindCol to read the column listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLColumns(hstmt, 0, 0, 0, 0, (SQLCHAR*)"DemoTable", SQL_NTS, 0, 0);

Get Column Information

You can use the SQLColAttribute function to get information about a column. The ColumnNumber parameter is the column index starting at 1. The FieldIdentifier parameter can be SQL_COLUMN_NAME, SQL_COLUMN_LENGTH, SQL_DESC_TYPE etc.

SQLCHAR columnName[30];
SQLSMALLINT cbColumnName;
SQLColAttribute(hstmt, 1, SQL_COLUMN_NAME, columnName, 30, &cbColumnName, NULL);

You can also use the SQLDescribeCol function to get the column name, type, size, decimal digits, and nullability of a column. The ColumnNumber parameter is the column index starting at 1.

SQLCHAR columnName[256];
SQLSMALLINT cbColumnName;
SQLSMALLINT dataType;
SQLULEN columnSize;
SQLSMALLINT decimalDigits;
SQLSMALLINT nullable;
SQLDescribeCol(hstmt, 1, columnName, 256, &cbColumnName, &dataType, &columnSize, &decimalDigits, &nullable);

List Primary Key Columns

You can use the SQLPrimaryKeys function to get the column name and the sequence number for the primary-key columns of a table. After calling SQLPrimaryKeys, use SQLFetch and SQLBindCol to read the table listing. This is similar to reading columns from any SQL query and is described in Querying Data.

SQLPrimaryKeys(hstmt, NULL, SQL_NTS, NULL, SQL_NTS, (SQLCHAR*)"DemoTable", SQL_NTS);

List Procedures

You can use the SQLProcedures function to list all available procedures. After calling SQLProcedures, you can use SQLFetch and SQLBindCol to read the table listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLProcedures(hstmt, NULL, SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);

List Procedure Columns

You can use the SQLProcedureColumns function to list all columns of a specified procedure. After calling SQLProcedureColumns, you can use SQLFetch and SQLBindCol to read the table listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLProcedureColumns(hstmt, NULL, SQL_NTS, NULL, SQL_NTS, (SQLCHAR*)"DemoProcedure", SQL_NTS, NULL, SQL_NTS);

List Supported ODBC Functions

You can use the SQLGetFunctions function to determine whether a specific ODBC function is supported in the ODBC driver. The FunctionId (second parameter) can be SQL_API_ALL_FUNCTIONS or SQL_API_ODBC3_ALL_FUNCTIONS. The SupportedPtr (third parameter) should be a SQLUSMALLINT array of 100 elements. The call will set the SQLUSMALLINT element to true if the ODBC function is supported by the driver, and false otherwise.

SQLUSMALLINT functions[100];
SQLGetFunctions(hdbc, SQL_API_ALL_FUNCTIONS, functions);

Get Type Information

You can use the SQLGetTypeInfo function to return the information of the specified data type or all types. After calling SQLGetTypeInfo, use SQLFetch and SQLBindCol to read the information; see Querying Data for a code example.

SQLGetTypeInfo(hstmt, SQL_ALL_TYPES);

Get Number of Parameters

You can use the SQLNumParams function to get the parameter count of a query.

SQLSMALLINT paramCount;
SQLNumParams(hstmt, &paramCount);

Get Number of Columns

You can use the SQLNumResultCols function to get the column count of a table.

SQLSMALLINT columnCount;
SQLNumResultCols(hstmt, &columnCount);

Get Number of Rows

You can use the SQLRowCount function to get the row count of a table.

SQLLEN rowCount;
SQLRowCount(hstmt, &rowCount);

List Special Information for Columns

You can use the SQLSpecialColumns function to list all columns of a table with special information. The IdentifierType (second parameter) can be SQL_BEST_ROWID or SQL_ROWVER. The Scope (ninth parameter) can be SQL_SCOPE_CURROW, SQL_SCOPE_TRANSACTION or SQL_SCOPE_SESSION. After calling SQLSpecialColumns, use SQLFetch and SQLBindCol to read the column listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLSpecialColumns(hstmt, SQL_BEST_ROWID, NULL, 0, NULL,0, (SQLCHAR *)"DemoProcedure", SQL_NTS, SQL_SCOPE_SESSION, SQL_NULLABLE);

List Table Statistics Information

You can use the SQLStatistics function to list statistics and indices associated with a table. The IndexType (eighth parameter) can be SQL_INDEX_UNIQUE or SQL_INDEX_ALL. After calling SQLStatistics, you can use SQLFetch and SQLBindCol to read the table listing. This is similar to reading columns from any SQL query, described in Querying Data.

SQLStatistics(hstmt, NULL, 0, NULL, 0, (SQLCHAR*)"DemoProcedure", SQL_NTS, SQL_INDEX_UNIQUE, SQL_QUICK);

CData ODBC Driver for Anzo

From Go

This section provides a walk-through to writing ODBC data access code to Anzo in Go, using the Go ODBC driver and the built-in sql package.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from Go

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo.

Dependencies describes the necessary steps to install the Go ODBC driver. Once it is installed, refer to Connecting to connect to Anzo.

Executing SQL

Use SQL functions to execute SQL on Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Dependencies

This section describes the dependencies for using Go with the CData ODBC Driver for Anzo.

Configure unixODBC (Linux and Mac Only)

Go ODBC uses unixOODBC on Linux and Mac, so make sure the driver is configured as described in Using unixODBC before continuing.

Install Go ODBC

Go ODBC can be installed through go get. You must also have Git installed for go get to download Go ODBC.

$ go get github.com/alexbrainman/odbc

Using Go ODBC

To use Go ODBC, you must import both the SQL package from the standard library as well as Go ODBC itself.

import (
        "database/sql"
        _ "github.com/alexbrainman/odbc"
)

CData ODBC Driver for Anzo

Connecting

To connect to Anzo, you can use either a DSN or an ODBC connection string. Both of these methods use the sql package's Open function.

Connect to a DSN

To connect using a DSN:

db, _ := sql.Open("odbc", "DSN=CData Anzo Sys;")
defer db.Close()

Provide a Driver Connection String

To connect using an ODBC connection string:

db, _ := sql.Open("odbc", "DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;;")
defer db.Close()

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can execute a SQL statement and retrieve the results.

SELECT Procedure

You can use Query to execute the statement, which will return a Row object you can use to fetch results.

rows, _ := db.Query("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")
defer rows.Close()

Iterating over the Results

You can use Next to iterate through the rows in the resultset. To extract values from a row, use Scan to bind columns to local variables. The number of pointers given to Scan must match the number of columns in the resultset exactly, otherwise Scan will return an error.

for rows.Next() {
        var (
                Id string
                location_displayName string
        )

        rows.Scan(&Id, &location_displayName)
        fmt.Printf("Id = %s, location_displayName = %s\n", Id, location_displayName)
}

You may use types with Scan other than strings, as long as the data can be converted by the sql package. Please refer to the Scan function in the sql package documentation for supported types and type conversion rules.

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

You can use Exec to execute data modification statements. Exec returns a Result value which contains the number of affected rows.

INSERT

To insert updates:

result, _ := db.Exec("INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES ('Zenburger')")
affected, _ := result.RowsAffected()

UPDATE

To retrieve updates:

result, _ := db.Exec("UPDATE [Anzo].[ExpandData].Events SET location_displayName = 'Zenburger' WHERE Id = 'Jq74mCczmFXk1tC10GB'")
affected, _ := result.RowsAffected()

DELETE

To delete updates:

result, _ := db.Exec("DELETE FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")
affected, _ := result.RowsAffected()

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Single-Use Statements

The Query and Exec functions both accept additional parameters for binding query parameters to values.

rows, _ := db.Query("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?", "Jq74mCczmFXk1tC10GB")
defer rows.Close()
for rows.Next() {
        var (
                Id string
                location_displayName string
        )

        rows.Scan(&Id, &location_displayName)
        fmt.Printf("Id = %s, location_displayName = %s\n", Id, location_displayName)
}

Reusable Statements

The Prepare function creates prepared Stmt objects, which can be re-used across multiple Query and Exec calls.

stmt, _ := db.Prepare("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?")
defer stmt.Close()

rows, _ := stmt.Query("Jq74mCczmFXk1tC10GB 1")
defer rows.Close()
for rows.Next() {
        var (
                Id string
                location_displayName string
        )

        rows1.Scan(&Id, &location_displayName)
        fmt.Printf("Id = %s, location_displayName = %s\n", Id, location_displayName)
}

rows, _ = stmt.Query("Jq74mCczmFXk1tC10GB 2")
defer rows.Close()
for rows.Next() {
        var (
                Id string
                location_displayName string
        )

        rows2.Scan(&Id, &location_displayName)
        fmt.Printf("Id = %s, location_displayName = %s\n", Id, location_displayName)
}

CData ODBC Driver for Anzo

Executing Stored Procedures

The following code example shows how to execute stored procedures and retrieve their results.

Procedure for Calling Stored Procedures

The Query function can be used to call a stored procedure with the EXECUTE syntax, as described in EXECUTE Statements. As with Querying Data, the results will be available through the Rows object.

rows, _ := db.Query("EXECUTE SendMail MessageId = 'abc123'")
defer rows.Close()

for rows.Next() {
        var (
                result string
        )

        rows.Scan(&result)
        fmt.Printf("result = %s\n", result)
}

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information.

List Tables and Views

Although the sql package does not provide a native interface to query tables and views, you can use the sys_tables system table provided by the driver.

tables, _ := db.Query("SELECT CatalogName, SchemaName, TableName FROM sys_tables WHERE TableType='TABLE'")
defer tables.Close()

for tables.Next() {
        var (
                catalog string
                schema string
                table string
        )

        rows.Scan(&catalog, &schema, &table)
        fmt.Printf("Catalog: %s, Schema: %s, Table: %s", catalog, schema, table)
}

views, _ := db.Query("SELECT CatalogName, SchemaName, TableName FROM sys_tables WHERE TableType='VIEW'")
defer views.Close()

for views.Next() {
        var (
                catalog string
                schema string
                view string
        )

        rows.Scan(&catalog, &schema, &view)
        fmt.Printf("Catalog: %s, Schema: %s, Table: %s", catalog, schema, table)
}

List Table Columns

You can use the sys_tablecolumns to get information about columns.

columns, _ := db.Query("SELECT ColumnName, DataType, Length, NumericPrecision, IsNullable FROM sys_tablecolumns WHERE TableName = '[Anzo].[ExpandData].Events'")
defer columns.Close()

for columns.Next() {
        var (
                column string
                datatype int
                length int
                precision int
                nullable bool
        )

        rows.Scan(&column, &datatype, &length, &precision, &nullable)
        fmt.Printf("Name: %s, Type: %d, Length: %d, Precision: %d, Nullable: %t\n", column, datatype, length, precision, nullable)
}

CData ODBC Driver for Anzo

From Node.js

This section provides a walk-through to writing ODBC data access code to Anzo in Node.js, using the node-odbc package.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from Node.js

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo.

Dependencies describes the necessary steps to install the node-odbc package. Once it is installed, refer to Connecting to connect to Anzo.

Executing SQL

Use node-odbc functions to execute SQL on Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Dependencies

This section describes the dependencies for using Node.js with the CData ODBC Driver for Anzo.

Configure unixODBC (Linux and Mac Only)

node-odbc uses unixODBC on Linux and Mac, so make sure the driver is configured as described in Using unixODBC before continuing.

Install node-odbc

You can install node-odbc using NPM.

npm install odbc

Using node-odbc

Before using node-odbc, you need to require it.

var Database = require("odbc").Database;

CData ODBC Driver for Anzo

Connecting

To connect to Anzo, you can use either a DSN or an ODBC connection string. Both of these methods use the Database's Open method.

Connect to a DSN

To connect using a DSN:

var db = new Database();
db.open("DSN=CData Anzo Sys", (err) => {
    // Use the connection
});

Provide a Driver Connection String

To connect using an ODBC connection string:

var db = new Database();
db.open("DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;;", (err) => {
    // Use the connection
});

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can execute a SQL statement and retrieve the results.

SELECT Procedure

You can use the query method to execute the statement. It will split the query results into batches, and invoke a callback once for each batch. The rows are given to the callback as a list of objects, along with a flag indicating whether more rows are available.

db.open("...", (err) => {
    db.query("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", (err, rows, moreRows) => {
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            console.log("Id = " + row["Id"]);
            console.log("location_displayName = " + row["location_displayName"]);
        }

        if (!moreRows) {
            console.log("All rows have been processed");
        }
    });
});

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

You can use separate statements to execute data modification statements. Once you create the statement, you can call its executeNonQueryMethod and retrieve the number of affected rows.

INSERT

To insert updates:

db.open("...", (err) => {
    db.prepare("INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES ('Zenburger')", (err, stmt) => {
        stmt.executeNonQuery((err, affected) => {
            console.log("Affected: " + affected);
        });
    });
});

UPDATE

To retrieve updates:

db.open("...", (err) => {
    db.prepare("UPDATE [Anzo].[ExpandData].Events SET location_displayName = 'Zenburger' WHERE Id = 'Jq74mCczmFXk1tC10GB'", (err, stmt) => {
        stmt.executeNonQuery((err, affected) => {
            console.log("Affected: " + affected);
        });
    });
});

DELETE

To delete updates:

db.open("...", (err) => {
    db.prepare("DELETE FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", (err, stmt) => {
        stmt.executeNonQuery((err, affected) => {
            console.log("Affected: " + affected);
        });
    });
});

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Single-Use Statements

The query method accepts an additional array parameter for binding query parameters to values.

db.open("...", (err) => {
     db.query(
        "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?",
        ["Jq74mCczmFXk1tC10GB"],
        (err, rows, moreRows) => {
        for (var i = 0; i < rows.length; i++) {
            console.log("Id = " + rows["Id"]);
            console.log("location_displayName = " + rows["location_displayName"]);
        }

        if (!moreRows) {
            console.log("All rows have been processed");
        }
    });
});

Reusable Statements

The prepare method creates prepared ODBCStatement objects, which can be re-used across multiple execute and executeNonQuery calls.

When you execute an ODBCStatement, your callback receives an ODBCResult object which is used to fetch results. It can be used to fetch all results at once into an array, or it can fetch rows one at a time.

db.open("...", (err) => {
    db.prepare(
        "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?",
        (err, stmt) => {
        function printData(result, done) {
            result.fetch((err, row) => {
                if (row === null) done();

                console.log("Id = " + row["Id"]);
                console.log("location_displayName = " + row["location_displayName"]);
                printData(result);
            }
        }

        stmt.executeQuery("Jq74mCczmFXk1tC10GB 1", (err, result) => {
            printData(result, () => {
                stmt.executeQuery("Jq74mCczmFXk1tC10GB 2", (err, result) => {
                    printData(result);
                });
            });
        });
    });
});

CData ODBC Driver for Anzo

Executing Stored Procedures

The following code example shows how to execute stored procedures and retrieve their results.

Procedure for Calling Stored Procedures

The query method can be used to call a stored procedure with the EXECUTE syntax, as described in EXECUTE Statements. As with Querying Data, the results will be given to a callback in batches.

db.open("...", (err) => {
    db.query("EXECUTE SendMail MessageId = 'abc123'", (err, rows, moreRows) => {
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            console.log("result = " + row["result"]);
        }

        if (!moreRows) {
            console.log("All rows have been processed");
        }
    });
});

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information.

List Tables and Views

You can use the tables method to discover what tables and views are available through the driver. This returns results through a callback like a query would.

db.tables(null, null, null, null, (err, tables_views)  => {
    for (var i = 0; i < tables_views.length; i++) {
        var row = tables_views[i];
        console.log("Catalog: " + row.TABLE_CAT +
                    ", Schema: " + row.TABLE_SCHEM +
                    ", Table: " + row.TABLE_NAME +
                    ", Type: " + row.TABLE_TYPE);
    }
});

You can use the columns method to discover what columns are available on a table or view.

db.columns("Anzo","ExpandData","Events", null, (err, columns)  => {
    for (var i = 0; i < columns.length; i++) {
        var row = columns[i];
        console.log("Name: " + row.COLUMN_NAME +
                    ", Type: " + row.DATA_TYPE +
                    ", Length: " + row.COLUMNS_SIZE +
                    ", Precision: " + row.DECIMAL_DIGITS +
                    ", Nullable: " + row.IS_NULLABLE);
    }
});

CData ODBC Driver for Anzo

From PHP

This section provides a walk-through to writing ODBC data access code to Anzo in PHP, using the build-in Unified ODBC API.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from PHP

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo.

Dependencies describes the necessary steps to configure Unified ODBC. Once it is prepared, refer to Connecting to connect to Anzo.

Executing SQL

Use Unified ODBC functions to execute SQL on Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Dependencies

This section describes the dependencies for using PHP with the CData ODBC Driver for Anzo.

Configure unixODBC (Linux Only)

PHP uses unixODBC on Linux, so make sure the driver is configured as described in Using unixODBC before continuing.

Install Unified ODBC

Linux

Most Linux distributions distribute ODBC support in their own packages apart from core PHP. Usually the package is named php-odbc.

# Debian, Ubuntu and related distributions
$ apt install php-odbc

# Red Hat, CentOS and related distributions
$ yum install php-odbc

Windows

On Windows, PHP is typically distributed with built-in ODBC support, so no extra packages are required.

Mac

On recent versions of Mac, the built-in PHP is not compiled with support for ODBC. Refer to the iODBC documentation for instructions on how to compile a version of PHP with iODBC support.

CData ODBC Driver for Anzo

Connecting

To connect to Anzo, you can use either a DSN or an ODBC connection string. Both of these methods use the odbc_connect function.

Connect to a DSN

To connect using a DSN:

$cnx = odbc_connect("CData Anzo Sys", "", "");

Provide a Driver Connection String

To connect using an ODBC connection string:

$cnx = odbc_connect("DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;", "", "");

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can execute a SQL statement and retrieve the results.

SELECT Procedure

You can execute queries using odbc_exec. This will return a resource that you can use to read results.

$stmt = odbc_exec($cnx, "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'");

Iterating over the Results

You can use odbc_fetch_array to fetch the next row as an array.

while ($row = odbc_fetch_array($stmt)) {
    echo "Id = ", $row["Id"], "\n";
    echo "location_displayName = ", $row["location_displayName"], "\n";
}

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

You can use odbc_exec to execute data modification statements. This will return a resource which contains the number of affected rows.

INSERT

To insert updates:

$result = odbc_exec($cnx, "INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES ('Zenburger')");
$affected = odbc_num_rows($result);

UPDATE

To retrieve updates:

$result = odbc_exec($cnx, "UPDATE [Anzo].[ExpandData].Events SET location_displayName = 'Zenburger' WHERE Id = 'Jq74mCczmFXk1tC10GB'");
$affected = odbc_num_rows($result);

DELETE

To delete updates:

$result = odbc_exec($cnx, "DELETE FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'");
$affected = odbc_num_rows($result);

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Reusable Statements

The odbc_prepare function creates prepared statements, which can be re-used across multiple calls to odbc_execute. The statement object can be used to fetch results like a non-parameterized query.

$stmt = odbc_prepare($cnx, "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?");

odbc_execute($stmt, array("Jq74mCczmFXk1tC10GB 1"));
while ($row = odbc_fetch_array($stmt)) {
    echo "Id = ", $row["Id"], "\n";
    echo "location_displayName = ", $row["location_displayName"], "\n";
}

odbc_execute($stmt, array("Jq74mCczmFXk1tC10GB 2"));
while ($row = odbc_fetch_array($stmt)) {
    echo "Id = ", $row["Id"], "\n";
    echo "location_displayName = ", $row["location_displayName"], "\n";
}

CData ODBC Driver for Anzo

Executing Stored Procedures

The following code example shows how to execute stored procedures and retrieve their results.

Procedure for Calling Stored Procedures

The odbc_exec function called be used to call a stored procedure with the EXECUTE syntax, as described in EXECUTE Statements. As with Querying Data, the results can be obtained by iterating on the returned resource.

$stmt = odbc_exec($cnx, "EXECUTE SendMail MessageId = 'abc123'");
while ($row = odbc_fetch_array($stmt)) {
    echo "result = ", $row["result"], "\n";
}

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information.

List Tables and Views

You can use the odbc_tables function to discover what tables and views are available through the driver. This returns results through a resource like a query would.

$stmt = odbc_tables($cnx);
while ($row = odbc_fetch_array($stmt)) {
    echo "Catalog: ", $row["TABLE_CAT"], "\n";
    echo "Schema: ", $row["TABLE_SCHEM"], "\n";
    echo "Table: ", $row["TABLE_NAME"], "\n";
    echo "Type: ", $row["TABLE_TYPE"], "\n";
}

You can use the odbc_columns method to discover what columns are available on a table or view.

$stmt = odbc_columns($cnx);
while ($row = odbc_fetch_array($stmt)) {
    if ($row["TABLE_NAME"] == "Events") {
        echo "Name: ", $row["COLUMN_NAME"], "\n";
        echo "Type: ", $row["DATA_TYPE"], "\n";
        echo "Length: ", $row["COLUMN_SIZE"], "\n";
        echo "Precision: ", $row["DECIMAL_DIGITS"], "\n";
        echo "Nullable: ", $row["IS_NULLABLE"], "\n";
    }
}

CData ODBC Driver for Anzo

From Python

This section provides a walk-through to writing ODBC data access code to Anzo in Python, using the pyodbc module.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from Python

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo.

Dependencies describes the necessary steps to install pyodbc. Once it is prepared, refer to Connecting to connect to Anzo.

Executing SQL

Use pyodbc functions to execute SQL on Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Dependencies

This section describes the dependencies for using Python with the CData ODBC Driver for Anzo.

Configure unixODBC (Linux and Mac Only)

pyodbc uses unixODBC on Linux and Mac, so make sure your driver is configured as described in Using unixODBC before continuing.

Install pyodbc

You can use pip to install the module.

pip install pyodbc

Using pyodbc

To use pyodbc, you must import the pyodbc package.

import pyodbc

CData ODBC Driver for Anzo

Connecting

To connect to Anzo, you can use either a DSN or an ODBC connection string. Both of these methods use the connect function.

Connect to a DSN

To connect using a DSN:

cnxn = pyodbc.connect("DSN=CData Anzo Sys;User=MyUser;Password=MyPassword")

Provide a Driver Connection String

To connect using an ODBC connection string:

cnxn = pyodbc.connect("DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;")

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can execute a SQL statement and retrieve the results.

SELECT Procedure

You will need to obtain a cursor before executing any SQL. Once you have one, you can use the cursor's execute method.

cursor = cnxn.cursor()
cursor.execute("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")

Iterating over the Results

You can use a for loop to iterate over the rows of the resultset. Each row is presented as a tuple containing column values:

for (Id, location_displayName) in cursor:
    print("Id = {}, location_displayName = {}".format(Id, location_displayName))

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

You can use execute method to execute data modification statements. This will update the cursor's rowcount property with the number of affected rows.

Note that you must commit the connection after performing the modification, or your changes may be lost.

INSERT

To insert updates:

cursor.execute("INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES ('Zenburger')")
cnxn.commit()
affected = cursor.rowcount

UPDATE

To retrieve updates:

cursor.execute("UPDATE [Anzo].[ExpandData].Events SET location_displayName = 'Zenburger' WHERE Id = 'Jq74mCczmFXk1tC10GB'")
cnxn.commit()
affected = cursor.rowcount

DELETE

To delete updates:

cursor.execute("DELETE FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")
cnxn.commit()
affected = cursor.rowcount

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Single-Use Statements

The execute method accepts an additional sequence for binding query parameters to values.

cursor.execute("SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?", ("Jq74mCczmFXk1tC10GB",))
for (Id, location_displayName) in cursor:
    print("Id = {}, location_displayName = {}".format(Id, location_displayName))

Multi-Use Statements

The executemany method can be used to execute the same query repeatedly with different sets of parameters. Instead of a sequence of parameters, executemany accepts a nested sequence of parameters which are used for each execution.

executemany works only with INSERT, UPDATE and DELETE statements. It cannot be used with any operation that returns results, such as a SELECT or an EXECUTE.

params = [
  ("Zenburger 1",),
  ("Zenburger 2",),
  ("Zenburger 3",),
]

cursor.executemany("INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES (?)", params)

CData ODBC Driver for Anzo

Executing Stored Procedures

The following code example shows how to execute stored procedures and retrieve their results.

Procedure for Calling Stored Procedures

The execute method can be used to call a stored procedure with the EXECUTE syntax, as described in EXECUTE Statements. As with Querying Data, the results will be available through the cursor.

cursor.execute("EXECUTE SendMail MessageId = 'abc123'")
for (result,) in cursor:
    print("result = ", result)

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information.

List Tables and Views

You can use the tables method to discover what tables and views are available through the driver. This returns results on the cursor like a query would.

cursor.tables()
for (catalog, schema, table, table_type, description) in cursor:
    print("Catalog: {}, Schema: {}, Table: {}, Type: {}".format(
        catalog, schema, table, table_type
    ))

You can use the columns method to discover what columns are available on a table or view.

cursor.columns("Events","Anzo","ExpandData")
for row in cursor:
    print("Name: {}, Type: {}, Length: {}, Precision: {}, Nullable: {}".format(
        row[3], row[5], row[6], row[8], row[17]
    ))

CData ODBC Driver for Anzo

From R

This section provides a walk-through to writing ODBC data access code to Anzo in R, using the RODBC module.

See Data Model for more information on the available API objects and any API limitations or requirements. See SQL Compliance for the SQL syntax.

Connecting from R

See Getting Started for the prerequisite information you need to deploy the driver and configure the connection to Anzo.

Dependencies describes the necessary steps to install RODBC. Once it is prepared, refer to Connecting to connect to Anzo.

Executing SQL

Use RODBC functions to execute SQL on Anzo:

  • See Querying Data to execute SELECT statements and iterate over the results.
  • See Updating Data to execute other SQL data manipulation statements.
  • See Parameterized Statements to execute parameterized statements. Parameterized statements provide a means to efficiently execute queries more than once and to mitigate SQL injection attacks.

Executing Stored Procedures

See Executing Stored Procedures to execute stored procedures as SQL statements.

CData ODBC Driver for Anzo

Dependencies

This section describes the dependencies for using R with the CData ODBC Driver for Anzo.

Configure unixODBC (Linux and Mac Only)

RODBC uses unixODBC on Linux and Mac, so make sure your driver is configured as described in Using unixODBC before continuing.

Install RODBC

You can install the latest RODBC package from CRAN using install.packages.

install.packages("RODBC")

If you are interested in using parameterized queries, you should install RODBCext as well. RODBCext is an add-on library to RODBC that adds support for parameterized queries.

install.packages("RODBCext")

Using RODBC

To use RODBC, you must load the RODBC and RODBCext libraries.

library(RODBC)
library(RODBCext)

CData ODBC Driver for Anzo

Connecting

To connect to Anzo, you can use either a DSN or an ODBC connection string. Both of these methods use the odbcConnect function.

Connect to a DSN

To connect using a DSN:

cnx <- odbcConnect("CData Anzo Sys")

Provide a Driver Connection String

To connect using an ODBC connection string:

cnx <- odbcDriverConnect(connection = "DRIVER={CData ODBC Driver for Anzo};User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;")

CData ODBC Driver for Anzo

Querying Data

After Connecting, you can execute a SQL statement and retrieve the results.

SELECT Procedure

You can use the sqlQuery function to execute queries. By default, it will return all the results as a single data frame. This works well for smaller result sets.

results <- sqlQuery(cnx, "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")
for (row in 1:nrow(results)) {
    cat(paste("Id = ", results[row,]$Id, "\n"))
    cat(paste("location_displayName = ", results[row,]$location_displayName, "\n"))
}

Iterating over the Results

For larger result sets, sqlQuery can return results in batches instead of storing the entire result set in memory. When there are no results left, or an error occurs, sqlQuery and sqlGetResults will return an integer error code instead of a data frame.

results <- sqlQuery(cnx, "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", max = 1000)
while (is.data.frame(results)) {
    for (row in 1:nrow(results)) {
        cat(paste("Id = ", results[row,]$Id))
        cat(paste("location_displayName = ", results[row,]$location_displayName))
    }
    rows <- sqlGetResults(cnx, max = 1000)
}

CData ODBC Driver for Anzo

Updating Data

The following code examples show how to use data modification statements.

Procedure for Updates

You can use sqlQuery method to execute data modification statements.

INSERT

To insert updates:

sqlQuery("INSERT INTO [Anzo].[ExpandData].Events(location_displayName) VALUES ('Zenburger')")

UPDATE

To retrieve updates:

sqlQuery("UPDATE [Anzo].[ExpandData].Events SET location_displayName = 'Zenburger' WHERE Id = 'Jq74mCczmFXk1tC10GB'")

DELETE

To delete updates:

sqlQuery("DELETE FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'")

CData ODBC Driver for Anzo

Parameterized Statements

The following code example shows how to bind parameters to create parameterized statements.

Single-Use Statements

The sqlExecute function from RODBCext accepts an additional data frame for binding query parameters to values.

sqlExecute(
    cnx,
    query = "SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = ?",
    data = data.frame("Jq74mCczmFXk1tC10GB")
)

results <- sqlGetResults(cnx, max = 1000)
while (is.data.frame(results)) {
    for (row in 1:nrow(results)) {
        cat(paste("Id = ", results[row,]$Id, "\n"))
        cat(paste("location_displayName = ", results[row,]$location_displayName, "\n"))
    }
    results <- sqlGetResults(cnx, max = 1000)
}

CData ODBC Driver for Anzo

Executing Stored Procedures

The following code example shows how to execute stored procedures and retrieve their results.

Procedure for Calling Stored Procedures

The sqlQuery function can be used to call a stored procedure with the EXECUTE syntax, as described in EXECUTE Statements. As with Querying Data, the results will be returned as a data frame directly from sqlQuery.

results <- sqlQuery("EXECUTE SendMail MessageId = 'abc123'")
for (row in 1:nrow(results)) {
    cat(paste("result = ", results[row,]$result, "\n"))
}

CData ODBC Driver for Anzo

Discovering Schemas

The following sections show how to obtain schema information.

List Tables and Views

You can use the sqlTables function to discover what tables and views are available through the driver. This returns results in a data frame like a query would.

results <- sqlTables(cnx)
for (row in 1:nrow(results)) {
    cat(paste("Catalog: ", results[row,]$TABLE_CAT,
              ", Schema: ", results[row,]$TABLE_SCHEM,
              ", Table: ", results[row,]$TABLE_NAME,
              ", Type: ", results[row,]$TABLE_TYPE, "\n"))
}

You can use the sqlColumns function to discover what columns are available on a table or view.

results <- sqlColumns(cnx, sqtable = "Events", schema = "ExpandData", catalog = "Anzo")
for (row in 1:nrow(results)) {
    cat(paste("Name: ", results[row,]$COLUMN_NAME,
              ", Type: ", results[row,]$DATA_TYPE,
              ", Length: ", results[row,]$COLUMN_SIZE,
              ", Precision: ", results[row,]$DECIMAL_DIGITS,
              ", Nullable: ", results[row,]$IS_NULLABLE, "\n")
}

CData ODBC Driver for Anzo

Using from Tools

The driver provides the standard ODBC connection process in analytics tools and other applications.

ODBC Integration Quickstarts

The following sections show how to create and start querying Anzo ODBC data sources, walking through data access in ODBC from popular tools.

Complete List of Anzo Integration Quickstarts

See Anzo integration guides for information on connecting from other applications.

CData ODBC Driver for Anzo

From Excel

This section describes how to use the driver with two Excel utilities, the Data Connection Wizard and Microsoft Query. If you are interested in using data from Anzo in Power Pivot, see the section: From PowerPivot.

macOS Configuration

On macOS, you need to set the AnsiCodePage configuration setting in the cdata.odbc.anzo.ini file, which is located in the folder containing the driver library, the lib subfolder under /Applications/CData ODBC Driver for Anzo. Add the AnsiCodePage property in the Driver section.

You need to set the value of this property to the code page of your machine's current system locale. Here are several examples:

LanguageCode Page
EnglishISO-8859-1
ChineseGB2312
JapaneseShift_JIS

Data Connection Wizard

Select From Other Sources > From Data Connection Wizard in the Data tab. Select ODBC DSN as your chosen data source type and click Next. Here, you can view all of the ODBC data sources on your machine. See "DSN Configuration" to configure a new ODBC data source if the CData Anzo data source is not listed. Once you select the data source, you will be presented with a list of tables. On this page, you can select the table and then import the data.

Microsoft Query in Windows

Select From Other Sources > From Microsoft Query from the Data tab. Here, you can view all of the ODBC data sources on your machine. See "DSN Configuration" to configure an ODBC data source if you do not see the CData Anzo data source. Once you select the correct data source, you will be guided through the following windows:

  • Choose Columns: Preview the data in any column and select the columns you want to include.
  • Filter Data: Add conditions that will filter data based on your criteria.
  • Sort Order: Select how the data should be sorted.
Click Finish to create the external data connection.

Microsoft Query in macOS

Select New Database Query > From Database from the Data tab. Here, you can view all of the ODBC data sources on your machine. See "DSN Configuration" to configure an ODBC data source if you do not see the CData Anzo data source.

Once you select the correct data source, you will need to build your query in the SQL Statement section. Clicking the table names will add the select statement that retrieves all data from that table. You will now have an external data connection.

Refreshing Data

Both the Data Connection Wizard and Microsoft Query create an external data connection in Excel. External data connections have options that control refreshing the data; you can control these settings from the WorkBook Connections window under the Data tab. There are options available to refresh the data each time the file is opened, or periodically at a specified interval.

CData ODBC Driver for Anzo

From PowerPivot

Power Pivot is a popular business-intelligence add-in from Microsoft for Microsoft Excel. When PowerPivot is installed, the PowerPivot tab is added to the Excel ribbon. PowerPivot is freely available from Microsoft. You can follow this guide to import tables into PowerPivot.

macOS Configuration

On macOS, you need to set the AnsiCodePage configuration setting in the cdata.odbc.anzo.ini file, which is located in the folder containing the driver library, the lib subfolder under /Applications/CData ODBC Driver for Anzo. Add the AnsiCodePage property in the Driver section.

You need to set the value of this property to the code page of your machine's current system locale. Here are several examples:

LanguageCode Page
English28591
Chinese936
Japanese932

Load Anzo Tables

Follow the steps below after creating a DSN and configuring the driver:
  1. Launch the PowerPivot window from the PowerPivot Window button on the PowerPivot tab of Excel.
  2. Click Get External Data > Other Data Sources to open the Table Import Wizard.
  3. Select Other/Advanced (OLEDB/ODBC) Relational Data Source and click Next. You will be presented with a dialog that allows you to define a user-friendly connection name for your connection and build a connection string for it.
  4. Click Build to open the Data Link Properties window.
  5. On the Provider tab, select Microsoft OLEDB Provider for ODBC Drivers.
  6. On the Connection tab of the Data Link Properties window, select Use data source name and select the CData Anzo Data Source. See "DSN Configuration" to configure an ODBC Data Source if you do not see the CData Anzo data source. Once you select the correct data source and exit the Data Link Properties dialog, a connection string will be built for you. It should resemble the following example:
    Provider=MSDASQL.1;Persist Security Info=False;DSN=MyAnzoDSN
  7. Select the option to select from a list of tables for the data to import.
  8. Select the tables you want to import and click Finish.

If you want to import specific columns or only the results that match your criteria, you can also select the option to write a query.

CData ODBC Driver for Anzo

From Access

You can use the CData ODBC Driver for Anzo to import data into an Access table and to create a linked table.

Import a Table into Access

To import a table into Access:

  1. Select External Data > ODBC Database from the ribbon. This opens the ODBC Database wizard. Select the option to import the source data into a new table in the current database.
  2. Select the CData Anzo data source from the Machine Data Source tab.
  3. Select the tables to import into Access.

Importing data into Access is a one-time import.; This means that any changes made to the Access table will not be reflected back to the main data source and vice versa. Use linked tables if you want the changes to propagate back to the data source.

Link a Table in Access

To link a table in Access to a table in Anzo:

  1. Select External Data > ODBC Data sources from the ribbon.
  2. Select the option to link to the data source by creating a linked table.
  3. On the next page of the wizard, select the CData Anzo data source in the Machine Data Source tab.

Once you select the correct data source, you will be presented with a list of tables. Here, you can select a table that you want as a linked table in Access. The linked table will always have fresh data and any changes made to it will be reflected back to the underlying table in Anzo.

Limitations in Access

There are a few limitations with using the driver from Access in linked mode.

Inserting a new row may result in Access showing a new row with a value of #deleted for all of its fields. This is because Access is unable to select the recently inserted row correctly. The row was created, which a refresh will verify. Optionally, you can also set the MaximumColumnSize to less than 255, which will allow Access to select the inserted row.

CData ODBC Driver for Anzo

From FileMaker Pro

You can connect to a DSN to load Anzo data into FileMaker Pro tables that can be refreshed on demand.

Building a Query to Anzo

FileMaker Pro provides a wizard to build the data import SQL.

  1. In your FileMaker Pro database, select File > Import Records > ODBC Data Source, and select the CData Anzo Source DSN.
  2. In the resulting SQL Query Builder wizard, select tables and columns and then click Insert into SQL Query. You can also edit this query directly.

    You can use the UI to build filters in the WHERE clause by clicking the WHERE tab.

  3. In the resulting Import Field Mapping wizard, you can define mappings from columns in the data source to the columns in a destination table. To create a new table for the query results, select New Table ("CData Anzo Source") from the Target box and click Import.

Refreshing Data

You can load any changes made to the external data into your FileMaker tables in Browse by selecting Records > Refresh Window. FileMaker Pro also executes a SELECT to Anzo when you run a search on the Fields tab of the relationships graph. To pick up new fields added to Anzo, select File > Manage > Database. In the resulting dialog, click the Fields tab, select a table, and then select columns to sync.

CData ODBC Driver for Anzo

From OBIEE

This section describes how to create Anzo DSNs for use in Oracle Business Intelligence Enterprise Edition (OBIEE) installations on Linux.

Configure a DSN

Follow the procedure in Using the DataDirect Driver Manager to set the driver encoding, register the driver, and create a DSN. In OBIEE 12c, you can find the odbc.ini and odbcinst.ini configuration files in BI_DOMAIN/config/fmwconfig/bienv/core.

Test the Connection

To test the newly configured DSN 'CData Anzo Source', you can use the nqcmd OBIEE utility command.

CData ODBC Driver for Anzo

From Informatica

This section describes how to create a DSN on the Informatica PowerCenter server. To connect to Anzo from Informatica PowerCenter, install the driver on the machine running Informatica Information Services and the machine you are connecting from. On both machines, you will then need to specify the connection properties in a DSN.

On Windows, you can use the Microsoft ODBC Data Source Administrator to create and configure ODBC DSNs. Linux editions of Informatica embed the DataDirect driver manager: the following steps show how to use this driver manager to configure a DSN for Informatica. You can then connect to the DSN from client tools like the Workflow Manager and Informatica.

Configure a DSN on a Linux Server

Before defining the DSN, complete these prerequisite steps:

  1. Set the ODBCSYSINI environment variable:
    >$ export ODBCSYSINI=/home/infar/Informatica/9.6.1/ODBC7.1
  2. Set the ODBCINI environment variable:
    >$ export ODBCINI=$ODBCSYSINI/odbc.ini
  3. Set the LD_LIBRARY_PATH environment variable:
    >$ export LD_LIBRARY_PATH=/home/infar/Informatica/9.6.1/ODBC7.1/lib:$LD_LIBRARY_PATH
You can then follow the procedure in Using the DataDirect Driver Manager to set the driver encoding and create the DSN in odbc.ini. For example, in /home/infar/Informatica/9.6.1/ODBC7.1/odbc.ini or /opt/informatica/10.1/ODBC7.1/odbc.ini. Note that the step to register the driver in odbcinst.ini is not required for Informatica.

Test the Connection

To test the newly configured DSN 'CData Anzo Source', you can use the utility ssgodbc:

  1. Change to the directory containing the tool in your Informatica installation. For example, enter the following command, changing the destination folder to match your operating system, as necessary:
    cd $INFA_HOME/tools/debugtools/ssgodbc/linux64
  2. Enter the following to test the DSN:
    ssgodbc -d "CData Anzo Source"-u username -p password -v

CData ODBC Driver for Anzo

From SAS

This section describes how to create a DSN for use with SAS running on a Linux machine.

Configure a DSN

Before defining the DSN, complete the following the prerequisite steps:

  1. Set ODBCHOME env:
    >$ export ODBCHOME=/usr/local/SASHome/dfs/etc
  2. Set ODBCINI env:
    >$ export ODBCINI=$ODBCHOME/odbc.ini
  3. Set LD_LIBRARY_PATH env:
    >$ export LD_LIBRARY_PATH=/usr/local/SASHome/dfs/lib:$LD_LIBRARY_PATH
You can then follow the procedure in Using the DataDirect Driver Manager to set the driver encoding configure the DSN for SAS in the odbc.ini file. For example, in /usr/local/SASHome/dfs/etc/odbc.ini.

Note: The step to register the driver in odbcinst.ini is not required for SAS.

CData ODBC Driver for Anzo

Advanced Features

This section details a selection of advanced features of the Anzo driver.

User Defined Views

The driver allows you to define virtual tables, called user defined views, whose contents are decided by a pre-configured query. These views are useful when you cannot directly control queries being issued to the drivers. See User Defined Views for an overview of creating and configuring custom views.

SSL Configuration

Use SSL Configuration to adjust how driver handles TLS/SSL certificate negotiations. You can choose from various certificate formats; see the SSLServerCert property under "Connection String Options" for more information.

Firewall and Proxy

Configure the driver for compliance with Firewall and Proxy, including Windows proxies and HTTP proxies. You can also set up tunnel connections.

Linked Server

The driver can create a Linked Server that can execute linked server queries. In addition, if you are using Windows, you can set up ODBC remoting, which allows you to connect to the ODBC driver from remote machines.

SQL Gateway

The SQL Gateway enables remote access to ODBC data sources as virtual SQL Servers or MySQL databases. In addition to brokering requests, the SQL Gateway allows for secure connections through firewalls. Connections are secured via TLS/SSL. SQL Gateway also supports SSH reverse tunneling, which is very useful for allowing cloud services to access on-premises data.

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.

Logging

See Logging for an overview of configuration settings that can be used to refine CData logging. For basic logging, you only need to set two connection properties, but there are numerous features that support more refined logging, where you can select subsets of information to be logged using the LogModules connection property.

CData ODBC Driver for Anzo

User Defined Views

The CData ODBC Driver for Anzo allows you to define a virtual table whose contents are decided by a pre-configured query. These are called User Defined Views, which are useful in situations where you cannot directly control the query being issued to the driver, e.g. when using the driver from a tool. The User Defined Views can be used 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 driver 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 driver.

This User Defined View configuration file is formatted as follows:

  • Each root element defines the name of a view.
  • Each root element contains a child element, called query, which contains the custom SQL query for the view.

For example:

{
	"MyView": {
		"query": "SELECT * FROM [Anzo].[ExpandData].Events WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}
Use the UserDefinedViews connectio 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 driver 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

User Defined Views are exposed in the UserViews schema by default. This is done to avoid the view's name clashing with an actual entity in the data model. You can change the name of the schema used for UserViews by setting 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 ODBC Driver for Anzo

SSL Configuration

Customizing the SSL Configuration

By default, the driver 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 ODBC Driver for Anzo

Firewall and Proxy

Connecting Through a Firewall or Proxy

HTTP Proxies

To connect through the Windows system proxy, you do not need to set any additional connection properties. To connect to other proxies, set ProxyAutoDetect to false.

In addition, to authenticate to an HTTP proxy, set ProxyAuthScheme, ProxyUser, and ProxyPassword, in addition to ProxyServer and ProxyPort.

Other Proxies

Set the following properties:

  • To use a proxy-based firewall, set FirewallType, FirewallServer, and FirewallPort.
  • To tunnel the connection, set FirewallType to TUNNEL.
  • To authenticate, specify FirewallUser and FirewallPassword.
  • To authenticate to a SOCKS proxy, additionally set FirewallType to SOCKS5.

CData ODBC Driver for Anzo

Linked Server

CData supports creating a linked server in SQL Server Management Studio with our ODBC drivers. This section describes how to create a linked server and then execute queries from that linked server.

Create a Linked Server

See Create a Linked Server for information on creating a linked server in SQL Server Management Studio.

Linked server support is enabled through the ODBC remoting feature. The ODBC remoting feature allows you to connect to the ODBC driver from remote machines. You connect to each ODBC data source as a virtual MySQL or SQL Server database, communicating through the MySQL or TDS (SQL Server) protocols. ODBC remoting is managed through the CData SQL Gateway application. The remoting feature is only available in the Windows edition.

Execute Queries on a Linked Server

See Execute Queries on a Linked Server for information on executing queries to the Anzo linked server from any tool that can connect to SQL Server.

Connect from MySQL Workbench

See Connect from MySQL Workbench for information on configuring ODBC remoting and accessing Anzo as a virtual MySQL database in MySQL Workbench.

CData ODBC Driver for Anzo

Create a Linked Server

This section describes how to configure and create a linked SQL Server instance.

Linked Server Benefits

You can use SQL Linked Server to connect to the CData SQL Gateway. SQL Server treats the CData SQL Gateway as a linked SQL Server instance, so you can write full SQL queries to query your Anzo data without losing performance as would happen connecting to an ODBC data source directly. The connection can be made locally or to the Gateway located on a separate machine.

Configure the Linked Server

Configuring remote access to an ODBC data source in the SQL Gateway administration tool consists of the following steps:

  1. Configure the proxying service on the Services tab.
  2. Configure database users on the Users tab.
  3. Configure TLS/SSL on the Other tab.
  4. Access services hosted behind a firewall by configuring the Tunneling.

Create a Linked Server from the UI

To create a linked server from the UI in SQL Server Management Studio:

  1. Open SQL Server Management Studio and connect to an instance of SQL Server.
  2. Expand the Server Objects node, right-click Linked Servers, and click New Linked Server. The New Linked Server dialog is displayed.
  3. In the General section, select Other Data Source and enter the following information after naming the linked server:
    • Provider: Select the SQL Server Native Client Provider that corresponds to your version of SQL Server. For example, SQL Server Native Client 11.0.
    • Data Source: Enter the host and port the service is running on, separated by a comma. For example, "localhost,1434". If you are connecting off-network through the SSH Tunnel enter the host and port of your SSH host. Note that a value of "localhost" in the Data Source input refers to the machine where SQL Server is running, so be careful when creating a linked server in Management Studio when not running on the same machine as SQL Server.
    • Catalog: Enter the system DSN as the catalog. For example, "CData Anzo Sys".
  4. In the Security section, select Be Made Using this Security Context and enter the username and password of a user you authorized on the SSH Tunnel tab in the SQL Gateway administration console.

Create a Linked Server Programmatically

In addition to using the SQL Server Management Studio UI to create a linked server, you can use stored procedures. The following inputs are required to create the linked server:

  • Server: The linked server name.
  • Provider: Enter "SQLNCLI", for the SQL Server Native Client Provider.
  • Datasrc: The host and port the service is running on, separated by a comma. Note that a value of "localhost" in the datasrc input refers to the machine where SQL Server is running, so be careful when creating a linked server in Management Studio when not running on the same machine as SQL Server.
  • Catalog: Enter the system DSN configured for the service.
  • Srvproduct: Enter the product name of the data source; this can be an arbitrary value, such as "CData SQL Gateway" or an empty string.

To create the linked server and configure authentication to the SQL Gateway:

  1. Call sp_addlinkedserver to create the linked server:
    EXEC sp_addlinkedserver @server='Anzo',
      @srvproduct = '',
      @provider='SQLNCLI',
      @datasrc='<Machine IP address>,1434',
      @catalog='CData Anzo Sys';
    GO
  2. Call sp_addlinkedsrvlogin to allow SQL Server users to connect with the credentials of an authorized user of the service. Note that the credentials you use to connect to the service must map to a user you defined on the Users tab in the SQL Gateway administration tool.
    EXEC sp_addlinkedsrvlogin @rmtsrvname='Anzo',
      @rmtuser='admin',
      @rmtpassword='test',
      @useself='FALSE',
      @locallogin=NULL;
    GO

Connect from SQL Server Management Studio

SQL Server Management Studio uses the SQL Server Client OLE DB provider, which requires the ODBC driver to be used inprocess. You must enable the Allow inprocess option for the SQL Server Client Provider in Management Studio to query the linked server from SQL Server Management Studio. To do this, open the properties for the provider you are using under Server Objects > Linked Servers > Providers.

CData ODBC Driver for Anzo

Execute Queries on a Linked Server

This section describes how to execute queries to the Anzo linked server from any tool that can connect to SQL Server.

When executing queries from a linked server, you must use a four-part name format, as shown below.

[<Linked Server Name>].[<DSN Name>].[<Schema Name (normally but not always the service name)>].[<Table Name>]

Where:

  • Linked Server Name is the name of the linked server that you created.
  • DSN Name is the name of the data source.
  • Schema Name is the name of the system schema or user-defined schema.
  • Table Name is the name of the table you are copying data from.

SELECT Statements

To create new records:

SELECT * FROM [Linked Server Name].[CData Anzo Sys].[Anzo].[[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'

Note that if the data source supports case-sensitive identifiers, it is not possible to query tables of the same name that only vary by casing (ex: Account and ACCOUNT in the same schema). This is due to the fact that SQL Server and MySQL treats identifiers as case-insensitive, so multiple tables of the same name in a single schema are fundamentally incompatible with the SQL Server and MySQL protocols.

INSERT, UPDATE, and DELETE Statements

To insert, update, or delete a single row of data (that is, not a batch of records), you need to use the four-part name. For example:

INSERT INTO [Linked Server Name].[CData Anzo Sys].[Anzo].[[Anzo].[ExpandData].Events] (Id) VALUES ('Jq74mCczmFXk1tC10GB');

To retrieve newly created IDs from an INSERT operation, you can query the sys_identity system table. For example:

SELECT * FROM OPENQUERY([Linked Server Name], 'SELECT * FROM sys_identity');

Execute Stored Procedures

To execute stored procedures, you must first enable RPC and RPC Out in the settings for the linked server. Then, you can use the following set of commands to run the stored procedure:

DECLARE @RunStoredProcSQL VARCHAR(1000);
SET @RunStoredProcSQL = 'EXEC SendMail MessageId=''abc123''';
EXEC (@RunStoredProcSQL) AT [Linked Server Name];

CData ODBC Driver for Anzo

Connect from MySQL Workbench

The CData ODBC Driver for Anzo integrates with MySQL clients through MySQL virtualization managed through the CData SQL Gateway application. The SQL Gateway enables you to create MySQL interfaces for ODBC data sources. Clients like MySQL Workbench can connect to Anzo ODBC data sources as virtual MySQL databases.

This section describes how to configure ODBC remoting and access Anzo as a virtual MySQL database in MySQL Workbench.

Configure ODBC Remoting

Creating a virtual MySQL database in the SQL Gateway administration tool consists of the following steps:

  1. Configure and start the proxying service on the Services tab.
  2. Configure database users on the Users tab.
  3. If you need to connect over TLS/SSL, configure it on the Other tab.
  4. Access services hosted behind a firewall by configuring Tunneling.

Connect to the Database

Click Database > Connect to Database in the main menu. Name the connection and enter the following information in the resulting dialog:

Hostname and PortEnter the hostname and port of the service or, if you are connecting from off network, enter the location of the Tunneling.
UsernameEnter the username of a user account you created in the SQL Gateway.

When you click Test Connection, you are prompted for the password and also to accept the SQL Gateway's digital certificate, if you enabled SSL when you configured the service. You can configure the certificate on the Other tab.

Query the Database

After connecting to the database, you can browse metadata in the Schemas section of the Navigator pane. You can also visually build queries. For example, right-click a table and select Select Rows - Limit 1000.

CData ODBC Driver for Anzo

SQL Gateway

The CData SQL Gateway enables remote access to ODBC data sources as virtual SQL Server or MySQL databases. The SQL Gateway application listens on a configured port for requests made in the MySQL or TDS (SQL Server) wire protocols and responds to those by reading from and writing to the ODBC data source. This allows you to connect to any ODBC DSN from remote machines, using any tool or application that can work with either MySQL or SQL Server.

In addition to brokering the SQL request to ODBC DSNs, the SQL Gateway also makes it easy to securely connect to data from across the firewall. You can configure the SQL Gateway to create an SSH reverse tunnel to a machine that is outside the firewall with just a few simple settings. Any connections made to this external machine are then relayed securely to the SQL Gateway instance within the firewall. Connections are secured via TLS/SSL and standard access control mechanisms available in MySQL and SQL Server. SSH reverse tunneling support is especially useful in allowing cloud services to access on-premises data.

Configuring Remoting Services

To enable remote access, you create a service that listens for database queries over the MySQL or TDS (SQL Server) protocols and then proxies them to the ODBC driver tied to the DSN. You can create remoting services for any ODBC driver.

The MySQL and TDS remoting services you create can be managed on the Services tab in the CData SQL Gateway administration tool. Define access control lists on the Users tab to manage access to your created services.

Hosting Services Behind the Firewall

The Gateway feature enables you to build an SSH reverse tunnel to an SSH host outside the firewall. The Gateway can also manage the reverse tunnel connection, reconnecting if the connection is lost or interrupted, without any need for a third-party tool.

Configure the SSH reverse tunnel on the Tunneling tab.

CData ODBC Driver for Anzo

Services

On the Services tab, you configure services to proxy MySQL or SQL Server connections to ODBC drivers. To run services as Windows services, select "Run as a Windows Service" on the Status tab.

For additional connection settings, such as configuring TLS/SSL, see Other.

Service Settings

The following settings configure the proxy service. Note that you must have Windows administrator access, as the SQL Gateway connects through system DSNs.

  • Service Name: Specify the name of the database.
  • SQL Server or MySQL: Select the database to emulate.
  • Data Source: Select the system DSN for the ODBC data source you want to access as a SQL Server or MySQL database.

  • SSL: Select this option to use TLS/SSL to encrypt client connections. You must configure TLS/SSL for SQL Server databases. See Other to configure the server certificate.
  • Port: Select the port the service will listen on.
  • Expose on Gateway: Enable this option to allow remote access to firewalled databases through an SSH server. You need to first configure the SSH Tunnel feature on the Tunneling tab. If the SSH server is running, the SQL Gateway will automatically select a port on the server: When connecting to the SSH server, specify the Remote Port value.

Startup Settings

Windows services have the following startup options:

  • Automatic: The service automatically starts at boot.

  • Manual: Services configured for manual startup can be started manually or from an application, such as the SQL Gateway or a script.
  • Disabled: The service can only be started manually from the Services snap-in to the Microsoft Management Console or the Task Manager.
You can start Windows services from the SQL Gateway's Services tab or from the Services snap-in to the Microsoft Management Console. To load the snap-in, enter "run" in the Start menu and then enter "services.msc".

Logging Options

Basic information about the service, such as startup and shutdown, is displayed on the Status tab.

To retrieve more verbose service-specific logs, select the Log Mode option and enable the Write Log to a File option on the service configuration dialog accessed on the Services tab.

The logging options on the Other tab will log to a file when the configured services start and stop and also any errors encountered in the SQL Gateway app itself.

Managing Incoming Connections

Advanced database connection settings, such as the idle connection timeout, are available on the Other tab.

CData ODBC Driver for Anzo

Users

On the Users tab, you can control access to services through privileged user accounts. The following options are available to add or edit a user:

  • User: Enter the username.
  • Password: Enter the password for the user.
  • Privilege Settings: Specify whether the user is an administrator of the SQL Gateway. This setting applies to all services. Or, select an access scope for each service you want to allow the adminstrator access to: full, read-only, or none.

CData ODBC Driver for Anzo

Status

The Status tab reports basic information about each service. On this tab you can also configure whether SQL Gateway services run as Windows services.

To obtain database logs, see Services. To obtain SQL Gateway logs, see Other.

CData ODBC Driver for Anzo

Tunneling

The Gateway simplifies hosting services behind a firewall: It enables you to tunnel connections through an SSH server.

Configuring Local Database Access

The connection from the SQL Gateway to the SSH server is a reverse SSH tunnel; after authenticating the SQL Gateway, the server automatically forwards remote connections.

Along with the Host and Port in the Remote Server section, you need to specify the credentials needed to perform SSH authentication. You also need to have already created a service and selected the "Enable on Gateway" option on the Services tab.

Authenticating to the Server

Select one of the following options in the Auth Mode menu in the Remote Server section and then click Test SSH Connection to initiate a login to the SSH server.

Password Authentication

In this authentication method, the SQL Gateway logs in with the username and password of a user account on the machine running the SSH server. The password is securely sent through the encrypted SSH tunnel.

Public Key Authentication

You will need a key pair to perform this authentication method. Specify a digital certificate or create a certificate to obtain a key pair: Click the button in the Certificate box.

  • Private Key: Select the private key from the Windows certificate stores, from a .pfx file, or from a .pem file.

  • Public Key: Click Export Public Key to save the public key as an OpenSSH public key, an SSH2 public key, or an X.509 public key certificate.

The public key is configured on the server and used to encrypt data that can only be decrypted by the private key. The SQL Gateway uses the private key to decrypt data packets from the server and to authenticate.

Managing SSH

In the Advanced Settings section, you can configure SSH connection behavior:

  • Timeout: Configure the seconds the connection is allowed to idle.
  • Auto Reconnect: Select whether the SQL Gateway will attempt to reconnect when the SSH connection is lost.
  • Reconnect Count: Enter the number of reconnection attempts the SQL Gateway will make when the connection is lost. A value of -1 signifies that the SQL Gateway will attempt to reconnect indefinitely.
  • Reconnect Interval: Select the retry interval, in seconds.

CData ODBC Driver for Anzo

Other

On the Other tab, you can configure TLS/SSL and more advanced connection settings. You can also configure logging for the SQL Gateway.

Securing Connections with TLS/SSL

You must configure SSL for SQL Server connections. The certificate specified on this tab will also be used for SSL-enabled MySQL connections.

A default certificate is shipped for testing purposes; this certificate is not suitable for production.

To secure database connections with SSL, specify a digital certificate by clicking the button in the SSL Cert box. Configure the SQL Gateway with the private key in the resulting dialog.

You can select a private key from the available certificate stores. Or, click Create New Certificate on the System Store tab to create a new key pair. Select an existing private key from the system store, the user store, a PFX file, or a PEM file.

After configuring the private key in the SQL Gateway, clients need to be able to trust the public key. To trust the key, clients validate the certificate's chain of trust.

A self-signed certificate, such as a certificate you create with the SQL Gateway, is the only certificate in the chain. To trust a self-signed certificate, you must manually validate and accept the certificate.

One way to accept the certificate is to add it to the trusted system store. Your application may require a different store.

Logging Application Info

To record SQL Gateway activity, enable the Write Log to a File option and specify the logfile, verbosity, and log rotation interval.

CData ODBC Driver for Anzo

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 driver'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 driver 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 ODBC Driver for Anzo

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 driver uses a platform-dependent default location.

CacheConnection

The CacheConnection property specifies a database driver and the connection string to the caching database.

CacheProvider

The CacheProvider property specifies a database driver and the connection string to the caching database.

CData ODBC Driver for Anzo

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 driver 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 ODBC Driver for Anzo

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 driver automatically initializes and builds a cache in the background. When AutoCache = true, the driver uses the cache for subsequent query executions, resulting in faster response times.

Configuring Automatic Caching

Caching the Events Table

The following example caches the Events table in the file specified by the CacheLocation property of the connection string.

SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

SQLHSTMT hstmt;
SQLTCHAR connectString[1024];
SQLSMALLINT cbconnectString;
SQLDriverConnect(hdbc, 0, (SQLTCHAR*)"DSN=CData Anzo Source;AutoCache=true;Cache Location=C:\\cache.db", SQL_NTS, connectString, 1024, &cbconnectString, SQL_DRIVER_COMPLETE);
SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
SQLExecDirect(hstmt, (SQLCHAR*)"SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'", SQL_NTS);
while(SQLFetch(hstmt) == SQL_SUCCESS) {}
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);

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 ODBC Driver for Anzo

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 driver.

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 [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

SQLCHAR *cmd = (SQLCHAR*)"CACHE SELECT * FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'";
SQLExecDirect(hstmt, cmd, SQL_NTS);

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 [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'
  

SQLCHAR *cmd = (SQLCHAR*)"CACHE WITH TRUNCATE SELECT * FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'";
SQLExecDirect(hstmt, cmd, SQL_NTS);

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 [Anzo].[ExpandData].Events#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 [Anzo].[ExpandData].Events WHERE Id='Jq74mCczmFXk1tC10GB' ORDER BY location_displayName ASC

Delete Data from the Cache

You can delete data from the cache by building a direct connection to the database. Note that the driver 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 ODBC Driver for Anzo

Data Type Mapping

The driver 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 ODBC Driver for Anzo

Logging

Capturing driver logging can be very helpful when diagnosing error messages or other unexpected behavior.

Basic Logging

You will simply need to set two connection properties to begin capturing driver logging.

  • Logfile: A filepath which designates the name and location of the log file.
  • Verbosity: This is a numerical value (1-5) that determines the amount of detail in the log. See the page in the Connection Properties section for a breakdown 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 this property is set, the driver will populate 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 will be created.

Log Verbosity

The verbosity level determines the amount of detail that the driver reports to the Logfile. Verbosity levels from 1 to 5 are supported. These are described in the following list:

1Setting Verbosity to 1 will log the query, the number of rows returned by it, the start of execution and the time taken, and any errors.
2Setting Verbosity to 2 will log everything included in Verbosity 1, cache queries, and additional information about the request.
3Setting Verbosity to 3 will additionally log HTTP headers, as well as the body of the request and the response.
4Setting Verbosity to 4 will additionally log transport-level communication with the data source. This includes SSL negotiation.
5Setting Verbosity to 5 will additionally log communication with the data source and additional details that may be helpful in troubleshooting problems. This includes interface commands.

The Verbosity should not be set to greater than 1 for normal operation. Substantial amounts of data can be logged at higher verbosities, which can delay execution times.

To refine the logged content further by showing/hiding specific categories of information, see LogModules.

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.

All modules are four characters long. Please note that modules containing three letters have a required trailing blank space. The available modules are:

  • EXEC: Query Execution. Includes execution messages for original SQL queries, parsed SQL queries, and normalized SQL queries. Query and page success/failure messages appear here as well.
  • INFO: General Information. Includes the connection string, driver version (build number), and initial connection messages.
  • HTTP: HTTP Protocol messages. Includes HTTP requests/responses (including POST messages), as well as Kerberos related messages.
  • SSL : SSL certificate messages.
  • OAUT: OAuth related failure/success messages.
  • SQL : Includes SQL transactions, SQL bulk transfer messages, and SQL result set messages.
  • META: Metadata cache and schema messages.
  • TCP : Incoming and Ongoing raw bytes on TCP transport layer messages.
An example value for this property would be.
LogModules=INFO;EXEC;SSL ;SQL ;META;

Note that these modules refine the information as it is pulled after taking the Verbosity into account.

CData ODBC Driver for Anzo

SQL Compliance

The CData ODBC Driver for Anzo supports several operations on data, including querying, deleting, modifying, and inserting.

SELECT Statements

See SELECT Statements for a syntax reference and examples.

See Data Model for information on the capabilities of the Anzo API.

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 driver'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').

Transactions and Batching

Transactions are not currently supported.

Additionally, the driver does not support batching of SQL statements. To execute multiple commands, you can create multiple instances and execute each separately. [Or, use Batch Processing.

CData ODBC Driver for Anzo

SELECT Statements

A SELECT statement can consist of the following basic clauses. This statement can be accessed using the Odbc.Query function in the M formula language.

  • 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 driver:

SELECT {
  [ TOP <numeric_literal> | DISTINCT ]
  { 
    * 
    | { 
        <expression> [ [ AS ] <column_reference> ] 
        | { <table_name> | <correlation_name> } .* 
      } [ , ... ] 
  }
  [ INTO csv:// [ filename= ] <file_path> [ ;delimiter=tab ] ]
  { 
    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 
  | <literal>
  | <sql_function> 

<search_condition> ::= 
  {
    <expression> { = | > | < | >= | <= | <> | != | LIKE | NOT LIKE | IN | NOT IN | IS NULL | IS NOT NULL | AND | OR | CONTAINS | BETWEEN } [ <expression> ]
  } [ { AND | OR } ... ] 

Examples

  1. Return all columns:
    SELECT * FROM [Anzo].[ExpandData].Events
  2. Rename a column:
    SELECT [location_displayName] AS MY_location_displayName FROM [Anzo].[ExpandData].Events
  3. Cast a column's data as a different data type:
    SELECT CAST(Reminder AS VARCHAR) AS Str_Reminder FROM [Anzo].[ExpandData].Events
  4. Search data:
    SELECT * FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'
  5. Return the number of items matching the query criteria:
    SELECT COUNT(*) AS MyCount FROM [Anzo].[ExpandData].Events 
  6. Return the number of unique items matching the query criteria:
    SELECT COUNT(DISTINCT location_displayName) FROM [Anzo].[ExpandData].Events 
  7. Return the unique items matching the query criteria:
    SELECT DISTINCT location_displayName FROM [Anzo].[ExpandData].Events 
  8. Summarize data:
    SELECT location_displayName, MAX(Reminder) FROM [Anzo].[ExpandData].Events GROUP BY location_displayName
    See Aggregate Functions for details.
  9. Retrieve data from multiple tables.
    SELECT Groups.displayName, Conversations.Topic FROM Groups, Conversations WHERE Groups.Id=Conversations.GroupId
    See JOIN Queries for details.
  10. Sort a result set in ascending order:
    SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events  ORDER BY location_displayName ASC
  11. Restrict a result set to the specified number of rows:
    SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events LIMIT 10 
  12. Parameterize a query to pass in inputs at execution time. This enables you to create prepared statements and mitigate SQL injection attacks.
    SELECT * FROM [Anzo].[ExpandData].Events WHERE Id = @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 Anzo.

    SELECT * FROM [Anzo].[ExpandData].Events WHERE Pseudo = '@Pseudo'
    

CData ODBC Driver for Anzo

Aggregate Functions

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(Reminder) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

COUNT(DISTINCT)

Returns the number of distinct, non-null field values matching the query criteria.

SELECT COUNT(DISTINCT Id) AS DistinctValues FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

AVG

Returns the average of the column values.

SELECT location_displayName, AVG(Reminder) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'  GROUP BY location_displayName

MIN

Returns the minimum column value.

SELECT MIN(Reminder), location_displayName FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB' GROUP BY location_displayName

MAX

Returns the maximum column value.

SELECT location_displayName, MAX(Reminder) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB' GROUP BY location_displayName

SUM

Returns the total sum of the column values.

SELECT SUM(Reminder) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

CData ODBC Driver for Anzo

JOIN Queries

The CData ODBC Driver for Anzo 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 Groups.displayName, Conversations.Topic FROM Groups, Conversations WHERE Groups.Id=Conversations.GroupId

Left Join

A left join selects all rows in the FROM table and only matching rows in the JOIN table:

SELECT Groups.displayName, Conversations.Topic FROM Groups LEFT OUTER JOIN Conversations ON Groups.Id=Conversations.GroupId

CData ODBC Driver for Anzo

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 ODBC Driver for Anzo

SELECT INTO Statements

You can use the SELECT INTO statement to export formatted data to a file. This statement can be accessed using the Odbc.Query function in the M formula language.

Data Export with an SQL Query

The following query exports data into a file formatted in comma-separated values (CSV):

SELECT Id, location_displayName INTO [csv://[Anzo].[ExpandData].Events.txt] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'
You can specify other formats in the file URI. The possible delimiters are tab, semicolon, and comma with the default being a comma. The following example exports tab-separated values:
SELECT Id, location_displayName INTO [csv://[Anzo].[ExpandData].Events.txt;delimiter=tab] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'

C#

String connectionString = "User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;";

using (AnzoConnection connection = new AnzoConnection(connectionString)) {
  AnzoCommand cmd = new AnzoCommand("SELECT Id, location_displayName INTO [csv://[Anzo].[ExpandData].Events.txt] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB' ", connection);
  int rowsAffected = cmd.ExecuteNonQuery();
} 

VB.NET

Dim connectionString As [String] = "User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;" 

Using connection As New AnzoConnection(connectionString)
  Dim cmd As New AnzoCommand("SELECT Id, location_displayName INTO [csv://[Anzo].[ExpandData].Events.txt] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'", connection)
  Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
End Using
You can specify other file formats in the URI. The following example exports tab-separated values:

C#

String connectionString = "User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;";

using (AnzoConnection connection = new AnzoConnection(connectionString)) {
  AnzoCommand cmd = new AnzoCommand("SELECT * INTO [[Anzo].[ExpandData].Events] IN [csv://filename=c:/[Anzo].[ExpandData].Events.csv;delimiter=tab] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'", connection);
  int rowsAffected = cmd.ExecuteNonQuery();
} 

VB.NET

Dim connectionString As [String] = "User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;" 

Using connection As New AnzoConnection(connectionString)
  Dim cmd As New AnzoCommand("SELECT * INTO [[Anzo].[ExpandData].Events] IN [csv://filename=c:/[Anzo].[ExpandData].Events.csv;delimiter=tab] FROM [[Anzo].[ExpandData].Events] WHERE Id = 'Jq74mCczmFXk1tC10GB'", connection)
  Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
End Using

CData ODBC Driver for Anzo

SQL Functions

The driver 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 driver 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 driver syntax for the DATENAME function:

  • SQL Server:
    SELECT DATENAME(yy,GETDATE())
  • driver:
    SELECT DATENAME('yy',GETDATE())

String Functions

These functions perform string manipulations and return a string value. See STRING Functions for more details.

SELECT CONCAT(firstname, space(4), lastname) FROM [Anzo].[ExpandData].Events WHERE Id = 'Jq74mCczmFXk1tC10GB'

Date Functions

These functions perform date and date time manipulations. See DATE Functions for more details.

SELECT CURRENT_TIMESTAMP() FROM [Anzo].[ExpandData].Events

Math Functions

These functions provide mathematical operations. See MATH Functions for more details.

SELECT RAND() FROM [Anzo].[ExpandData].Events

Function Parameters and Nesting SQL Functions

The driver supports column names, constants, and results of other functions as parameters to functions. The following are all valid uses of SQL functions:
SELECT CONCAT('Mr.', SPACE(2), firstname, SPACE(4), lastname) FROM [Anzo].[ExpandData].Events

CData ODBC Driver for Anzo

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
                    

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: The 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 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.
  • *: The optional 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 to read the size from.

				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'
                    

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
                    

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: The optional character position to start searching for expressionToFind in expressionToSearch.

                      SELECT INDEXOF('0123456', '456');
                      -- Result: 4

                      SELECT INDEXOF('0123456', '456', 5);
                      -- Result: -1
                    

ISNULL ( check_expression , replacement_value )

Replaces null with the specified replacement value.

  • check_expression: The expression to be checked for null.
  • replacement_value: The expression to be returned if check_expression is null.

                      SELECT ISNULL(42, 'Was NULL');
                      -- Result: 42

                      SELECT ISNULL(NULL, 'Was NULL');
                      -- Result: 'Was NULL'
                    

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_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
                    

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
                    

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 will be searched for the substring.

				SELECT LOCATE('sample','XXXXXsampleXXXXX');
				-- Result: 6
				

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 255.

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: The optional single character to be used as the delimiter. Can be a single quotation mark, a left or right bracket, or a double quotation mark. If quote_character is not specified brackets are used.

                      SELECT QUOTENAME('table_name');
                      -- Result: '[table_name]'

                      SELECT QUOTENAME('table_name', '"');
                      -- Result: '"table_name"'

                      SELECT QUOTENAME('table_name', '[');
                      -- Result: '[table_name]'
                    

REPLACE(string_expression, string_pattern, string_replacement)

Replaces all occurrences of a string with another string.

  • string_expression: The string expression to be searched. 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'
                    

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 ODBC Driver for Anzo

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), dayofyear (dy, y), day (dd, d), week (wk, ww), weekday (dw), hour (hh), minute (mi, n), second (ss, s), and 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 day (dd, d), hour (hh), minute (mi, n), second (ss, s), and 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
                

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), nanosecond (ns), and TZoffset (tz).
  • 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), TZoffset (tz), 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
                  

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
                  

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
                  

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
                  

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
                

FDWEEK(date)

Returns the first day of the week of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT FDWEEK('02-08-2018');
				  -- Result: 2/4/2018
				  

FDMONTH(date)

Returns the first day of the month of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT FDMONTH('02-08-2018');
				  -- Result: 2/1/2018
				  

FDQUARTER(date)

Returns the first day of the quarter of the given date part.
  • date: The datetime string that specifies the date.

				  SELECT FDQUARTER('05-08-2018');
				  -- Result: 4/1/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
				

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.

                  SELECT GETUTCDATE();
                  -- For example, if the local timezone is Eastern European Time (GMT+2)
                  -- Result: 2018-02-01 05:04:05
                

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
				

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
				

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
				

LDWEEK(date)

Returns the last day of the provided week.

  • date: The datetime string.

				SELECT LDWEEK('02-02-2020');
				-- Result: 2/8/2020
				

LDMONTH(date)

Returns the last day of the provided month.

  • date: The datetime string.

				SELECT LDMONTH('02-02-2020');
				-- Result: 2/29/2020
				

LDQUARTER(date)

Returns the last day of the provided quarter.

  • date: The datetime string.

				SELECT LDQUARTER('02-02-2020');
				-- Result: 3/31/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. Follows standard .NET date format syntax. 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 ODBC Driver for Anzo

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
				

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 ommitted, 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
				

CData ODBC Driver for Anzo

INSERT Statements

To create new records, use INSERT statements. This statement can be accessed using the Odbc.Query function in the M formula language.

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 [Anzo].[ExpandData].Events (location_displayName) VALUES ('Zenburger')

CData ODBC Driver for Anzo

UPDATE Statements

To modify existing records, use UPDATE statements. This statement can be accessed using the Odbc.Query function in the M formula language.

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 { <column_reference> = <expression> } [ , ... ] WHERE { Id = <expression>  } [ { AND | OR } ... ] 

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>

The following is an example query:

UPDATE [Anzo].[ExpandData].Events SET location_displayName='Zenburger' WHERE Id = @myId

CData ODBC Driver for Anzo

DELETE Statements

To delete information from a table, use DELETE statements. This statement can be accessed using the Odbc.Query function in the M formula language.

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 [Anzo].[ExpandData].Events WHERE Id = @myId

CData ODBC Driver for Anzo

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 driver 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.

This statement can be accessed using the Odbc.Query function in the M formula language.

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 driver 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 driver 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 driver 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 driver creates the cache table based on the SELECT statement without executing the query.

ALTER SCHEMA

If this option is set, the driver 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 [Anzo].[ExpandData].Events

Use the following cache statement to cache all rows of a table into the cache table Cached[Anzo].[ExpandData].Events:

CACHE CachedEvents SELECT * FROM [Anzo].[ExpandData].Events

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 CachedEvents SELECT * FROM [Anzo].[ExpandData].Events 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 Id and location_displayName even though the cache table Cached[Anzo].[ExpandData].Events has all the columns in [Anzo].[ExpandData].Events.

CACHE CachedEvents SCHEMA ONLY SELECT * FROM [Anzo].[ExpandData].Events
CACHE CachedEvents SELECT Id, location_displayName FROM [Anzo].[ExpandData].Events

CData ODBC Driver for Anzo

EXECUTE Statements

To execute stored procedures, you can use EXECUTE or EXEC statements. This statement can be accessed using the Odbc.Query function in the M formula language.

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 ODBC Driver for Anzo

Data Model

The CData ODBC Driver for Anzo models Anzo entities in relational Views, or read-only tables. The table definitions are dynamically obtained from the Anzo source you connect to. Any changes in the metadata, such as added or removed columns or changes in data type, can be loaded by reconnecting.

Views

The driver models the entity sets and singletons described in the API's service metadata document as Tables. Since Anzo is currently read-only, tables can only be read from at this time.

CData ODBC Driver for Anzo

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 Anzo:

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 driver 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 ODBC Driver for Anzo

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 ODBC Driver for Anzo

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 ODBC Driver for Anzo

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.

CData ODBC Driver for Anzo

sys_tablecolumns

Describes the columns of the available tables and views.

The following query returns the columns and data types for the [Anzo].[ExpandData].Events table:

SELECT ColumnName, DataTypeName FROM sys_tablecolumns WHERE TableName='Events' AND CatalogName='Anzo' AND SchemaName='ExpandData'

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.

CData ODBC Driver for Anzo

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 ODBC Driver for Anzo

sys_procedureparameters

Describes stored procedure parameters.

The following query returns information about all of the input parameters for the SendMail stored procedure:

SELECT * FROM sys_procedureparameters WHERE ProcedureName='SendMail' AND Direction=1 OR Direction=2

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.
DataTypeName String The name of the data type.
DataType Int32 An integer indicating the data type. This value is determined at run time based on the environment.
Length Int32 The number of characters allowed for character data. The number of digits allowed for numeric data.
NumericPrecision Int32 The maximum precision for numeric data. The column length in characters for character and date-time 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.

CData ODBC Driver for Anzo

sys_keycolumns

Describes the primary and foreign keys.

The following query retrieves the primary key for the [Anzo].[ExpandData].Events table:

         SELECT * FROM sys_keycolumns WHERE IsKey='True' AND TableName='Events' AND CatalogName='Anzo' AND SchemaName='ExpandData'
          

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 ODBC Driver for Anzo

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 ODBC Driver for Anzo

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 ODBC Driver for Anzo

sys_connection_props

Returns information on the available connection properties and those set in the connection string.

When querying this table, the config connection string should be used:

jdbc:cdata:anzo:config:

This connection string enables you to query this table without a valid connection.

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 ODBC Driver for Anzo

sys_sqlinfo

Describes the SELECT query processing that the driver can offload to the data source.

Collaborative Query Processing

When working with data sources that do not support SQL-92, you can query the sys_sqlinfo view to determine the query capabilities of the underlying APIs, expressed in SQL syntax. The driver offloads as much of the SELECT statement processing as possible to the server and then processes the rest of the query in memory.

See SupportEnhancedSQL for more information on how the driver circumvents API limitations with in-memory client-side processing. See SQL Compliance for SQL syntax details.

Discovering the Data Source's SELECT Capabilities

Below is an example data set of SQL capabilities. The following result set indicates the SELECT functionality that the driver can offload to the data source or process client side. Your data source may support additional SQL syntax. 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 ODBC Driver for Anzo

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 ODBC Driver for Anzo

Data Type Mapping

Data Type Mappings

The driver maps types from the data source to the corresponding data type available in the schema. The table below documents these mappings.

Anzo (OData V4) CData Schema
Edm.Binary binary
Edm.Boolean bool
Edm.Date datetime
Edm.DateTimeOffset datetime
Edm.Decimal decimal
Edm.Double double
Edm.Guid guid
Edm.Int32 int
Edm.String string
Edm.TimeOfDay time

CData ODBC Driver for Anzo

Connection Properties

The connection 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 settings for this provider. Click the links for further details.

For more information on establishing a connection, see Getting Started.

Authentication


PropertyDescription
URLURL to the Anzo endpoint.
UserThe Anzo user account used to authenticate.
PasswordThe password used to authenticate the user.

SSL


PropertyDescription
SSLServerCertThe certificate to be accepted from the server when connecting using TLS/SSL.

Firewall


PropertyDescription
FirewallTypeThe protocol used by a proxy-based firewall.
FirewallServerThe name or IP address of a proxy-based firewall.
FirewallPortThe TCP port for a proxy-based firewall.
FirewallUserThe user name to use to authenticate with a proxy-based firewall.
FirewallPasswordA password used to authenticate to a proxy-based firewall.

Proxy


PropertyDescription
ProxyAutoDetectThis indicates whether to use the system proxy settings or not. This takes precedence over other proxy settings, so you'll need to set ProxyAutoDetect to FALSE in order use custom proxy settings.
ProxyServerThe hostname or IP address of a proxy to route HTTP traffic through.
ProxyPortThe TCP port the ProxyServer proxy is running on.
ProxyAuthSchemeThe authentication type to use to authenticate to the ProxyServer proxy.
ProxyUserA user name to be used to authenticate to the ProxyServer proxy.
ProxyPasswordA password to be used to authenticate to the ProxyServer proxy.
ProxySSLTypeThe SSL type to use when connecting to the ProxyServer proxy.
ProxyExceptionsA semicolon separated list of destination hostnames or IPs that are exempt from connecting through the ProxyServer .

Logging


PropertyDescription
LogfileA filepath which designates the name and location of the log file.
VerbosityThe verbosity level that determines the amount of detail included in the log file.
LogModulesCore modules to be included in the log file.
MaxLogFileSizeA string specifying the maximum size in bytes for a log file (for example, 10 MB).
MaxLogFileCountA string specifying the maximum file count of log files.

Schema


PropertyDescription
LocationA path to the directory that contains the schema files defining tables, views, and stored procedures.
BrowsableSchemasThis property restricts the schemas reported to a subset of the available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC.
ViewsRestricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC.

Caching


PropertyDescription
AutoCacheAutomatically caches the results of SELECT queries into a cache database specified by either CacheLocation or both of CacheConnection and CacheProvider .
CacheProviderThe name of the provider to be used to cache data.
CacheConnectionThe connection string for the cache database. This property is always used in conjunction with CacheProvider . Setting both properties will override the value set for CacheLocation for caching data.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceThe tolerance for stale data in the cache specified in seconds when using AutoCache .
OfflineUse offline mode to get the data from the cache instead of the live source.
CacheMetadataThis property determines whether or not to cache the table metadata to a file store.

Miscellaneous


PropertyDescription
CustomHeadersOther headers as determined by the user (optional).
CustomUrlParamsThe custom query string to be included in the request.
DefaultDomainThis property is used for the Oracle Database Gateway for ODBC.
EnableForeignKeyDetectionWhether to detect the foreign keys in ODBC.
IncludeDualTableSet this property to mock the Oracle DUAL table for better compatibility with Oracle database.
LimitKeySizeThe maximum length of a primary key column.
MapBigintToVarcharThis property controls whether or not the bigint type maps to SQL_VARCHAR instead of SQL_BIGINT. This property is false by default.
MapToIntThis property controls whether or not the long type maps to SQL_INTEGER instead of SQL_BIGINT. This property is false by default.
MapToLongVarcharThis property controls whether or not a column is returned as SQL_LONGVARCHAR.
MapToWVarcharThis property controls whether or not string types map to SQL_WVARCHAR instead of SQL_VARCHAR. This property is set by default.
MaximumColumnSizeThe maximum column size.
MaxRowsLimits the number of rows returned rows when no aggregation or group by is used in the query. This helps avoid performance issues at design time.
OtherThese hidden properties are used only in specific use cases.
PagesizeThe maximum number of results to return per page from Anzo.
PseudoColumnsThis property indicates whether or not to include pseudo columns as columns to the table.
SupportEnhancedSQLThis property enhances SQL functionality beyond what can be supported through the API directly, by enabling in-memory client-side processing.
TimeoutThe value in seconds until the timeout error is thrown, canceling the operation.
UpperCaseIdentifiersThis property reports all identifiers in uppercase. This is the default for Oracle databases and thus allows better integration with Oracle tools such as the Oracle Database Gateway.
CData ODBC Driver for Anzo

Authentication

This section provides a complete list of the Authentication properties you can configure in the connection settings for this provider.


PropertyDescription
URLURL to the Anzo endpoint.
UserThe Anzo user account used to authenticate.
PasswordThe password used to authenticate the user.
CData ODBC Driver for Anzo

URL

URL to the Anzo endpoint.

Data Type

string

Default Value

""

Remarks

URL to the Anzo endpoint. For example:

http://35.184.41.230:8080/dataondemand/MyData

CData ODBC Driver for Anzo

User

The Anzo user account used to authenticate.

Data Type

string

Default Value

""

Remarks

Together with Password, this field is used to authenticate against the Anzo server.

The ODBC UID property maps to User.

CData ODBC Driver for Anzo

Password

The password used to authenticate the user.

Data Type

string

Default Value

""

Remarks

The User and Password are together used to authenticate with the server.

The ODBC PWD property maps to Password.

CData ODBC Driver for Anzo

SSL

This section provides a complete list of the SSL properties you can configure in the connection settings for this provider.


PropertyDescription
SSLServerCertThe certificate to be accepted from the server when connecting using TLS/SSL.
CData ODBC Driver for Anzo

SSLServerCert

The certificate to be accepted from the server when connecting using TLS/SSL.

Data Type

string

Default Value

""

Remarks

If using a TLS/SSL connection, this property can be used to specify the TLS/SSL certificate to be accepted from the server. Any other certificate that is not trusted by the machine is 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

If not specified, any certificate trusted by the machine is accepted.

Use '*' to signify to accept all certificates. Note that this is not recommended due to security concerns.

CData ODBC Driver for Anzo

Firewall

This section provides a complete list of the Firewall properties you can configure in the connection settings for this provider.


PropertyDescription
FirewallTypeThe protocol used by a proxy-based firewall.
FirewallServerThe name or IP address of a proxy-based firewall.
FirewallPortThe TCP port for a proxy-based firewall.
FirewallUserThe user name to use to authenticate with a proxy-based firewall.
FirewallPasswordA password used to authenticate to a proxy-based firewall.
CData ODBC Driver for Anzo

FirewallType

The protocol used by a proxy-based firewall.

Possible Values

NONE, TUNNEL, SOCKS4, SOCKS5

Data Type

string

Default Value

"NONE"

Remarks

This property specifies the protocol that the driver will use to tunnel traffic through the FirewallServer proxy. Note that by default, the driver connects to the system proxy; to disable this behavior and connect to one of the following proxy types, set ProxyAutoDetect to false.

Type Default Port Description
TUNNEL 80 When this is set, the driver opens a connection to Anzo and traffic flows back and forth through the proxy.
SOCKS4 1080 When this is set, the driver sends data through the SOCKS 4 proxy specified by FirewallServer and FirewallPort and passes the FirewallUser value to the proxy, which determines if the connection request should be granted.
SOCKS5 1080 When this is set, the driver sends data through the SOCKS 5 proxy specified by FirewallServer and FirewallPort. If your 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 ODBC Driver for Anzo

FirewallServer

The name or IP address of a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

This property specifies the IP address, DNS name, or host name of a proxy allowing traversal of a firewall. The protocol is specified by FirewallType: Use FirewallServer with this property to connect through SOCKS or do tunneling. Use ProxyServer to connect to an HTTP proxy.

Note that the driver uses the system proxy by default. To use a different proxy, set ProxyAutoDetect to false.

CData ODBC Driver for Anzo

FirewallPort

The TCP port for a proxy-based firewall.

Data Type

int

Default Value

0

Remarks

This specifies the TCP port for a proxy allowing traversal of a firewall. Use FirewallServer to specify the name or IP address. Specify the protocol with FirewallType.

CData ODBC Driver for Anzo

FirewallUser

The user name to use to authenticate with a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

The FirewallUser and FirewallPassword properties are used to authenticate against the proxy specified in FirewallServer and FirewallPort, following the authentication method specified in FirewallType.

CData ODBC Driver for Anzo

FirewallPassword

A password used to authenticate to a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

This property is passed to the proxy specified by FirewallServer and FirewallPort, following the authentication method specified by FirewallType.

CData ODBC Driver for Anzo

Proxy

This section provides a complete list of the Proxy properties you can configure in the connection settings for this provider.


PropertyDescription
ProxyAutoDetectThis indicates whether to use the system proxy settings or not. This takes precedence over other proxy settings, so you'll need to set ProxyAutoDetect to FALSE in order use custom proxy settings.
ProxyServerThe hostname or IP address of a proxy to route HTTP traffic through.
ProxyPortThe TCP port the ProxyServer proxy is running on.
ProxyAuthSchemeThe authentication type to use to authenticate to the ProxyServer proxy.
ProxyUserA user name to be used to authenticate to the ProxyServer proxy.
ProxyPasswordA password to be used to authenticate to the ProxyServer proxy.
ProxySSLTypeThe SSL type to use when connecting to the ProxyServer proxy.
ProxyExceptionsA semicolon separated list of destination hostnames or IPs that are exempt from connecting through the ProxyServer .
CData ODBC Driver for Anzo

ProxyAutoDetect

This indicates whether to use the system proxy settings or not. This takes precedence over other proxy settings, so you'll need to set ProxyAutoDetect to FALSE in order use custom proxy settings.

Data Type

bool

Default Value

true

Remarks

This takes precedence over other proxy settings, so you'll need to set ProxyAutoDetect to FALSE in order use custom proxy settings.

On Windows, the proxy settings are read from the Internet Options in the registry.

On Mac, proxy settings are read 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 ODBC Driver for Anzo

ProxyServer

The hostname or IP address of a proxy to route HTTP traffic through.

Data Type

string

Default Value

""

Remarks

The hostname or IP address of a proxy to route HTTP traffic through. The driver can use the HTTP, Windows (NTLM), or Kerberos authentication types to authenticate to an HTTP proxy.

If you need to connect through a SOCKS proxy or tunnel the connection, see FirewallType.

By default, the driver uses the system proxy. If you need to use another proxy, set ProxyAutoDetect to false.

CData ODBC Driver for Anzo

ProxyPort

The TCP port the ProxyServer proxy is running on.

Data Type

int

Default Value

80

Remarks

The port the HTTP proxy is running on that you want to redirect HTTP traffic through. Specify the HTTP proxy in ProxyServer. For other proxy types, see FirewallType.

CData ODBC Driver for Anzo

ProxyAuthScheme

The authentication type to use to authenticate to the ProxyServer proxy.

Possible Values

BASIC, DIGEST, NONE, NEGOTIATE, NTLM, PROPRIETARY

Data Type

string

Default Value

"BASIC"

Remarks

This value specifies the authentication type to use to authenticate to the HTTP proxy specified by ProxyServer and ProxyPort.

Note that the driver will use the system proxy settings by default, without further configuration needed; if you want to connect to another proxy, you will need to set ProxyAutoDetect to false, in addition to ProxyServer and ProxyPort. To authenticate, set ProxyAuthScheme and set ProxyUser and ProxyPassword, if needed.

The authentication type can be one of the following:

  • BASIC: The driver performs HTTP BASIC authentication.
  • DIGEST: The driver performs HTTP DIGEST authentication.
  • NEGOTIATE: The driver retrieves an NTLM or Kerberos token based on the applicable protocol for authentication.
  • PROPRIETARY: The driver does not generate an NTLM or Kerberos token. You must supply this token in the Authorization header of the HTTP request.

If you need to use another authentication type, such as SOCKS 5 authentication, see FirewallType.

CData ODBC Driver for Anzo

ProxyUser

A user name to be used to authenticate to the ProxyServer proxy.

Data Type

string

Default Value

""

Remarks

The ProxyUser and ProxyPassword options are used to connect and authenticate against the HTTP proxy specified in ProxyServer.

You can select one of the available authentication types in ProxyAuthScheme. If you are using HTTP authentication, set this to the user name of a user recognized by the HTTP proxy. If you are using Windows or Kerberos authentication, set this property to a user name in one of the following formats:

user@domain
domain\user

CData ODBC Driver for Anzo

ProxyPassword

A password to be used to authenticate to the ProxyServer proxy.

Data Type

string

Default Value

""

Remarks

This property is used to authenticate to an HTTP proxy server that supports NTLM (Windows), Kerberos, or HTTP authentication. To specify the HTTP proxy, you can set ProxyServer and ProxyPort. To specify the authentication type, set ProxyAuthScheme.

If you are using HTTP authentication, additionally set ProxyUser and ProxyPassword to HTTP proxy.

If you are using NTLM authentication, set ProxyUser and ProxyPassword to your Windows password. You may also need these to complete Kerberos authentication.

For SOCKS 5 authentication or tunneling, see FirewallType.

By default, the driver uses the system proxy. If you want to connect to another proxy, set ProxyAutoDetect to false.

CData ODBC Driver for Anzo

ProxySSLType

The SSL type to use when connecting to the ProxyServer proxy.

Possible Values

AUTO, ALWAYS, NEVER, TUNNEL

Data Type

string

Default Value

"AUTO"

Remarks

This property determines when to use SSL for the connection to an HTTP proxy specified by ProxyServer. This value can be AUTO, ALWAYS, NEVER, or TUNNEL. The applicable values are the following:

AUTODefault setting. If the URL is an HTTPS URL, the driver will use the TUNNEL option. If the URL is an HTTP URL, the component will use the NEVER option.
ALWAYSThe connection is always SSL enabled.
NEVERThe connection is not SSL enabled.
TUNNELThe connection is through a tunneling proxy. The proxy server opens a connection to the remote host and traffic flows back and forth through the proxy.

CData ODBC Driver for Anzo

ProxyExceptions

A semicolon separated list of destination hostnames or IPs that are exempt from connecting through the ProxyServer .

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 that the driver uses the system proxy settings by default, without further configuration needed; if you want to explicitly configure proxy exceptions for this connection, you need to set ProxyAutoDetect = false, and configure ProxyServer and ProxyPort. To authenticate, set ProxyAuthScheme and set ProxyUser and ProxyPassword, if needed.

CData ODBC Driver for Anzo

Logging

This section provides a complete list of the Logging properties you can configure in the connection settings for this provider.


PropertyDescription
LogfileA filepath which designates the name and location of the log file.
VerbosityThe verbosity level that determines the amount of detail included in the log file.
LogModulesCore modules to be included in the log file.
MaxLogFileSizeA string specifying the maximum size in bytes for a log file (for example, 10 MB).
MaxLogFileCountA string specifying the maximum file count of log files.
CData ODBC Driver for Anzo

Logfile

A filepath which designates the name and location of the log file.

Data Type

string

Default Value

""

Remarks

Once this property is set, the driver will populate 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 will be created.

Connection strings and version information are also logged, though connection properties containing sensitive information are masked automatically.

If a relative filepath is supplied, the location of the log file will be resolved based on the path found in the Location connection property.

For more control over what is written to the log file, you can adjust the Verbosity property.

Log contents are categorized into several modules. You can show/hide individual modules using the LogModules property.

To edit the maximum size of a single logfile before a new one is created, see MaxLogFileSize.

If you would like to place a cap on the number of logfiles generated, use MaxLogFileCount.

CData ODBC Driver for Anzo

Verbosity

The verbosity level that determines the amount of detail included in the log file.

Data Type

string

Default Value

"1"

Remarks

The verbosity level determines the amount of detail that the driver reports to the Logfile. Verbosity levels from 1 to 5 are supported. These are detailed in the Logging page.

CData ODBC Driver for Anzo

LogModules

Core modules to be included in the log file.

Data Type

string

Default Value

""

Remarks

Only the modules specified (separated by ';') will be included in the log file. By default all modules are included.

See the Logging page for an overview.

CData ODBC Driver for Anzo

MaxLogFileSize

A string specifying the maximum size in bytes for a log file (for example, 10 MB).

Data Type

string

Default Value

"100MB"

Remarks

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.

Adjust the maximum number of logfiles generated with MaxLogFileCount.

CData ODBC Driver for Anzo

MaxLogFileCount

A string specifying the maximum file count of log files.

Data Type

int

Default Value

-1

Remarks

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.

The minimum supported value is 2. A value of 0 or a negative value indicates no limit on the count.

Adjust the maximum size of the logfiles generated with MaxLogFileSize.

CData ODBC Driver for Anzo

Schema

This section provides a complete list of the Schema properties you can configure in the connection settings for this provider.


PropertyDescription
LocationA path to the directory that contains the schema files defining tables, views, and stored procedures.
BrowsableSchemasThis property restricts the schemas reported to a subset of the available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC.
ViewsRestricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC.
CData ODBC Driver for Anzo

Location

A path to the directory that contains the schema files defining tables, views, and stored procedures.

Data Type

string

Default Value

"%APPDATA%\\CData\\Anzo Data Provider\\Schema"

Remarks

Note for Power BI Gateway users: When running the driver through the PowerBI Gateway, the Location property will need to be set to an absolute path. This is because the Gateway runs under a Windows service account.

The path to a directory which contains the schema files for the driver (.rsd files for tables and views, .rsb files for stored procedures). The folder location can be a relative path from the location of the executable. The Location property is only needed if you want to customize definitions (for example, change a column name, ignore a column, and so on) or extend the data model with new tables, views, or stored procedures.

If left unspecified, the default location is "%APPDATA%\\CData\\Anzo Data Provider\\Schema" with %APPDATA% being set to the user's configuration directory:

Platform %APPDATA%
Windows The value of the APPDATA environment variable
Mac ~/.config
Linux ~/.config

CData ODBC Driver for Anzo

BrowsableSchemas

This property restricts the schemas reported to a subset of the available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC.

Data Type

string

Default Value

""

Remarks

Listing the schemas from databases can be expensive. Providing a list of schemas in the connection string improves the performance.

CData ODBC Driver for Anzo

Views

Restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC.

Data Type

string

Default Value

""

Remarks

Listing the views from some databases can be expensive. Providing a list of views in the connection string improves the performance of the driver.

This property can also be used as an alternative to automatically listing views if you already know which ones you want to work with and there would otherwise be too many to work with.

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 that when connecting to a data source with multiple schemas or catalogs, you will need to provide the fully qualified name of the table in this property, as in the last example here, to avoid ambiguity between tables that exist in multiple catalogs or schemas.

CData ODBC Driver for Anzo

Caching

This section provides a complete list of the Caching properties you can configure in the connection settings for this provider.


PropertyDescription
AutoCacheAutomatically caches the results of SELECT queries into a cache database specified by either CacheLocation or both of CacheConnection and CacheProvider .
CacheProviderThe name of the provider to be used to cache data.
CacheConnectionThe connection string for the cache database. This property is always used in conjunction with CacheProvider . Setting both properties will override the value set for CacheLocation for caching data.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceThe tolerance for stale data in the cache specified in seconds when using AutoCache .
OfflineUse offline mode to get the data from the cache instead of the live source.
CacheMetadataThis property determines whether or not to cache the table metadata to a file store.
CData ODBC Driver for Anzo

AutoCache

Automatically caches the results of SELECT queries into a cache database specified by either CacheLocation or both of CacheConnection and CacheProvider .

Data Type

bool

Default Value

false

Remarks

When AutoCache = true, the driver automatically maintains a cache of your table's data in the database of your choice.

Setting the Caching Database

When AutoCache = true, the driver caches to a simple, file-based cache. You can configure its location or cache to a different database with the following properties:

See Also

  • CacheMetadata: This property reduces the amount of metadata that crosses the network by persisting table schemas retrieved from the Anzo metadata. Metadata then needs to be retrieved only once instead of every connection.
  • Explicitly Caching Data: This section provides more examples of using AutoCache in Offline mode.
  • CACHE Statements: You can use the CACHE statement to persist any SELECT query, as well as manage the cache; for example, refreshing schemas.

CData ODBC Driver for Anzo

CacheProvider

The name of the provider to be used to cache data.

Data Type

string

Default Value

""

Remarks

You can cache to any database for which you have an ADO.NET provider . The caching database is determined based on the CacheProvider and CacheConnection properties.

The following sections show connection examples and address other requirements for several popular database drivers. Refer to CacheConnection for more information on typical connection properties.

Loading the Caching Database's Driver

The CacheProvider property specifies the name of the DbProviderFactory used to cache data. You can find the provider factories available to you in your machine.config.

SQLite

The driver simplifies SQLite configuration; in most caching scenarios, you need to specify only the CacheLocation.

CacheLocation=C:\\Users\\Public\\cache.db;User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;

MySQL

To cache to MySQL, you can use the included 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";User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;

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';User=username;Password=password;url=http://35.184.41.230:8080/dataondemand/MyData;

The Oracle Data Provider for .NET also requires the Oracle Database Client. When you download the Oracle Database Client, ensure that the bitness matches the 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 included 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 ODBC Driver for Anzo

CacheConnection

The connection string for the cache database. This property is always used in conjunction with CacheProvider . Setting both properties will override the value set for CacheLocation for caching data.

Data Type

string

Default Value

""

Remarks

The cache database is determined based on the CacheProvider and CacheConnection properties. Both properties are required to use the cache database. Examples of common cache database settings can be found below. For more information on setting the caching database's driver, refer to CacheProvider.

The connection string specified in the CacheConnection property is passed directly to the underlying CacheProvider. Consult the documentation for the specific ADO.NET provider for more information on the available properties.

SQLite

The driver simplifies caching to SQLite, only requiring you to set the CacheLocation property to make a basic connection.

MySQL

The installation includes the CData ADO.NET Provider for MySQL. The following are typical connection properties:

  • Server: The IP address or domain name of the server you want to connect to.
  • Port: The port that the server is running on.
  • User: The user name provided for authentication to the database.
  • Password: The password provided for authentication to the database.
  • Database: The name of the database.

SQL Server

To cache to SQL Server, you can use the .NET Framework Provider for SQL Server, included in the .NET Framework. 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, this property can be used to specify the host name and the instance, separated by a backslash.
  • Port: The port SQL Server is running on.
  • Database: The name of the SQL Server database.
  • Integrated Security: Set this option to true to use the current Windows account for authentication. Set this option to false if you are setting the User and Password in the connection.
  • User Id: The user name provided for authentication with SQL Server. This property is only needed if you are not using integrated security.
  • Password: The password provided for authentication with SQL Server. This property is only needed if you are not using integrated security.

Oracle

To cache to Oracle, you can use the Oracle Data Provider for .NET. 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).

  • Password: The password provided for authentication with the Oracle database.
  • User Id: The user Id provided for authentication with the Oracle database.

PostgreSQL

To cache to PostgreSQL, you can use the Npgsql ADO.NET provider. The following are typical connection properties:

  • Host: The address of the server hosting the PostgreSQL database.
  • Port: The port used to connect to the server hosting the PostgreSQL database.
  • Database: The name of the database.
  • User name: The user Id provided for authentication with the PostgreSQL database.
  • Password: The password provided for authentication with the PostgreSQL database.

CData ODBC Driver for Anzo

CacheLocation

Specifies the path to the cache when caching to a file.

Data Type

string

Default Value

"%APPDATA%\\CData\\Anzo Data Provider"

Remarks

The CacheLocation is a simple, file-based cache. The driver uses SQLite.

If left unspecified, the default location is "%APPDATA%\\CData\\Anzo Data Provider" with %APPDATA% being set to the user's configuration directory:

Platform %APPDATA%
Windows The value of the APPDATA environment variable
Mac ~/.config
Linux ~/.config

See Also

  • AutoCache: Set to implicitly create and maintain a cache for later offline use.
  • CacheMetadata: Set to persist the Anzo catalog in CacheLocation.

CData ODBC Driver for Anzo

CacheTolerance

The tolerance for stale data in the cache specified in seconds when using AutoCache .

Data Type

int

Default Value

600

Remarks

The tolerance for stale data in the cache specified in seconds. This only applies when AutoCache is used. The driver checks with the data source for newer records after the tolerance interval has expired. Otherwise, it returns the data directly from the cache.

CData ODBC Driver for Anzo

Offline

Use offline mode to get the data from the cache instead of the live source.

Data Type

bool

Default Value

false

Remarks

When Offline = true, all queries execute against the cache as opposed to the live data source. In this mode, certain queries like INSERT, UPDATE, DELETE, and CACHE are not allowed.

CData ODBC Driver for Anzo

CacheMetadata

This property determines whether or not to cache the table metadata to a file store.

Data Type

bool

Default Value

false

Remarks

As you execute queries with this property set, table metadata in the Anzo catalog are cached to the file store specified by CacheLocation if set or the user's home directory otherwise. A table's metadata will be retrieved only once, when the table is queried for the first time.

When to Use CacheMetadata

The driver automatically persists metadata in memory for up to two hours when you first discover the metadata for a table or view and therefore, CacheMetadata is generally not required. CacheMetadata becomes useful when metadata operations are expensive such as when you are working with large amounts of metadata or when you have many short-lived connections.

When Not to Use CacheMetadata

  • When you are working with volatile metadata: Metadata for a table is only retrieved the first time the connection to the table is made. To pick up new, changed, or deleted columns, you would need to delete and rebuild the metadata cache. Therefore, it is best to rely on the in-memory caching for cases where metadata changes often.
  • When you are caching to a database: CacheMetadata can only be used with CacheLocation. If you are caching to another database with the CacheProvider and CacheConnection properties, use AutoCache to cache implicitly. Or, use CACHE Statements to cache explicitly.

CData ODBC Driver for Anzo

Miscellaneous

This section provides a complete list of the Miscellaneous properties you can configure in the connection settings for this provider.


PropertyDescription
CustomHeadersOther headers as determined by the user (optional).
CustomUrlParamsThe custom query string to be included in the request.
DefaultDomainThis property is used for the Oracle Database Gateway for ODBC.
EnableForeignKeyDetectionWhether to detect the foreign keys in ODBC.
IncludeDualTableSet this property to mock the Oracle DUAL table for better compatibility with Oracle database.
LimitKeySizeThe maximum length of a primary key column.
MapBigintToVarcharThis property controls whether or not the bigint type maps to SQL_VARCHAR instead of SQL_BIGINT. This property is false by default.
MapToIntThis property controls whether or not the long type maps to SQL_INTEGER instead of SQL_BIGINT. This property is false by default.
MapToLongVarcharThis property controls whether or not a column is returned as SQL_LONGVARCHAR.
MapToWVarcharThis property controls whether or not string types map to SQL_WVARCHAR instead of SQL_VARCHAR. This property is set by default.
MaximumColumnSizeThe maximum column size.
MaxRowsLimits the number of rows returned rows when no aggregation or group by is used in the query. This helps avoid performance issues at design time.
OtherThese hidden properties are used only in specific use cases.
PagesizeThe maximum number of results to return per page from Anzo.
PseudoColumnsThis property indicates whether or not to include pseudo columns as columns to the table.
SupportEnhancedSQLThis property enhances SQL functionality beyond what can be supported through the API directly, by enabling in-memory client-side processing.
TimeoutThe value in seconds until the timeout error is thrown, canceling the operation.
UpperCaseIdentifiersThis property reports all identifiers in uppercase. This is the default for Oracle databases and thus allows better integration with Oracle tools such as the Oracle Database Gateway.
CData ODBC Driver for Anzo

CustomHeaders

Other headers as determined by the user (optional).

Data Type

string

Default Value

""

Remarks

This property can be set to a string of headers to be appended to the HTTP request headers created from other properties, like ContentType, From, and so on.

The headers must be of the format "header: value" as described in the HTTP specifications. Header lines should be separated by the carriage return and line feed (CRLF) characters.

Use this property with caution. If this property contains invalid headers, HTTP requests may fail.

This property is useful for fine-tuning the functionality of the driver to integrate with specialized or nonstandard APIs.

CData ODBC Driver for Anzo

CustomUrlParams

The custom query string to be included in the request.

Data Type

string

Default Value

""

Remarks

The CustomUrlParams allow 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. The values in the query string must be URL encoded.

CData ODBC Driver for Anzo

DefaultDomain

This property is used for the Oracle Database Gateway for ODBC.

Data Type

string

Default Value

""

Remarks

The Oracle Database Gateway will always truncate the username from the "@" character. When DefaultDomain is specified, an "@" character and the domain will be appended to the username before authenticating.

CData ODBC Driver for Anzo

EnableForeignKeyDetection

Whether to detect the foreign keys in ODBC.

Data Type

bool

Default Value

false

Remarks

Whether to detect the foreign keys in ODBC.

CData ODBC Driver for Anzo

IncludeDualTable

Set this property to mock the Oracle DUAL table for better compatibility with Oracle database.

Data Type

bool

Default Value

false

Remarks

Set this property to mock the Oracle DUAL table. This table is used by Oracle database in a few special cases. This property facilitates connectivity when accessing Anzo as a remote Oracle database through the ODBC Gateway. For example, in SQL Developer, this table is queried to test the connection.

When using the ODBC Gateway, set the following properties, as well:

MapToWVarchar=False Set this property to map string data types to SQL_VARCHAR instead of SQL_WVARCHAR. By default, the driver uses SQL_WVARCHAR to accommodate various international character sets. You can use this property to avoid the ORA-28528 Heterogeneous Services data type conversion error when the Unicode type is returned.
MaximumColumnSize=4000 Set this property to restrict the maximum column size to 4000 characters.
UpperCaseIdentifiers=True Set this property to avoid quoting identifiers. Use this property to report uppercase identifiers to Oracle. By default, Oracle stores identifiers in uppercase, so uppercase identifiers do not need to be escaped with quotes.

CData ODBC Driver for Anzo

LimitKeySize

The maximum length of a primary key column.

Data Type

int

Default Value

255

Remarks

In some ODBC tools, for example, Microsoft Access, the length of the primary key column cannot be larger than a specific value. This property makes the ODBC Driver override the reported length of all the primary key columns. It is especially useful when using the ODBC Driver as a Microsoft Access Linked Data Source.

Setting the LimitKeySize to zero will make the key length revert to the original length.

This property can also be set using the SQLSetConnectAttr method, as shown in the following example:

SQLSetConnectAttr(hdbc, 20001, (SQLPOINTER)128, 0);

CData ODBC Driver for Anzo

MapBigintToVarchar

This property controls whether or not the bigint type maps to SQL_VARCHAR instead of SQL_BIGINT. This property is false by default.

Data Type

bool

Default Value

false

Remarks

SQL_BIGINT type columns have to be mapped to SQL_VARCHAR to accommodate certain tools such as Access. MapBigintToVarchar is set to false by default. You may set it to true to use SQL_VARCHAR instead.

CData ODBC Driver for Anzo

MapToInt

This property controls whether or not the long type maps to SQL_INTEGER instead of SQL_BIGINT. This property is false by default.

Data Type

bool

Default Value

false

Remarks

SQL_BIGINT type columns have to be mapped to SQL_INTEGER to accommodate certain tools such as Access. MapToInt is set to false by default. You may set it to true to use SQL_INTEGER instead.

CData ODBC Driver for Anzo

MapToLongVarchar

This property controls whether or not a column is returned as SQL_LONGVARCHAR.

Data Type

string

Default Value

"-1"

Remarks

Some applications require all text data larger than a certain number of characters to be reported as SQL_LONGVARCHAR. Use MapToLongVarchar to map any column larger than the specified size so they are reported as SQL_LONGVARCHAR instead of SQL_VARCHAR.

CData ODBC Driver for Anzo

MapToWVarchar

This property controls whether or not string types map to SQL_WVARCHAR instead of SQL_VARCHAR. This property is set by default.

Data Type

bool

Default Value

true

Remarks

String columns must be mapped to SQL_WVARCHAR to accommodate various international character sets, so MapToWVarchar is set to true by default. You may set it to false to use SQL_VARCHAR instead.

CData ODBC Driver for Anzo

MaximumColumnSize

The maximum column size.

Data Type

int

Default Value

16000

Remarks

Some tools restrain the largest size of a column or the total size of all the columns selected. You can set the MaximumColumnSize to overcome these schema-based restrictions. The driver will not report any column to be larger than the MaximumColumnSize.

Set a MaximumColumnSize of zero to eliminate limits on column size, as shown in the following example:

SQLSetConnectAttr(hdbc, 20002, (SQLPOINTER)2048, 0);

The following are a few examples of how you can use this property to avoid compatibility issues with several tools:

  • Oracle ODBC Gateway: Set MaximumColumnSize=4000 to avoid the ORA-28562 data truncation error. Note that Oracle ODBC Gateway additionally requires that you set the MapToWVarchar connection property to false.
  • Microsoft Access: Set MaximumColumnSize=255 to report string fields as TEXT instead of MEMO in Access. MEMO fields have no length limit but have restrictions on joins and filters. TEXT fields have a fixed length but support more functionality in Access tables.

CData ODBC Driver for Anzo

MaxRows

Limits the number of rows returned rows when no aggregation or group by is used in the query. This helps avoid performance issues at design time.

Data Type

int

Default Value

-1

Remarks

Limits the number of rows returned rows when no aggregation or group by is used in the query. This helps avoid performance issues at design time.

CData ODBC Driver for Anzo

Other

These hidden properties are used only in specific use cases.

Data Type

string

Default Value

""

Remarks

The properties listed below are available for specific use cases. Normal driver use cases and functionality should not require these properties.

Specify multiple properties in a semicolon-separated list.

Caching Configuration

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 driver.

Integration and Formatting

SupportAccessLinkedModeIn Access' linked mode, it is generally a good idea to always use a cache as most data sources do not support multiple Id queries. However if you want to use the driver in Access but not in linked mode, this property must be set to False to avoid using a cache of a SELECT * query for the given table.
DefaultColumnSizeSets the default length of string fields when the data source does not provide column length in the metadata. The default value is 2000.
ConvertDateTimeToGMTDetermines whether to convert date-time values to GMT, instead of the local time of the machine.
RecordToFile=filenameRecords the underlying socket data transfer to the specified file.

CData ODBC Driver for Anzo

Pagesize

The maximum number of results to return per page from Anzo.

Data Type

int

Default Value

5000

Remarks

The Pagesize property affects the maximum number of results to return per page from Anzo. Setting a higher value may result in better performance at the cost of additional memory allocated per page consumed.

CData ODBC Driver for Anzo

PseudoColumns

This property indicates whether or not to include pseudo columns as columns to the table.

Data Type

string

Default Value

""

Remarks

This setting is particularly helpful in Entity Framework, which does not allow you to set a value for a pseudo column unless it is a table column. The value of this connection setting is of the format "Table1=Column1, Table1=Column2, Table2=Column3". You can use the "*" character to include all tables and all columns; for example, "*=*".

CData ODBC Driver for Anzo

SupportEnhancedSQL

This property enhances SQL functionality beyond what can be supported through the API directly, by enabling in-memory client-side processing.

Data Type

bool

Default Value

true

Remarks

When SupportEnhancedSQL = true, the driver offloads as much of the SELECT statement processing as possible to Anzo and then processes the rest of the query in memory. In this way, the driver can execute unsupported predicates, joins, and aggregation.

When SupportEnhancedSQL = false, the driver limits SQL execution to what is supported by the Anzo API.

Execution of Predicates

The driver determines which of the clauses are supported by the data source and then pushes them to the source to get the smallest superset of rows that would satisfy the query. It then filters the rest of the rows locally. The filter operation is streamed, which enables the driver to filter effectively for even very large datasets.

Execution of Joins

The driver uses various techniques to join in memory. The driver trades off memory utilization against the requirement of reading the same table more than once.

Execution of Aggregates

The driver retrieves all rows necessary to process the aggregation in memory.

CData ODBC Driver for Anzo

Timeout

The value in seconds until the timeout error is thrown, canceling the operation.

Data Type

int

Default Value

300

Remarks

If Timeout = 0, operations do not time out. The operations run until they complete successfully or until they encounter an error condition.

If Timeout expires and the operation is not yet complete, the driver throws an exception.

CData ODBC Driver for Anzo

UpperCaseIdentifiers

This property reports all identifiers in uppercase. This is the default for Oracle databases and thus allows better integration with Oracle tools such as the Oracle Database Gateway.

Data Type

bool

Default Value

false

Remarks

Set this property to report all identifiers, including table and column names, in uppercase. This is the default for Oracle databases and thus allows better integration with Oracle tools such as the Oracle Database Gateway. For example, you can use this property to avoid quoting identifiers.

Copyright (c) 2022 CData Software, Inc. - All rights reserved.
Build 21.0.8171