Cloud

Build 22.0.8462
  • Couchbase
    • Getting Started
      • Establishing a Connection
    • NoSQL Database
      • Automatic Schema Discovery
      • Query Mapping
      • Vertical Flattening
      • User-Defined Functions
      • JSON Functions
      • Custom Schema Definitions
      • Custom Schema Example
      • Changelog
    • Advanced Features
      • User Defined Views
      • SSL Configuration
      • Firewall and Proxy
      • Caching Data
        • Configuring the Cache Connection
        • Caching Metadata
        • Automatically Caching Data
        • Explicitly Caching Data
        • Data Type Mapping
      • Query Processing
      • Logging
    • SQL Compliance
      • SELECT Statements
        • Aggregate Functions
        • JOIN Queries
        • Date Literal Functions
        • Aggregate Functions
        • Projection Functions
        • Predicate Functions
      • SELECT INTO Statements
      • SQL Functions
        • STRING Functions
        • DATE Functions
        • MATH Functions
      • INSERT Statements
      • UPDATE Statements
      • DELETE Statements
      • CACHE Statements
      • EXECUTE Statements
      • PIVOT and UNPIVOT
    • Data Model
      • Stored Procedures
        • AddDocument
        • CreateBucket
        • CreateCollection
        • CreateSchema
        • CreateScope
        • CreateUserTable
        • DeleteBucket
        • DeleteCollection
        • DeleteScope
        • FlushBucket
        • ListIndices
        • ManageIndices
      • System Tables
        • sys_catalogs
        • sys_schemas
        • sys_tables
        • sys_tablecolumns
        • sys_procedures
        • sys_procedureparameters
        • sys_keycolumns
        • sys_foreignkeys
        • sys_primarykeys
        • sys_indexes
        • sys_connection_props
        • sys_sqlinfo
        • sys_identity
    • Connection String Options
      • Authentication
        • AuthScheme
        • User
        • Password
        • CredentialsFile
        • Server
        • CouchbaseService
        • ConnectionMode
        • DNSServer
        • N1QLPort
        • AnalyticsPort
        • WebConsolePort
      • SSL
        • SSLClientCert
        • SSLClientCertType
        • SSLClientCertPassword
        • SSLClientCertSubject
        • UseSSL
        • SSLServerCert
      • Firewall
        • FirewallType
        • FirewallServer
        • FirewallPort
        • FirewallUser
        • FirewallPassword
      • Proxy
        • ProxyAutoDetect
        • ProxyServer
        • ProxyPort
        • ProxyAuthScheme
        • ProxyUser
        • ProxyPassword
        • ProxySSLType
        • ProxyExceptions
      • Logging
        • Logfile
        • Verbosity
        • LogModules
        • MaxLogFileSize
        • MaxLogFileCount
      • Schema
        • Location
        • BrowsableSchemas
        • Tables
        • Views
        • Dataverse
        • TypeDetectionScheme
        • InferNumSampleValues
        • InferSampleSize
        • InferSimilarityMetric
        • FlexibleSchemas
        • ExposeTTL
        • NumericStrings
        • IgnoreChildAggregates
        • TableSupport
        • NewChildJoinsMode
      • Caching
        • AutoCache
        • CacheLocation
        • CacheTolerance
        • Offline
        • CacheMetadata
      • Miscellaneous
        • AllowJSONParameters
        • ChildSeparator
        • CreateTableRamQuota
        • DataverseSeparator
        • FlattenArrays
        • FlattenObjects
        • FlavorSeparator
        • GenerateSchemaFiles
        • InsertNullValues
        • MaxRows
        • Other
        • Pagesize
        • PeriodsSeparator
        • PseudoColumns
        • QueryExecutionTimeout
        • QueryPassthrough
        • Readonly
        • RowScanDepth
        • RTK
        • StrictComparison
        • Timeout
        • TransactionDurability
        • TransactionTimeout
        • UpdateNullValues
        • UseCollectionsForDDL
        • UserDefinedViews
        • UseTransactions
        • ValidateJSONParameters

CData Cloud

Overview

CData Cloud offers access to Couchbase across several standard services and protocols, in a cloud-hosted solution. Any application that can connect to a MySQL or SQL Server database can connect to Couchbase through CData Cloud.

CData Cloud allows you to standardize and configure connections to Couchbase as though it were any other OData endpoint, or standard SQL Server/MySQL database.

Key Features

  • Full SQL Support: Couchbase appears as standard relational databases, allowing you to perform operations - Filter, Group, Join, etc. - using standard SQL, regardless of whether these operations are supported by the underlying API.
  • CRUD Support: Both read and write operations are supported, restricted only by security settings that you can configure in Cloud or downstream in the source itself.
  • Secure Access: The administrator can create users and define their access to specific databases and read-only operations or grant full read & write privileges.
  • Comprehensive Data Model & Dynamic Discovery: CData Cloud provides comprehensive access to all of the data exposed in the underlying data source, including full access to dynamic data and easily searchable metadata.

CData Cloud

Getting Started

This page provides a guide to Establishing a Connection to Couchbase in CData Cloud, as well as information on the available resources, and a reference to the available connection properties.

Connecting to Couchbase

Establishing a Connection shows how to authenticate to Couchbase and configure any necessary connection properties to create a database in CData Cloud

Accessing Data from CData Cloud Services

Accessing data from Couchbase through the available standard services and CData Cloud administration is documented in further details in the CData Cloud Documentation.

CData Cloud

Establishing a Connection

Connect to Couchbase by selecting the corresponding icon in the Database tab. Required properties are listed under Settings. The Advanced tab lists connection properties that are not typically required.

Connecting to Couchbase

To connect to data, set the Server property to the hostname or IP address of the Couchbase server(s) you are authenticating to.

If your Couchbase server is configured to use SSL, you can enable it either by using an https URL for Server (like https://couchbase.server), or by setting the UseSSL property to True.

Couchbase Analytics

By default, the Cloud connects to the N1QL Query service. In order to connect to the Couchbase Analytics service, you will also need to set the CouchbaseService property to Analytics.

Couchbase Cloud

Set the following to connect to Couchbase Cloud:

  • AuthScheme: Set this to Basic.
  • ConnectionMode: Set this to Cloud.
  • DNSServer: Set this to a DNS server. In most cases, this should be a public DNS service like 1.1.1.1 or 8.8.8.8.
  • SSLServerCert: Set this to the TLS/SSL certificate to be accepted from the server. Any other certificate that is not trusted by the machine is rejected. Alternatively, set "*" to accept all certificates.

Authenticating to Couchbase

The Cloud supports several forms of authentication. Couchbase Cloud only accepts Standard authentication, while Couchbase Server accepts Standard authentication, client certificates, and credentials files.

Standard Authentication

To authenticate with standard authentication, set the following:

  • AuthScheme: Set this to Basic.
  • User: The user authenticating to Couchbase.
  • Password: The password of the user authenticating to Couchbase.

Client Certificates

The Cloud supports authenticating with client certificates when SSL is enabled. To use client certificate authentication, set the following properties:

  • AuthScheme: Set this to SSLCertificate.
  • SSLClientCertType: The type of client certificate set within SSLClientCert.
  • SSLClientCert: The client certificate in the format given by SSLClientCertType.
  • SSLClientCertPassword (optional): The password of the client certificate, if it is encrypted.
  • SSLClientCertSubject (optional): The subject of the client certificate, which, by default, is the first certificate found in the store. This is required if more than one certificate is available in the certificate store.

Credentials File

You can also authenticate using using a credentials file containing multiple logins. This is included for legacy use and is not recommended when connecting to a Couchbase Server that supports role-based authentication.

  • AuthScheme: Set this to CredentialsFile.
  • CredentialsFile: The path to the credentials file. Refer to Couchbase's documentation for more information on the format of this file.

CData Cloud

NoSQL Database

Couchbase is a schema-free document database that provides high performance, availability, and scalability. These features are not necessarily incompatible with a standards-compliant query language like SQL-92.

The Cloud models the schema-free Couchbase objects into relational tables and translates SQL queries into N1QL or SQL++ (Analytics) queries to get the requested data. In this section we will show various schemes that the Cloud offers to bridge the gap with relational SQL and a document database.

Automatic Schema Discovery

When the Cloud first connects to Couchbase, it opens each bucket and scans a configurable number of rows from that bucket. It uses those rows to determine the columns in that bucket and their data types, as well as how to build flavored and child tables for any arrays within those documents. For Couchbase Enterprise version 4.5.1 and later, the Cloud may can also be configured to use the INFER command when TypeDetectionScheme is set to INFER. This allows the Cloud to get a more accurate column listing for the bucket, and to detect more complex flavors.

When using the Analytics service, the Cloud only does column and child table detection. Flavored tables are provided by Couchbase itself using shadow datasets. Also, Analytics mode does not currently have INFER support, so only row scan is supported.

For more details, refer to Automatic Schema Discovery to see how flavored tables and child tables are modelled from Couchbase data. Setting NumericStrings is also recommended as it can avoid type detection issues with certain kinds of text data.

Custom Schema Definitions

Optionally, you can use Custom Schema Definitions to project your chosen relational structure on top of a Couchbase object. This allows you to define your chosen column names, their data types, and the locations of their values in the Couchbase document.

Query Mapping

See Query Mapping for more details on how various N1QL and SQL++ operations are represented as SQL.

Vertical Flattening

See Vertical Flattening for more details on how arrays and objects are mapped into fields.

JSON Functions

See JSON Functions for more details on how to extract data from raw JSON strings.

CData Cloud

Automatic Schema Discovery

Child Tables

If the documents within a bucket contain fields with arrays, then the Cloud will expose those fields as their own tables in addition to exposing them as JSON aggregates on the main table. The structure of these child tables depends upon whether the array contains objects or primitive values.

Array Child Tables

If the arrays contain primitive values like numbers or strings, the child table will have only two columns: one called "Document.Id" which is the primary key of the document containing the array, and one called "value" which contains the value within the array. For example, if the bucket "Games" contains these documents:

/* Primary key "1" */
{
  "scores": [1,2,3]
}

/* Primary key "2" */
{
  "scores": [4,5,6]
}

The Cloud will build a table called "Games_scores" containing these rows:

Document.Id value
1 1
1 2
1 3
2 4
2 5
2 6

Object Child Tables

If the arrays contain objects, the child table will have a column for each field that occurs within the objects, as well as a "Document.Id" column which contains the primary key of the document containing the array. For example, if the bucket "Games" contains these documents:

/* Primary key "1" */
{
  "moves": [
    {"piece": "pawn", "square": "c3"},
    {"piece": "rook", "square": "d5"}
  ]
}

/* Primary key "2" */
{
  "moves": [
    {"piece": "knight", "square": "f1"},
    {"piece": "bishop", "square": "e4"}
  ]
}

The Cloud will build a table called "Games_moves" containing these rows:

Document.Id piece square
1 pawn c3
1 rook d5
2 knight f1
2 biship e4

NewChildJoinsMode

Note that the above data model is not fully relational, which has important limitations for use-cases that involve complex JOINs or DML operations on child tables. The NewChildJoinsMode connection property exposes an alternative data model which avoids these limitations. Please refer to its page in the connection property section of the documentation for more details.

Flavored Tables

The Cloud can also detect when there are multiple types of documents within the same bucket, as long as TypeDetectionScheme is set to Infer or DocType and CouchbaseService is set to N1QL. These different types of documents are exposed as their own tables containing only the appropriate rows.

For example, the bucket "Games" contains documents which have a "type" value of either "chess" or "football":

/* Primary key "1" */
{
  "type": "chess",
  "result": "stalemate"
}

/* Primary key "2" */
{
  "type": "chess",
  "result": "black win"
}

/* Primary key "3" */
{
  "type": "football",
  "score": 23
}

/* Primary key "4" */
{
  "type": "football",
  "score": 18
}

The Cloud will create three tables for this bucket: one called "Games" which contains all the documents:

Document.Id result score type
1 stalemate NULL chess
2 black win NULL chess
3 NULL 23 football
4 NULL 18 football

One called "Games.chess" which contains only documents where the type is "chess":

Document.Id result type
1 stalemate chess
2 black win chess

And one called "Games.football" which contains only documents where the type is "football":

Document.Id score type
3 23 football
4 18 football

Note that the Cloud will not include columns in a flavored table that are not defined on the documents in that flavor. For example, even though both the "result" and "score" columns are included on the base table, "Games.chess" only includes "result" and "Games.football" only includes "score".

Flavored Child Tables

It is also possible for a flavored table to contain arrays, which will become their own child tables. For example, if the bucket "Games" contains these documents:
/* Primary key "1" */
{
  "type": "chess",
  "results": ["stalemate", "white win"]
}

/* Primary key "2" */
{
  "type": "chess",
  "results": ["black win", "stalemate"]
}

/* Primary key "3" */
{
  "type": "football",
  "scores": [23, 12]
}

/* Primary key "4" */
{
  "type": "football",
  "scores": [18, 36]
}
Then the Cloud will generate these tables:

Table Name Child Field Flavor Condition
Games
Games_results results
Games_scores scores
Games.chess "type" = "chess"
Games.chess_results results "type" = "chess"
Games.football "type" = "football"
Games.football_scores scores "type" = "football"

CData Cloud

Query Mapping

The Cloud maps SQL-92-compliant queries into corresponding N1QL or SQL++ queries. Although the mapping below is not complete, it should help you get a sense for the common patterns the Cloud uses during this transformation.

SELECT Queries

The SELECT statements are translated to the appropriate N1QL SELECT query as shown below. Due to the similarities between SQL-92 and N1QL, many queries will simply be direct translations.

One major difference is that when the schema for a given Couchbase bucket exists in the Cloud, a SELECT * query will be translated to directly select the individual fields in the bucket. The Cloud will also automatically create a Document.Id column based on the primary key of each document in the bucket.

SQL Query N1QL Query
SELECT * FROM users SELECT META(`users`).id AS `id`, ... FROM `users`
SELECT [Document.Id], status FROM users SELECT META(`users`).id AS `Document.Id`, `users`.`status` FROM `users`
SELECT * FROM users WHERE status = 'A' OR age = 50 SELECT META(`users`).id AS `id`, ... FROM `users` WHERE TOSTRING(`users`.`status`) = "A" OR TONUMBER(`users`.`age`) = 50
SELECT * FROM users WHERE name LIKE 'A%' SELECT META(`users`).id AS `id`, ... FROM `users` WHERE TOSTRING(`users`.`name`) LIKE "A%"
SELECT * FROM users WHERE status = 'A' ORDER BY [Document.Id] DESC SELECT META(`users`).id AS `id`, ... FROM `users` WHERE TOSTRING(`users`.`status`) = "A" ORDER BY META(`users`).id DESC
SELECT * FROM users WHERE status IN ('A', 'B') SELECT META(`users`).id, ... FROM `users` WHERE TOSTRING(`users`.`status`) IN ["A", "B"]

Note that conditions can include extra type functions if the Cloud detects that a type conversion may be necessary. You can disable these type conversions using the StrictComparison property. For clarity, the rest of the N1QL samples are shown without these extra conversion functions.

USE KEYS Optimizations

When a query has either equals or IN clause that targets the Document.Id column, and there is no OR clause to override it, the Cloud will convert the Document.Id filter into a USE KEYS clause. This avoids the overhead of scanning an index because the document keys are already known to the N1QL engine (this optimization does not apply to the Analytics CouchbaseService).

SQL Query N1QL Query
SELECT * FROM users WHERE [Document.Id] = '1'SELECT ... FROM `users` USE KEYS ["1"]
SELECT * FROM users WHERE [Document.Id] IN ('2', '3') SELECT ... FROM `users` USE KEYS ["2", "3"]
SELECT * FROM users WHERE [Document.Id] = '4' OR [Document.Id] = '5' SELECT ... FROM `users` USE KEYS ["4", "5"]
SELECT * FROM users WHERE [Document.Id] = '6' AND status = 'A' SELECT ... FROM `users` USE KEYS ["6"] WHERE `status` = "A"

In addition to being used for SELECT queries, the same optimization is performed for DML operations as shown below.

Child Tables

As long as all the child tables in a query share the same parent, and they are combined using INNER JOINs on their Document.Id columns, the Cloud will combine the JOINs into a single UNNEST expression. Unlike N1QL UNNEST queries, you must explicitly JOIN with the base table if you want to access its fields.

SQL Query N1QL Query
SELECT * FROM users_posts SELECT META(`users`).id, `users_posts`.`text`, ... FROM `users` UNNEST `users`.`posts` AS `users_posts`
SELECT * FROM users INNER JOIN users_posts ON users.[Document.Id] = users_posts.[Document.Id] SELECT META(`users`).id, `users`.`name`, ..., `users_posts`.`text`, ... FROM `users` UNNEST `users`.`posts` AS `users_posts`
SELECT * FROM users INNER JOIN users_posts ... INNER JOIN users_comments ON ... SELECT ... FROM `users` UNNEST `users`.`posts` AS `users_posts` UNNEST `users`.`comments` AS `users_comments`

Flavor Tables

Flavored tables always have the appropriate condition included when you query, so that only documents from the flavor will be returned:

SQL Query N1QL Query
SELECT * FROM [users.subscriber] SELECT ... FROM `users` WHERE `docType` = "subscriber"
SELECT * FROM [users.subscriber] WHERE age > 50 SELECT ... FROM `users` WHERE `docType` = "subscriber" AND `age` > 50

Aggregate Queries

N1QL has several built-in aggregate functions. The Cloud makes extensive use of this for various aggregate queries. See some examples below:

SQL QueryN1QL Query
SELECT Count(*) As Count FROM OrdersSELECT Count(*) AS `count` FROM `Orders`
SELECT Sum(price) As total FROM OrdersSELECT Sum(`price`) As `total` FROM `Orders`
SELECT cust_id, Sum(price) As total FROM Orders GROUP BY cust_id ORDER BY totalSELECT `cust_id`, Sum(`price`) As `total` FROM `Orders` GROUP BY `cust_id` ORDER BY `total`
SELECT cust_id, ord_date, Sum(price) As total FROM Orders GROUP BY cust_id, ord_date Having total > 250SELECT `cust_id`, `ord_date`, Sum(`price`) As `total` FROM `Orders` GROUP BY `cust_id`, `ord_date` Having `total` > 250

Insert Statements

The SQL INSERT statement is mapped to the N1QL INSERT statement as shown below. This works the same for both top-level fields as well as fields produced by Vertical Flattening:

SQL QueryN1QL Query
INSERT INTO users([Document.Id], age, status) VALUES ('bcd001', 45, 'A') INSERT INTO `users`(KEY, VALUE) VALUES ('bcd001', { "age" : 45, "status" : "A" })
INSERT INTO users([Document.Id], [metrics.posts]) VALUES ('bcd002', 0) INSERT INTO `users`(KEY, VALUE) VALUES ('bcd002', {"metrics': {"posts": 0}})

Child Table Inserts

Inserts on child tables are converted internally into N1QL UPDATEs using array operations. Since that this does not create the top-level document, the Document.Id provided must refer to a document that already exists.

Another limitation of child table inserts is that multi-valued inserts must all use the same Document.Id. The provider will verify this before modifying any data and raise an error if this constraint is violated.

SQL Query N1QL Query
INSERT INTO users_ratings([Document.Id], value) VALUES ('bcd001', 4.8), ('bcd001', 3.2) UPDATE `users` USE KEYS "bcd001" SET `ratings` = ARRAY_PUT(`ratings`, 4.8, 3.2)
INSERT INTO users_reviews([Document.Id], score) VALUES ('bcd002', 'Great'), ('bcd002', 'Lacking') UPDATE `users` USE KEYS "bcd001" SET `ratings` = ARRAY_PUT(`ratings`, {"score": "Great"}, {"score": "Lacking"})

Bulk Insert Statements

Bulk inserts are also supported the SQL Bulk Insert is converted as shown below:

INSERT INTO users#Temp([Document.Id], KEY, VALUE) VALUES('bcd001', 45, "A")
INSERT INTO users#Temp([Document.Id], KEY, VALUE) VALUES('bcd002', 24, "B")
INSERT INTO users SELECT * FROM users#Temp
is converted to:
INSERT INTO `users` (KEY, VALUE) VALUES
  ('bcd001', {"age": 45, "status": "A"}),
  ('bcd002', {"age": 24, "status": "B"})

Like multi-valued inserts on child tables, all the rows in a bulk insert must also have the same Document.Id.

Update Statements

The SQL UPDATE statement is mapped to the N1SQL UPDATE statement as shown below:

SQL QueryN1QL Query
UPDATE users SET status = 'C' WHERE [Document.Id] = 'bcd001' UPDATE `users` USE KEYS ["bcd001"] SET `status` = "C"
UPDATE users SET status = 'C' WHERE age > 45 UPDATE `users` SET `status` = "C" WHERE `age` > 45

Child Table Updates

When updating a child table, the SQL query is converted to an UPDATE query using either a "FOR" expression or an "ARRAY" expression:

SQL Query N1QL Query
UPDATE users_ratings SET value = 5.0 WHERE value > 5.0 UPDATE `users` SET `ratings` = ARRAY CASE WHEN `value` > 5.0 THEN 5 ELSE `value` END FOR `value` IN `ratings` END
UPDATE users_reviews SET score = 'Unknown' WHERE score = '' UPDATE `users` SET `$child`.`score` = 'Unknown' FOR `$child` IN `reviews` WHEN `$child`.`score` = "" END

Flavor Table Updates

Like flavor table SELECTs, UPDATEs on flavor tables always include the appropriate condition, so only docments belonging to the flavor are affected:

SQL Query N1QL Query
UPDATE [users.subscriber] SET status = 'C' WHERE age > 45 UPDATE `users` SET `status` = "C" WHERE `docType` = "subscriber" AND `age` > 45

Delete Statements

The SQL DELETE statement is mapped to the N1QL DELETE statement as shown below:

SQL QueryN1QL Query
DELETE FROM users WHERE [Document.Id] = 'bcd001' DELETE FROM `users` USE KEYS ["bcd001"]
DELETE FROM users WHERE status = 'inactive' DELETE FROM `users` WHERE `status` = "inactive"

Child Table Deletes

When deleting from a child table, the SQL query is converted to an UPDATE query using an "ARRAY" expression:

SQL Query N1QL Query
DELETE FROM users_ratings WHERE value < 0 UPDATE `users` SET `ratings` = ARRAY `value` FOR `value` IN `ratings` WHEN NOT (`value` < 0) END
DELETE FROM users_reviews WHERE score = '' UPDATE `users` SET `reviews` = ARRAY `$child` FOR `$child` IN `reviews` WHEN NOT (`$child`.`score` = "") END

Flavor Tables Deletes

Like flavor table SELECTs, DELETEs on flavor tables always include the appropriate condition, so only docments belonging to the flavor are affected:

SQL Query N1QL Query
DELETE FROM [users.subscriber] WHERE status = 'inactive' DELETE FROM `users` WHERE `docType` = "subscriber" AND status = "inactive"

CData Cloud

Vertical Flattening

Example Document


/* Primary key "1" */
{
  "address" : {
    "building" : "1007",
    "coord" : [-73.856077, 40.848447],
    "street" : "Morris Park Ave",
    "zipcode" : "10462"
  },
  "borough" : "Bronx",
  "cuisine" : "Bakery",
  "grades" : [{
      "date" : "2014-03-03T00:00:00Z",
      "grade" : "A",
      "score" : 2
    }, {
      "date" : "2013-09-11T00:00:00Z",
      "grade" : "A",
      "score" : 6
    }, {
      "date" : "2013-01-24T00:00:00Z",
      "grade" : "A",
      "score" : 10
    }, {
      "date" : "2011-11-23T00:00:00Z",
      "grade" : "A",
      "score" : 9
    }, {
      "date" : "2011-03-10T00:00:00Z",
      "grade" : "B",
      "score" : 14
    }],
  "name" : "Morris Park Bake Shop",
  "restaurant_id" : "30075445"
}

Selecting Values In Objects

If the FlattenObjects property is configured to allow object flattening, then the Cloud will traverse objects and map the fields inside them as columns. For example, this query:
SELECT [address.building], [address.street] FROM restaurants
Would return this resultset:

address.building addres.street
1007 Morris Park Ave

Selecting Values In Arrays

If the FlattenArrays property is configured to allow array flattening, then the Cloud will traverse arrays and map their individual values as columns. For example, if Flatten Arrays were set to "2", then this query:
SELECT [address.coord.0], [address.coord.1] FROM restaurants
Would return this resultset:

address.coord.0 address.coord.1
-73.856077 40.838447

Note that array flattening should only be used in cases where you know the number of array items in advance, such as with "address.coord" which will always contain two items. For arrays like "grades" which can contain arbitrary numbers of items, consider using the child tables described in Automatic Schema Discovery instead, since they will allow you to read all of the values within the array.

CData Cloud

User-Defined Functions

User-defined functions are a new feature provided by Couchbase 7 and up. They can be used with the Cloud like normal functions but with a special naming convention for using scoped functions. Normally the Cloud requires that functions already exist before they are used, to define them refer to the Couchbase documentation on CREATE FUNCTION queries. These may be run at the Couchbase console or with the Cloud in QueryPassthrough mode.

Couchbase has support for both scalar functions as well as functions that return results from subqueries. The Cloud supports scalar functions within its SQL dialect but subquery functions can only be used when QueryPassthrough is enabled. The rest of this section covers the Cloud's SQL dialect and assums that QueryPassthrough is disabled.

Global Functions

In both N1QL and Analytics mode, global user-defined functions can be accessed using either their simple names or their qualified names. The simple name is just the name of the function:

SELECT ageInYears(birthdate) FROM users

Global functions may also be invoked by qualifying them with the default namespace. Qualified names are quoted names that contain internal separators, which by default is a period though this can be changed using the DataverseSeparator property. In both N1QL and Analytics the global namespace is called Default:

SELECT [Default.ageInYears](birthdate) FROM users

Calling global functions using simple names is recommended. While the default qualfier is supported, its only intended use is for when a UDF clashes with a standard SQL function that the Cloud would otherwise translate.

Scoped Functions

Both N1QL and Analytics also allow functions to be defined outside of a global context. In Analytics functions can be attached to both dataverses and scopes which are called using two-part and three-part names respectively. In N1QL functions may only be attached to scopes so only three-part names may be used.

/* N1QL AND Analytics */
SELECT [socialNetwork.accounts.ageInYears](birthdate) FROM [socialNetwork.accounts.users]

/* Analytics only */
SELECT [socailNetwork.ageInYears](birthdate) FROM [socialNetwork.accounts.users]

CData Cloud

JSON Functions

The Cloud can return JSON structures as column values. The Cloud enables you to use standard SQL functions to work with these JSON structures. The examples in this section use the following array:

[
     { "grade": "A", "score": 2 },
     { "grade": "A", "score": 6 },
     { "grade": "A", "score": 10 },
     { "grade": "A", "score": 9 },
     { "grade": "B", "score": 14 }
]

JSON_EXTRACT

The JSON_EXTRACT function can extract individual values from a JSON object. The following query returns the values shown below based on the JSON path passed as the second argument to the function:
SELECT Name, JSON_EXTRACT(grades,'[0].grade') AS Grade, JSON_EXTRACT(grades,'[0].score') AS Score FROM Students;

Column NameExample Value
GradeA
Score2

JSON_COUNT

The JSON_COUNT function returns the number of elements in a JSON array within a JSON object. The following query returns the number of elements specified by the JSON path passed as the second argument to the function:
SELECT Name, JSON_COUNT(grades,'[x]') AS NumberOfGrades FROM Students;

Column NameExample Value
NumberOfGrades5

JSON_SUM

The JSON_SUM function returns the sum of the numeric values of a JSON array within a JSON object. The following query returns the total of the values specified by the JSON path passed as the second argument to the function:
SELECT Name, JSON_SUM(score,'[x].score') AS TotalScore FROM Students;

Column NameExample Value
TotalScore 41

JSON_MIN

The JSON_MIN function returns the lowest numeric value of a JSON array within a JSON object. The following query returns the minimum value specified by the JSON path passed as the second argument to the function:
SELECT Name, JSON_MIN(score,'[x].score') AS LowestScore FROM Students;

Column NameExample Value
LowestScore2

JSON_MAX

The JSON_MAX function returns the highest numeric value of a JSON array within a JSON object. The following query returns the maximum value specified by the JSON path passed as the second argument to the function:
SELECT Name, JSON_MAX(score,'[x].score') AS HighestScore FROM Students;

Column NameExample Value
HighestScore14

DOCUMENT

The DOCUMENT function can be used to return an document as a JSON string. DOCUMENT(*) can be used with any type of SELECT query, including queries including other columns, queries including just DOCUMENT(*), and even more complex queries like JOINs.
SELECT [Document.Id], grade, score, DOCUMENT(*) FROM grades
For example, that query would return:

Document.Id grade score DOCUMENT
1 A 6 {"document.id":1,"grade":"A","score":6}
2 A 10 {"document.id":1,"grade":"A","score":10}
3 A 9 {"document.id":1,"grade":"A","score":9}
4 B 14 {"document.id":1,"grade":"B","score":14}

When used alone, DOCUMENT(*) returns the structure directly from Couchbase as if a N1QL or SQL++ SELECT * query were used. This means that no Document.Id value will be present since Couchbase does not include it automatically.

SELECT DOCUMENT(*) FROM grades
This query would return:

DOCUMENT
{"grades":{"grade":"A","score":6"}}
{"grades":{"grade":"A","score":10"}}
{"grades":{"grade":"A","score":9"}}
{"grades":{"grade":"B","score":14"}}

CData Cloud

Custom Schema Definitions

In addition to Automatic Schema Discovery the Cloud also allows you to statically define the schema for your Couchbase object. Schemas are defined in text-based configuration files, which makes them easy to extend. You can call the CreateSchema stored procedure to generate a schema file; see Automatic Schema Discovery for more information.

Set the Location property to the file directory that will contain the schema file. The following sections show how to extend the resulting schema or write your own.

Example Document

Let's consider the document below and extract out the nested properties as their own columns:

/* Primary key "1" */
{
  "id": 12,
  "name": "Lohia Manufacturers Inc.",
  "homeaddress": {"street": "Main "Street", "city": "Chapel Hill", "state": "NC"},
  "workaddress": {"street": "10th "Street", "city": "Chapel Hill", "state": "NC"}
  "offices": ["Chapel Hill", "London", "New York"]
  "annual_revenue": 35600000
}
/* Primary key "2" */
{
  "id": 15,
  "name": "Piago Industries",
  "homeaddress": {street": "Main Street", "city": "San Francisco", "state": "CA"},
  "workaddress": {street": "10th Street", "city": "San Francisco", "state": "CA"}
  "offices": ["Durham", "San Francisco"]
  "annual_revenue": 42600000
}

Custom Schema Definition


<rsb:info title="Customers" description="Customers" other:dataverse="" other:bucket=customers"" other:flavorexpr="" other:flavorvalue="" other:isarray="false" other:pathspec="" other:childpath="">
  <attr name="document.id"        xs:type="string"  key="true" other:iskey="true" other:pathspec=""  />
  <attr name="annual_revenue"     xs:type="integer" other:iskey="false"           other:pathspec=""  other:field="annual_revenue" />
  <attr name="homeaddress.city"   xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.city" />
  <attr name="homeaddress.state"  xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.state" />
  <attr name="homeaddress.street" xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.street" />
  <attr name="name"               xs:type="string"  other:iskey="false"           other:pathspec=""  other:field="name" />
  <attr name="id"                 xs:type="integer" other:iskey="false"           other:pathspec=""  other:field="id" />
  <attr name="offices"            xs:type="string"  other:iskey="false"           other:pathspec=""  other:field="offices" />
  <attr name="offices.0"          xs:type="string"  other:iskey="false"           other:pathspec="[" other:field="offices.0" />
  <attr name="offices.1"          xs:type="string"  other:iskey="false"           other:pathspec="[" other:field="offices.1" />
  <attr name="workaddress.city"   xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.city" />
  <attr name="workaddress.state"  xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.state" />
  <attr name="workaddress.street" xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.street" />
</rsb:info>
In Custom Schema Example, you will find the complete schema that contains the example above.

Table Properties

The schema above uses the following properties to define specific qualities for the whole table. All of them are required:

Property Meaning
other:dataverse The name of the dataverse the dataset belongs to. Empty if not an Analytics view.
other:bucket The name of the bucket or dataset within Couchbase
other:flavorexpr The URL encoded condition in a flavored table. For example, "%60docType%60%20%3D%20%22chess%22".
other:flavorvalue The name of the flavor in a flavored table. For example, "chess".
other:isarray Whether the table is an array child table.
other:pathspec This is used to interpret the separators within other:childpath. See Column Properties for more details.
other:childpath The path to the attribute that is used to UNNEST the child table. Empty if not a child table.

Column Properties

The schema above uses the following properties to define specific qualities for each column:

Property Meaning
name Required. The name of the column, lower-cased.
key Used to mark the primary key. Required for Document.Id but optional for other columns.
xs:type Required. The type of the column within the Cloud.
other:iskey Required. Must be the same value as key, or "false" if key is not included.
other:pathspec Required. This is used to interpret the separators within other:field.
other:field Required. The path to the field in Couchbase.

Note that the fields which are produced by vertical flattening use the same syntax for separating array values and field values. This introduces a potential ambiguity in cases like the following, where the Cloud exposes the columns "numeric_object.0" and "array.0":

{
  "numeric_object": {
    "0": 0
  },
  "array": [
    0
  ]
}
To ensure that the Cloud can distinguish between field and array accesses, the pathspec is used to determine whether each "." in the field is an array or an object. Each "{" represents a field access, while each "[" represents an array access.

For example, with a field of "a.0.b.1" and a "pathspec" of "[{[", the N1QL expression "a[0].b[1]" would be generated. If instead the "pathspec" were "{{{", then the N1QL expression "a.`0`.b.`1`" would be generated.

CData Cloud

Custom Schema Example

This section contains a complete schema. Set the Location property to the file directory that will contain the schema file. The info section enables a relational view of a Couchbase object. For more details, see Custom Schema Definitions. The table below allows the SELECT, INSERT, UPDATE, and DELETE commands as implemented in the GET, POST, MERGE, and DELETE sections of the schema below. The operations, such as couchbaseadoSysData, are internal implementations.

<rsb:script xmlns:rsb="http://www.rssbus.com/ns/rsbscript/2">  
  <rsb:info title="Customers" description="Customers" other:dataverse="" other:bucket=customers"" other:flavorexpr="" other:flavorvalue="" other:isarray="false" other:pathspec="" other:childpath="">
    <attr name="document.id"        xs:type="string"  key="true" other:iskey="true" other:pathspec=""  />
    <attr name="annual_revenue"     xs:type="integer" other:iskey="false"           other:pathspec=""  other:field="annual_revenue" />
    <attr name="homeaddress.city"   xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.city" />
    <attr name="homeaddress.state"  xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.state" />
    <attr name="homeaddress.street" xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="homeaddress.street" />
    <attr name="name"               xs:type="string"  other:iskey="false"           other:pathspec=""  other:field="name" />
    <attr name="id"                 xs:type="integer" other:iskey="false"           other:pathspec=""  other:field="id" />
    <attr name="offices"            xs:type="string"  other:iskey="false"           other:pathspec=""  other:field="offices" />
    <attr name="offices.0"          xs:type="string"  other:iskey="false"           other:pathspec="[" other:field="offices.0" />
    <attr name="offices.1"          xs:type="string"  other:iskey="false"           other:pathspec="[" other:field="offices.1" />
    <attr name="workaddress.city"   xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.city" />
    <attr name="workaddress.state"  xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.state" />
    <attr name="workaddress.street" xs:type="string"  other:iskey="false"           other:pathspec="{" other:field="workaddress.street" />
  </rsb:info>
</rsb:script>

CData Cloud

Changelog

General Changes

DateBuild
Number
Change
Type
Description
[8452] 02/21/20238452CouchbaseAdded
  • Added support for Analytics views and tabular Analytics views. Tabular Analytics views use the metadata provided as part of the
    CREATE ANALYTICS VIEW
    DDL statement instead of performing rowscan. Supported column metadata includes column names, types, nullability, primary keys, and foreign keys. Both types of views have similar limitations to external Analytics collections (they do not support Document.Id or Document.TTL, and are not scanned for child tables).
12/14/20228383GeneralChanged
  • Added the Default column to the sys_procedureparameters table.
09/30/20228308GeneralChanged
  • Added the IsPath column to the sys_procedureparameters table.
08/17/20228264GeneralChanged
  • We now support handling the keyword "COLLATE" as standard function name as well.
[8045] 01/10/20228045CouchbaseAdded
  • Added support for the NATIVEQUERY table function. This function can be used after a FROM to execute a query using Couchbase-native N1QL instead of SQL. For example,
    SELECT * FROM NATIVEQUERY('SELECT META(a).id, b.rowdata FROM abucket AS a UNNEST a.rows AS b')
    will execute the inner query directly on Couchbase and return the results. This will work even in tools which are not normally compatible with QueryPassthrough=true.
12/20/20218024CouchbaseAdded
  • Added support for UpdateNullValues. This provides control over whether NULL values written to doucments via UPDATE are stored as NULL in Couchbase, or are removed from the document.
10/26/20217969CouchbaseAdded
  • Added support for N1Q transactions. They apply to all N1QL queries that are not triggered by metadata or stored procedures. They can be either disabled entirely (the default), enabled for explicit use only (like setAutoCommit(false) or BeginTransaction()), or for implicit use where a one-statement transaction is used when no explicit transaction is active on the connection. Connection properties were also added to control transaction durability and lifetime requirements.
  • Added the corresponding connection properties, UseTransactions, TransactionDurability, and TransactionTimeout.
09/13/20217926CouchbaseAdded
  • Added support for calling user-defined functions in N1QL and Analytics. Global functions may be called using their unscoped names (to_meters("geo.lat")) or their scoped names ("Default.to_meters"("geo.lat")). Scoped functions must be called using their fully qualified names, which are two-parts or three-parts in Analytics ("experiments.to_meters") or three-parts only in N1QL ("experiments.units.to_meters").
09/02/20217915GeneralAdded
  • Added support for the STRING_SPLIT table-valued function in the CROSS APPLY clause.
08/07/20217889GeneralChanged
  • Added the KeySeq column to the sys_foreignkeys table.
08/06/20217888GeneralChanged
  • Added the new sys_primarykeys system table.
07/23/20217874GeneralChanged
  • 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.
07/14/20217865CouchbaseAdded
  • Added support for performing DML on nested child tables in NewChildJoinsMode, which completes our new relational model. You can now INSERT, UPDATE, and DELETE on every table exposed by the provider when NCJM is enabled.
  • Added support for creating collections via DDL. When the hidden UseCollectionsForDDL property is enabled, CREATE TABLE "abucket.ascope.acollection"(...) will create the bucket, scope and collection which correspond to the table's name.
07/08/20217859GeneralAdded
  • 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.
05/12/20217802CouchbaseAdded
  • Added support for creating collections via DDL. When the hidden UseCollectionsForDDL property is enabled, CREATE TABLE "abucket.ascope.acollection"(...) will create the bucket, scope and collection which correspond to the table's name.
04/23/20217785GeneralAdded
  • Added support for handling client side formulas during insert / update. For example: UPDATE Table SET Col1 = Concat(Col1, " - ", Col2) WHERE Col2 LIKE 'A%'
04/23/20217783GeneralChanged
  • Updated how display sizes are determined for varchar primary key and foreign key columns so they will match the reported length of the column.
04/16/20217776GeneralAdded
  • 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.
04/15 /20217775GeneralChanged
  • Kerberos authentication is updated to use TCP by default, but will fall back to UDP if a TCP connection cannot be established
04/12/20217772CouchbaseAdded
  • Added support for the USE KEYS query construct. When executing an N1QL query, the driver will attempt to determine if it contains any eligible filters on Document.Id - if there are any they are removed from the WHERE clause and migrated to the USE KEYS clause. When this transformation is applied the resulting query can avoid index scans, which allows for more queries to be run without a primary index and improves execution speed.
03/12/20217741CouchbaseChanged
  • Updated AddDocuments and ManageIndices so the interface no longer operates based on column#1 values. AddDocuments now accepts either a single ID and Document or a SourceTable that refers to a #TEMP table (analogus to a normal bulk insert), while ManageIndices accepts JSON arrays for multiple values since these are mostly typed by hand and have very few elements.
01/19/20217689CouchbaseAdded
  • Added support for collections and scopes within Couchbase v7. This touches on a lot of the driver but here are the main aspects:
    • Tables are now generated for collections as well as buckets/datasets in both N1Ql and Analytics. They have dotted names similar to Analytics datasets. The only exceptions are N1QL default collections which just use the bucket name (the server calls them _default) and Analytics legacy dataverses (which have the same two-level hierarchy)
    • Queries can now use data from collections in all the usual ways (flavors, UNNEST, etc), and collection tables can now be used with DROP TABLE. Buckets still work with DROP TABLE as well but only in limited contexts to prevent users from deleting data outside the default collection.
    • Added new stored procedures for creating and dropping scopes/collections, and updated index management stored predures to report information about scopes/collections.
    • The Dataverse option now expects to follow SQL quoting rules, and can be either a single SQL identifier (foo) for legacy dataverses, or a two-level qualified identifier (foo.bar) for Analytics dataverses/scopes

CData Cloud

Advanced Features

This section details a selection of advanced features of the Couchbase Cloud.

User Defined Views

The Cloud 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 Cloud 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 Cloud for compliance with Firewall and Proxy, including Windows proxies and HTTP proxies. You can also set up tunnel connections.

Query Processing

The Cloud offloads as much of the SELECT statement processing as possible to Couchbase and then processes the rest of the query in memory (client-side).

See Query Processing for more information.

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 Cloud

User Defined Views

The CData Cloud 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.

Defining Views Using a Configuration File

User Defined Views are defined in a JSON-formatted configuration file called UserDefinedViews.json. The Cloud 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 Cloud.

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 Customer WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}
Use the UserDefinedViews connection property to specify the location of your JSON configuration file. For example:
"UserDefinedViews", "C:\\Users\\yourusername\\Desktop\\tmp\\UserDefinedViews.json"

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 Cloud

SSL Configuration

Customizing the SSL Configuration

By default, the Cloud 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.

Client SSL Certificates

The Couchbase Cloud also supports setting client certificates. Set the following to connect using a client certificate.

  • SSLClientCert: The name of the certificate store for the client certificate.
  • SSLClientCertType: The type of key store containing the TLS/SSL client certificate.
  • SSLClientCertPassword: The password for the TLS/SSL client certificate.
  • SSLClientCertSubject: The subject of the TLS/SSL client certificate.

CData Cloud

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 Cloud

Caching Data

CData Cloud

Configuring the Cache Connection

CData Cloud

Caching Metadata

CData Cloud

Automatically Caching Data

CData Cloud

Explicitly Caching Data

CData Cloud

Data Type Mapping

CData Cloud

Query Processing

Query Processing

CData has a client-side SQL engine built into the Cloud library. This enables support for the full capabilities that SQL-92 offers, including filters, aggregations, functions, etc.

For sources that do not support SQL-92, the Cloud offloads as much of SQL statement processing as possible to Couchbase and then processes the rest of the query in memory (client-side). This results in optimal performance.

For data sources with limited query capabilities, the Cloud handles transformations of the SQL query to make it simpler for the Cloud. The goal is to make smart decisions based on the query capabilities of the data source to push down as much of the computation as possible. The Couchbase Query Evaluation component examines SQL queries and returns information indicating what parts of the query the Cloud is not capable of executing natively.

The Couchbase Query Slicer component is used in more specific cases to separate a single query into multiple independent queries. The client-side Query Engine makes decisions about simplifying queries, breaking queries into multiple queries, and pushing down or computing aggregations on the client-side while minimizing the size of the result set.

There's a significant trade-off in evaluating queries, even partially, client-side. There are always queries that are impossible to execute efficiently in this model, and some can be particularly expensive to compute in this manner. CData always pushes down as much of the query as is feasible for the data source to generate the most efficient query possible and provide the most flexible query capabilities.

More Information

For a full discussion of how CData handles query processing, see CData Architecture: Query Execution.

CData Cloud

Logging

Capturing Cloud 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 Cloud 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 an explanation of the five levels.
  • MaxLogFileSize: When the limit is hit, a new log is created in the same folder with the date and time appended to the end. The default limit is 100 MB. Values lower than 100 kB will use 100 kB as the value instead.
  • MaxLogFileCount: A string specifying the maximum file count of log files. When the limit is hit, a new log is created in the same folder with the date and time appended to the end and the oldest log file will be deleted. Minimum supported value is 2. A value of 0 or a negative value indicates no limit on the count.

Once this property is set, the Cloud 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 Cloud 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 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.

Sensitive Data

Verbosity levels 3 and higher may capture information that you do not want shared outside of your organization. The following lists information of concern for each level:

  • Verbosity 3: The full body of the request and the response, which includes all the data returned by the Cloud
  • Verbosity 4: SSL certificates
  • Verbosity 5: Any extra transfer data not included at Verbosity 3, such as non human-readable binary transfer data

Best Practices for Data Security

Although we mask sensitive values, such as passwords, in the connection string and any request in the log, it is always best practice to review the logs for any sensitive information before sharing outside your organization.

Advanced Logging

You may want to refine the exact information that is recorded to the log file. This can be accomplished using the LogModules property.

This property allows you to filter the logging using a semicolon-separated list of logging modules.

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 Cloud

SQL Compliance

The CData Cloud 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 Couchbase 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.

UPSERT Statements

An UPSERT updates a record if it exists and inserts the record if it does not. See UPSERT 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.

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 Cloud does not support batching of SQL statements. To execute multiple commands, you can create multiple instances and execute each separately.

CData Cloud

SELECT Statements

A SELECT statement can consist of the following basic clauses.

  • SELECT
  • INTO
  • FROM
  • JOIN
  • WHERE
  • GROUP BY
  • HAVING
  • UNION
  • ORDER BY
  • LIMIT

SELECT Syntax

The following syntax diagram outlines the syntax supported by the SQL engine of the Cloud:

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 Customer
  2. Rename a column:
    SELECT [TotalDue] AS MY_TotalDue FROM Customer
  3. Cast a column's data as a different data type:
    SELECT CAST(AnnualRevenue AS VARCHAR) AS Str_AnnualRevenue FROM Customer
  4. Search data:
    SELECT * FROM Customer WHERE CustomerId = '12345'
  5. The Couchbase APIs support the following operators in the WHERE clause: =, !=, <, <=, >, >=, IS NULL, LIKE, AND, OR, NOT, IN.
    SELECT * FROM Customer WHERE CustomerId = '12345';
  6. Return the number of items matching the query criteria:
    SELECT COUNT(*) AS MyCount FROM Customer 
  7. Return the number of unique items matching the query criteria:
    SELECT COUNT(DISTINCT TotalDue) FROM Customer 
  8. Return the unique items matching the query criteria:
    SELECT DISTINCT TotalDue FROM Customer 
  9. Summarize data:
    SELECT TotalDue, MAX(AnnualRevenue) FROM Customer  GROUP BY TotalDue
    See Aggregate Functions for details.
  10. Summarize data:
    SELECT TotalDue, MAX(AnnualRevenue) FROM Customer GROUP BY TotalDue
    See Aggregate Functions for details.
  11. Retrieve data from multiple tables.
    SELECT Customers.ContactName, Orders.OrderDate FROM Customers, Orders WHERE Customers.CustomerId=Orders.CustomerId
    See JOIN Queries for details.
  12. Sort a result set in ascending order:
    SELECT Name, TotalDue FROM Customer  ORDER BY TotalDue ASC
  13. Restrict a result set to the specified number of rows:
    SELECT Name, TotalDue FROM Customer LIMIT 10 
  14. Parameterize a query to pass in inputs at execution time. This enables you to create prepared statements and mitigate SQL injection attacks.
    SELECT * FROM Customer WHERE CustomerId = @param

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

    SELECT * FROM Customer WHERE PSEUDO = '@PSEUDO'
    

CData Cloud

Aggregate Functions

Examples of Aggregate Functions

Below are several examples of SQL aggregate functions. You can use these with a GROUP BY clause to aggregate rows based on the specified GROUP BY criterion. This can be a reporting tool.

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM Customer WHERE CustomerId = '12345'

COUNT(DISTINCT)

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

SELECT COUNT(DISTINCT Name) AS DistinctValues FROM Customer WHERE CustomerId = '12345'

AVG

Returns the average of the column values.

SELECT TotalDue, AVG(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), TotalDue FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MAX

Returns the maximum column value.

SELECT TotalDue, MAX(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM Customer WHERE CustomerId = '12345'

COUNT(DISTINCT)

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

SELECT COUNT(DISTINCT Name) AS DistinctValues FROM Customer WHERE CustomerId = '12345'

AVG

Returns the average of the column values.

SELECT TotalDue, AVG(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'  GROUP BY TotalDue

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), TotalDue FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MAX

Returns the maximum column value.

SELECT TotalDue, MAX(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'

CData Cloud

JOIN Queries

The CData Cloud 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 Customers.ContactName, Orders.OrderDate FROM Customers, Orders WHERE Customers.CustomerId=Orders.CustomerId

Left Join

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

SELECT Customers.ContactName, Orders.OrderDate FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerId=Orders.CustomerId

CData Cloud

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 Cloud

Aggregate Functions

Examples of Aggregate Functions

Below are several examples of SQL aggregate functions. You can use these with a GROUP BY clause to aggregate rows based on the specified GROUP BY criterion. This can be a reporting tool.

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM Customer WHERE CustomerId = '12345'

COUNT(DISTINCT)

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

SELECT COUNT(DISTINCT Name) AS DistinctValues FROM Customer WHERE CustomerId = '12345'

AVG

Returns the average of the column values.

SELECT TotalDue, AVG(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), TotalDue FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MAX

Returns the maximum column value.

SELECT TotalDue, MAX(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM Customer WHERE CustomerId = '12345'

COUNT(DISTINCT)

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

SELECT COUNT(DISTINCT Name) AS DistinctValues FROM Customer WHERE CustomerId = '12345'

AVG

Returns the average of the column values.

SELECT TotalDue, AVG(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'  GROUP BY TotalDue

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), TotalDue FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

MAX

Returns the maximum column value.

SELECT TotalDue, MAX(AnnualRevenue) FROM Customer WHERE CustomerId = '12345' GROUP BY TotalDue

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM Customer WHERE CustomerId = '12345'

CData Cloud

Projection Functions

ARRAY_AGG(column)

Returns array of the non-MISSING values in the group, including NULL values.

  • column: Any column expression.

ARRAY_APPEND(column, value)

Returns new array with value appended.

  • column: Any column expression.
  • value: The value to be appended to the array.

ARRAY_CONCAT(column1, column2)

Returns new array with the concatenation of the input arrays.

  • column1: Any column expression.
  • column2: Any column expression.

ARRAY_DISTINCT(column)

Returns new array with distinct elements of input array.

  • column: Any column expression.

ARRAY_IFNULL(column)

Returns the first non-NULL value in the array, or NULL.

  • column: Any column expression.

ARRAY_PREPEND(column, value)

Returns new array with value pre-pended.

  • column: Any column expression.
  • value: The value to be pre-pended to the array.

ARRAY_PUT(column, value)

Returns new array with value appended, if value is not already present, otherwise returns the unmodified input array.

  • column: Any column expression.
  • value: The value to append to the array.

ARRAY_REMOVE(column, value)

Returns new array with all occurrences of value removed.

  • column: Any column expression.
  • value: The value to be removed from the array.

ARRAY_REPLACE(column, value1, value2 [, integer_n])

Returns new array with all occurrences of value removed.

  • column: Any column expression.
  • value1: The value to be replaced by value2.
  • value2: The value to replace value1.
  • integer_n: The maximum number of replacements to be performed.

ARRAY_REVERSE(column)

Returns new array with all elements in reverse order.

  • column: Any column expression.

ARRAY_SORT(column)

Returns new array with elements sorted in N1QL collation order.

  • column: Any column expression.

DECODE_JSON(column)

Unmarshals the JSON-encoded string into a N1QL value. The empty string is MISSING.

  • column: Any column expression.

ENCODE_JSON(column)

Marshals the N1QL value into a JSON-encoded string. MISSING becomes the empty string.

  • column: Any column expression.

ENCODED_SIZE(column)

Number of bytes in an uncompressed JSON encoding of the value. The exact size is implementation-dependent. Always returns an integer, and never MISSING or NULL. Returns 0 for MISSING.

  • column: Any column expression.

POLY_LENGTH(column)

Returns length of the value after evaluating the expression. The exact meaning of length depends on the type of the value: MISSING: MISSING; NULL: NULL; String: The length of the string.; Array: The number of elements in the array.; Object: The number of name/value pairs in the object; Any other value: NULL.

  • column: Any column expression.

OBJECT_LENGTH(column)

Returns number of name-value pairs in the object.

  • column: Any column expression.

OBJECT_NAMES(column)

Returns array containing the attribute names of the object, in N1QL collation order.

  • column: Any column expression.

OBJECT_PAIRS(column)

Returns array containing the attribute name and value pairs of the object, in N1QL collation order of the names.

  • column: Any column expression.

OBJECT_VALUES(column)

Returns array containing the attribute values of the object, in N1QL collation order of the corresponding names.

  • column: Any column expression.

ARRAY_AVG(column)

Returns arithmetic mean (average) of all the non-NULL number values in the array, or NULL if there are no such values.

  • column: Any column expression.

ARRAY_CONTAINS(column, value)

Returns true if the array contains value.

  • column: Any column expression.
  • value: The value contained within the array.

ARRAY_COUNT(column)

Returns count of all the non-NULL values in the array, or zero if there are no such values.

  • column: Any column expression.

ARRAY_LENGTH(column)

Returns the number of elements in the array.

  • column: Any column expression.

ARRAY_MAX(column)

Returns the largest non-NULL, non-MISSING array element, in N1QL collation order.

  • column: Any column expression.

ARRAY_MIN(column)

Returns smallest non-NULL, non-MISSING array element, in N1QL collation order.

  • column: Any column expression.

ARRAY_POSITION(column, value)

Returns the first position of value within the array, or -1. Array position is zero-based, i.e. the first position is 0.

  • column: Any column expression.
  • value: The value contained within the array.

ARRAY_SUM(column)

Sum of all the non-NULL number values in the array, or zero if there are no such values.

  • column: Any column expression.

GREATEST(column1, column2 [,column3 [,column4]])

Largest non-NULL, non-MISSING value if the values are of the same type; otherwise NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

LEAST(column1, column2 [,column3 [,column4]])

Returns smallest non-NULL, non-MISSING value if the values are of the same type, otherwise returns NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFMISSING(column1, column2 [,column3 [,column4]])

Returns the first non-MISSING value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFMISSINGORNULL(column1, column2 [,column3 [,column4]])

Returns first non-NULL, non-MISSING value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNULL(column1, column2 [,column3 [,column4]])

Returns first non-NULL value. Note that this function might return MISSING if there is no non-NULL value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

MISSINGIF(column1, column2)

Returns MISSING if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.

NULLIF(column1, column2)

Returns NULL if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.

IFINF(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-Inf number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNAN(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-NaN number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNANORINF(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-Inf, or non-NaN number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

NANIF(column1, column2 [,column3 [,column4]])

Returns NaN if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

NEGINFIF(column1, column2 [,column3 [,column4]])

Returns NegInf if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

POSINFIF(column1, column2 [,column3 [,column4]])

Returns PosInf if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

CLOCK_MILLIS()

Returns system clock at function evaluation time, as UNIX milliseconds. Varies during a query.

CLOCK_STR([string_fmt])

Returns system clock at function evaluation time, as a string in a supported format. Varies during a query.

  • string_fmt: The datetime format to return the system clock in.

DATE_ADD_MILLIS(column, integer_n, string_part)

Performs date arithmetic, and returns result of computation. n and part are used to define an interval or duration, which is then added (or subtracted) to the UNIX time stamp, returning the result.

  • column: Any column expression.
  • integer_n: The number of string_part's to add to the column value.
  • string_part: The part to add integer_n to, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_ADD_STR(column, integer_n, string_part)

Performs date arithmetic. n and part are used to define an interval or duration, which is then added (or subtracted) to the date string in a supported format, returning the result.

  • column: Any column expression.
  • integer_n: The number of string_part's to add to the column value.
  • string_part: The part to add integer_n to, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_DIFF_MILLIS(column1, column2, string_part)

Performs date arithmetic. Returns the elapsed time between two UNIX time stamps as an integer whose unit is part.

  • column1: Any column expression.
  • column2: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_DIFF_STR(column1, column2, string_part)

Performs date arithmetic. Returns the elapsed time between two date strings in a supported format, as an integer whose unit is part.

  • column1: Any column expression.
  • column2: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_PART_MILLIS(column1, string_part [, tz])

Returns date part as an integer. The date expression is a number representing UNIX milliseconds, and part is one of the following date part strings.

  • column1: Any column expression.
  • string_part: The component of the date to extract. Available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, millisecond, day_of_year, day_of_week, iso_week, iso_year, iso_dow, timezone, timezone_hour, and timezone_minute.
  • tz: The timezone to convert the local time to. Default to the system timezone if not specified. If an incorrect time zone is provided, the null is returned.

DATE_PART_STR(column1, string_part)

Returns date part as an integer. The date expression is a string in a supported format, and part is one of the supported date part strings.

  • column1: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, millisecond, day_of_year, day_of_week, iso_week, iso_year, iso_dow, timezone, timezone_hour, and timezone_minute.

DATE_TRUNC_MILLIS(column1, string_part)

Returns UNIX time stamp that has been truncated so that the given date part string is the least significant.

  • column1: Any column expression.
  • string_part: The least significant date part, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_TRUNC_STR(column1, string_part)

Returns ISO 8601 time stamp that has been truncated so that the given date part string is the least significant.

  • column1: Any column expression.
  • string_part: The least significant date part, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

MILLIS(column1)

Returns date that has been converted in a supported format to UNIX milliseconds.

  • column1: Any column expression.

STR_TO_MILLIS(column1)

Returns date that has been converted in a supported format to UNIX milliseconds.

  • column1: Any column expression.

MILLIS_TO_STR(column [, string_fmt])

Returns the string in the supported format to which the UNIX milliseconds has been converted.

  • column1: Any column expression.
  • string_fmt: The datetime format to return the system clock in.

MILLIS_TO_UTC(column [, string_fmt])

Returns the UTC string to which the UNIX time stamp has been converted in the supported format.

  • column1: Any column expression.
  • string_fmt: The datetime format to return the system clock in.

MILLIS_TO_TZ(column, string_tzname [, string_fmt])

Converts the UNIX time stamp to a string in the named time zone, and returns the string.

  • column1: Any column expression.
  • string_tzname: The time zone name.
  • string_fmt: The datetime format to return the system clock in.

NOW_MILLIS()

Returns statement time stamp as UNIX milliseconds; does not vary during a query.

NOW_STR([string_fmt])

Returns statement time stamp as a string in a supported format; does not vary during a query.

  • string_fmt: The datetime format to return the timestamp in.

STR_TO_UTC(column1)

Converts the ISO 8601 time stamp to UTC.

  • column1: Any column expression.

STR_TO_ZONE_NAME(column, string_tzname)

Converts the supported time stamp string to the named time zone.

  • column1: Any column expression.
  • string_tzname: The time zone name.

BASE64(expression)

Returns base64 encoding of expression.

  • expression: Any column or literal expression.

ABS(expression)

Returns absolute value of the number.

  • expression: Any column or literal expression.

ACOS(expression)

Returns arccosine in radians.

  • expression: Any column or literal expression.

ASIN(expression)

Returns arcsine in radians.

  • expression: Any column or literal expression.

ATAN(expression)

Returns arctangent in radians.

  • expression: Any column or literal expression.

ATAN2(expression1, expression2)

Returns arctangent of expression2/expression1.

  • expression1: Any column or literal expression.
  • expression2: Any column or literal expression.

CEIL(expression)

Returns smallest integer not less than the number.

  • expression: Any column or literal expression.

COS(expression)

Returns cosine.

  • expression: Any column or literal expression.

DEGREES(expression)

Returns radians to degrees.

  • expression: Any column or literal expression.

E()

Base of natural logarithms.

EXP(expression)

Returns e^expression.

  • expression: Any column or literal expression.

LN(expression)

Returns log base e.

  • expression: Any column or literal expression.

LOG(expression)

Returns log base 10.

  • expression: Any column or literal expression.

FLOOR(expression)

Largest integer not greater than the number.

  • expression: Any column or literal expression.

PI()

Returns PI.

POWER(expression1, expression2)

Returns expression1^expression2.

  • expression1: Any column or literal expression.
  • expression2: Any column or literal expression.

RADIANS(expression)

Returns degrees to radians.

  • expression: Any column or literal expression.

RANDOM([expression])

Returns pseudo-random number with optional seed.

  • expression: Any column or literal expression.

ROUND(expression [, integer_digits])

Rounds the value to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits is 0 if not given.

  • expression: Any column or literal expression.
  • integer_digits: The number of digits to round to.

SIGN(expression)

Valid values: -1, 0, or 1 for negative, zero, or positive numbers respectively.

  • expression: Any column or literal expression.

SIN(expression)

Returns sine.

  • expression: Any column or literal expression.

SQRT(expression)

Returns square root.

  • expression: Any column or literal expression.

TAN(expression)

Returns tangent.

  • expression: Any column or literal expression.

TRUNC(expression [, integer_digits])

Truncates the number to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits is 0 if not given.

  • expression: Any column or literal expression.
  • integer_digits: The number of digits to truncate.

CONTAINS(column, string_substring)

True if the string contains the substring.

  • column: Any column or literal expression.
  • string_substring: The substring to search for.

INITCAP(column)

Converts the string so that the first letter of each word is uppercase and every other letter is lowercase.

  • column: Any column or literal expression.

LENGTH(column)

Returns length of the string value.

  • column: Any column or literal expression.

LOWER(column)

Returns lowercase of the string value.

  • column: Any column or literal expression.

LTRIM(column [, string_chars])

Returns string with all leading chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The leading characters to remove.

POSITION(column, string_substring)

Returns the first position of the substring within the string, or -1. The position is zero-based, i.e., the first position is 0.

  • column: Any column or literal expression.
  • string_substring: The substring to search for.

REPEAT(column, integer_n)

Returns string formed by repeating expression n times.

  • column: Any column or literal expression.
  • integer_n: The number of times to repeat column.

REPLACE(column, string_substring, string_replace [, integer_n])

Returns string with all occurrences of substr replaced with repl. If n is given, at most n replacements are performed.

  • column: The column expression.
  • string_substring: The regular expression to match.
  • string_replace: The value to replace the matched pattern.
  • integer_n: The maximum number of replacements to make.

RTRIM(column [, string_chars])

Returns string with all trailing chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The trailing characters to remove.

SPLIT(column [, string_sep])

Splits the string into an array of substrings separated by string_sep. If string_sep is not given, any combination of white space characters is used.

  • column: Any column or literal expression.
  • string_sep: The separator to split column on.

SUBSTR(column, integer_position [, integer_length])

Returns substring from the integer position of the given length, or to the end of the string. The position is zero-based, i.e. the first position is 0. If position is negative, it is counted from the end of the string; -1 is the last position in the string.

  • column: Any column or literal expression.
  • integer_position: The starting position.
  • integer_length: The total length of the substring to retrieve.

TRIM(column [, string_chars])

Returns string with all leading and trailing chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The leading and trailing characters to remove.

UPPER(column)

Returns uppercase of the string value.

  • column: Any column or literal expression.

TOARRAY(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Arrays are themselves; All other values are wrapped in an array.

  • column: Any column expression.

TOATOM(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Arrays of length 1 are the result of TOATOM() on their single element; Objects of length 1 are the result of TOATOM() on their single value; Booleans, numbers, and strings are themselves; All other values are NULL.

  • column: Any column expression.

TOBOOLEAN(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is false; Numbers +0, -0, and NaN are false; Empty strings, arrays, and objects are false; All other values are true.

  • column: Any column expression.

TONUMBER(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is 0; True is 1; Numbers are themselves; Strings that parse as numbers are those numbers; All other values are NULL.

  • column: Any column expression.

TOOBJECT(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Objects are themselves; All other values are the empty object.

  • column: Any column expression.

TOSTRING(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is "false"; True is "true"; Numbers are their string representation; Strings are themselves; All other values are NULL.

  • column: Any column expression.

CData Cloud

Predicate Functions

REGEXP_CONTAINS(column, string_pattern)

Returns True if the string value contains the regular expression pattern.

  • column: The column expression.
  • string_pattern: The regular expression to match.

REGEXP_LIKE(column, string_pattern)

Returns True if the string value matches the regular expression pattern.

  • column: The column expression.
  • string_pattern: The regular expression to match.

REGEXP_POSITION(column, string_pattern)

Returns first position of the regular expression pattern within the string, or -1.

  • column: The column expression.
  • string_pattern: The regular expression to match.

REGEXP_REPLACE(column, string_pattern, string_replace [, integer_n])

Returns new string with occurrences of pattern replaced with string_replace. If n is given, at most n replacements are performed.

  • column: The column expression.
  • string_pattern: The regular expression to match.
  • string_replace: The value to replace the matched pattern.
  • integer_n: The maximum number of replacements to make.

ISARRAY(column)

Returns True if expression is an array, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

ISATOM(column)

Returns True if expression is a Boolean, number, or string, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

ISBOOLEAN(column)

Returns True if expression is a Boolean, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

ISNUMBER(column)

Returns True if expression is a number, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

ISOBJECT(column)

Returns True if expression is an object, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

ISSTRING(column)

Returns True if expression is a string, otherwise returns MISSING, NULL or false.

  • column: Any column expression.

TYPE(column)

Returns one of the following strings, based on the value of expression: missing, null, boolean, number, string, array, object, or binary.

  • column: Any column expression.

ARRAY_AVG(column)

Returns arithmetic mean (average) of all the non-NULL number values in the array, or NULL if there are no such values.

  • column: Any column expression.

ARRAY_CONTAINS(column, value)

Returns true if the array contains value.

  • column: Any column expression.
  • value: The value contained within the array.

ARRAY_COUNT(column)

Returns count of all the non-NULL values in the array, or zero if there are no such values.

  • column: Any column expression.

ARRAY_LENGTH(column)

Returns the number of elements in the array.

  • column: Any column expression.

ARRAY_MAX(column)

Returns the largest non-NULL, non-MISSING array element, in N1QL collation order.

  • column: Any column expression.

ARRAY_MIN(column)

Returns smallest non-NULL, non-MISSING array element, in N1QL collation order.

  • column: Any column expression.

ARRAY_POSITION(column, value)

Returns the first position of value within the array, or -1. Array position is zero-based, i.e. the first position is 0.

  • column: Any column expression.
  • value: The value contained within the array.

ARRAY_SUM(column)

Sum of all the non-NULL number values in the array, or zero if there are no such values.

  • column: Any column expression.

GREATEST(column1, column2 [,column3 [,column4]])

Largest non-NULL, non-MISSING value if the values are of the same type; otherwise NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

LEAST(column1, column2 [,column3 [,column4]])

Returns smallest non-NULL, non-MISSING value if the values are of the same type, otherwise returns NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFMISSING(column1, column2 [,column3 [,column4]])

Returns the first non-MISSING value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFMISSINGORNULL(column1, column2 [,column3 [,column4]])

Returns first non-NULL, non-MISSING value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNULL(column1, column2 [,column3 [,column4]])

Returns first non-NULL value. Note that this function might return MISSING if there is no non-NULL value.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

MISSINGIF(column1, column2)

Returns MISSING if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.

NULLIF(column1, column2)

Returns NULL if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.

IFINF(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-Inf number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNAN(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-NaN number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

IFNANORINF(column1, column2 [,column3 [,column4]])

Returns first non-MISSING, non-Inf, or non-NaN number. Returns MISSING or NULL if a non-number input is encountered first.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

NANIF(column1, column2 [,column3 [,column4]])

Returns NaN if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

NEGINFIF(column1, column2 [,column3 [,column4]])

Returns NegInf if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

POSINFIF(column1, column2 [,column3 [,column4]])

Returns PosInf if column1 = column2, otherwise returns column1. Returns MISSING or NULL if either input is MISSING or NULL.

  • column1: Any column expression.
  • column2: Any column expression.
  • column3: Any column expression.
  • column4: Any column expression.

CLOCK_MILLIS()

Returns system clock at function evaluation time, as UNIX milliseconds. Varies during a query.

CLOCK_STR([string_fmt])

Returns system clock at function evaluation time, as a string in a supported format. Varies during a query.

  • string_fmt: The datetime format to return the system clock in.

DATE_ADD_MILLIS(column, integer_n, string_part)

Performs date arithmetic, and returns result of computation. n and part are used to define an interval or duration, which is then added (or subtracted) to the UNIX time stamp, returning the result.

  • column: Any column expression.
  • integer_n: The number of string_part's to add to the column value.
  • string_part: The part to add integer_n to, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_ADD_STR(column, integer_n, string_part)

Performs date arithmetic. n and part are used to define an interval or duration, which is then added (or subtracted) to the date string in a supported format, returning the result.

  • column: Any column expression.
  • integer_n: The number of string_part's to add to the column value.
  • string_part: The part to add integer_n to, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_DIFF_MILLIS(column1, column2, string_part)

Performs date arithmetic. Returns the elapsed time between two UNIX time stamps as an integer whose unit is part.

  • column1: Any column expression.
  • column2: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_DIFF_STR(column1, column2, string_part)

Performs date arithmetic. Returns the elapsed time between two date strings in a supported format, as an integer whose unit is part.

  • column1: Any column expression.
  • column2: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_PART_MILLIS(column1, string_part [, tz])

Returns date part as an integer. The date expression is a number representing UNIX milliseconds, and part is one of the following date part strings.

  • column1: Any column expression.
  • string_part: The component of the date to extract. Available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, millisecond, day_of_year, day_of_week, iso_week, iso_year, iso_dow, timezone, timezone_hour, and timezone_minute.
  • tz: The timezone to convert the local time to. Default to the system timezone if not specified. If an incorrect time zone is provided, the null is returned.

DATE_PART_STR(column1, string_part)

Returns date part as an integer. The date expression is a string in a supported format, and part is one of the supported date part strings.

  • column1: Any column expression.
  • string_part: The unit of the result, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, millisecond, day_of_year, day_of_week, iso_week, iso_year, iso_dow, timezone, timezone_hour, and timezone_minute.

DATE_TRUNC_MILLIS(column1, string_part)

Returns UNIX time stamp that has been truncated so that the given date part string is the least significant.

  • column1: Any column expression.
  • string_part: The least significant date part, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

DATE_TRUNC_STR(column1, string_part)

Returns ISO 8601 time stamp that has been truncated so that the given date part string is the least significant.

  • column1: Any column expression.
  • string_part: The least significant date part, available values are: millennium, century, decade, year, quarter, month, week, day, hour, minute, second, and millisecond.

MILLIS(column1)

Returns date that has been converted in a supported format to UNIX milliseconds.

  • column1: Any column expression.

STR_TO_MILLIS(column1)

Returns date that has been converted in a supported format to UNIX milliseconds.

  • column1: Any column expression.

MILLIS_TO_STR(column [, string_fmt])

Returns the string in the supported format to which the UNIX milliseconds has been converted.

  • column1: Any column expression.
  • string_fmt: The datetime format to return the system clock in.

MILLIS_TO_UTC(column [, string_fmt])

Returns the UTC string to which the UNIX time stamp has been converted in the supported format.

  • column1: Any column expression.
  • string_fmt: The datetime format to return the system clock in.

MILLIS_TO_TZ(column, string_tzname [, string_fmt])

Converts the UNIX time stamp to a string in the named time zone, and returns the string.

  • column1: Any column expression.
  • string_tzname: The time zone name.
  • string_fmt: The datetime format to return the system clock in.

NOW_MILLIS()

Returns statement time stamp as UNIX milliseconds; does not vary during a query.

NOW_STR([string_fmt])

Returns statement time stamp as a string in a supported format; does not vary during a query.

  • string_fmt: The datetime format to return the timestamp in.

STR_TO_UTC(column1)

Converts the ISO 8601 time stamp to UTC.

  • column1: Any column expression.

STR_TO_ZONE_NAME(column, string_tzname)

Converts the supported time stamp string to the named time zone.

  • column1: Any column expression.
  • string_tzname: The time zone name.

BASE64(expression)

Returns base64 encoding of expression.

  • expression: Any column or literal expression.

ABS(expression)

Returns absolute value of the number.

  • expression: Any column or literal expression.

ACOS(expression)

Returns arccosine in radians.

  • expression: Any column or literal expression.

ASIN(expression)

Returns arcsine in radians.

  • expression: Any column or literal expression.

ATAN(expression)

Returns arctangent in radians.

  • expression: Any column or literal expression.

ATAN2(expression1, expression2)

Returns arctangent of expression2/expression1.

  • expression1: Any column or literal expression.
  • expression2: Any column or literal expression.

CEIL(expression)

Returns smallest integer not less than the number.

  • expression: Any column or literal expression.

COS(expression)

Returns cosine.

  • expression: Any column or literal expression.

DEGREES(expression)

Returns radians to degrees.

  • expression: Any column or literal expression.

E()

Base of natural logarithms.

EXP(expression)

Returns e^expression.

  • expression: Any column or literal expression.

LN(expression)

Returns log base e.

  • expression: Any column or literal expression.

LOG(expression)

Returns log base 10.

  • expression: Any column or literal expression.

FLOOR(expression)

Largest integer not greater than the number.

  • expression: Any column or literal expression.

PI()

Returns PI.

POWER(expression1, expression2)

Returns expression1^expression2.

  • expression1: Any column or literal expression.
  • expression2: Any column or literal expression.

RADIANS(expression)

Returns degrees to radians.

  • expression: Any column or literal expression.

RANDOM([expression])

Returns pseudo-random number with optional seed.

  • expression: Any column or literal expression.

ROUND(expression [, integer_digits])

Rounds the value to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits is 0 if not given.

  • expression: Any column or literal expression.
  • integer_digits: The number of digits to round to.

SIGN(expression)

Valid values: -1, 0, or 1 for negative, zero, or positive numbers respectively.

  • expression: Any column or literal expression.

SIN(expression)

Returns sine.

  • expression: Any column or literal expression.

SQRT(expression)

Returns square root.

  • expression: Any column or literal expression.

TAN(expression)

Returns tangent.

  • expression: Any column or literal expression.

TRUNC(expression [, integer_digits])

Truncates the number to the given number of integer digits to the right of the decimal point (left if digits is negative). Digits is 0 if not given.

  • expression: Any column or literal expression.
  • integer_digits: The number of digits to truncate.

CONTAINS(column, string_substring)

True if the string contains the substring.

  • column: Any column or literal expression.
  • string_substring: The substring to search for.

INITCAP(column)

Converts the string so that the first letter of each word is uppercase and every other letter is lowercase.

  • column: Any column or literal expression.

LENGTH(column)

Returns length of the string value.

  • column: Any column or literal expression.

LOWER(column)

Returns lowercase of the string value.

  • column: Any column or literal expression.

LTRIM(column [, string_chars])

Returns string with all leading chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The leading characters to remove.

POSITION(column, string_substring)

Returns the first position of the substring within the string, or -1. The position is zero-based, i.e., the first position is 0.

  • column: Any column or literal expression.
  • string_substring: The substring to search for.

REPEAT(column, integer_n)

Returns string formed by repeating expression n times.

  • column: Any column or literal expression.
  • integer_n: The number of times to repeat column.

REPLACE(column, string_substring, string_replace [, integer_n])

Returns string with all occurrences of substr replaced with repl. If n is given, at most n replacements are performed.

  • column: The column expression.
  • string_substring: The regular expression to match.
  • string_replace: The value to replace the matched pattern.
  • integer_n: The maximum number of replacements to make.

RTRIM(column [, string_chars])

Returns string with all trailing chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The trailing characters to remove.

SPLIT(column [, string_sep])

Splits the string into an array of substrings separated by string_sep. If string_sep is not given, any combination of white space characters is used.

  • column: Any column or literal expression.
  • string_sep: The separator to split column on.

SUBSTR(column, integer_position [, integer_length])

Returns substring from the integer position of the given length, or to the end of the string. The position is zero-based, i.e. the first position is 0. If position is negative, it is counted from the end of the string; -1 is the last position in the string.

  • column: Any column or literal expression.
  • integer_position: The starting position.
  • integer_length: The total length of the substring to retrieve.

TRIM(column [, string_chars])

Returns string with all leading and trailing chars removed. White space by default.

  • column: Any column or literal expression.
  • string_chars: The leading and trailing characters to remove.

UPPER(column)

Returns uppercase of the string value.

  • column: Any column or literal expression.

TOARRAY(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Arrays are themselves; All other values are wrapped in an array.

  • column: Any column expression.

TOATOM(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Arrays of length 1 are the result of TOATOM() on their single element; Objects of length 1 are the result of TOATOM() on their single value; Booleans, numbers, and strings are themselves; All other values are NULL.

  • column: Any column expression.

TOBOOLEAN(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is false; Numbers +0, -0, and NaN are false; Empty strings, arrays, and objects are false; All other values are true.

  • column: Any column expression.

TONUMBER(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is 0; True is 1; Numbers are themselves; Strings that parse as numbers are those numbers; All other values are NULL.

  • column: Any column expression.

TOOBJECT(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; Objects are themselves; All other values are the empty object.

  • column: Any column expression.

TOSTRING(column)

Returns array as follows: MISSING is MISSING; NULL is NULL; False is "false"; True is "true"; Numbers are their string representation; Strings are themselves; All other values are NULL.

  • column: Any column expression.

CData Cloud

SELECT INTO Statements

You can use the SELECT INTO statement to export formatted data to a file.

Data Export with an SQL Query

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

SELECT Name, TotalDue INTO [csv://Customer.txt] FROM [Customer] WHERE CustomerId = '12345'
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 Name, TotalDue INTO [csv://Customer.txt;delimiter=tab] FROM [Customer] WHERE CustomerId = '12345'
You can specify other file formats in the URI. The following example exports tab-separated values:

CData Cloud

SQL Functions

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

  • SQL Server:
    SELECT DATENAME(yy,GETDATE())
  • Cloud:
    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 Customer WHERE CustomerId = '12345'

Date Functions

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

SELECT CURRENT_TIMESTAMP() FROM Customer

Math Functions

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

SELECT RAND() FROM Customer

Function Parameters and Nesting SQL Functions

The Cloud 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 Customer

Predicate Functions

These functions can be used to specify criteria in the WHERE clause of your SQL query. See Predicate Functions for more details.

* FROM Customer WHERE CreatedDate = NOW()

CData Cloud

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 Cloud

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

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 Cloud

INSERT Statements

To create new records, use INSERT statements.

INSERT Syntax

The INSERT statement specifies the columns to be inserted and the new column values. You can specify the column values in a comma-separated list in the VALUES clause, as shown in the following example:

INSERT INTO <table_name> 
( <column_reference> [ , ... ] )
VALUES 
( { <expression> | NULL } [ , ... ] ) 
  

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>
The following is an example query:
INSERT INTO Customer (TotalDue) VALUES ('John')

CData Cloud

UPDATE Statements

To modify existing records, use UPDATE statements.

Update Syntax

The UPDATE statement takes as input a comma-separated list of columns and new column values as name-value pairs in the SET clause, as shown in the following example:

UPDATE <table_name> SET { <column_reference> = <expression> } [ , ... ] WHERE { Id = <expression>  } [ { AND | OR } ... ] 

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

The following is an example query:

UPDATE Customer SET TotalDue='John' WHERE Id = @myId

CData Cloud

DELETE Statements

To delete information from a table, use DELETE statements.

DELETE Syntax

The DELETE statement requires the table name in the FROM clause and the row's primary key in the WHERE clause, as shown in the following example:

<delete_statement> ::= DELETE FROM <table_name> WHERE { Id = <expression> } [ { AND | OR } ... ]

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

The following is an example query:

DELETE FROM Customer WHERE Id = @myId

CData Cloud

CACHE Statements

CData Cloud

EXECUTE Statements

To execute stored procedures, you can use EXECUTE or EXEC statements.

EXEC and EXECUTE assign stored procedure inputs, referenced by name, to values or parameter names.

Stored Procedure Syntax

To execute a stored procedure as an SQL statement, use the following syntax:

 
{ EXECUTE | EXEC } <stored_proc_name> 
{
  [ @ ] <input_name> = <expression>
} [ , ... ]

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

Example Statements

Reference stored procedure inputs by name:

EXECUTE my_proc @second = 2, @first = 1, @third = 3;

Execute a parameterized stored procedure statement:

EXECUTE my_proc second = @p1, first = @p2, third = @p3; 

CData Cloud

PIVOT and UNPIVOT

PIVOT and UNPIVOT can be used to change a table-valued expression into another table.

PIVOT

PIVOT rotates a table-value expression by turning unique values from one column into multiple columns in the output. PIVOT can run aggregations where required on any column value.
PIVOT Synax

 
"SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, [0], [1], [2], [3], [4]
FROM
(
SELECT DaysToManufacture, StandardCost
FROM Production.Product
) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;"

UNPIVOT

UNPIVOT carries out nearly the opposite to PIVOT by rotating columns of a table-valued expressions into column values.
UNPIVOT Sytax

 
"SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;"

For further information on PIVOT and UNPIVOT, see FROM clause plus JOIN, APPLY, PIVOT (Transact-SQL)

CData Cloud

Data Model

Overview

Depending upon the connection settings being used, the Cloud can present several different mappings between Couchbase entities and relational tables and views. For more details on each of these capabilities, refer to the NoSQL portion of this documentation.

  • When connecting to the N1QL query service, the Cloud models Couchbase buckets as relational tables. In addition, if TypeDetectionScheme is set to DocType or Infer, the Cloud will present different document flavors in each bucket as their own tables.
  • When connecting to the Analytics service, the Cloud models Couchbase datasets as relational views.
  • When connecting with either service, the Cloud can expose arrays of data as child tables or views.

Please see the Automatic Schema Discovery section for more details on how flavor and child tables are exposed. In addition, the NewChildJoinsMode connection property is recommended for workflows that make heavy use of child tables. The documentation for that connection property details the improvements it makes to the Cloud data model.

Dataverses, Scopes and Collections

Couchbase has different ways of grouping buckets and datasets depending on the CouchbaseService and version of Couchbase you are connecting to:

  • Couchbase organizes Analytics datsets into groups called dataverses. By default the Cloud exposes datasets from all dataverses using compound names like Default.users as described in DataverseSeparator. It is important to remember that these compound names must be quoted when used in queries, for example SELECT * FROM [Default.users]
  • You may also set the Dataverse property to limit the the Cloud to exposing a single dataverse. This disables compound names so view names will not include the dataset.
  • When connecting to Couchbase 7 and above, the Cloud will use the scope, collection and bucket/dataset name to build table and view names. For example, a table with a name like crm.accounts.customers exposes the customers collection under the accounts scope of the crm bucket. These must be quoted the same as other compound names when used in queries, for example SELECT * FROM [crm.accounts.customers]

Live Metadata

All of the schemas provided by the Cloud are dynamically retrieved from Couchbase, so any changes in the buckets or fields within Couchbase will be reflected in the Cloud the next time you connect. You may also issue a reset query to refresh schemas without having to close the connection:

RESET SCHEMA CACHE

CData Cloud

Stored Procedures

Stored procedures are function-like interfaces that extend the functionality of the Cloud beyond simple SELECT/INSERT/UPDATE/DELETE operations with Couchbase.

Stored procedures accept a list of parameters, perform their intended function, and then return, if applicable, any relevant response data from Couchbase, along with an indication of whether the procedure succeeded or failed.

CData Cloud - Couchbase Stored Procedures

Name Description
AddDocument Upsert entire JSON documents to Couchbase as-is.
CreateBucket Creates a new bucket in CouchBase.
CreateCollection Creates a collection under an existing scope
CreateScope Creates a scope under an existing bucket
CreateUserTable An internal operation used when GenerateSchemaFiles=OnCreate
DeleteBucket Deletes a bucket (and all its collections and scopes, where supported)
DeleteCollection Deletes a collection (Couchbase 7 and up)
DeleteScope Deletes a scope and all its collections (Couchbase 7 and up)
FlushBucket Removes all documents from a bucket in Couchbase.
ListIndices Lists all indices available in Couchbase
ManageIndices Creates/Drops an index in a target bucket in Couchbase.

CData Cloud

AddDocument

Upsert entire JSON documents to Couchbase as-is.

Input

Name Type Required Description
BucketName String True The bucket to insert the document into.
SourceTable String False The name of the temp table containing ID and Document columns. Required if no ID is specified.
ID String False The primary key to insert the document under. Required if no SourceTable is specified.
Document String False The JSON text of the document to insert. Required if not SourceTable is specified.

Result Set Columns

Name Type Description
RowsAffected String The number of rows successfully updated

CData Cloud

CreateBucket

Creates a new bucket in CouchBase.

Creating Buckets

Buckets using @AuthType 'none' can be created by specifying only the @Name, @AuthType, @BucketType, and @RamQuotaMB. The @ProxyPort option may also be required, depending upon what version of Couchbase you are connecting to.

EXECUTE CreateBucket
  @Name = 'Players',
  @AuthType = 'NONE',
  @BucketType = 'COUCHBASE',
  @RamQuotaMB = 100,
  @ProxyPort = 1234

When creating a bucket with @AuthType 'sasl', the @ProxyPort must not be provided, and the @SaslPassword is optional:

EXECUTE CreateBucket
  @Name = 'Players',
  @AuthType = 'SASL',
  @BucketType = 'COUCHBASE',
  @RamQuotaMB = 100

All other parameters can be used regardless of what @AuthType you provide.

Input

Name Type Required Description
Name String True The name of the bucket to create.
AuthType String True The type of authentication to use can be sasl or none.
BucketType String True The type of the bucket, can be memcached or couchbase.
EvictionPolicy String False What to evict from the cache if the bucket is full, can be fullEviction or valueOnly
FlushEnabled String False Enables or disables flush all support, can be 0 or 1.
ParallelDBAndViewCompaction String False Enables simultaneous compactions of the database and the views, can be true or false.
ProxyPort String False The proxy port, must be unused, required if authorization is not SASL.
RamQuotaMB String True The amount of RAM to allocate to the bucket, in megabytes.
ReplicaIndex String False Enables or disables replicate indexes, can be 1 or 0.
ReplicaNumber String False A number between 0 and 3, specifies number of replicas.
SaslPassword String False SASL password, may be provided if the authentication type is SASL.
ThreadsNumber String False A number between 2 and 8, specifies number of concurrent readers/writers.
CompressionMode String False Either Off (no compression), Passive (documents inserted compressed stay comressed) or Active (server can compress any document). On Couchbase Enterprise, Passive is the default.
ConflictResolutionType String False How the server will resolve conflicts between cluster nodes. Either lww (timestamp-based resolution) or seqno (revision ID-based resolution). Defaults to seqno on Couchbase Enterprise.

Result Set Columns

Name Type Description
Success String Whether or not the bucket was successfully created.

CData Cloud

CreateCollection

Creates a collection under an existing scope

Input

Name Type Required Description
Bucket String True The name of the bucket containing the collection.
Scope String True The name of the scope containing the collection.
Name String True The name of the collection to create.

Result Set Columns

Name Type Description
Success Bool Whether or not the collection was successfully created.

CData Cloud

CreateSchema

Creates a schema definition of a table in Couchbase. Results may change depending of the value of FlattenObjects, FlattenArrays, and TypeDetectionScheme.

Input

Name Type Required Accepts Output Streams Description
TableName String True False The name of the table.
FileName String False False The full file path and name of the schema to generate. Ex : 'C:\\Users\\User\\Desktop\\Couchbase\\sheet.rsd'
Overwrite String False False Will delete any existing schema file for this table.
FileStream String False True Stream to write the schema to. Only used if FileName is not provided.

Result Set Columns

Name Type Description
Result String Whether or not the schema was successfully built.
FileData String The content of the schema encoded as base64. Only returned if the FileName and FileStream are not provided.

CData Cloud

CreateScope

Creates a scope under an existing bucket

Input

Name Type Required Description
Bucket String True The name of the bucket containing the scope.
Name String True The name of the scope to create.

Result Set Columns

Name Type Description
Success Bool Whether or not the scope was successfully created.

CData Cloud

CreateUserTable

An internal operation used when GenerateSchemaFiles=OnCreate

Note: This procedure makes use of indexed parameters. These input parameters are denoted with a '#' character at the end of their names.

Indexed parameters facilitate providing multiple instances a single parameter as inputs for the procedure.

Suppose there is an input parameter named Param#. Input multiple instances of an indexed parameter like this:

EXEC ProcedureName Param#1 = "value1", Param#2 = "value2", Param#3 = "value3"

Input

Name Type Required Description
CreateNotExist String False Whether an existing table is an error or not
TableName String False The name of the table to create
ColumnNames# String False For each column, its name
ColumnDataTypes# String False For each column, its type
ColumnSizes# String False For each column, its size (ignored)
ColumnScales# String False For each column, its scale (ignored)
ColumnIsNulls# String False For each column, whether it allows NULLs (ignored)
ColumnDefaults# String False For each column, its default value (ignored)
Location String False Where the schema file is generated

Result Set Columns

Name Type Description
AffectedTables String The number of tables created, either 0 or 1

CData Cloud

DeleteBucket

Deletes a bucket (and all its collections and scopes, where supported)

Input

Name Type Required Description
Name String True The name of the bucket to delete.

Result Set Columns

Name Type Description
Success Bool Whether or not the bucket was successfully deleted.

CData Cloud

DeleteCollection

Deletes a collection (Couchbase 7 and up)

Input

Name Type Required Description
Bucket String True The name of the bucket containing the collection.
Scope String True The name of the scope containing the collection.
Name String True The name of the collection to delete.

Result Set Columns

Name Type Description
Success Bool Whether or not the collection was successfully deleted.

CData Cloud

DeleteScope

Deletes a scope and all its collections (Couchbase 7 and up)

Input

Name Type Required Description
Bucket String True The name of the bucket containing the scope.
Name String True The name of the scope to delete.

Result Set Columns

Name Type Description
Success Bool Whether or not the scope was successfully deleted.

CData Cloud

FlushBucket

Removes all documents from a bucket in Couchbase.

Input

Name Type Required Description
Name String True The name of the bucket to delete. Flush must be enabled on this bucket.

Result Set Columns

Name Type Description
Success Bool Whether or not the bucket was successfully flushed.

CData Cloud

ListIndices

Lists all indices available in Couchbase

Result Set Columns

Name Type Description
Id String The unique index ID
Datastore_id String The server hosting the indexed bucket
Namespace_id String The pool hosting the indexed bucket
Bucket_id String The bucket the index applies to if the index applies to a collection (Couchbase 7 and up). NULL otherwise.
Scope_id String The scope the index applies to if the index applies to a collection (Couchbase 7 and up). NULL otherwise.
Keyspace_id String The collection the index applies to, if the index applis to a collection (Couchbase 7 and up). The bucket the index applies to otherwise.
Index_key String A list of keys participating in the index
Condition String The N1QL filter that the index applies to
Is_primary String Whether the index is on the primary key
Name String The name of the index
State String Whether the index is available
Using String Whether the index is backed by GSI or a view

CData Cloud

ManageIndices

Creates/Drops an index in a target bucket in Couchbase.

Building Indices

An anonymous primary index can be created with these parameters:

EXECUTE ManageIndices
  @BucketName = 'Players'
  @Action = 'CREATE'
  @IsPrimary = 'true'
  @IndexType = 'VIEW'

This is the same as executing this N1QL:

CREATE PRIMARY INDEX ON `Players` USING VIEW

A named primary index can be created by specifying an @Name, in addition to the parameters listed above:

EXECUTE ManageIndices
  @BucketName = 'Players'
  @Action = 'CREATE'
  @IsPrimary = 'true'
  @Name = 'Players_primary'
  @IndexType = 'VIEW'

A secondary index can be created by setting @IsPrimary to false and providing at least one expression.

EXECUTE ManageIndices
  @BucketName = 'Players',
  @Action = 'CREATE',
  @IsPrimary = 'false',
  @Name = 'Players_playtime_score',
  @Expressions = '["score", "playtime"]'

This is the same as running the following N1QL:

CREATE INDEX `Players_playtime_score` ON `Players`(score, playtime) USING GSI;

Multiple nodes and filters can also be provied to generate more complex indices. They must be provided as JSON lists:

EXECUTE ManageIndices
  @BucketName = 'Players',
  @Name = 'TopPlayers',
  @Expressions = '["score", "playtime"]',
  @Filter = '["topscore > 1000", "playtime > 600"]',
  @Nodes = '["127.0.0.1:8091", "192.168.0.100:8091"]'

This is the same as running the following N1QL:

CREATE INDEX `TopPlayers` ON `Players`(score, playtime) WHERE topscore > 1000 AND playtime > 600 USING GSI WITH { "nodes": ["127.0.0.1:8091", "192.168.0.100:8091"]};

Input

Name Type Required Description
BucketName String True The target bucket to create or drop the the index from.
ScopeName String False The target scope to create or drop the index from (Couchbase 7 and up)
CollectionName String False The target collection to create or drop the index from (Couchbase 7 and up)
Action String True Specifies which action to perform on the index, can be Create or Drop.
Expressions String False A list of expressions or functions, encoded as JSON, that the index will be based off of. At least one is required if IsPrimary is set to false and the action is Create.
Name String False The name of the index to create or drop, required if IsPrimary is set to false.
IsPrimary String False Specifies wether the index should be a primary index.

The default value is true.

Filters String False A list of filters, encoded as JSON, to apply on the index.
IndexType String False The type of index to create, can be GSI or View, only used if the action is Create.

The default value is GSI.

ViewName String False Deprecated, included for compatibility only. Does nothing.
Nodes String False A list, encoded as JSON, of nodes to contain the index, must contain the port. Only used if the action is Create.
NumReplica String False How many replicas to create among the index nodes in the cluster.

Result Set Columns

Name Type Description
Success String Whether or not the index was successfully created or dropped.

CData Cloud

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

  • sys_catalogs: Lists the available databases.
  • sys_schemas: Lists the available schemas.
  • sys_tables: Lists the available tables and views.
  • sys_tablecolumns: Describes the columns of the available tables and views.
  • sys_procedures: Describes the available stored procedures.
  • sys_procedureparameters: Describes stored procedure parameters.
  • sys_keycolumns: Describes the primary and foreign keys.
  • sys_indexes: Describes the available indexes.

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

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 Cloud

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 Cloud

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 Cloud

sys_tablecolumns

Describes the columns of the available tables and views.

The following query returns the columns and data types for the Customer table:

SELECT ColumnName, DataTypeName FROM sys_tablecolumns WHERE TableName='Customer' 

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 Cloud

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 Cloud

sys_procedureparameters

Describes stored procedure parameters.

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

SELECT * FROM sys_procedureparameters WHERE ProcedureName='SelectEntries' 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 Cloud

sys_keycolumns

Describes the primary and foreign keys.

The following query retrieves the primary key for the Customer table:

         SELECT * FROM sys_keycolumns WHERE IsKey='True' AND TableName='Customer' 
          

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 Cloud

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 Cloud

sys_primarykeys

Describes the primary keys.

The following query retrieves the primary keys from all tables and views:

         SELECT * FROM sys_primarykeys
          

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
KeySeq String The sequence number of the primary key.
KeyName String The name of the primary key.

CData Cloud

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 Cloud

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:couchbase: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 Cloud

sys_sqlinfo

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

See SQL Compliance for SQL syntax details.

Discovering the Data Source's SELECT Capabilities

Below is an example data set of SQL capabilities. The following result set indicates the SELECT functionality that the Cloud 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 Cloud

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 Cloud

Connection String Options

The connection string properties are the various options that can be used to establish a connection. This section provides a complete list of the options you can configure in the connection string for this provider. Click the links for further details.

Authentication


PropertyDescription
AuthSchemeThe type of authentication to use when connecting to Couchbase.
UserThe Couchbase user account used to authenticate.
PasswordThe password used to authenticate the user.
CredentialsFileUse this property if you need to provide credentials for multiple users or buckets. This file takes priority over other forms of authentication.
ServerThe address of the Couchbase server or servers to which you are connecting.
CouchbaseServiceDetermines the Couchbase service to connect to. Default is N1QL. Available options are N1QL and Analytics.
ConnectionModeDetermines how to connect to the Couchbase server. Must be either Direct or Cloud.
DNSServerDetermines what DNS server to use when retrieving Couchbase Capella information.
N1QLPortThe port for connecting to the Couchbase N1QL Endpoint.
AnalyticsPortThe port for connecting to the Couchbase Analytics Endpoint.
WebConsolePortThe port for connecting to the Couchbase Web Console.

SSL


PropertyDescription
SSLClientCertThe TLS/SSL client certificate store for SSL Client Authentication (2-way SSL).
SSLClientCertTypeThe type of key store containing the TLS/SSL client certificate.
SSLClientCertPasswordThe password for the TLS/SSL client certificate.
SSLClientCertSubjectThe subject of the TLS/SSL client certificate.
UseSSLWhether to negotiate TLS/SSL when connecting to the Couchbase server.
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.
TablesThis property restricts the tables reported to a subset of the available tables. For example, Tables=TableA,TableB,TableC.
ViewsRestricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC.
DataverseWhich Analytics dataverse to scan when discovering tables.
TypeDetectionSchemeDetermines how the provider builds tables and columns from the buckets found in Couchbase.
InferNumSampleValuesThe maximum number of values for every field to scan before determining its data type. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
InferSampleSizeThe maximum number of documents to scan for the columns available in the bucket. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
InferSimilarityMetricSpecifies the similarity degree where different schemas will be considered to be the same flavor. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
FlexibleSchemasWhether the provider allows queries to use columns that it has not discovered.
ExposeTTLSpecifies whether document TTL information should be exposed.
NumericStringsWhether to allow string values to be treated as numbers.
IgnoreChildAggregatesWhether the provider exposes aggregate columns that are also available as child tables. Ignored if TableSupport is not set to Full.
TableSupportHow much effort the provider will put into discovering tables on the Couchbase server.
NewChildJoinsModeDetermines the kind of child table model the provider exposes.

Caching


PropertyDescription
AutoCacheAutomatically caches the results of SELECT queries into a cache database specified by either CacheLocation or both of CacheConnection and CacheProvider .
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
AllowJSONParametersAllows raw JSON to be used in parameters when QueryPassthrough is enabled.
ChildSeparatorThe character or characters used to denote child tables.
CreateTableRamQuotaThe default RAM quota, in megabytes, to use when inserting buckets via the CREATE TABLE syntax.
DataverseSeparatorThe character or characters used to denote Analytics dataverses and scopes/collections.
FlattenArraysThe number of elements to expose as columns from nested arrays. Ignored if IgnoreChildAggregates is enabled.
FlattenObjectsSet FlattenObjects to true to flatten object properties into columns of their own. Otherwise, objects nested in arrays are returned as strings of JSON.
FlavorSeparatorThe character or characters used to denote flavors.
GenerateSchemaFilesIndicates the user preference as to when schemas should be generated and saved.
InsertNullValuesDetermines whether an INSERT should include fields that have NULL values.
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 Couchbase.
PeriodsSeparatorThe character or characters used to denote hierarchy.
PseudoColumnsThis property indicates whether or not to include pseudo columns as columns to the table.
QueryExecutionTimeoutThis sets the server-side timeout for the query, which governs how long Couchbase will execute the query before returning a timeout error.
QueryPassthroughThis option passes the query to the Couchbase server as is.
ReadonlyYou can use this property to enforce read-only access to Couchbase from the provider.
RowScanDepthThe maximum number of rows to scan to look for the columns available in a table.
RTKThe runtime key used for licensing.
StrictComparisonAdjusts how precisely to translate filters on SQL input queries into Couchbase queries. This can be set to a comma-separated list of values, where each value can be one of: date, number, boolean, or string.
TimeoutThe value in seconds until the timeout error is thrown, canceling the operation.
TransactionDurabilitySpecifies how a document must be stored for a transaction to succeed. Specifies whether to use N1QL transactions when executing queries.
TransactionTimeoutThis sets the amount of time a transaction may execute before it is timed out by Couchbase.
UpdateNullValuesDetermines whether an UPDATE writes NULL values as NULL, or removes them.
UseCollectionsForDDLWhether to assume that CREATE TABLE statements use collections instead of flavors. Only takes effect when connecting to Couchbase v7+ and GenerateSchemaFiles is set to OnCreate.
UserDefinedViewsA filepath pointing to the JSON configuration file containing your custom views.
UseTransactionsSpecifies whether to use N1QL transactions when executing queries.
ValidateJSONParametersAllows the provider to validate that string parameters are valid JSON before sending the query to Couchbase.
CData Cloud

Authentication

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


PropertyDescription
AuthSchemeThe type of authentication to use when connecting to Couchbase.
UserThe Couchbase user account used to authenticate.
PasswordThe password used to authenticate the user.
CredentialsFileUse this property if you need to provide credentials for multiple users or buckets. This file takes priority over other forms of authentication.
ServerThe address of the Couchbase server or servers to which you are connecting.
CouchbaseServiceDetermines the Couchbase service to connect to. Default is N1QL. Available options are N1QL and Analytics.
ConnectionModeDetermines how to connect to the Couchbase server. Must be either Direct or Cloud.
DNSServerDetermines what DNS server to use when retrieving Couchbase Capella information.
N1QLPortThe port for connecting to the Couchbase N1QL Endpoint.
AnalyticsPortThe port for connecting to the Couchbase Analytics Endpoint.
WebConsolePortThe port for connecting to the Couchbase Web Console.
CData Cloud

AuthScheme

The type of authentication to use when connecting to Couchbase.

Possible Values

Auto, Basic, CredentialsFile, SSLCertificate

Data Type

string

Default Value

"Auto"

Remarks

  • Auto: This option is deprecated and included only for compatibility.
  • Basic: Uses HTTP Basic authentication with User and Password.
  • CredentialsFile: Uses a credentials file. This will require that the CredentialsFile property be set.
  • SSLCertificate: Uses SSL client certificate authentication. Requires that UseSSL be enabled and that SSLClientCert and SSLClientCertType be set.

Note that only Basic authentication is supported when using the "Cloud" ConnectionMode.

CData Cloud

User

The Couchbase user account used to authenticate.

Data Type

string

Default Value

""

Remarks

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

CData Cloud

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.

CData Cloud

CredentialsFile

Use this property if you need to provide credentials for multiple users or buckets. This file takes priority over other forms of authentication.

Data Type

string

Default Value

""

Remarks

Use this property if you need to provide credentials for multiple users or buckets. This takes priority over other forms of authentication.

Set CredentialsFile to the path to a file that has the same markup as below:

[{"user": "YourUserName1", "pass":"YourPassword1"},
  {"user": "YourUserName2", "pass":"YourPassword2"}] 

CData Cloud

Server

The address of the Couchbase server or servers to which you are connecting.

Data Type

string

Default Value

""

Remarks

This value can be set to a hostname or an IP address, like "couchbase-server.com" or "1.2.3.4". It can also be set to an HTTP or HTTPS URL, such as "https://couchbase-server.com" or "http://1.2.3.4". If ConnectionMode is set to Cloud then this should be the hostname of the Couchbase Cloud instance as reported in the control panel.

If the URL form is used, then setting this option will also set the UseSSL option: if the URL scheme is "https://", then UseSSL will be set to true, and a URL with "http://" will set UseSSL to false.

A port value cannot be used as part of this option, so values like "http://couchbase-server.com:8093" are not allowed. Please use WebConsolePort, N1QLPort and AnalyticsPort.

This value can also accept multiple servers in the above format separated by commas, such as "1.2.3.4, couchbase-server.com". This will allow the Cloud to recover the connection in case some of the servers listed are inaccessible.

Note that while the Cloud will try to recover the connection as a whole, it may lose individual operations. For example, while a long-running query will fail if the server becomes inaccesssible while that query is running, that query can be retried on the same connection and the Cloud will execute it on the next active server.

CData Cloud

CouchbaseService

Determines the Couchbase service to connect to. Default is N1QL. Available options are N1QL and Analytics.

Possible Values

N1QL, Analytics

Data Type

string

Default Value

"N1QL"

Remarks

Determines the Couchbase service to connect to. Default is N1QL. Available options are N1QL and Analytics

CData Cloud

ConnectionMode

Determines how to connect to the Couchbase server. Must be either Direct or Cloud.

Possible Values

Direct, Cloud

Data Type

string

Default Value

"Direct"

Remarks

By default the Cloud connects to Couchbase directly using the address given in the Server option. The Server must be running the appropriate CouchbaseService to accept the connection. This will work in most on-premise or basic cloud deployments.

This should be set to Cloud when connecting to Couchbase Capella or a custom deployment that uses service records. These records will allow the Cloud to determine the exact Couchbase servers that provide the appropriate CouchbaseService. You must also set the DNSServer property so that the Cloud is able to fetch these service records.

Note that enabling Cloud mode will override these connection properties with the values discovered by contacting the cluster:

  • Server
  • N1QLPort
  • AnalyticsPort

CData Cloud

DNSServer

Determines what DNS server to use when retrieving Couchbase Capella information.

Data Type

string

Default Value

""

Remarks

In most cases any public DNS server can be provided here such as the ones provided by OpenDNS, Cloudflare or Google.

If these are not accessible then you will need to use the DNS server configured by your network administrator.

CData Cloud

N1QLPort

The port for connecting to the Couchbase N1QL Endpoint.

Data Type

string

Default Value

""

Remarks

This defaults to 8093 when not using SSL, and 18093 when using SSL. See UseSSL.

This port is used for submitting queries when CouchbaseService is set to N1QL. Any requests to manage indices will also go through this port.

CData Cloud

AnalyticsPort

The port for connecting to the Couchbase Analytics Endpoint.

Data Type

string

Default Value

""

Remarks

This defaults to 8095 when not using SSL, and 18095 when using SSL. See UseSSL.

This port is used for submitting queries when CouchbaseService is set to Analytics.

CData Cloud

WebConsolePort

The port for connecting to the Couchbase Web Console.

Data Type

string

Default Value

""

Remarks

This defaults to 8091 when not using SSL, and 18091 when using SSL. See UseSSL.

This port is used for API operations like managing buckets.

CData Cloud

SSL

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


PropertyDescription
SSLClientCertThe TLS/SSL client certificate store for SSL Client Authentication (2-way SSL).
SSLClientCertTypeThe type of key store containing the TLS/SSL client certificate.
SSLClientCertPasswordThe password for the TLS/SSL client certificate.
SSLClientCertSubjectThe subject of the TLS/SSL client certificate.
UseSSLWhether to negotiate TLS/SSL when connecting to the Couchbase server.
SSLServerCertThe certificate to be accepted from the server when connecting using TLS/SSL.
CData Cloud

SSLClientCert

The TLS/SSL client certificate store for SSL Client Authentication (2-way SSL).

Data Type

string

Default Value

""

Remarks

The name of the certificate store for the client certificate.

The SSLClientCertType field specifies the type of the certificate store specified by SSLClientCert. If the store is password protected, specify the password in SSLClientCertPassword.

SSLClientCert is used in conjunction with the SSLClientCertSubject field in order to specify client certificates. If SSLClientCert has a value, and SSLClientCertSubject is set, a search for a certificate is initiated. See SSLClientCertSubject for more information.

Designations of certificate stores are platform-dependent.

The following are designations of the most common User and Machine certificate stores in Windows:

MYA certificate store holding personal certificates with their associated private keys.
CACertifying authority certificates.
ROOTRoot certificates.
SPCSoftware publisher certificates.

In Java, the certificate store normally is a file containing certificates and optional private keys.

When the certificate store type is PFXFile, this property must be set to the name of the file. When the type is PFXBlob, the property must be set to the binary contents of a PFX file (for example, PKCS12 certificate store).

CData Cloud

SSLClientCertType

The type of key store containing the TLS/SSL client certificate.

Possible Values

USER, MACHINE, PFXFILE, PFXBLOB, JKSFILE, JKSBLOB, PEMKEY_FILE, PEMKEY_BLOB, PUBLIC_KEY_FILE, PUBLIC_KEY_BLOB, SSHPUBLIC_KEY_FILE, SSHPUBLIC_KEY_BLOB, P7BFILE, PPKFILE, XMLFILE, XMLBLOB

Data Type

string

Default Value

"USER"

Remarks

This property can take one of the following values:

USER - defaultFor Windows, this specifies that the certificate store is a certificate store owned by the current user. Note that this store type is not available in Java.
MACHINEFor Windows, this specifies that the certificate store is a machine store. Note that this store type is not available in Java.
PFXFILEThe certificate store is the name of a PFX (PKCS12) file containing certificates.
PFXBLOBThe certificate store is a string (base-64-encoded) representing a certificate store in PFX (PKCS12) format.
JKSFILEThe certificate store is the name of a Java key store (JKS) file containing certificates. Note that this store type is only available in Java.
JKSBLOBThe certificate store is a string (base-64-encoded) representing a certificate store in JKS format. Note that this store type is only available in Java.
PEMKEY_FILEThe certificate store is the name of a PEM-encoded file that contains a private key and an optional certificate.
PEMKEY_BLOBThe certificate store is a string (base64-encoded) that contains a private key and an optional certificate.
PUBLIC_KEY_FILEThe certificate store is the name of a file that contains a PEM- or DER-encoded public key certificate.
PUBLIC_KEY_BLOBThe certificate store is a string (base-64-encoded) that contains a PEM- or DER-encoded public key certificate.
SSHPUBLIC_KEY_FILEThe certificate store is the name of a file that contains an SSH-style public key.
SSHPUBLIC_KEY_BLOBThe certificate store is a string (base-64-encoded) that contains an SSH-style public key.
P7BFILEThe certificate store is the name of a PKCS7 file containing certificates.
PPKFILEThe certificate store is the name of a file that contains a PuTTY Private Key (PPK).
XMLFILEThe certificate store is the name of a file that contains a certificate in XML format.
XMLBLOBThe certificate store is a string that contains a certificate in XML format.

CData Cloud

SSLClientCertPassword

The password for the TLS/SSL client certificate.

Data Type

string

Default Value

""

Remarks

If the certificate store is of a type that requires a password, this property is used to specify that password to open the certificate store.

CData Cloud

SSLClientCertSubject

The subject of the TLS/SSL client certificate.

Data Type

string

Default Value

"*"

Remarks

When loading a certificate the subject is used to locate the certificate in the store.

If an exact match is not found, the store is searched for subjects containing the value of the property. If a match is still not found, the property is set to an empty string, and no certificate is selected.

The special value "*" picks the first certificate in the certificate store.

The certificate subject is a comma separated list of distinguished name fields and values. For example, "CN=www.server.com, OU=test, C=US, [email protected]". The common fields and their meanings are shown below.

FieldMeaning
CNCommon Name. This is commonly a host name like www.server.com.
OOrganization
OUOrganizational Unit
LLocality
SState
CCountry
EEmail Address

If a field value contains a comma, it must be quoted.

CData Cloud

UseSSL

Whether to negotiate TLS/SSL when connecting to the Couchbase server.

Data Type

bool

Default Value

false

Remarks

When this is set to true, the defaults for the following options change:

Property Plaintext Default SSL Default
AnalyticsPort 8095 18095
N1QLPort 8093 18093
WebConsolePort 8091 18091

This option should be enabled when connecting to Couchbase Capella because all Capella deployments use SSL by default.

CData Cloud

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 Cloud

Firewall

This section provides a complete list of the Firewall properties you can configure in the connection string 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 Cloud

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 Cloud will use to tunnel traffic through the FirewallServer proxy. Note that by default, the Cloud 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 Cloud opens a connection to Couchbase and traffic flows back and forth through the proxy.
SOCKS4 1080 When this is set, the Cloud 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 Cloud 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 Cloud

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 Cloud uses the system proxy by default. To use a different proxy, set ProxyAutoDetect to false.

CData Cloud

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 Cloud

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 Cloud

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 Cloud

Proxy

This section provides a complete list of the Proxy properties you can configure in the connection string 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 Cloud

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.

To connect to an HTTP proxy, see ProxyServer. For other proxies, such as SOCKS or tunneling, see FirewallType.

CData Cloud

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 Cloud 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 Cloud uses the system proxy. If you need to use another proxy, set ProxyAutoDetect to false.

CData Cloud

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 Cloud

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 Cloud 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 Cloud performs HTTP BASIC authentication.
  • DIGEST: The Cloud performs HTTP DIGEST authentication.
  • NEGOTIATE: The Cloud retrieves an NTLM or Kerberos token based on the applicable protocol for authentication.
  • PROPRIETARY: The Cloud 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 Cloud

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 Cloud

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 Cloud uses the system proxy. If you want to connect to another proxy, set ProxyAutoDetect to false.

CData Cloud

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

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

Logging

This section provides a complete list of the Logging properties you can configure in the connection string 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 Cloud

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

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 Cloud reports to the Logfile. Verbosity levels from 1 to 5 are supported. These are detailed in the Logging page.

CData Cloud

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 Cloud

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 Cloud

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 Cloud

Schema

This section provides a complete list of the Schema properties you can configure in the connection string 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.
TablesThis property restricts the tables reported to a subset of the available tables. For example, Tables=TableA,TableB,TableC.
ViewsRestricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC.
DataverseWhich Analytics dataverse to scan when discovering tables.
TypeDetectionSchemeDetermines how the provider builds tables and columns from the buckets found in Couchbase.
InferNumSampleValuesThe maximum number of values for every field to scan before determining its data type. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
InferSampleSizeThe maximum number of documents to scan for the columns available in the bucket. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
InferSimilarityMetricSpecifies the similarity degree where different schemas will be considered to be the same flavor. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.
FlexibleSchemasWhether the provider allows queries to use columns that it has not discovered.
ExposeTTLSpecifies whether document TTL information should be exposed.
NumericStringsWhether to allow string values to be treated as numbers.
IgnoreChildAggregatesWhether the provider exposes aggregate columns that are also available as child tables. Ignored if TableSupport is not set to Full.
TableSupportHow much effort the provider will put into discovering tables on the Couchbase server.
NewChildJoinsModeDetermines the kind of child table model the provider exposes.
CData Cloud

Location

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

Data Type

string

Default Value

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

Remarks

The path to a directory which contains the schema files for the Cloud (.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\\Couchbase Data Provider\\Schema" with %APPDATA% being set to the user's configuration directory:

CData Cloud

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 Cloud

Tables

This property restricts the tables reported to a subset of the available tables. For example, Tables=TableA,TableB,TableC.

Data Type

string

Default Value

""

Remarks

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

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 tables you want in a comma-separated list. Each table should be a valid SQL identifier with any special characters escaped using square brackets, double-quotes or backticks. For example, Tables=TableA,[TableB/WithSlash],WithCatalog.WithSchema.`TableC With Space`.

Note 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 Cloud

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

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 Cloud

Dataverse

Which Analytics dataverse to scan when discovering tables.

Data Type

string

Default Value

""

Remarks

This property is empty by default, which means that all dataverses will be scanned and table names will be generated as described in DataverseSeparator.

If you assign this property to a non-blank value, then the Cloud will scan only the corresponding dataverse (for example, setting this to "Default" scans the Default dataverse). Since only one dataverse is being scanned, table names will not be prefixed with the dataverse name. It is recommended to set this property to "Default" if you are coming from a previous version of the Cloud and need backwards compatability.

If you are connecting to Couchbase 7.0 or later, this option will be treated as a compound name containing both a dataset and a scope. For example, if you have previously created collections like these:

CREATE ANALYTICS SCOPE websites.exampledotcom
CREATE ANALYTICS COLLECTION websites.exampledotcom.traffic ON examplecom_traffic_bucket
CREATE ANALYTICS COLLECTION websites.exampledotcom.ads ON examplecom_ads_bucket
You would set this option to "websites.exampledotcom".

CData Cloud

TypeDetectionScheme

Determines how the provider builds tables and columns from the buckets found in Couchbase.

Data Type

string

Default Value

"DocType"

Remarks

A comma-separated list of the following options:

DocType This discovers tables by checking at each bucket and looking for different values of the "docType" field in the documents. For example, if the bucket beer-sample contains documents with "docType" = 'brewery' and "docType" = 'beer', this will generate three tables: beer-sample (containing all documents), beer-sample.brewery (containing just breweries) and beer-sample.beer (containing just beers).

Like RowScan, this will scan a sample of the documents in each flavor and determine the data type for each field. RowScanDepth determines how many documents are scanned from each flavor.

DocType=fieldName Like DocType, but this scans based off of a field called "fieldName" rather than "docType". "fieldName" must match the field name in Couchbase exactly, including case.
Infer This uses the N1QL INFER statement to determine what tables and columns exist. This does more flexible flavor detection than DocType, but is only available for Couchbase Enterprise.
RowScan This reads a sample of documents from a bucket, and heuristically determines the data type. RowScanDepth determines how many documents are scanned. It does not do any flavor detection.
None This is like RowScan, but will always return columns that have string types instead of the detected type.

CData Cloud

InferNumSampleValues

The maximum number of values for every field to scan before determining its data type. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.

Data Type

string

Default Value

"10"

Remarks

The maximum number of values to scan from every field of the sampled documents before determining the field's data type. This property enables additional configuration of Automatic Schema Discovery when you are using the Couchbase Infer command -- TypeDetectionScheme must also be set to Infer to use this propery.

CData Cloud

InferSampleSize

The maximum number of documents to scan for the columns available in the bucket. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.

Data Type

string

Default Value

"100"

Remarks

The maximum number of documents to scan for the columns available in the bucket. The Infer command will return column metadata by scanning a random sample of documents of the size specified here.

Setting a high value may decrease performance. Setting a low value may prevent the column and data type from being determined properly, especially when there is null data.

This property enables additional configuration of Automatic Schema Discovery when you are using the Couchbase Infer command -- TypeDetectionScheme must also be set to Infer to use this propery.

CData Cloud

InferSimilarityMetric

Specifies the similarity degree where different schemas will be considered to be the same flavor. Applies to Automatic Schema Discovery when TypeDetectionScheme is set to INFER.

Data Type

string

Default Value

"0.7"

Remarks

This property specifies how similar two schemas must be to be considered to be the same flavor. As an example, consider the following rows:

Row 1: ColA, ColB, ColC, ColD
Row 2: ColA, ColB, ColE, ColF
Row 3: ColB, ColF, ColX, ColY

You can configure the columns returned for each flavor with different InferSimilarityMetric values, as in the following examples:

  • If you set InferSimilarityMetric to 1, the Cloud will return no flavors.
  • If you set InferSimilarityMetric to 0.5, the Cloud will return 2 flavors, Row1 and Row2 making up one, and Row3 making up another.
  • If you set InferSimilarityMetric to 0.25, the Cloud will return a single flavor containing all rows.

You can then query document flavors using dot notation, as in the following statement:

SELECT * FROM [Items.Technology]

This property enables additional configuration of Automatic Schema Discovery when you are using the Couchbase Infer command -- TypeDetectionScheme must also be set to Infer to use this propery.

CData Cloud

FlexibleSchemas

Whether the provider allows queries to use columns that it has not discovered.

Data Type

bool

Default Value

false

Remarks

By default Cloud will only allow queries to use columns that it has found during the metadata discovery process (see TypeDetectionScheme for details). This means that the Cloud has the full information for each column it presents, but it also means that fields set on only a few documents may not be exposed. Disabling this option means that the Cloud will allow you to write a query with any columns you want. If you use columns in a query that have not been discovered the Cloud will assume that they are simple strings.

For example, the Cloud uses column type information to automatically convert dates for comparision since Couchbase cannot natively compare dates directly. If the Cloud detects that datecol is a date field, it can apply the STR_TO_MILLIS conversion automatically:

/* SQL */
WHERE datecol < '2020-06-12';

/* N1QL */
WHERE STR_TO_MILLIS(datecol) < STR_TO_MILLIS('2020-06-12');

When using undiscovered columns the Cloud cannot make this type of conversion for you. You must apply any needed conversions manually to ensure that operations behave the way you want them to.

CData Cloud

ExposeTTL

Specifies whether document TTL information should be exposed.

Data Type

bool

Default Value

false

Remarks

By default the Cloud does not expose TTL values or consider document TTLs when performing DML operations. Enabling this option exposes TTL values in two ways:

  • All tables get a new column called Document.Expiration which contains the TTL value for each document. This column is an integer and returns whatever TTL value is stored in Couchbase directly. This column is read-write on bucket tables and read-only on child tables.
  • INSERT and UPDATE will use this field to set TTL values, or to preserve them (for update) when none is provided. Setting the field to either 0 or NULL will remove the TTL from any affected documents.

Note that enabling this features requires that your server be version 6.5.1 or later and that your CouchbaseService is set to N1QL. If either of these is not the case the Cloud will not connect.

CData Cloud

NumericStrings

Whether to allow string values to be treated as numbers.

Data Type

bool

Default Value

true

Remarks

By default this property is enabled and the Cloud will treat string values as numeric if they all the values it samples during schema detection are numeric. This can cause type errors later on if the field contains non-numeric values in other documents. If this property is disabled then numeric strings are left as strings although other string-based data types like timestamps will still be detected.

For example, the "code" field in the below bucket would be affected by this setting. By default it would be considered an integer but if this property were enabled it would be treated as a string.

{ "code": "123", "message": "Please restart your computer" }
{ "code": "456", "message": "Urgent update must be applied" }

CData Cloud

IgnoreChildAggregates

Whether the provider exposes aggregate columns that are also available as child tables. Ignored if TableSupport is not set to Full.

Data Type

bool

Default Value

false

Remarks

The Cloud will expose array fields within a bucket as a separate child table, such as in the Games_scores example described in Automatic Schema Discovery. By default the Cloud will also expose these array fields as JSON aggregates on the base table. For example, either of these queries would return information on game scores:

/* Return each score as an individual row */ 
SELECT value FROM Games_scores;

/* Return all scores for each Game as a JSON string */
SELECT scores FROM Games;

Since these aggregates are exposed on the base table, they will be generated even when the information they contain is redundant. For example, when performing this join the scores aggregate on Games is populated as well as the value column on Games_scores. Internally this causes two copies of the scores data to be transferred from Couchbase.

/* Retrieves score data twice, once for Games.scores and once for Games_scores.value */
SELECT * FROM Games INNER JOIN Games_scores ON Games.[Document.Id] = Games_scores.[Document.Id]

This option can be used to prevent the aggregate field from being exposed when the same information is also available from a child table. In the games example, setting this option to true means that the Games table would only expose a primary key column. The only way to retrieve information about scores would be the child table, so score data would only be read once from Couchbase.

/* Only exposes Document.Id, not scores */
SELECT * FROM Games;

/* Only retrieves score data once for Games_scores.value */
SELECT * FROM Games INNER JOIN Games_scores ON Games.[Document.Id] = Games_scores.[Document.Id]

Note that this option overrides FlattenArrays, since all data from flattened arrays is also avaialable as child tables. If this option is set then no array flattening is performed, even if FlattenArrays is set to a value over 0.

CData Cloud

TableSupport

How much effort the provider will put into discovering tables on the Couchbase server.

Possible Values

Full, Basic, None

Data Type

string

Default Value

"Full"

Remarks

The available options are:

Full The Cloud will discover the available buckets, and look inside of each of those buckets for child tables. This provides the most flexible way to access nested data, but requires that each bucket on your server have primary indexes.
Basic The Cloud will discover the available buckets, but will not look inside of them for child tables. This is recommended for cases where you either want to reduce the time that schema detection takes, or if your buckets do not have primary indexes.
None The Cloud will only use the schema files found in the Location directory, and will not discover buckets on the server. This option should only be used after you have already created schema files. Using this option without schema files will result in no tables being available.

CData Cloud

NewChildJoinsMode

Determines the kind of child table model the provider exposes.

Data Type

string

Default Value

"false"

Remarks

By default the Cloud exposes a backwards-compatible data model that is not fully relational. In this mode non-child tables have a primary key called Document.Id, but child tables do not have a primary key. Instead they have a column called Document.Id which has the same value as the Document.Id of the parent row that contains the child row.

For example, a parent table invoices containing invoice records may look like this:

Document.Id customer
1 Adam
2 Beatrice
3 Charlie

And its child invoices_lineitems containing line items may look like this:

Document.Id item
1 laptop
1 keyboard
2 stapler
3 whiteboard
3 markers

This model has several limitations:

  • Complex JOIN results may be incorrect. In most cases the Cloud can translate a JOIN like SELECT * FROM invoices INNERT JOIN invoices_lineitems ON invoices.[Document.Id] = invoices_lineitems.[Document.Id] into an UNNEST. But if the JOIN is too complex then both sides are executed separately which can produce incorrect results.
  • DML operations on nested child tables are impossible because there is no way to specify what row of the middle child to use. For example, you cannot change rows in a table like invoices_lineitems_discounts because there is no way to specify the lineitem that contains the discount you are updating.
  • Some environments like SSIS may not be able to operate on child tables at all because they do not have primary keys.

The NewChildJoins data model is fully relational. In this mode non-child tables have the same Document.Id as before, but child tables are extended to have both a foreign key and a primary key. The foreign key is called Document.Parent and it refers to the Document.Id of the row in the parent table that contains the child row. The primary key is called Document.Id and it contains a path which uniquely refers to that child row.

For example, the same tables as above would look like this in the NewChildJoins model. invoices would be the same:

Document.Id customer
1 Adam
2 Beatrice
3 Charlie

However, invoices_lineitems would have both a primary and foreign key. The primary key contains the ID of the parent row as well as the child row's position in the parent.

Document.Id Document.Parent item
1$1 1 laptop
1$2 1 keyboard
2$1 2 stapler
3$1 3 whiteboard
3$2 3 markers

This fixes the limitations of the old data model:

  • Complex JOIN results are always consistent because they link foreign keys to primary keys. SELECT * FROM invoices INNERT JOIN invoices_lineitems ON invoices.[Document.Id] = invoices_lineitems.[Document.Parent]
  • DML operations on nested child tables are allowed because the Document.Id contains all the required information to pick out specific rows, regardless of the table's depth.
  • Environments which depend on primary keys can use these tables and generate JOIN queries since the relationships between Document.Id and Document.Parent columns are included in the Cloud metadata.

CData Cloud

Caching

This section provides a complete list of the Caching properties you can configure in the connection string 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 .
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 Cloud

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 Cloud automatically maintains a cache of your table's data in the database of your choice.

Setting the Caching Database

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

  • CacheLocation: Specifies the path to the file store.
  • CacheProvider and CacheConnection: Specifies a driver to a database and the connection string.

See Also

  • CacheMetadata: This property reduces the amount of metadata that crosses the network by persisting table schemas retrieved from the Couchbase 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 Cloud

CacheLocation

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

Data Type

string

Default Value

"%APPDATA%\\CData\\Couchbase Data Provider"

Remarks

The CacheLocation is a simple, file-based cache.

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

See Also

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

CData Cloud

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 Cloud checks with the data source for newer records after the tolerance interval has expired. Otherwise, it returns the data directly from the cache.

CData Cloud

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 Cloud

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 Couchbase 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 Cloud 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 Cloud

Miscellaneous

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


PropertyDescription
AllowJSONParametersAllows raw JSON to be used in parameters when QueryPassthrough is enabled.
ChildSeparatorThe character or characters used to denote child tables.
CreateTableRamQuotaThe default RAM quota, in megabytes, to use when inserting buckets via the CREATE TABLE syntax.
DataverseSeparatorThe character or characters used to denote Analytics dataverses and scopes/collections.
FlattenArraysThe number of elements to expose as columns from nested arrays. Ignored if IgnoreChildAggregates is enabled.
FlattenObjectsSet FlattenObjects to true to flatten object properties into columns of their own. Otherwise, objects nested in arrays are returned as strings of JSON.
FlavorSeparatorThe character or characters used to denote flavors.
GenerateSchemaFilesIndicates the user preference as to when schemas should be generated and saved.
InsertNullValuesDetermines whether an INSERT should include fields that have NULL values.
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 Couchbase.
PeriodsSeparatorThe character or characters used to denote hierarchy.
PseudoColumnsThis property indicates whether or not to include pseudo columns as columns to the table.
QueryExecutionTimeoutThis sets the server-side timeout for the query, which governs how long Couchbase will execute the query before returning a timeout error.
QueryPassthroughThis option passes the query to the Couchbase server as is.
ReadonlyYou can use this property to enforce read-only access to Couchbase from the provider.
RowScanDepthThe maximum number of rows to scan to look for the columns available in a table.
RTKThe runtime key used for licensing.
StrictComparisonAdjusts how precisely to translate filters on SQL input queries into Couchbase queries. This can be set to a comma-separated list of values, where each value can be one of: date, number, boolean, or string.
TimeoutThe value in seconds until the timeout error is thrown, canceling the operation.
TransactionDurabilitySpecifies how a document must be stored for a transaction to succeed. Specifies whether to use N1QL transactions when executing queries.
TransactionTimeoutThis sets the amount of time a transaction may execute before it is timed out by Couchbase.
UpdateNullValuesDetermines whether an UPDATE writes NULL values as NULL, or removes them.
UseCollectionsForDDLWhether to assume that CREATE TABLE statements use collections instead of flavors. Only takes effect when connecting to Couchbase v7+ and GenerateSchemaFiles is set to OnCreate.
UserDefinedViewsA filepath pointing to the JSON configuration file containing your custom views.
UseTransactionsSpecifies whether to use N1QL transactions when executing queries.
ValidateJSONParametersAllows the provider to validate that string parameters are valid JSON before sending the query to Couchbase.
CData Cloud

AllowJSONParameters

Allows raw JSON to be used in parameters when QueryPassthrough is enabled.

Data Type

bool

Default Value

false

Remarks

This option affects how string parameters are handled when using direct N1QL and SQL++ queries through QueryPassthrough. For example, consider this query:

INSERT INTO `bucket` (KEY, VALUE) VALUES ("1", @x)

By default, this option is disabled and string parameters are quoted and escaped into JSON strings. That means that any value can be safely used as a string parameter, but it also means that parameters cannot be used as raw JSON documents:

/*
 * If @x is set to: test value " contains quote
 *
 * Result is a valid query
*/
INSERT INTO `bucket` (KEY, VALUE) VALUES ("1", "test value \" contains quote")

/*
 * If @x is set to: {"a": ["valid", "JSON", "value"]}
 *
 * Result contains string instead of JSON document
*/
INSERT INTO `bucket` (KEY, VALUE) VALUES ("1", "{\"a\": [\"valid\", \"JSON\", \"value\"]})

When this option is enabled, string parameters are assumed to be valid JSON. This means that raw JSON documents can be used as parameters, but it also means that all simple strings must be escaped:

/*
 * If @x is set to: test value " contains quote
 *
 * Result is an invalid query
*/
INSERT INTO `bucket` (KEY, VALUE) VALUES ("1", test value " contains quote)

/*
 * If @x is set to: {"a": ["valid", "JSON", "value"]}
 *
 * Result is a JSON document
*/
INSERT INTO `bucket` (KEY, VALUE) VALUES ("1", {"a": ["valid", "JSON", "value"]})

Please refer to ValidateJSONParameters for more details on how parameters are validated when this option is enabled.

CData Cloud

ChildSeparator

The character or characters used to denote child tables.

Data Type

string

Default Value

"_"

Remarks

When creating a child table for an array underneath a bucket, the Cloud will generate the name of the child table by concatenating the name of the base table, along with this separator and each path element.

For example, if this document were in the bucket "customers", then the child table for the addresses field would be called "customers_addresses".

{
  "addresses": [
    {"street": "123 Main St"},
    {"street": "424 Pleasant Ct"},
    {"street": "719 Blue Way"}
  ]
}

CData Cloud

CreateTableRamQuota

The default RAM quota, in megabytes, to use when inserting buckets via the CREATE TABLE syntax.

Data Type

string

Default Value

"250"

Remarks

The default RAM quota, in megabytes, to use when inserting buckets via the CREATE TABLE syntax.

CData Cloud

DataverseSeparator

The character or characters used to denote Analytics dataverses and scopes/collections.

Data Type

string

Default Value

"."

Remarks

When using the Analytics serivce, the Cloud will scan all datasets from all available dataverses. To avoid potential name conflicts, it will include the dataverse name and the dataset name in the generated table name.

By default this is set to ".", so that if there is a dataset called "users" on the "Default" dataverse, then the table generated will be "Default.users".

This property is also used when generating table names for collections (on both N1QL and Analytics) on Couchbase 7 and later. For example, a bucket called "users" that has two collections called "active" and "inactive" under the "status" scope would be detected as the tables "users.status.active" and "users.status.inactive".

CData Cloud

FlattenArrays

The number of elements to expose as columns from nested arrays. Ignored if IgnoreChildAggregates is enabled.

Data Type

string

Default Value

"0"

Remarks

By default, nested arrays are returned as strings of JSON. The FlattenArrays property can be used to flatten the elements of nested arrays into columns of their own. This is only recommended for arrays that are expected to be short.

Set FlattenArrays to the number of elements you want to return from nested arrays. The specified elements are returned as columns. The zero-based index is concatenated to the column name. Other elements are ignored.

For example, you can return an arbitrary number of elements from an array of strings:

["FLOW-MATIC","LISP","COBOL"]
When FlattenArrays is set to 1, the preceding array is flattened into the following table:

Column NameColumn Value
languages.0FLOW-MATIC

CData Cloud

FlattenObjects

Set FlattenObjects to true to flatten object properties into columns of their own. Otherwise, objects nested in arrays are returned as strings of JSON.

Data Type

bool

Default Value

true

Remarks

Set FlattenObjects to true to flatten object properties into columns of their own. Otherwise, objects nested in arrays are returned as strings of JSON. The property name is concatenated onto the object name with an underscore to generate the column name.

For example, you can flatten the nested objects below at connection time:

address : {
  "street" : "123 Main St.",
  "city"   : "Nowhere",
  "state"  : "NY",
  "zip"    : "12345"
}
When FlattenObjects is set to true, the preceding object is flattened into the following table:

Column NameColumn Value
address.street123 Main St.
address.cityNowhere
address.stateNY
address.zip12345

CData Cloud

FlavorSeparator

The character or characters used to denote flavors.

Data Type

string

Default Value

"."

Remarks

When the Cloud detects a flavored table, using either a DocType or Infer TypeDetectionScheme, it names flavored tables by concatenating the underlying bucket name, this seprator, and the value of the bucket's primary flavor.

For example, if the Cloud detects the flavor "docType = 'beer'" on the "beer-sample" bucket, then it will generate the table "beer-sample.beer" which contains only documents in "beer-sample" which have the "beer" doctype.

CData Cloud

GenerateSchemaFiles

Indicates the user preference as to when schemas should be generated and saved.

Possible Values

Never, OnUse, OnStart, OnCreate

Data Type

string

Default Value

"Never"

Remarks

GenerateSchemaFiles enables you to save the table definitions identified by Automatic Schema Discovery. This property outputs schemas to .rsd files in the path specified by Location.

Available settings are the following:

  • Never: A schema file will never be generated.
  • OnUse: A schema file will be generated the first time a table is referenced, provided the schema file for the table does not already exist.
  • OnStart: A schema file will be generated at connection time for any tables that do not currently have a schema file.
  • OnCreate: A schema file will be generated by when running a CREATE TABLE SQL query.
Note that if you want to regenerate a file, you will first need to delete it.

Generate Schemas with SQL

When you set GenerateSchemaFiles to OnUse, the Cloud generates schemas as you execute SELECT queries. Schemas are generated for each table referenced in the query.

When you set GenerateSchemaFiles to OnCreate, schemas are only generated when a CREATE TABLE query is executed.

Generate Schemas on Connection

Another way to use this property is to obtain schemas for every table in your database when you connect. To do so, set GenerateSchemaFiles to OnStart and connect.

Alternatives to Static Schemas

If your data structures are volatile, consider setting GenerateSchemaFiles to Never and using dynamic schemas. See Automatic Schema Discovery for more information about dynamic schemas.

Editing Schemas

Schema files have a simple format that makes them easy to modify. See Custom Schema Definitions for more information.

CData Cloud

InsertNullValues

Determines whether an INSERT should include fields that have NULL values.

Data Type

bool

Default Value

true

Remarks

By default the Cloud uses NULL values provided in an INSERT statement and inserts them as JSON null values.

If this option is disabled, SQL NULL values are ignored during an INSERT. In the case of array columns (FlattenArrays must be set to retrieve these), this means that array indices are shifted over to compensate for the values that have been removed.

CData Cloud

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 Cloud

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.

Integration and Formatting

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 Cloud

Pagesize

The maximum number of results to return per page from Couchbase.

Data Type

int

Default Value

1000

Remarks

The Pagesize property affects the maximum number of results to return per page from Couchbase. Setting a higher value may result in better performance at the cost of additional memory allocated per page consumed.

CData Cloud

PeriodsSeparator

The character or characters used to denote hierarchy.

Data Type

string

Default Value

"."

Remarks

When flattening objects and arrays, the Cloud will use this value to separate different levels of objects and arrays. For example, if your Couchbase server returns a document like this (and FlattenObjects is enabled), then the Cloud will return the columns "geo.latitude" and "geo.longitude" if the periods separator is set to ".".

{
  "geo": {
    "latitude": 35.9132,
    "longitude": -79.0558
  }
}

CData Cloud

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 Cloud

QueryExecutionTimeout

This sets the server-side timeout for the query, which governs how long Couchbase will execute the query before returning a timeout error.

Data Type

string

Default Value

"-1"

Remarks

Th default is -1, which disables the timeout. When enabling the timeout, the value must include both an amount and a unit, which can be one of: "ns" (nanoseconds), "us" (microseconds), "ms" (milliseconds), "s" (seconds), "m" (minutes) or "h" (hours). For example, "5m" and "300s" both set timeouts of 5 minutes.

There is a server-side timeout as well called the "index scan timeout", which will override this one if it is lower. By default the index scan timeout is 2 minutes, but it can be changed by setting the "indexer.settings.scan_timeout" property on your Couchbase server.

CData Cloud

QueryPassthrough

This option passes the query to the Couchbase server as is.

Data Type

bool

Default Value

false

Remarks

When this is set, queries are passed through directly to Couchbase.

CData Cloud

Readonly

You can use this property to enforce read-only access to Couchbase from the provider.

Data Type

bool

Default Value

false

Remarks

If this property is set to true, the Cloud will allow only SELECT queries. INSERT, UPDATE, DELETE, and stored procedure queries will cause an error to be thrown.

CData Cloud

RowScanDepth

The maximum number of rows to scan to look for the columns available in a table.

Data Type

int

Default Value

100

Remarks

The columns in a table must be determined by scanning table rows. This value determines the maximum number of rows that will be scanned.

Setting a high value may decrease performance. Setting a low value may prevent the data type from being determined properly, especially when there is null data.

CData Cloud

RTK

The runtime key used for licensing.

Data Type

string

Default Value

""

Remarks

The RTK property may be used to license a build.

CData Cloud

StrictComparison

Adjusts how precisely to translate filters on SQL input queries into Couchbase queries. This can be set to a comma-separated list of values, where each value can be one of: date, number, boolean, or string.

Data Type

string

Default Value

""

Remarks

This option is empty by default, which means that WHERE clauses sent to Couchbase will include extra functions that convert values so that more comparisons work.

For example, leaving the "string" setting out of the list causes arrays to be converted, so that they can be compared with strings:

SELECT * FROM Bucket WHERE MyArrayColumn = '[1,2,3]'

If set to a value, queries including the relevant types of comparisons will be translated literally. This makes better use of Couchbase's indexes, but means that the types of comparisons must be in a format Couchbase can compare directly.

For example, if "date" is provided as one of the options, then dates must match the format they are stored as in Couchbase since they will not be converted automatically:

SELECT * FROM Bucket WHERE MyDateColumn = '2018-10-31T10:00:00';

CData Cloud

Timeout

The value in seconds until the timeout error is thrown, canceling the operation.

Data Type

int

Default Value

60

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 Cloud throws an exception.

CData Cloud

TransactionDurability

Specifies how a document must be stored for a transaction to succeed. Specifies whether to use N1QL transactions when executing queries.

Possible Values

None, Majority, MajorityAndPersistActive, PersistToMajority

Data Type

string

Default Value

"Majority"

Remarks

If UseTransactions is enabled, then this option can be set to determine when Couchbase will allow writes in transactions to commit. The Couchbase documentation on Durability and Transactions contains the full details, below is a high-level summary.

This option controls requirements on both quorum and persistence. The quorum may either require no bucket replicas to receive the document (None), or a majority of replicas to have the document (all others). The persistence level requires either that the document be stored in the replica memory (Majoriy) or on the replica disk (MajorityAndPersistActive, PersistToMajority).

None is only useful if the bucket you are using is not configured for replicas. The other options can be used depending on the required performance and durability tradeoffs. Persisting to more replicas is slower but provides greater resilience against a node crashing.

CData Cloud

TransactionTimeout

This sets the amount of time a transaction may execute before it is timed out by Couchbase.

Data Type

string

Default Value

""

Remarks

If transactions are enabled, then the Cloud will default to the server's default transaction timeout setting.

When enabling the timeout, the value must include both an amount and a unit, which can be one of: "ns" (nanoseconds), "us" (microseconds), "ms" (milliseconds), "s" (seconds), "m" (minutes) or "h" (hours). For example, "5m" and "300s" both set timeouts of 5 minutes.

There are also cluster-level and node-level transaction timeouts which override this one if they are smaller. For example, if the node-level timeout is set to a minute then setting this option to "5m" will have no effect.

CData Cloud

UpdateNullValues

Determines whether an UPDATE writes NULL values as NULL, or removes them.

Data Type

bool

Default Value

true

Remarks

By default the Cloud will use NULL values provided in an UPDATE statement and set the field in Couchbase to NULL.

If this option is disabled SQL NULL values in an UPDATE will cause the Cloud to mark the field as MISSING. This removes the field from the object containing it, or if the field is contained in an array (per FlattenArrays) then that element is set to NULL.

This option should be used with care as the Cloud may not detect that the field exists if it is removed from enough documents within a bucket.

CData Cloud

UseCollectionsForDDL

Whether to assume that CREATE TABLE statements use collections instead of flavors. Only takes effect when connecting to Couchbase v7+ and GenerateSchemaFiles is set to OnCreate.

Data Type

bool

Default Value

false

Remarks

Normally the Cloud will assume that compound table names referenced in a CREATE TABLE statement are flavors. For compatibility, this is still the default with Couchbase v7+ even though flavors are not recommended there.

CREATE TABLE [myBucket.myFlavor](
  [Document.Id] VARCHAR PRIMARY KEY,
  docType VARCHAR,
  sometext VARCHAR,
  somenum INT
)

Enable this option to assume that CREATE TABLE statements refer to collection instead. In that scenario this query willl create the bucket and scope if necessary, before creating the colleciton and setting a primary index:

CREATE TABLE [myBucket.myScope.myCollection](
  [Document.Id] VARCHAR PRIMARY KEY,
  sometext VARCHAR,
  somenum INT
)

CData Cloud

UserDefinedViews

A filepath pointing to the JSON configuration file containing your custom views.

Data Type

string

Default Value

""

Remarks

User Defined Views are defined in a JSON-formatted configuration file called UserDefinedViews.json. The Cloud 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 Cloud.

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 Customer WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}
Use the UserDefinedViews connection property to specify the location of your JSON configuration file. For example:
"UserDefinedViews", "C:\\Users\\yourusername\\Desktop\\tmp\\UserDefinedViews.json"

CData Cloud

UseTransactions

Specifies whether to use N1QL transactions when executing queries.

Possible Values

Never, Always, Explicit

Data Type

string

Default Value

"Never"

Remarks

By default the Cloud does not use transactions for compatibility with older versions of Couchbase. All of the other options require a connection to Couchbase 7 or above. The N1QL service must also be enabled using CouchbaseService.

Setting this to Always means that all queries will use transactions. An explicit transaction may be created on the connection and queries will use that transaction while it is active. If there is no explicit transaction then queries will use implicit transactions instead.

Setting this to Explicit enables support for explicit transactions only. Explicit transactions may be created but if one is not currently active, then statements will not create an implicit transaction.

CData Cloud

ValidateJSONParameters

Allows the provider to validate that string parameters are valid JSON before sending the query to Couchbase.

Data Type

bool

Default Value

true

Remarks

When AllowJSONParameters and QueryPassthrough are enabled, the query parameters given to the Cloud will be treated as raw JSON documents instead of arbitrary string values. This option controls what happens when invalid JSON is given to the Cloud in this mode.

When this option is enabled, the Cloud will check that all string parameters can be parsed as valid JSON. If any cannot be, an error will be raised and the query will not be run.

When this option is disabled, no check is performed and all string parameter values are substituted into the query directly. This makes executing prepared statements faster, but less safe since invalid N1QL or SQL++ may be sent to the Couchbase.

Copyright (c) 2023 CData Software, Inc. - All rights reserved.
Build 22.0.8462