CData Python Connector for Facebook Ads

Build 26.0.9655

CData Python Connector for Facebook Ads

Overview

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

Key Features

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

Getting Started

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

Using the Python Connector/Using from Tools

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

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

SQLAlchemy ORM

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

Pandas

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

Schema Discovery

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

Advanced Features

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

SQL Compliance

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

Data Model

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

Connection String Options

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

CData Python Connector for Facebook Ads

Getting Started

Connecting to Facebook Ads

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

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

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

Python Version Support

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

Facebook Ads Version Support

By default, the connector models the current version of the Facebook Graph API, as bidirectional tables.

See Also

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

CData Python Connector for Facebook Ads

Package Installation

Dependencies

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

Installation

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

Windows:

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

Linux:

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

macOS:

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

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

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

Upgrading

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

Licensing

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

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

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

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

Uninstallation

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

pip uninstall cdata-facebookads-connector

CData Python Connector for Facebook Ads

Establishing a Connection

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

  1. Import the module as follows:
    import cdata.facebookads as mod
  2. To establish a connection string, call the connect() method from the connector object using an appropriate connection string, such as:
    mod.connect("InitiateOAuth=GETANDREFRESH;")

Connecting to Facebook Ads

The following are optional connection properties:

  • Target: Some Facebook tables can be filtered by a target. For example, to retrieve comments on a video, specify the Id of the video as the target. This property enables you to restrict the results of all queries in the connection to records that match the specified target. You can also specify this restriction per query with the Target column.
  • AggregateFormat: The connector returns some columns as a string aggregate. For example, the available likes data for an entity is returned in aggregate. By default, the connector returns aggregate columns in JSON. You can also return aggregates in XML.
  • RetryLevel: Use this property to control automatic query retry for specific ad insights queries and errors.

Authenticating to Facebook Ads

Facebook Ads uses the OAuth standard to authenticate users.

OAuth

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. Alternatively, you can create a custom OAuth application. See Creating an Entra ID (Azure AD) Application for information about creating custom applications and reasons for doing so.

For authentication, the only difference between the two methods is that you must set two additional connection properties when using custom OAuth applications. After setting the following connection properties, you are ready to connect:

  • InitiateOAuth: Set this to GETANDREFRESH. You can use InitiateOAuth to avoid repeating the OAuth exchange and manually setting the OAuthAccessToken.
  • OAuthClientId: (custom applications only) Set this to the client Id in your application settings.
  • OAuthClientSecret: (custom applications only) Set this to the client secret in your application settings.
  • CallbackURL: Set this to the Redirect URL in your application settings.
  • Scope (optional): Set this if you need to customizie the permissions that the driver requests.
  • AuthenticateAsPage (optional): Set this to a page name or Id to make requests as a page. The page must be managed by the authenticated user.

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

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

Web Applications

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

Get an OAuth Access Token

Set the following connection properties to obtain the OAuthAccessToken:

  • OAuthClientId: Set this to the client Id in your application settings.
  • OAuthClientSecret: Set this to the client secret in your application settings
  • Scope (optional): Set this if you need to customizie the permissions that the driver requests.
  • AuthenticateAsPage (optional): Set this to a page name or Id to make requests as a page. The page must be managed by the authenticated user.

Then call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the AuthMode input to WEB and set the CallbackURL input to the Redirect URI you specified in your app settings. If necessary, set the "Permissions" parameter to request custom permissions.
  2. Open the URL, log in, and authorize the application. You are redirected back to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the "code" parameter in the query string of the callback URL. If necessary, set the "Permissions" parameter to request custom permissions.

To connect to data, set the OAuthAccessToken connection property to the access token returned by the stored procedure. When the access token expires after ExpiresIn seconds, call GetOAuthAccessToken again to obtain a new access token. [

Headless Machines

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

Creating a custom OAuth app is optional in the headless OAuth flow; if you want to skip creating an app, you can connect with the driver's embedded OAuth credentials. However, you might want to create a custom OAuth app to change the information displayed when users log into Facebook to grant permissions to the driver. For information on how to create a custom OAuth application, see Creating a Custom OAuth App.

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

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL. Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. If you are using the Embedded OAuth Application:
    1. Call the GetOAuthAuthorizationURL stored procedure.
    2. Click Facebook Ads OAuth endpoint to open the endpoint in your browser.
  2. If you are using a custom OAuth application, create the Authorization URL by setting the following properties:
  3. Call the GetOAuthAuthorizationURL stored procedure with the CallbackURI input parameter set to the exact Redirect URI you specified in your application settings.
  4. Open the URL returned by the stored procedure in a browser.
  5. Log in and grant permissions to the connector. You are then redirected to the callback URL, which contains the verifier code.
  6. Save the value of the verifier code. Later you will set this in the OAuthVerifier connection property.

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

Connect to Data

After the OAuth settings file is generated, set the following properties to connect to data:

  • OAuthSettingsLocation: Set to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the provider to enable the automatic refreshing of the access token.
  • InitiateOAuth: Set to REFRESH.

Option 2: Transfer OAuth Settings

To install the connector on another machine, authenticate, and then transfer the resulting OAuth values:

  1. On a second machine, install the connector and connect with the following properties set:
  2. Test the connection to authenticate. The resulting authentication values are written and encrypted to the path specified by OAuthSettingsLocation. After you have successfully tested the connection, copy the OAuth settings file to your headless machine. On the headless machine, set the following connection properties to connect to data:
    • InitiateOAuth: Set to REFRESH.
    • OAuthSettingsLocation: Set to the location of your OAuth settings file. Make sure this location gives read and write permissions to the connector to enable the automatic refreshing of the access token.

Requesting Additional Permissions

You may find while using the connector that Facebook returns an error stating your app does not have permissions to do a certain action. To resolve this, you must generate a new OAuth access token with the required permissions. Set the Scope property in the authentication step for a desktop application.

Web applications need to call the GetOAuthAuthorizationURL and GetOAuthAccessToken stored procedures, which have inputs for the permissions you would like to request.

Note that these are comma-separated lists of permissions, so you can request more than one per authorization request. You can find a list of available Facebook permissions here:

http://developers.facebook.com/docs/authentication/permissions/

Note that in some cases, permissions restrictions might not be due to missing but requestable Facebook Ads OAuth permissions, but instead might be due to missing OAuth app features, like Page Public Content Access or Page Public Metadata Access. These features are tied to the OAuth app as a whole, and cannot be approved or denied for individual OAuth access tokens requested by users. Consider Creating a Custom OAuth App if you need access to app features not available with the embedded OAuth app.

AuthenticateAsPage Property

Use the AuthenticateAsPage connection property if you want to post as a single page. To query collections of pages, leave AuthenticateAsPage blank, in which case CData tools automatically detect which page tokens to use. Alternatively, if you would like to disable this automatic detection and thus require usage of AuthenticateAsPage when querying a page, set AutoDetectPageTokens to "False".

The following sections compare the two options.

Posting as a Page

After authenticating to Facebook Ads with your user account, you can post, etc. as one of the pages you manage: Set the AuthenticateAsPage property to the Id of the page you want. You can find the Ids for all pages your account has access to by querying the Pages view.

Automatic Page

Facebook Ads has made a number of recent changes that require page tokens for most resources owned by a page. This can be troublesome if you manage multiple pages and want to execute the same queries across all pages (such as retrieving Insights). In order to make this work seamlessly with our tools, we have added a way to automatically detect the page token to use. For this to work, simply do not specify the AuthenticateAsPage and leave AutoDetectPageTokens set to "True". Note that the correct page token can only be resolved if the page id is specified as part of the target in the request. This means for some requests you will still need to manually specify AuthenticateAsPage.

Setting AutoDetectPageTokens to "False" will disable automatic page token detection.

CData Python Connector for Facebook Ads

Configuring JNI

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

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

Configure the Config INI File

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

{path_to_distribution_site-packages}/cdata/config.ini

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

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

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

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

Configure Environment Variables

Additionally, set the following environment variables:

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

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

The following are some examples of this syntax:

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

Custom Logger

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

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

To enable custom logging:

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

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

import cdata.facebookads as mod
import time

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

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

mod.setCustomLoggerFactory(createLogger)

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

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

CData Python Connector for Facebook Ads

Creating a Custom OAuth App

Create a Custom OAuth App

To obtain the OAuth client credentials, follow the steps below:

  1. Log into Facebook and navigate to https://developers.facebook.com/apps.
  2. Create a new app and select Settings > Basic. The OAuthClientId is the App Id displayed. The OAuthClientSecret is the App Secret.
  3. Add a website platform on the Settings tab. Enter a Site URL. This value is not used in authentication.

Follow the steps below to configure the OAuth redirect URI.

  1. Go to your app settings and add the Facebook Login product from the Products section.
  2. In the product settings, define the OAuth redirect URI.

    Set the redirect URI:

    • For desktop applications, set the redirect URI to https://localhost:33333/, or a similar https url.
    • For web applications, set the redirect URI you want to be used as a callback URL, where the user returns with the token that verifies that they have granted your app access.

CData Python Connector for Facebook Ads

Fine-Tuning Data Access

Fine Tuning Data Access

You can use the following properties to gain greater control over Facebook Ads API features and the strategies the connector uses to surface them:

  • AccountID: Set this to specify an ad account ID that will be used for the Target input for queries if none is specified. Both Target connection property and Target query input have precedence over this property.
  • RetryLevel: Use this property to control query retry for certain types of ad insights queries and errors. Please see the pages for AdInsights and AdInsightsActions views in Data Model for more information.

CData Python Connector for Facebook Ads

Changelog

General Changes

DateVersionSourceCategoryTypeDescription
2026-05-2726.0.9643GeneralConnectionRemoved
  • Removed the deprecated ReplaceInvalidTypesWithNull connection property. Use the ReplaceInvalidValuesWithNull property instead.
2026-05-2226.0.9638PythonRemoved
  • Remove support for Intel x64 architecture on macOS
2026-05-1926.0.9635Facebook AdsData ModelAdded
  • In the LeadValues view, filters on the CreateTime column are now processed server-side, improving query performance.
2026-05-0726.0.9623GeneralData ModelAdded
  • Added the ColumnCapabilities column to the sys_tablecolumns system table. This column is a bit mask denoting the column's write capabilities.
2026-05-0726.0.9623PythonChanged
  • Updated embedded JRE to jre-17.0.19+10 (Linux x64 / MacOs x64).
2026-04-1526.0.9601GeneralQuery ExecChanged
  • String comparisons using GREATER, LESS, and CONTAINS operators are now case-insensitive by default.
2026-04-0126.0.9587Facebook AdsRemoved
  • Removed the BatchSize connection property.
2026-03-1725.0.9572Facebook AdsData ModelAdded
  • Added the following breakdown columns to the AdInsightsActions view: ComscoreMarket, FlexibleFormatAssetType, ReelsTrendingTopic, RuleSetId, and RuleSetName.
2026-03-1625.0.9571Facebook AdsConnectionChanged
  • The GraphAPIVersion and MarketingAPIVersion properties now default to 25.0 in order to utilize the most up-to-date API version.
2026-03-0425.0.9559Facebook AdsData ModelChanged
  • In the AdInsightsMMM view, the DateStop column has been renamed to DateEnd. Additionally, the data type for both DateEnd and DateStart is now "date".
2026-01-1525.0.9511Facebook AdsAdded
  • Added the AdInsightsMMM view.
2026-01-1325.0.9509GeneralAdded
  • Added support for the REGEXP_REPLACE() string function.
2026-01-0625.0.9502Facebook AdsAdded
  • Added the following fields to the AdInsights view: AdvancedReach1DLookback, AdvancedReach7DLookback, AdvancedReach28DLookback, AnchorEventAttributionSetting, AnchorEventsPerformanceIndicator, AttributionSetting, AuctionBid, AuctionCompetitiveness, AuctionMaxCompetitorBid, CanvasAvgViewPercent, CanvasAvgViewTime, CostPerDDACountByConvs, CostPerObjectiveResult, CostPerResult, CreatedTime, DDACountByConvs, DDAResults, FullViewImpressions, FullViewReach, InstagramProfileVisits, InstagramUpcomingEventRemindersSet, LandingPageViewPerLinkClick, MarketingMessagesDelivered, MarketingMessagesDeliveryRate, MarketingMessagesReadRateBenchmark, MultiEventConversionAttributionSetting, OptimizationGoal, PlacePageName, ProductGroupRetailerId, ProductRetailerId, ProductViews, PurchasePerLandingPageView, QualifyingQuestionQualifyAnswerRate, ResultRate, Results, ResultValuesPerformanceIndicator, ShopsAssistedPurchases, SocialSpend, TotalCardView, UpdatedTime, and WishBid.
  • Added the following breakdown columns to the AdInsights view: ComscoreMarket, FlexibleFormatAssetType, ReelsTrendingTopic, RuleSetId, and RuleSetName.
2025-12-2125.0.9486PythonAdded
  • Added support for custom loggers in Python connectors on Linux and macOS.
2025-12-0525.0.9470GeneralAdded
  • Added support for the INSERT INTO SELECT statement, with driver-side execution for providers that do not support the operation natively.
2025-10-3025.0.9434PythonChanged
  • Updated embedded JRE to jre-17.0.17+10 (Linux x64 / MacOs x64).
2025-10-0625.0.9410GeneralAdded
  • Support for parsing datetime formats using ".S" and ",S" for milliseconds and nanoseconds.
2025-09-1725.0.9391Facebook AdsAdded
  • Added the TotalPostbacks and TotalPostbacksDetailed fields to the AdInsights and AdInsightsActions views.
  • Added the following breakdown columns to the AdInsights and AdInsightsActions views: AdFormatAsset, BodyAssetId, BodyAssetText, CallToActionAssetId, CallToActionAssetName, DescriptionAssetId, DescriptionAssetText, ImageAssetId, ImageAssetHash, ImageAssetUrl, TitleAssetId, TitleAssetText, LinkUrlAssetId, LinkUrlAssetWebsiteUrl, LinkUrlAssetDisplayUrl, VideoAssetId, VideoAssetVideoId, VideoAssetUrl, VideoAssetThumbnailUrl, VideoAssetVideoName, AppId, IsConversionIdModeled, SkanCampaignId, SkanConversionId, and UserSegmentKey.
  • Added the following action breakdown columns to the AdInsightsActions view: ConversionDestination, SignalSourceBucket, and StandardEventContentType.
2025-09-1225.0.9386GeneralAdded
  • Added the IsInsertable, IsUpdateable, and IsDeleteable columns to the sys_tables table.
2025-09-1025.0.9384GeneralChanged
  • All columns in statically defined Views are now reported as read-only.
2025-09-0325.0.9377GeneralChanged
  • Corrected the behavior when IN criteria with NULL values are used in the projection part. It now returns NULL instead of 0. For example, "NULL IN (1,2)" returns "NULL".
2025-09-0125.0.9375GeneralAdded
  • Added support for using the CAST function with infinity values. This function can cast "inf" and "-inf" to DOUBLE, FLOAT, or REAL.
2025-08-2125.0.9364GeneralChanged
  • Report behavior change:
    • Fixed inconsistent string value comparisons in non-table queries.
    • For example, "SELECT 'A' = 'a'" previously returned false, but it now returns true.
2025-08-1325.0.9356GeneralChanged
  • Changed the maximum number of pages held in memory from 15 to 5 for the page providers to decrease heap usage.
2025-08-0625.0.9349Facebook AdsChanged
  • Changed the default Graph API and Marketing API versions from 21.0 to 23.0.
2025-07-0725.0.9319PythonRemoved
  • Removed the 32-bit version of Windows Python.
2025-07-0225.0.9314PythonRemoved
  • Removed support for Python 3.9.
2025-06-2625.0.9308Facebook AdsRemoved
  • In the AdCreatives view: removed the columns InstagramActorId and EffectiveInstagramStoryId. As replacements, use the columns InstagramUserId and EffectiveInstagramMediaId, both of which are already in the view.
2025-06-2625.0.9308Facebook AdsReplaced
  • In the CreateAdPreview stored procedure: replaced the input parameter ApplyStandardEnhancement with CreativeFeature.
2025-06-2525.0.9307GeneralRemoved
  • Removed the "ADLS Gen 1" value from the ConnectionType property.
2025-06-2525.0.9307PythonAdded
  • Added support for Python 3.13 in Windows, Linux, and Mac editions.
2025-06-2525.0.9307PythonRemoved
  • Removed support for Python 3.8 as it is no longer supported.
2025-06-2025.0.9302GeneralAdded
  • Created the following functions:
    • TEXT_ENCODE: encodes a string into a different charset (UTF8 → UTF7 and returns a binary array as the result).
    • TEXT_DECODE: takes a binary array and decodes it back into a string when provided the charset.
    • BASE64_ENCODE: takes a binary array and encodes it as a base64 string (varchar).
    • BASE64_DECODE: takes a base 64-encoded string and decodes it into a binary array.
2025-06-1825.0.9300GeneralChanged
  • The internal code for exception handling has been refactored. Exception messages returned during certain error conditions may now have different wording or formatting.
2025-05-2725.0.9278GeneralRemoved
  • Removed the "Proprietary" enum option from ProxyAuthscheme.
2025-05-1225.0.9263PythonChanged
  • Updated embedded JRE to jre-17.0.15+6 (Linux x64 / MacOS x64) and jre-17.0.15+6 (MacOS aarch64).
2025-02-1524.0.9177GeneralAdded
  • Added support for converting unsigned integer types to the nearest signed data type that has enough precision to hold the unsigned value.This is done for JDBC only because it does not have support for unsigned data types.
2024-11-2724.0.9097GeneralAdded
  • Added ThreadId to LogModule output. Logfile lines now include the Thread ID associated with the action being performed.
2024-09-0324.0.9012Facebook AdsAdded
  • Added the PixelAddToCart and PixelPurchase columns to the AdInsights view. These columns expose the offsite_conversion.fb_pixel_add_to_cart and offsite_conversion.fb_pixel_purchase action types.
2024-08-1224.0.8990Facebook AdsAdded
  • Added the AutoDetectPageTokens connection property. By default, the driver continues to automatically gather page access tokens for mapping when necessary. This new property allows users to disable the automatic retrieval of page access tokens when executing queries that target specific Facebook pages.
2024-07-1724.0.8964Facebook AdsAdded
  • Added the AsyncTimeout connection property, which specifies how long the driver should wait for results when submitting an asynchronous request for insights. If insights are not returned by the time specified in AsyncTimeout, an error message is returned.
2024-06-2224.0.8939Facebook AdsAdded
  • Added the following columns to the Ads view: AdActiveTime, AdScheduledEndTime, AdScheduledStartTime, BidAmount, LastUpdatedByAppId, PreviewShareableLink, and SourceAdId.
2024-06-0524.0.8922PythonAdded
  • Added support for Python 3.12.
2024-05-2324.0.8909Facebook AdsAdded
  • The CustomConversions table now supports INSERT and UPDATE queries.
2024-05-0924.0.8895GeneralChanged
  • The ROUND function previously did not accept negative precision values. That feature has now been restored.
2024-04-2523.0.8881Facebook AdsChanged
  • Changed the default Graph API and Market API versions to 19.0.
2024-03-1523.0.8840GeneralAdded
  • Created a new SQL function called STRING_COMPARE that provides java's String.compare() ability to SQL queries. Returns a number representative of the compared value of two strings
2024-02-2823.0.8824Facebook AdsRemoved
  • Removed "region" breakdown from Demographic_DMA_Region_Report. Demographic_Region_Report covers the "region" breakdown.
2024-02-2123.0.8817Facebook AdsAdded
  • Added the CustomConversions view.
2024-02-1423.0.8810Facebook AdsAdded
  • Added the IgnoreValidationException connection property.
2023-12-2823.0.8762Facebook AdsAdded
  • Added the BoostedObjectId column to the Campaigns view.
2023-11-2923.0.8733GeneralChanged
  • The ROUND function doesn't accept the negative precision values anymore.
2023-11-2923.0.8733GeneralChanged
  • The returning types of the FDMonth, FDQuarter, FDWeek, LDMonth, LDQuarter, LDWeek functions are changed from Timestamp to Date.
  • The return type of the ABS function will be consistent with the parameter value type.
2023-11-2823.0.8732GeneralAdded
  • Added the HMACSHA256 formatter to allow for secrets to be decoded if it is in base64 format
2023-08-2923.0.8641PythonAdded
  • Added support for SQLAlchemy 2.0.
2023-07-2623.0.8607Facebook AdsChanged
  • Changed the default Graph API and Market API versions to 17.0.
2023-06-2023.0.8571GeneralAdded
  • Added the new sys_lastresultinfo system table.
2023-06-1223.0.8563Facebook AdsAdded
  • Added the following predefined views to facilitate easier access to specific ad insights reporting: Action_Canvas_Component_Report, Action_Carousel_Card_Report, Action_Conversion_Device_Report, Action_Product_Id_Report, Action_Reactions_Report, Action_Video_Sound_Report, Action_Video_View_Type_Report, Basic_Ad_Set_Report, Basic_All_Levels_Report, Basic_Campaign_Report, Delivery_Device_Report, Delivery_Platform_Report, Demographic_Age_And_Gender_Report, Demographic_Age_Report, Demographic_Country_Report, Demographic_DMA_Region_Report, Demographic_Gender_Report, Demographic_Region_Report.
2023-06-0723.0.8558Facebook AdsChanged
  • Changed the default Graph API and Market API versions to 16.0.
2023-05-1923.0.8539PythonAdded
  • Added support for Python 3.11 on Windows, Linux and Mac.
2023-05-1623.0.8536PythonRemoved
  • Removed support for Python 3.7 on Windows and Linux
2023-04-2923.0.8519Facebook AdsRemoved
  • Removed the Version connection property. Graph API and Marketing API versions will now be managed internally by the driver, and updated as necessary in new driver releases per API deprecations.
2023-04-2523.0.8515GeneralRemoved
  • Removed support for the SELECT INTO CSV statement. The core code doesn't support it anymore.
2022-12-1422.0.8383GeneralChanged
  • Added the Default column to the sys_procedureparameters table.
2022-12-0922.0.8378Facebook AdsAdded
  • Added the AdImages view for querying ad images associated with an ad account.
2022-12-0922.0.8378Facebook AdsChanged
  • Changed the API version default of the Version property from 14.0 to 15.0.
2022-11-1522.0.8354PythonChanged
  • Updated embedded JRE to jre8u345-b01(Linux x64 / MacOS x64) and jre-17.0.5+8(MacOS aarch64).
2022-11-1422.0.8353Facebook AdsAdded
  • Added the CreateAdInsightsReport stored procedure for the generation of custom ad insights reports.
2022-10-2522.0.8333Facebook AdsAdded
  • Added retry method, governed by new RetryLevel connection property, for avoiding data limit API errors for ad insights requests. For Target-less queries executed at the ad account level, the driver will now attempt to retry initial data requests that encounter errors about requesting insights over too many rows by attempting to retry the request at a lower level of ad object. The deepest level of ad object to which the driver might retry is determined by the Level query parameter and RetryLevel connection property, in order of precedence.
2022-09-3022.0.8308GeneralChanged
  • Added the IsPath column to the sys_procedureparameters table.
2022-05-1822.0.8173PythonAdded
  • Added support for Python 3.10 on Windows, Linux, and Mac
  • Added support for Python 3.9 on Mac
  • Added support for Mac M1
2022-05-1822.0.8173PythonRemoved
  • Removed support for Python 3.6 on Windows and Linux
2022-01-1221.0.8047Facebook AdsAdded
  • Added the following fields for AdCreatives: EffectiveInstagramMediaId, EffectiveInstagramStoryId, SourceInstagramMediaId.
2021-11-0221.0.7976Facebook AdsChanged
  • Updated the maximum pagesize to be unrestricted for all tables. Previously Facebook would throw exceptions if the pagesize was exceeded, but this seems to have been removed.
2021-10-2621.0.7969Facebook AdsChanged
  • The default API version is updated to 12.0.
2021-10-1421.0.7957Facebook AdsAdded
  • Added the TargetingDevicePlatforms, TargetingPublisherPlatforms, and TargetingInstagramPositions to the drivers.
2021-09-2721.0.7940Facebook AdsAdded
  • Added extra columns for Dimension, Hierarchy and OLAPType to sys_tablecolumns for OLAP properties.
2021-09-0221.0.7915GeneralAdded
  • Added support for the STRING_SPLIT table-valued function in the CROSS APPLY clause.
2021-08-0721.0.7889GeneralChanged
  • Added the KeySeq column to the sys_foreignkeys table.
2021-08-0621.0.7888GeneralChanged
  • Added the new sys_primarykeys system table.
2021-07-2321.0.7874GeneralChanged
  • Updated the Literal Function Names for relative date/datetime functions. Previously, relative date/datetime functions resolved to a different value when used in the projection as opposed to the predicate. For example: SELECT LAST_MONTH() AS lm, Col FROM Table WHERE Col > LAST_MONTH(). Formerly, the two LAST_MONTH() methods would resolve to different datetimes. Now, they will match.
  • As a replacement for the previous behavior, the relative date/datetime functions in the criteria may have an 'L' appended to them. For example: WHERE col > L_LAST_MONTH(). This will continue to resolve to the same values that were previously calculated in the criteria. Note that the "L_" prefix will only work in the predicate - it not available for the projection.
2021-06-1421.0.7835Facebook AdsChanged
  • The default API version is updated to 11.0.
  • Facebook has removed access from apps to return comment ids when the user does not also have permissions to moderate the comments. This may mean in some cases comments will stop returning with our driver when they were working previously.
  • The user_likes and user_posts permissions (no longer used by default with the embedded driver) now have much more difficult requirements to access them from Facebook.
  • Nearly all unique page type columns for the Pages table were deprecated by Facebook. For example, Parking columns, GeneralInfo, Attire, Restaurant Services columns, Awards, etc. These will all start returning null as Facebook transitions to the New Page Experience. These columns will be removed in the 2022 release of the driver.
2021-04-2521.0.7785GeneralAdded
  • Added support for handling client side formulas during insert / update. For example: UPDATE Table SET Col1 = CONCAT(Col1, " - ", Col2) WHERE Col2 LIKE 'A%'
2021-04-2321.0.7783GeneralChanged
  • Updated how display sizes are determined for varchar primary key and foreign key columns so they will match the reported length of the column.
2021-04-1621.0.7776GeneralAdded
  • Non-conditional updates between two columns is now available to all drivers. For example: UPDATE Table SET Col1=Col2
2021-04-1621.0.7776GeneralChanged
  • Reduced the length to 255 for varchar primary key and foreign key columns.
2021-04-1621.0.7776GeneralChanged
  • Updated implicit and metadata caching to improve performance and support for multiple connections. Old metadata caches are not compatible - you need to generate new metadata caches if you are currently using CacheMetadata.
2021-04-1621.0.7776GeneralChanged
  • Updated index naming convention to avoid duplicates.
2021-04-1321.0.7773Facebook AdsChanged
  • Updated the default Version to 10.0.
  • On the AdsInsights and AdInsightsActions tables, the date_preset input available input value of "lifetime" is changed to "maximum" to comply with Facebook API changes. The more relevant impact is that as of API version 10.0, apps may only retrieve up to 37 months prior data. In the past, older insight data was available.
2021-03-1921.0.7748Facebook AdsDeprecated
  • The Permissions connection property is deprecated and replaced with Scope to match other drivers.

CData Python Connector for Facebook Ads

Using the Connector

This section provides a walk-through for writing Facebook Ads data access code in Python script.

For more information on the available data source entities and how to query them with SQL, see Data Model. For the SQL syntax, see SQL Compliance.

Connecting from Code

For information on how to deploy the connector and configure the connection to Facebook Ads, see Package Installation and Establishing a Connection.

For information on how to connect with the facebookads.connector module and its related classes, see Connecting.

Executing SQL

The connection's cursor object is used to directly execute SQL queries. For information on how to execute SELECT statements and process the returned result sets, see Querying Data.

Executing Stored Procedures

You can call stored procedures by using the EXECUTE statement. For further information, see Calling Stored Procedures.

CData Python Connector for Facebook Ads

Connecting

Connecting with the cdata.facebookads Module:

The connector's module is used directly to establish a connection with the data source. It does this by using a connection string as its argument. For example:
import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")

Once the connection is created, you can use it to execute subsequent SQL queries.

CData Python Connector for Facebook Ads

Querying Data

After connecting as described in Connecting, you can use the open connection to execute SQL statements.

Executing Queries

To execute SQL statements that return data, use the execute() method. Once a query is executed, the result set is fetched from the cursor. This result set can then be iterated over to process the records individually.

For example:

cur = conn.execute("SELECT AccountId, Name FROM AdAccounts")
rs = cur.fetchall()
for row in rs:
	print(row)

Parameterized Queries

Various Python collections, such as arrays and tuples, can act as additional arguments for the execute() method. This enables you to parameterize the queries executed and help to prevent SQL Injection.

For example:

cmd = "SELECT AccountId, Name FROM AdAccounts WHERE Name = ?"
params = ["Act Name"]
cur = conn.execute(cmd, params)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for Facebook Ads

Calling Stored Procedures

You can execute stored procedures using either the execute() or callproc() method of the connection.

Calling Stored Procedures Using Execute()

When you call stored procedures by issuing EXECUTE commands, the stored procedure arguments are parameterized. For example:
cmd = "EXECUTE GetOAuthAccessToken AuthMode = ?"
params = ["APP"]
conn.execute(cmd, params)

Calling Stored Procedures Using Callproc()

When you call stored procedured by issuing the callproc() method, the stored procedure arguments are a procedure name and a list of parameters. For example:
cur = conn.cursor()
params = ["APP"]
cur.callproc("GetOAuthAccessToken", params)

CData Python Connector for Facebook Ads

Using from Tools

The connector is integrated with other tools and packages within Python.

Python Integration Guides

The following sections show how to create and use connections with the connector in common packages in Python:

Complete List of Facebook Ads Integration Quickstarts

For information on connecting from other applications, see Facebook Ads integration guides.

CData Python Connector for Facebook Ads

From SQLAlchemy

The CData Python Connector for Facebook Ads includes a Dialect class that enables integration with SQLAlchemy. Bear in mind that several aspects of connector functionality are not currently supported in SQLAlchemy 2.0 or above. If necessary, downgrade SQLAlchemy to version 1.4 or 1.3 before using this connector.

The following sections detail various aspects of this integration:

Connecting From SQLAlchemy

To construct a URL with which SQLAlchemy loads and uses the appropriate connector automatically, see Connecting

Reflecting Metadata With SQLAlchemy

To learn how to model Facebook Ads tables with mapped classes, see Reflecting Metadata.

Querying Data From SQLAlchemy

To learn how to use mapped classes to query the associated tables, see Querying Data.

CData Python Connector for Facebook Ads

Connecting

Connecting With a Dialect URL

Establishing a connection using SQLAlchemy requires a specific URL format.
from sqlalchemy import create_engine
engine = create_engine("facebookads:///?InitiateOAuth=GETANDREFRESH;")

For SQLAlchemy 2.0, the dialect name is facebookads_2. To establish a connection, use the following URL format:

from sqlalchemy import create_engine
engine = create_engine("facebookads_2:///?InitiateOAuth=GETANDREFRESH;")

CData Python Connector for Facebook Ads

Reflecting Metadata

SQLAlchemy can act as an Object-relational Map (ORM). This enables you to treat records of a database table as instantiable records. To leverage this functionality, you must reflect the underlying metadata in one of the following ways.

Note: The following examples employ SQLAlchemy 1.4.

Modeling Data Using a Mapping Class

Use "sqlalchemy.ext.declarative.declarative_base" to declare a mapping class for the table you wish to model in the ORM. A known table in the data model is modeled either partially or completely, as shown in the following example:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class AdAccounts(Base):
	__tablename__ = "AdAccounts"
	Id = Column(String, primary_key=True)
	AccountId = Column(String)
	Name = Column(String)

Automatically Reflecting Metadata

Rather than mapping tables manually, SQLAlchemy can discover the metadata for one or more tables automatically. To accomplish this across the entire data model, use automap_base:
from sqlalchemy import MetaData
from sqlalchemy.ext.automap import automap_base
meta = MetaData()
abase = automap_base(metadata=meta)
abase.prepare(autoload_with=engine)
AdAccounts = abase.classes.AdAccounts

You can also reflect a single table with an inspector. When reflecting this way, providing a list of specific columns to map is optional:

from sqlalchemy import MetaData, Table
from sqlalchemy import inspect
meta = MetaData()
insp = inspect(engine)
AdAccounts_table = Table("AdAccounts", meta)
insp.reflect_table(AdAccounts_table, ["Id","Name"])

CData Python Connector for Facebook Ads

Querying Data

After you use the steps in Connecting to connect, and use one of the methods in Reflecting Metadata to reflect some of the metadata, you can use a session object to query data.

Querying Data Using the Query Method

If the mapping class has been prepared, use it with a session object to query the data source. After binding the engine to the session, provide the mapping class to the session's query method.

For example:

engine = create_engine("facebookads:///?InitiateOAuth=GETANDREFRESH;")
factory = sessionmaker(bind=engine)
session = factory()
for instance in session.query(AdAccounts).filter_by(Name="Act Name"):
	print("Id: ", instance.Id)
	print("AccountId: ", instance.AccountId)
	print("Name: ", instance.Name)
	print("---------")

Querying Data Using the Execute Method

The session object can also run the query with the execute() method alongside the appropriate Table object. Assuming you have an active session, the following is just as viable:
AdAccounts_table = AdAccounts.metadata.tables["AdAccounts"]
for instance in session.execute(AdAccounts_table.select().where(AdAccounts_table.c.Name == "Act Name")):
	print("Id: ", instance.Id)
	print("FullName: ", instance.Name)
	print("City: ", instance.BillingCity)
	print("---------")

CData Python Connector for Facebook Ads

Executing JOINs

Implicit Joining

If mapped classes of related Facebook Ads objects have a singular foreign key relationship, the classes are implicitly joined. After importing the necessary objects, a relationship is established between your two mapped classes, as in the example below:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()
class Contact(Base):
	__tablename__ = "Contact"
	Id = Column(Integer, primary_key=True)
	Name = Column(String)
	Email = Column(String)
	BirthDate = Column(DateTime)
	AccountId = Column(String, ForeignKey("Account.Id"))
	Account_Link = relationship("Account", back_populates="Contact_Link")

class Account(Base):
	__tablename__ = "Account"
	Id = Column(String, primary_key=True)
	Name = Column(String)
	BillingCity = Column(String)
	NumberOfEmployees = Column(Integer)
	Contact_Link = relationship("Contact", order_by=Contact.Id, back_populates="Account_Link")

Once the relationship is established, the tables are queried simultaneously using the session's query() method. For example:

rs = session.query(Account, Contact).filter(Account.Id == Contact.AccountId)
for Ac, Ct in rs:
  print("AccountId: ", Ac.Id)
  print("AccountName: ", Ac.Name)
  print("ContactId: ", Ct.Id)
  print("ContactName: ", Ct.Name)

Other Join Forms

In situations where mapped classes have either no foreign keys or multiple foreign keys, you may need different forms of the JOIN query to accommodate them. Using the earlier classes as examples, the following JOIN queries are possible as well:
  • Explicit condition (necessary if there are no foreign keys in your mapped classes):
    rs = session.query(Account, Contact).join(Contact, Account.Id == Contact.AccountId)
    for Ac, Ct in rs:
  • Left-to-right relationship:
    rs = session.query(Account, Contact).join(Account.Contact_Link)
    for Ac, Ct in rs:
  • Left-to-right relationship with explicit target:
    rs = session.query(Account, Contact).join(Contact, Account.Contact_Link)
    for Ac, Ct in rs:
  • String form of a left-to-right relationship:
    rs = session.query(Account, Contact).join("Contact_Link")
    for Ac, Ct in rs:

CData Python Connector for Facebook Ads

Other SQL Clauses

SQLAlchemy ORM also exposes support for other clauses in SQL, such as ORDER BY, GROUP BY, LIMIT, and OFFSET. All of these are supported by this connector:

ORDER BY

The following example sorts by a specified column using the session object's query() method:
rs = session.query(AdAccounts).order_by(AdAccounts.AnnualRevenue)
for instance in rs:
	print("Id: ", instance.Id)
	print("AccountId: ", instance.AccountId)
	print("Name: ", instance.Name)
	print("---------")

You can also use the session object's execute() method perform an ORDER BY. For example:

rs = session.execute(AdAccounts_table.select().order_by(AdAccounts_table.c.AnnualRevenue))
for instance in rs:

GROUP BY

The following example uses the session object's query() method to group records with a specified column:
rs = session.query(func.count(AdAccounts.Id).label("CustomCount"), AdAccounts.AccountId).group_by(AdAccounts.AccountId)
for instance in rs:
	print("Count: ", instance.CustomCount)
	print("AccountId: ", instance.AccountId)
	print("---------")

You can also use the session object's execute() method to perform a GROUP BY:

rs = session.execute(AdAccounts_table.select().with_only_columns([func.count(AdAccounts_table.c.Id).label("CustomCount"), AdAccounts_table.c.AccountId]).group_by(AdAccounts_table.c.AccountId))
for instance in rs:

LIMIT and OFFSET

The following example uses the session object's query() method to skip the first 100 records and fetch the following 25:
rs = session.query(AdAccounts).limit(25).offset(100)
for instance in rs:
	print("Id: ", instance.Id)
	print("AccountId: ", instance.AccountId)
	print("Name: ", instance.Name)
	print("---------")

You can also use the session object's execute() method to set a LIMIT or OFFSET:

rs = session.execute(AdAccounts_table.select().limit(25).offset(100))
for instance in rs:

CData Python Connector for Facebook Ads

Aggregate Functions

Certain aggregate functions can also be used within SQLAlchemy by using the func module.

To import this module, execute:

from sqlalchemy.sql import func

Once func is imported, the following aggregate functions are available:

COUNT

The following example counts the number of records in a set of groups using the session object's query() method.
rs = session.query(func.count(AdAccounts.Id).label("CustomCount"), AdAccounts.AccountId).group_by(AdAccounts.AccountId)
for instance in rs:
	print("Count: ", instance.CustomCount)
	print("AccountId: ", instance.AccountId)
	print("---------")

You can also execute COUNT using the session object's execute() method:

rs = session.execute(AdAccounts_table.select().with_only_columns([func.count(AdAccounts_table.c.Id).label("CustomCount"), AdAccounts_table.c.AccountId])group_by(AdAccounts_table.c.AccountId))
for instance in rs:

SUM

This example calculates the cumulative amount of a numeric column in a set of groups.

rs = session.query(func.sum(AdAccounts.AnnualRevenue).label("CustomSum"), AdAccounts.AccountId).group_by(AdAccounts.AccountId)
for instance in rs:
	print("Sum: ", instance.CustomSum)
	print("AccountId: ", instance.AccountId)
	print("---------")

You can also invoke SUM using the session object's execute() method.

rs = session.execute(AdAccounts_table.select().with_only_columns([func.sum(AdAccounts_table.c.AnnualRevenue).label("CustomSum"), AdAccounts_table.c.AccountId]).group_by(AdAccounts_table.c.AccountId))
for instance in rs:

AVG

This example uses the session object's query() method to calculate the average amount of a numeric column in a set of groups:
rs = session.query(func.avg(AdAccounts.AnnualRevenue).label("CustomAvg"), AdAccounts.AccountId).group_by(AdAccounts.AccountId)
for instance in rs:
	print("Avg: ", instance.CustomAvg)
	print("AccountId: ", instance.AccountId)
	print("---------")

You can also use the session object's execute() method to invoke AVG:

rs = session.execute(AdAccounts_table.select().with_only_columns([func.avg(AdAccounts_table.c.AnnualRevenue).label("CustomAvg"), AdAccounts_table.c.AccountId]).group_by(AdAccounts_table.c.AccountId))
for instance in rs:

MAX and MIN

This example finds the maximum value and minimum value of a numeric column in a set of groups.
rs = session.query(func.max(AdAccounts.AnnualRevenue).label("CustomMax"), func.min(AdAccounts.AnnualRevenue).label("CustomMin"), AdAccounts.AccountId).group_by(AdAccounts.AccountId)
for instance in rs:
	print("Max: ", instance.CustomMax)
	print("Min: ", instance.CustomMin)
	print("AccountId: ", instance.AccountId)
	print("---------")

You can also use the session object's execute() method to invoke MAX and MIN:

rs = session.execute(AdAccounts_table.select().with_only_columns([func.max(AdAccounts_table.c.AnnualRevenue).label("CustomMax"), func.min(AdAccounts_table.c.AnnualRevenue).label("CustomMin"), AdAccounts_table.c.AccountId]).group_by(AdAccounts_table.c.AccountId))
for instance in rs:

CData Python Connector for Facebook Ads

From Pandas

When combined with the connector, Pandas can be used to generate data frames that contain your Facebook Ads data. Once created, a data frame can be passed to various other Python packages.

Connecting

Pandas relies on an SQLAlchemy engine to execute queries. Before you can use Pandas you must import it:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("facebookads:///?InitiateOAuth=GETANDREFRESH;")

Querying Data

In Pandas, SELECT queries are provided in a call to the read_sql() method, alongside a relevant connection object. Pandas executes the query on that connection, and returns the results in the form of a data frame, which can be used for a variety of purposes.
df = pd.read_sql("""
	SELECT
	   AccountId,
	   Name,
     $exNumericCol;
	FROM AdAccounts;""", engine)
print(df)

CData Python Connector for Facebook Ads

From Matplotlib

Matplotlib contains a number of tools that can graphically model Facebook Ads data after being fed a data frame From Pandas.

Using PyPlot

Before any Matplotlib tool, such as pyplot, can be used, it must be imported:
from matplotlib import pyplot as plt

Once a Pandas data frame is obtained, it can be used to create a plot visualizing Facebook Ads data. For example, the following plot generates and displays a bar graph relating AccountId and AnnualRevenue values:

df.plot(kind="bar", x="AccountId", y=["AnnualRevenue"])
plt.show()

CData Python Connector for Facebook Ads

From Petl

The connector can be used to create ETL applications and pipelines for CSV data in Python using Petl.

Install Required Modules

Install the Petl modules using the pip utility.
pip install petl

Connecting

After you import the modules, including the CData Python Connector for Facebook Ads, you can use the connector's connect function to create a connection using a valid Facebook Ads connection string. If you prefer not to use a direct connection, you can use a SQLAlchemy engine.
import petl as etl
import cdata.facebookads as mod
cnxn = mod.connect("InitiateOAuth=GETANDREFRESH;")

Extract, Transform, and Load the Facebook Ads Data

Create a SQL query string and store the query results in a DataFrame.
sql = "SELECT	AccountId, Name FROM AdAccounts "
table1 = etl.fromdb(cnxn,sql)

Loading Data

With the query results stored in a DataFrame, you can load your data into any supported Petl destination. The following example loads the data into a CSV file.
etl.tocsv(table1,'output.csv')

CData Python Connector for Facebook Ads

Schema Discovery

The extension supports schema discovery by using SQL queries to available System Tables.

Using SQL

The following sections describe the discovery of metadata through several System Tables:

CData Python Connector for Facebook Ads

Tables and Views

The connector possesses system tables that are used to discover the tables and views available in the data model. Of these system tables, "sys_tables" and "sys_views" are used to fetch information about the available tables and views respectively:

Tables


import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")
cur = conn.cursor()
cmd = "SELECT * FROM sys_tables"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

Views


import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")
cur = conn.cursor()
cmd = "SELECT * FROM sys_views"
cur.execute(cmd, params)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for Facebook Ads

Columns

The available columns for any given table are fetched from a system table called "sys_tablecolumns". A specific table name is provided in the WHERE criteria to restrict the table from which the column information is fetched:

import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")
cur = conn.cursor()
cmd = "SELECT * FROM sys_tablecolumns WHERE TableName = 'AdAccounts'"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for Facebook Ads

Procedures

Procedures

A system table called "sys_procedures" is queried to obtain the available stored procedures that are executed:
import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")
cur = conn.cursor()
cmd = "SELECT * FROM sys_procedures"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

Parameters

The input parameters of any stored procedure are similarly obtained from the "sys_procedureparameters" system table:
import cdata.facebookads as mod
conn = mod.connect("InitiateOAuth=GETANDREFRESH;")
cur = conn.cursor()
cmd = "SELECT * FROM sys_procedureparameters WHERE ProcedureName = 'GetOAuthAccessToken'"
cur.execute(cmd)
rs = cur.fetchall()
for row in rs:
	print(row)

CData Python Connector for Facebook Ads

Advanced Features

This section details a selection of advanced features of the Facebook Ads connector.

User Defined Views

The connector supports the use of user defined views, virtual tables whose contents are decided by a pre-configured user defined query. These views are useful when you cannot directly control queries being issued to the drivers. For an overview of creating and configuring custom views, see User Defined Views .

SSL Configuration

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

Firewall and Proxy

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

Caching Data

Caching Data enables faster access to data and reduces the number of API calls, improving performance. The connector supports a simple caching model where multiple connections can also share the cache over time. When configuring the cache connection, you can specify automatic or explicit data caching.

Query Processing

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

For further information, see Query Processing.

Logging

For an overview of configuration settings that can be used to refine CData logging, see Logging. Only two connection properties are required for basic logging, but there are numerous features that support more refined logging, which enables you to use the LogModules connection property to specify subsets of information to be logged.

Exception Handling

For an overview of how exceptions are reported and the components of an exception, see Exception Handling.

CData Python Connector for Facebook Ads

User Defined Views

The CData Python Connector for Facebook Ads supports the use of user defined views: user-defined virtual tables whose contents are decided by a preconfigured query. User defined views are useful in situations where you cannot directly control the query being issued to the driver; for example, when using the driver from a tool.

Use a user defined view to define predicates that are always applied. If you specify additional predicates in the query to the view, they are combined with the query already defined as part of the view.

There are two ways to create user defined views:

  • Create a JSON-formatted configuration file defining the views you want.
  • DDL statements.

Defining Views Using a Configuration File

User defined views are defined in a JSON-formatted configuration file called UserDefinedViews.json. The connector automatically detects the views specified in this file.

You can also have multiple view definitions and control them using the UserDefinedViews connection property. When you use this property, only the specified views are seen by the connector.

This user defined view configuration file is formatted so that each root element defines the name of a view, and includes a child element, called query, which contains the custom SQL query for the view.

For example:

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

Defining Views Using DDL Statements

The connector is also capable of creating and altering the schema via DDL Statements such as CREATE LOCAL VIEW, ALTER LOCAL VIEW, and DROP LOCAL VIEW.

Create a View

To create a new view using DDL statements, provide the view name and query as follows:

CREATE LOCAL VIEW [MyViewName] AS SELECT * FROM Customers LIMIT 20;

If no JSON file exists, the above code creates one. The view is then created in the JSON configuration file and is now discoverable. The JSON file location is specified by the UserDefinedViews connection property.

Alter a View

To alter an existing view, provide the name of an existing view alongside the new query you would like to use instead:

ALTER LOCAL VIEW [MyViewName] AS SELECT * FROM Customers WHERE TimeModified > '3/1/2020';

The view is then updated in the JSON configuration file.

Drop a View

To drop an existing view, provide the name of an existing schema alongside the new query you would like to use instead.

DROP LOCAL VIEW [MyViewName]

This removes the view from the JSON configuration file. It can no longer be queried.

Schema for User Defined Views

In order to avoid a view's name clashing with an actual entity in the data model, user defined views are exposed in the UserViews schema by default. To change the name of the schema used for UserViews, reset the UserViewsSchemaName property.

Working with User Defined Views

For example, a SQL statement with a user defined view called UserViews.RCustomers only lists customers in Raleigh:
SELECT * FROM Customers WHERE City = 'Raleigh';
An example of a query to the driver:
SELECT * FROM UserViews.RCustomers WHERE Status = 'Active';
Resulting in the effective query to the source:
SELECT * FROM Customers WHERE City = 'Raleigh' AND Status = 'Active';
That is a very simple example of a query to a user defined view that is effectively a combination of the view query and the view definition. It is possible to compose these queries in much more complex patterns. All SQL operations are allowed in both queries and are combined when appropriate.

CData Python Connector for Facebook Ads

SSL Configuration

Customizing the SSL Configuration

By default, the connector attempts to negotiate TLS with the server. The server certificate is validated against the default system trusted certificate store. You can override how the certificate gets validated using the SSLServerCert connection property.

To specify another certificate, see the SSLServerCert connection property.

CData Python Connector for Facebook Ads

Firewall and Proxy

Connecting Through a Firewall or Proxy

HTTP Proxies

Note: The connector uses the system proxy settings by default, without further configuration needed. If you want to connect to other proxies, set ProxyAutoDetect to False and read further.

To authenticate to an HTTP proxy, set the following:

  • ProxyServer: the hostname or IP address of the proxy server that you want to route HTTP traffic through.
  • ProxyPort: the TCP port that the proxy server is running on.
  • ProxyAuthScheme: the authentication method the connector uses when authenticating to the proxy server.
  • ProxyUser: the username of a user account registered with the proxy server.
  • ProxyPassword: the password associated with the ProxyUser.

Other Proxies

Set the following properties:

CData Python Connector for Facebook Ads

Caching Data

Caching Data

Caching data provides several benefits, including faster access to data and reducing the number of API calls, which improve performance. The connector supports a simple caching model where multiple connections can also share the cache over time. You can enable and configure caching features by setting the necessary connection properties.

Contents

The sections in this chapter detail the connector's caching functionality and link to the corresponding connection properties, as well as SQL statements.

Configuring the Cache Connection

Configuring the Cache Connection describes the properties that you can set when configuring the cache database.

Caching Metadata

Caching Metadata describes the CacheMetadata property. This property determines whether or not to cache the table metadata to a file store.

Automatically Caching Data

Automatically Caching Data describes how the connector automatically refreshes the cache when the AutoCache property is set.

Explicitly Caching Data

Explicitly Caching Data describes how you can decide what data is stored in the cache and when it is updated.

Data Type Mapping

Data Type Mapping shows the mappings between the data types configured in the schema and the data types in the database.

CData Python Connector for Facebook Ads

Configuring the Cache Connection

Configuring the Caching Database

This section describes the properties for caching data to the persistent store of your choice.

CacheLocation

The CacheLocation property species the path to a file-system-based database. When caching is enabled, a file-system-based database is used by default. If CacheLocation is not specified, this database is stored at the path in Location. If neither of these connection properties are specified, the connector uses a platform-dependent default location.

CacheConnection

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

CacheDriver and CacheProvider

Both the CacheDriver and CacheProvider properties are supported. Each specifies a database driver and the connection string to the caching database. CacheDriver is designed for Linux and MacOS; CacheProvider is Windows-based.

CData Python Connector for Facebook Ads

Automatically Caching Data

Automatically caching data is useful when you do not want to rebuild the cache for each query. When you query data for the first time, the connector automatically initializes and builds a cache in the background. When AutoCache = true, the connector uses the cache for subsequent query executions, resulting in faster response times.

If replication is enabled, the data is generated once and then copied to local and cloud data stores. With incremental updates, the connector achieves a performance advantage over dropping the cached tables and retrieving the entire table again on every refresh. With iterative updates, the connector only performs the query from the last time that the date was refreshed. If replication is not enabled, updates to the cache require downloading the entire data set.

Configuring Automatic Caching

To automatically update the cache and return results from the local cache, set the following connection string properties:

  • AutoCache: This property automatically updates the cache when the value is set to true.
  • CacheTolerance: This property ensures that the data retrieved from the database is the most current version. The default value is 600 seconds (10 minutes). The connector checks with the data source for newer records after the tolerance interval has expired. Otherwise, it returns the data directly from the cache.

Caching the AdAccounts Table

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

SELECT AccountId, Name FROM AdAccounts WHERE Name = 'Act Name'

Common Use Case

A common use for automatically caching data is to improve driver performance when making repeated requests to a live data source, such as building a report or creating a visualization. With auto caching enabled, repeated requests to the same data may be executed in a short period of time, but within an allowable tolerance (CacheTolerance) of what is considered "live" data.

CData Python Connector for Facebook Ads

Explicitly Caching Data

With explicit caching (AutoCache = false), you decide exactly what data is cached and when to query the cache instead of the live data. Explicit caching gives you full control over the cache contents by using CACHE Statements. This section describes some strategies to use the caching features offered by the connector.

Creating the Cache

To load data in the cache, issue the following statement.

CACHE SELECT * FROM tableName WHERE ...

Once the statement is issued, any matching data in tableName is loaded into the corresponding table.

Updating the Cache

This section describes two ways to update the cache.

Updating with the SELECT Statement

The following example shows a statement that can update modified rows and add missing rows in the cached table. However, this statement does not delete extra rows that are already in the cache. This statement only merges the new rows or updates the existing rows.

CACHE SELECT * FROM AdAccounts WHERE Name = 'Act Name'

Updating with the TRUNCATE Statement

The following example shows a statement that can update modified rows and add missing rows in the cached table. This statement can also delete rows in the cache table that are not present in the live data source.

  CACHE WITH TRUNCATE SELECT * FROM AdAccounts WHERE Name = 'Act Name'
  

Query the Data in Online or Offline Mode

This section describes how to query the data in online or offline mode.

Online: Select Cached Tables

You can use the tableName#CACHE syntax to explicitly execute queries to the cache while still online, as shown in the following example.

SELECT * FROM AdAccounts#CACHE

Offline: Select Cached Tables

With Offline = true, SELECT statements always execute against the local cache database, regardless of whether you explicitly specify the cached table or not. Modification of the cache is disabled in Offline mode to prevent accidentally updating only the cached data. Executing a DELETE/UPDATE/INSERT statement while in Offline mode results in an exception.

The following example selects from the local cache but not the live data source because Offline = true.

SELECT * FROM AdAccounts WHERE Name='Act Name' ORDER BY Name ASC

Delete Data from the Cache

You can delete data from the cache by building a direct connection to the database. Note that the connector does not support manually deleting data from the cache.

Common Use Case

A common use for caching is to have an application always query the cached data and only update the cache at set intervals, such as once every day or every two hours. There are two ways in which this can be implemented:

  • AutoCache = false and Offline = false. All queries issued by the application explicitly reference the tableName#CACHE table. When the cache needs to be updated, the application executes a tableName#CACHE ... statement to bring the cached data up to date.
  • Offline = true. Caching is transparent to the application. All queries are executed against the table as normal, so most application code does not need to be aware that caching is done. To update the cached data, simply create a separate connection with Offline = false and execute a tableName#CACHE ... statement.

CData Python Connector for Facebook Ads

Data Type Mapping

The connector maps types from the data source to the corresponding data type available in the chosen cache database. The following table shows the mappings between the data types configured in the schema and the data types in the database. Some schema types have synonyms which are all listed in the Schema column.

Data Type Mapping

Note: String columns can map to different data types depending on their length.

Schema .NET JDBC SQL Server Derby MySQL Oracle SQLite Access
int, integer, int32 Int32 int int INTEGER INT NUMBER integer LONG
smallint, short, int16 Int16 short smallint SMALLINT SMALLINT NUMBER integer SHORT
double, float, real Double double float DOUBLE DOUBLE NUMBER double DOUBLE
date DateTime java.sql.Date date DATE DATE DATE date DATETIME
datetime, timestamp DateTime java.sql.Date datetime TIMESTAMP DATETIME TIMESTAMP datetime DATETIME
time, timespan TimeSpan java.sql.Time time TIME TIME TIMESTAMP datetime DATETIME
string, varchar String java.lang.String If length > 4000: nvarchar(max), Otherwise: nvarchar(length)If length > 32672: LONG VARCHAR, Otherwise VARCHAR(length)If length > 255: LONGTEXT, Otherwise: VARCHAR(length)If length > 4000: CLOB, Otherwise: VARCHAR2(length)nvarchar(length)If length > 255: LONGTEXT, Otherwise: VARCHAR(length)
long, int64, bigint Int64 long bigint BIGINT BIGINT NUMBER bigint LONG
boolean, bool Boolean boolean tinyint SMALLINT BIT NUMBER tinyint BIT
decimal, numeric Decimal java.math.BigDecimal decimal DECIMAL DECIMAL DECIMAL decimal CURRENCY
uuid Guid java.util.UUID nvarchar(length) VARCHAR(length)VARCHAR(length) VARCHAR2(length)nvarchar(length) VARCHAR(length)
binary, varbinary, longvarbinary byte[] byte[] binary(1000) or varbinary(max) after SQL Server 2000, image otherwise BLOB LONGBLOB BLOB BLOB LONGBINARY

CData Python Connector for Facebook Ads

Query Processing

Query Processing

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

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

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

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

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

More Information

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

CData Python Connector for Facebook Ads

Logging

Logging

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

Basic Logging

To begin capturing connector logging, set these properties:

  • Logfile: A filepath that designates the name and location of the log file.
  • Verbosity: A numerical value (1-5) that determines the amount of detail in the log. See the page in the Connection Properties section for an explanation of the five levels.
  • MaxLogFileSize: When the limit is hit, a new log is created in the same folder with the date and time appended to the end. The default limit is 100 MB. Values lower than 100 kB will use 100 kB as the value instead.
  • MaxLogFileCount: A string specifying the maximum file count of log files. When the limit is hit, a new log is created in the same folder with the date and time appended to the end and the oldest log file will be deleted. Minimum supported value is 2. A value of 0 or a negative value indicates no limit on the count.

Once these properties are set, the connector populates the log file as it carries out various tasks, such as when authentication is performed or queries are executed. If the specified file doesn't already exist, it is created.

Log Verbosity

The verbosity level determines the amount of detail that the connector reports to the Logfile. Supported Verbosity levels range from 1 to 5.

The following list describes each level:

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

For normal operations, Verbosity should not be set to greater than 1. At higher verbosities you can log substantial amounts of data, which can delay execution times.

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

Sensitive Data

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

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

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

Advanced Logging

You may want to refine the exact information that is recorded to the log file. This can be accomplished using the LogModules property. This property allows you to filter the logging using a semicolon-separated list of logging modules.

Example property value:

LogModules=INFO;EXEC;SSL;SQL;META;

Note that the logfile filtering triggered by the Verbosity connection property takes precedence over the filtering imposed by this connection property. This means that operations of a higher verbosity level than the level specified in the Verbosity connection property are not printed in the logfile, even if they belong to one of the modules specified in this connection property.

The available modules and submodules are:

Module Name Module Description Submodules
INFO General Information. Includes the connection string, product version (build number), and initial connection messages.
  • Connec – Information related to creating or destroying connections.
  • Messag – Generic label for messages pertaining to connections, the connection string, and product version. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
EXEC Query Execution. Includes execution messages for user-written SQL queries, parsed SQL queries, and normalized SQL queries. Success/failure messages for queries and query pages appear here as well.
  • Messag – Messages pertaining to query execution. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Normlz – Query normalization steps. Query normalization is when the product takes the user-submitted query and rewrites the query to get the same results with optimal performance.
  • Origin – This label applies to any messages recording a user's original query (the exact, unaltered, non-normalized query executed by the user).
  • Page – Messages related to query paging.
  • Parsed – Query parsing steps. Parsing is the process of converting the user-submitted query into a standardized format for easier processing.
HTTP HTTP protocol messages. Includes HTTP requests/responses (including POST messages), as well as Kerberos related messages.
  • KERB – HTTP requests related to Kerberos.
  • Messag – Messages pertaining to HTTP protocols. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Unpack – This label applies to messages about zipped data being returned from the service API and unpacked by the product.
  • Res – Messages containing HTTP responses.
  • Req – Messages containing HTTP requests.
WSDL Messages pertaining to the generation of WSDL/XSD files.
SSL SSL certificate messages.
  • Certif – Messages pertaining to SSL certificates.
AUTH Authentication related failure/success messages.
  • Messag – Messages pertaining to authentication. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • OAuth – Messages related to OAuth authentication.
  • Krbros – Kerberos-related authentication messages.
SQL Includes SQL transactions, SQL bulk transfer messages, and SQL result set messages.
  • Bulk – Messages pertaining to bulk query execution.
  • Cache – Messages related to reading row data from and writing row data to the product's cache for better performance.
  • Messag – Messages pertaining to SQL transactions. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • ResSet – Query resultsets.
  • Transc – Messages related to handling transactions, including information about the number of jobs executed and backup table handling.
META Metadata cache and schema messages.
  • Cache – Messages related to reading from and modifying column and table definitions in the product's cache for better performance.
  • Schema – Messages related to retrieving metadata from or modifying the service schema.
  • MemSto – Messages related to writing to or reading from in-memory metadata cache.
  • Storag – Messages relating to storing metadata on disk or in an external data store, rather than in memory.
FUNC Information related to executing SQL functions.
  • Errmsg – Error messages related to executing SQL functions.
TCP Incoming and outgoing raw bytes on TCP transport layer messages.
  • Send – Raw data sent via the TCP protocol.
  • Receiv – Raw data received via the TCP protocol.
FTP Messages pertaining to the File Transfer Protocol.
  • Info – Status messages related to communication in the FTP protocol.
  • Client – Messages related to actions taken by the FTP client (the product) during FTP communication.
  • Server – Messages related to actions taken by the FTP server during FTP communication.
SFTP Messages pertaining to the Secure File Transfer Protocol.
  • Info – Status messages related to communication in the SFTP protocol.
  • To_Server – Messages related to actions taken by the SFTP client (the product) during SFTP communication.
  • From_Server – Messages related to actions taken by the SFTP server during SFTP communication.
POP Messages pertaining to data transferred via the Post Office Protocol.
  • Client – Messages related to actions taken by the POP client (the product) during POP communication.
  • Server – Messages related to actions taken by the POP server during POP communication.
  • Status – Status messages related to communication in the POP protocol.
SMTP Messages pertaining to data transferred via the Simple Mail Transfer Protocol.
  • Client – Messages related to actions taken by the SMTP client (the product) during SMTP communication.
  • Server – Messages related to actions taken by the SMTP server during SMTP communication.
  • Status – Status messages related to communication in the SMTP protocol.
CORE Messages relating to various internal product operations not covered by other modules.
DEMN Messages related to SQL remoting.
CLJB Messages about bulk data uploads (cloud job).
  • Commit – Submissions for bulk data uploads.
SRCE Miscellaneous messages produced by the product that don't belong in any other module.
TRANCE Advanced messages concerning low-level product operations.

CData Python Connector for Facebook Ads

Exception Handling

Exception Handling

Exceptions can be surfaced from either the API or the CData Python Connector for Facebook Ads. Each exception will have an error code, an error message, and a SQL state.

Error Codes

The error code classifies the type of error.

0 NONE Used for unclassified errors and internally handled errors. This code also covers data source-specific errors that do not fit in any specific category.
65537 TCP_UNKNOWN_HOST Unable to resolve a hostname (DNS failure).
65538 TCP_CONNECTION_REFUSED Could not connect to the remote port.
65539 TCP_AUTH_FAILED Login failed when using a binary authentication protocol. Use this for auth errors when the protocol is not HTTP (LDAP, SASL, Kerberos, ...).
65540 TCP_TIMEOUT Did not receive a response after sending a request to the server.
65541 TCP_PROTOCOL For wire protocol drivers. Either the server sent a bad packet that we are unable to process, or we cannot construct a packet to send.
131073 TLS_SERVER_UNTRUSTED Could not verify SSL server certificate.
131074 TLS_CLIENT_UNTRUSTED Server did not accept the client certificate we sent.
196609 OAUTH_DECRYPT_FAILED OAuthEncryptKey did not decrypt the OAuthSettings file.
196610 OAUTH_MISSING_CLIENT_INFO OAuthClientId / OAuthClientSecret / OAuthJWTCert is missing.
196611 OAUTH_MISSING_PROP General OAuth property missing. OAUTH_MISSING_CLIENT_INFO is used for missing client ID/secret and JWT cert.
196612 OAUTH_NO_ACCESS_TOKEN Unable to retrieve access token. Only use this when getting a token in GetOAuthAccessToken / RefreshOAuthAccessToken.
196613 OAUTH_TOKEN_EXPIRED The access token expired. Normally used with a RefreshOAuth/OAuthException behavior.
196614 OAUTH_INVALID_PROP OAuth property has an invalid value. OAUTH_MISSING_CLIENT_INFO / OAUTH_MISSING_PROP is used if the value is not set.
262145 HTTP_REQUEST_TIMEOUT Did not receive a response from the HTTP server.
262146 HTTP_CLIENT_ERROR Generic HTTP 4xx error. Only use for 4xx errors not covered by other codes.
262147 HTTP_AUTH_FAILED HTTP 401 error.
262148 HTTP_LIMIT_EXCEEDED HTTP 429 error.
262149 HTTP_SERVER_ERROR HTTP 5xx error.
262150 HTTP_NOT_FOUND_ERROR HTTP 404 error.
327681 CORE_TIMEOUT General timeout. Not related to a specific network request.
327682 CORE_OP_NOT_ALLOWED Operation blocked by provider permissions.
327683 CORE_CONNECTION_CONFIG Connection configuration is not valid.
327684 CORE_SERIALIZE Failed to encode data into a specific format (XML, JSON, CSV, ...).
327685 CORE_DESERIALIZE Failed to decode data from a specific format (XML, JSON, CSV, ...).
393217 SQL_SYNTAX_ERROR Unable to parse a SQL query.
393218 SQL_MISSING_COLUMNS Query did not include required columns.
393219 SQL_MISSING_PARAMS Stored procedure call did not include required parameters.
393220 SQL_QUERY_NOT_SUPPORTED A part of the query is not allowed in the current context.
458753 SSH_SERVER_UNTRUSTED Could not verify SSH server.
524289 STORAGE_LIST_EXCEPTION Issue listing storage resources.
524290 STORAGE_RESOURCE_NOT_FOUND Issue finding storage resources.
524291 STORAGE_ROOT_RESOURCE_NOT_FOUND The root resource (bucket/share/drive) was not found; cannot create it in flat file drivers.
524292 STORAGE_RESOURCE_NOT_A_DIRECTORY Storage resource is not a directory.
524293 STORAGE_RESOURCE_NOT_A_FILE Storage resource is not a file.
524294 STORAGE_PERMISSIONS_DENIED Storage permissions denied.

SQL State

The SQL state is used when throwing generic provider errors to the wrapper and indicates the success or failure of a call.

Some of the common SQL states are listed below:

07007 REQUIRED_CLAUSE Class Code 07: Dynamic SQL Error.
08001 OPEN_CONNECTION Class Code 08: Connection Exception. The connection was unable to be established to the application server or other server.
08004 REJECT_CONNECTION The application server rejected establishment of the connection.
42501 PRIVILEGE_IDENTIFIED_OBJECT Class Code 42: Syntax Error or Access Rule Violation. The authorization ID does not have the privilege to perform the specified operation on the identified object.
42506 AUTH_FAILED Owner authorization failure occurred.
42601 SQL_SYNTAX A character, token, or clause is invalid or missing.

Error Message

The error message provides more detailed reasoning about why the error occurred. It provides an explanation of the issue, and may include steps on how to resolve it.

CData Python Connector for Facebook Ads

SQL Compliance

SELECT Statements

See SELECT Statements for a syntax reference and examples.

See Data Model for information on the capabilities of the Facebook Ads API.

CACHE Statements

CACHE statements allow granular control over the connector's caching functionality. For a syntax reference and examples, see CACHE Statements.

For more information on the caching feature, see Caching Data.

EXECUTE Statements

Use EXECUTE or EXEC statements to execute stored procedures. See EXECUTE Statements for a syntax reference and examples.

Names and Quoting

  • Table and column names are considered identifier names; as such, they are restricted to the following characters: [A-Z, a-z, 0-9, _:@].
  • To use a table or column name with characters not listed above, the name must be quoted using square brackets ([name]) in any SQL statement.
  • Parameter names can optionally start with the @ symbol (e.g., @p1 or @CustomerName) and cannot be quoted.
  • Strings must be quoted using single quotes (e.g., 'John Doe').

CData Python Connector for Facebook Ads

SQL Functions

The connector provides functions that are similar to those that are available with most standard databases. These functions are implemented in the CData provider engine and thus are available across all data sources with the same consistent API. Three categories of functions are available: string, date, and math.

The connector interprets all SQL function inputs as either strings or column identifiers, so you need to escape all literals as strings, with single quotes. For example, contrast the SQL Server syntax and connector syntax for the DATENAME function:

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

String Functions

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

Date Functions

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

Math Functions

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

CData Python Connector for Facebook Ads

STRING Functions

ASCII(character_expression)

Returns the ASCII code value of the left-most character of the character expression.

  • character_expression: The character expression.

                      SELECT ASCII('0');
                      --  Result: 48
                    

BASE64_ENCODE(input_binary)

Returns the Base64-encoded string form of a binary input.

  • input_binary: The binary value to encode.

                        SELECT BASE64_ENCODE(BinaryData);
                    -- Result: 'QmFzZTY0RW5jb2RlZA=='
                    

BASE64_DECODE(input_string)

Returns the binary result of decoding a Base64-encoded string.

  • input_string: The Base64-encoded string.

                        SELECT BASE64_DECODE('QmFzZTY0RW5jb2RlZA==');
                    -- Result: (binary output)
                    

CHAR(integer_expression)

Converts the integer ASCII code to the corresponding character.

  • integer_expression: The integer from 0 through 255.

                      SELECT CHAR(48);
                      -- Result: '0'
                    

CHARINDEX(expressionToFind ,expressionToSearch [,start_location ])

Returns the starting position of the specified expression in the character string.

  • expressionToFind: The character expression to find.
  • expressionToSearch: The character expression, typically a column, to search.
  • start_location: An optional character position to start searching for expressionToFind in expressionToSearch.

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

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

CHAR_LENGTH(character_expression),

Returns the number of UTF-8 characters present in the expression.

  • character_expression: The set of characters to be evaluated for length.

				 SELECT CHAR_LENGTH('sample text') FROM Account LIMIT 1
				 -- Result: 11			
				

CONCAT(string_value1, string_value2, ..., string_valueN)

Returns the string that is the concatenation of two or more string values.

  • string_value1: The first string to be concatenated.
  • string_value2: The second string to be concatenated.
  • string_valueN: (optional) Any additional strings to be concatenated.

                      SELECT CONCAT('Hello, ', 'world!');
                      -- Result: 'Hello, world!'
                    

CONTAINS(expressionToSearch, expressionToFind)

Returns 1 if expressionToFind is found within expressionToSearch; otherwise, 0.

  • expressionToSearch: The character expression, typically a column, to search.
  • expressionToFind: The character expression to find.

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

                      SELECT CONTAINS('0123456', 'Not a number');
                      -- Result: 0
                    

ENDSWITH(character_expression, character_suffix)

Returns 1 if character_expression ends with character_suffix; otherwise, 0.

  • character_expression: The character expression.
  • character_suffix: The character suffix to search for.

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

                      SELECT ENDSWITH('0123456', '012');
                      -- Result: 0
                    

FILESIZE(uri)

Returns the number of bytes present in the file at the specified file path.

  • uri: The path of the file from which to read the size.

				SELECT FILESIZE('C:/Users/User1/Desktop/myfile.txt');
				-- Result: 23684
				

FORMAT(value [, parseFormat], format )

Returns the value formatted with the specified format.

  • value: The string to format.
  • format: The string specifying the output syntax of the date or numeric format.
  • parseFormat: The string specifying the input syntax of the date value. Not applicable to numeric types.

                      SELECT FORMAT(12.34, '#');
                      -- Result: 12

                      SELECT FORMAT(12.34, '#.###');
                      -- Result: 12.34

                      SELECT FORMAT(1234, '0.000E0');
                      -- Result: 1.234E3
                      
                      SELECT FORMAT('2019/01/01', 'yyyy-MM-dd');
                      -- Result: 2019-01-01
                      
                      SELECT FORMAT('20190101', 'yyyyMMdd', 'yyyy-MM-dd');
                      -- Result: '2019-01-01'
                    

HASHBYTES(algorithm, value)

Returns the hash of the input value as a byte array using the given algorithm. The supported algorithms are MD5, SHA1, SHA2_256, SHA2_512, SHA3_224, SHA3_256, SHA3_384, and SHA3_512.

  • algorithm: The algorithm to use for hashing. Must be one of MD5, SHA1, SHA2_256, SHA2_512, SHA3_224, SHA3_256, SHA3_384, or SHA3_512.
  • value: The value to hash. Must be either a string or byte array.

                      SELECT HASHBYTES('MD5', 'Test');
                      -- Result (byte array): 0x0CBC6611F5540BD0809A388DC95A615B
                    

INDEXOF(expressionToSearch, expressionToFind [,start_location ])

Returns the starting position of the specified expression in the character string.

  • expressionToSearch: The character expression, typically a column, to search.
  • expressionToFind: The character expression to find.
  • start_location: An optional character position to start searching for expressionToFind in expressionToSearch.

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

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

ISALPHABETIC(character_expression)

Returns 1 if the character expression consists only of alphabetic characters; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISALPHABETIC('Hello');
                      -- Result: 1

                      SELECT ISALPHABETIC('Hello123');
                      -- Result: 0

                      SELECT ISALPHABETIC('Hello!');
                      -- Result: 0
                    

ISALPHANUMERIC(character_expression)

Returns 1 if the character expression consists only of alphabetic and numeric characters; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISALPHANUMERIC('Hello123');
                      -- Result: 1

                      SELECT ISALPHANUMERIC('123');
                      -- Result: 1

                      SELECT ISALPHANUMERIC('Hello.123');
                      -- Result: 0
                    

ISNUMERIC(character_expression)

Returns 1 if the character expression consists only of numeric digits and up to one decimal point; otherwise, 0.

  • character_expression: The string expression to evaluate.

                      SELECT ISNUMERIC('123');
                      -- Result: 1

                      SELECT ISNUMERIC('123.45');
                      -- Result: 1

                      SELECT ISNUMERIC('123.45.67');
                      -- Result: 0

                      SELECT ISNUMERIC('12a3');
                      -- Result: 0
                    

JSON_EXTRACT(json, jsonpath)

Selects any value in a JSON array or object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to extract.
  • jsonpath: The XPath used to select the nodes. The JSONPath must be a string constant. The values of the nodes selected will be returned in a token-separated list.

                      SELECT JSON_EXTRACT('{"test": {"data": 1}}', '$.test');
                      -- Result: '{"data":1}'

                      SELECT JSON_EXTRACT('{"test": {"data": 1}}', '$.test.data');
                      -- Result: 1

                      SELECT JSON_EXTRACT('{"test": {"data": [1, 2, 3]}}', '$.test.data[1]');
                      -- Result: 2
                    

LEFT ( character_expression , integer_expression )

Returns the specified number of characters counting from the left of the specified string.

  • character_expression: The character expression.
  • integer_expression: The positive integer that specifies how many characters will be returned counting from the left of character_expression.

                      SELECT LEFT('1234567890', 3);
                      -- Result: '123'
                    

LEN(string_expression)

Returns the number of characters of the specified string expression.

  • string_expression: The string expression.

                      SELECT LEN('12345');
                      -- Result: 5
                    

LOCATE(substring,string)

Returns an integer representing how many characters into the string the substring appears.

  • substring: The substring to find inside larger string.
  • string: The larger string that is searched for the substring.
  • start locations: An optional integer that sets the character position (offset) from which to start searching.

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

                SELECT LOCATE('sample', 'XXXXXsampleXXXXX', 7)
                -- Result: 0
				

LOWER ( character_expression )

Returns the character expression with the uppercase character data converted to lowercase.

  • character_expression: The character expression.

                      SELECT LOWER('MIXED case');
                      -- Result: 'mixed case'
                    

LTRIM(character_expression)

Returns the character expression with leading blanks removed.

  • character_expression: The character expression.

                      SELECT LTRIM('     trimmed');
                      -- Result: 'trimmed'
                    

MASK(string_expression, mask_character [, start_index [, end_index ]])

Replaces the characters between start_index and end_index with the mask_character within the string.

  • string_expression: The string expression to be searched.
  • mask_character: The character to mask with.
  • start_index: The optional number of characters to leave unmasked at beginning of string. Defaults to 0.
  • end_index: The optional number of characters to leave unmasked at end of string. Defaults to 0.

                        SELECT MASK('1234567890','*',);
                        -- Result: '**********'
                        SELECT MASK('1234567890','*', 4);
                        -- Result: '1234******'
                        SELECT MASK('1234567890','*', 4, 2);
                        -- Result: '1234****90'  
                    

NCHAR(integer_expression)

Returns the Unicode character with the specified integer code as defined by the Unicode standard.

  • integer_expression: The integer from 0 through 65535 (0 through xFFFF).

OCTET_LENGTH(character_expression),

Returns the number of bytes present in the expression.

  • character_expression: The set of characters to be be evaluated.

				 SELECT OCTET_LENGTH('text') FROM Account LIMIT 1
				 -- Result: 4
				

PATINDEX(pattern, expression)

Returns the starting position of the first occurrence of the pattern in the expression. Returns 0 if the pattern is not found.

  • pattern: The character expression that contains the sequence to be found. The wild-card character % can be used only at the start or end of the expression.
  • expression: The expression, typically a column, to search for the pattern.

                      SELECT PATINDEX('123%', '1234567890');
                      -- Result: 1

                      SELECT PATINDEX('%890', '1234567890');
                      -- Result: 8

                      SELECT PATINDEX('%456%', '1234567890');
                      -- Result: 4
                    

POSITION(expressionToFind IN expressionToSearch)

Returns the starting position of the specified expression in the character string.

  • expressionToFind: The character expression to find.
  • expressionToSearch: The character expression, typically a column, to search.

                      SELECT POSITION('456' IN '123456');
                      -- Result: 4

                      SELECT POSITION('x' IN '123456');
                      -- Result: 0
                    

QUOTENAME(character_string [, quote_character])

Returns a valid SQL Server-delimited identifier by adding the necessary delimiters to the specified Unicode string.

  • character_string: The string of Unicode character data. The string is limited to 128 characters. Inputs greater than 128 characters return null.
  • quote_character: An optional single character to be used as the delimiter. These include:
    • a single quotation mark (')
    • a left or right bracket ([])
    • a double quotation mark (")
    • a left or right parenthesis ( () )
    • a greater or less than sign (><)
    • a left or right brace ({})
    • a backtick (`)

    If quote_character is not specified brackets are used. If an unacceptable character is supplied, it returns NULL.


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

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

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

REGEXP_REPLACE(expr, pattern [, replacement [, position [, occurrence [, match_type]]]])

Replaces occurrences of a regular expression pattern in the input string with a specified value and returns the resulting string.

  • expr: The string expression to be searched.
  • pattern: The regular expression pattern to match.
  • replacement: (optional) The string to replace each matched occurrence of pattern with. Supports backreferences \1 through \9 and escape sequences \n, \r, \t, and \\. By default, this argument is an empty string, meaning matched portions are removed from the output string.
  • position: (optional) The 1-based starting position used when searching for regular expression matches in expr. The default is 1. All characters prior to the starting position are included in the output string unaltered. Skipped characters are ignored when calculating regular expression matches, even if they match pattern.
  • occurrence: (optional) Specifies whether all occurrences of pattern,, or only a specific occurrence of pattern are replaced. The default is 0, which means all occurrences of pattern are replaced with replacement. Set to 1 to only replace the first instance of the pattern; 2 to replace the second; etc.
  • match_type: (optional) Modifiers used to customize matching behavior. Supported values are: 'c' (case-sensitive, default), 'i' (case-insensitive), 'm' (multiline), 'n' (dot matches newline), 'x' (extended mode). These can be freely combined by including the letters back to back. For example, 'im' applies the functionality of both 'i' and 'm'. The regular expression syntax used is that of the Extended mode ('x') ignores whitespace and allows inline comments. If the pattern needs to match a literal space, it must be explicitly escaped.

                      SELECT REGEXP_REPLACE('abc123def456', '\d+', 'NUM');
                      -- Result: 'abcNUMdefNUM'

                      SELECT REGEXP_REPLACE('Hello\nHELLO\nhello', '^hello', 'X', 1, 0, 'im');
                      -- Result: 'X\nX\nX'
                    

REPLACE(string_expression, string_pattern, string_replacement)

Replaces all occurrences of a string with another string.

  • string_expression: The string expression to be searched. This can be a character or binary data type.
  • string_pattern: The substring to be found. Cannot be an empty string.
  • string_replacement: The replacement string.

                      SELECT REPLACE('1234567890', '456', '|');
                      -- Result: '123|7890'

                      SELECT REPLACE('123123123', '123', '.');
                      -- Result: '...'

                      SELECT REPLACE('1234567890', 'a', 'b');
                      -- Result: '1234567890'
                    

REPLICATE ( string_expression ,integer_expression )

Repeats the string value the specified number of times.

  • string_expression: The string to replicate.
  • integer_expression: The repeat count.

                      SELECT REPLACE('x', 5);
                      -- Result: 'xxxxx'
                    

REVERSE ( string_expression )

Returns the reverse order of the string expression.

  • string_expression: The string.

                      SELECT REVERSE('1234567890');
                      -- Result: '0987654321'
                    

RIGHT ( character_expression , integer_expression )

Returns the right part of the string with the specified number of characters.

  • character_expression: The character expression.
  • integer_expression: The positive integer that specifies how many characters of the character expression will be returned.

                      SELECT RIGHT('1234567890', 3);
                      -- Result: '890'
                    

RTRIM(character_expression)

Returns the character expression after it removes trailing blanks.

  • character_expression: The character expression.

                      SELECT RTRIM('trimmed     ');
                      -- Result: 'trimmed'
                    

SOUNDEX(character_expression)

Returns the four-character Soundex code, based on how the string sounds when spoken.

  • character_expression: The alphanumeric expression of character data.

                      SELECT SOUNDEX('smith');
                      -- Result: 'S530'
                    

SPACE(repeatcount)

Returns the string that consists of repeated spaces.

  • repeatcount: The number of spaces.

                      SELECT SPACE(5);
                      -- Result: '     '
                    

SPLIT(string, delimiter, offset)

Returns a section of the string between to delimiters.

  • string: The string to split.
  • delimiter: The character to split the string with.
  • offset: The number of the split to return. Positive numbers are treated as offsets from the left, and negative numbers are treated as offsets from the right.

                      SELECT SPLIT('a/b/c/d', '/', 1);
                      -- Result: 'a'
                      SELECT SPLIT('a/b/c/d', '/', -2);
                      -- Result: 'c'
                    

STARTSWITH(character_expression, character_prefix)

Returns 1 if character_expression starts with character_prefix; otherwise, 0.

  • character_expression: The character expression.
  • character_prefix: The character prefix to search for.

                      SELECT STARTSWITH('0123456', '012');
                      -- Result: 1

                      SELECT STARTSWITH('0123456', '456');
                      -- Result: 0
                    

STR ( float_expression [ , integer_length [ , integer_decimal ] ] )

Returns the character data converted from the numeric data. For example, STR(123.45, 6, 1) returns 123.5.

  • float_expression: The float expression.
  • length: The optional total length to return. This includes decimal point, sign, digits, and spaces. The default is 10.
  • decimal: The optional number of places to the right of the decimal point. The decimal must be less than or equal to 16.

                      SELECT STR('123.456');
                      -- Result: '123'

                      SELECT STR('123.456', 2);
                      -- Result: '**'

                      SELECT STR('123.456', 10, 2);
                      -- Result: '123.46'
                    

STUFF(character_expression , integer_start , integer_length , replaceWith_expression)

Inserts a string into another string. It deletes the specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

  • character_expression: The string expression.
  • start: The integer value that specifies the location to start deletion and insertion. If start or length is negative, null is returned. If start is longer than the string to be modified, character_expression, null is returned.
  • length: The integer that specifies the number of characters to delete. If length is longer than character_expression, deletion occurs up to the last character in replaceWith_expression.
  • replaceWith_expression: The expression of character data that will replace length characters of character_expression beginning at the start value.

                      SELECT STUFF('1234567890', 3, 2, 'xx');
                      -- Result: '12xx567890'
                    

SUBSTRING(string_value FROM start FOR length)

Returns the part of the string with the specified length; starts at the specified index.

  • string_value: The character string.
  • start: The positive integer that specifies the start index of characters to return.
  • length: Optional. The positive integer that specifies how many characters will be returned.

                      SELECT SUBSTRING('1234567890' FROM 3 FOR 2);
                      -- Result: '34'

                      SELECT SUBSTRING('1234567890' FROM 3);
                      -- Result: '34567890'
                    
You can also drop the FROM and FOR clauses:
                    SELECT SUBSTRING('1234567890', 3, 2)
                    --Result: '34'
                    SELECT SUBSTRING('1234567890', 3)
                    --Result: '34567890'
                    

TEXT_ENCODE(input_string, charset)

Returns binary output by encoding a string using the specified character set.

  • input_string: The plain text string.
  • charset: The character set to use, such as 'UTF-8', 'ISO-8859-1'.

                    SELECT TEXT_ENCODE('Café', 'UTF-8');
                    -- Result: (binary output)
                    

TEXT_DECODE(input_binary, charset)

Returns a string decoded from binary data using the specified character set.

  • input_binary: The binary value to decode.
  • charset: The character set used for decoding.

                    SELECT TEXT_DECODE(BinaryData, 'UTF-8');
                    -- Result: 'Café'
                    

TOSTRING(string_value1)

Converts the value of this instance to its equivalent string representation.

  • string_value1: The string to be converted.

                      SELECT TOSTRING(123);
                      -- Result: '123'

                      SELECT TOSTRING(123.456);
                      -- Result: '123.456'

                      SELECT TOSTRING(null);
                      -- Result: ''
                    

TRIM(trimspec trimchar FROM string_value)

Returns the character expression with leading and/or trailing blanks removed.

  • trimspec: Optional. If included must be one of the keywords BOTH, LEADING or TRAILING.
  • trimchar: Optional. If included should be a one-character string value.
  • string_value: The string value to trim.

                      SELECT TRIM('     trimmed     ');
                      -- Result: 'trimmed'

                      SELECT TRIM(LEADING FROM '     trimmed     ');
                      -- Result: 'trimmed     '

                      SELECT TRIM('-' FROM '-----trimmed-----');
                      -- Result: 'trimmed'

                      SELECT TRIM(BOTH '-' FROM '-----trimmed-----');
                      -- Result: 'trimmed'

                      SELECT TRIM(TRAILING '-' FROM '-----trimmed-----');
                      -- Result: '-----trimmed'
                    

UNICODE(ncharacter_expression)

Returns the integer value defined by the Unicode standard of the first character of the input expression.

  • ncharacter_expression: The Unicode character expression.

UPPER ( character_expression )

Returns the character expression with lowercase character data converted to uppercase.

  • character_expression: The character expression.

                      SELECT UPPER('MIXED case');
                      -- Result: 'MIXED CASE'
                    

XML_EXTRACT(xml, xpath [, separator])

Extracts an XML document using the specified XPath to flatten the XML. A comma is used to separate the outputs by default, but this can be changed by specifying the third parameter.

  • xml: The XML document to extract.
  • xpath: The XPath used to select the nodes. The nodes selected will be returned in a token-separated list.
  • separator: The optional token used to separate the items in the flattened response. If this is not specified, the separator will be a comma.

                      SELECT XML_EXTRACT('<vowels><ch>a</ch><ch>e</ch><ch>i</ch><ch>o</ch><ch>u</ch></vowels>', '/vowels/ch');
                      -- Result: 'a,e,i,o,u'

                      SELECT XML_EXTRACT('<vowels><ch>a</ch><ch>e</ch><ch>i</ch><ch>o</ch><ch>u</ch></vowels>', '/vowels/ch', ';');
                      -- Result: 'a;e;i;o;u'
                    

CData Python Connector for Facebook Ads

MATH Functions

ABS ( numeric_expression )

Returns the absolute (positive) value of the specified numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT ABS(15);
                      -- Result: 15

                      SELECT ABS(-15);
                      -- Result: 15
                    

ACOS ( float_expression )

Returns the arc cosine, the angle in radians whose cosine is the specified float expression.

  • float_expression: The float expression that specifies the cosine of the angle to be returned. Values outside the range from -1 to 1 return null.

                      SELECT ACOS(0.5);
                      -- Result: 1.0471975511966
                    

ASIN ( float_expression )

Returns the arc sine, the angle in radians whose sine is the specified float expression.

  • float_expression: The float expression that specifies the sine of the angle to be returned. Values outside the range from -1 to 1 return null.

                      SELECT ASIN(0.5);
                      -- Result: 0.523598775598299
                    

ATAN ( float_expression )

Returns the arc tangent, the angle in radians whose tangent is the specified float expression.

  • float_expression: The float expression that specifies the tangent of the angle to be returned.

                      SELECT ATAN(10);
                      -- Result: 1.47112767430373
                    

ATN2 ( float_expression1 , float_expression2 )

Returns the angle in radians between the positive x-axis and the ray from the origin to the point (y, x) where x and y are the values of the two specified float expressions.

  • float_expression1: The float expression that is the y-coordinate.
  • float_expression2: The float expression that is the x-coordinate.

                      SELECT ATN2(1, 1);
                      -- Result: 0.785398163397448
                    

CEILING ( numeric_expression ) or CEIL( numeric_expression )

Returns the smallest integer greater than or equal to the specified numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT CEILING(1.3);
                      -- Result: 2

                      SELECT CEILING(1.5);
                      -- Result: 2

                      SELECT CEILING(1.7);
                      -- Result: 2
                    

COS ( float_expression )

Returns the trigonometric cosine of the specified angle in radians in the specified expression.

  • float_expression: The float expression of the specified angle in radians.

                      SELECT COS(1);
                      -- Result: 0.54030230586814
                    

COT ( float_expression )

Returns the trigonometric cotangent of the angle in radians specified by float_expression.

  • float_expression: The float expression of the angle in radians.

                      SELECT COT(1);
                      -- Result: 0.642092615934331
                    

DEGREES ( numeric_expression )

Returns the angle in degrees for the angle specified in radians.

  • numeric_expression: The angle in radians, an expression of an indeterminate numeric data type except for the bit data type.

                      SELECT DEGREES(3.1415926);
                      -- Result: 179.999996929531
                    

EXP ( float_expression )

Returns the exponential value of the specified float expression. For example, EXP(LOG(20)) is 20.

  • float_expression: The float expression.

                      SELECT EXP(2);
                      -- Result: 7.38905609893065
                    

EXPR ( expression )

Evaluates the expression.

  • expression: The expression. Operators allowed are +, -, *, /, ==, !=, >, <, >=, and <=.

                      SELECT EXPR('1 + 2 * 3');
                      -- Result: 7

                      SELECT EXPR('1 + 2 * 3 == 7');
                      -- Result: true
                    

FLOOR ( numeric_expression )

Returns the largest integer less than or equal to the numeric expression.

  • numeric_expression: The expression of an indeterminate numeric data type except for the bit data type.

                      SELECT FLOOR(1.3);
                      -- Result: 1

                      SELECT FLOOR(1.5);
                      -- Result: 1

                      SELECT FLOOR(1.7);
                      -- Result: 1
                    

GREATEST(int1,int2,....)

Returns the greatest of the supplied integers.

				SELECT GREATEST(3,5,8,10,1)
				-- Result: 10			
				

HEX(value)

Returns a the equivalent hex for the input value.

  • value: A string or numerical value to be converted into hex.

				SELECT HEX(866849198);
				-- Result: 33AB11AE
				
				SELECT HEX('Sample Text');
				-- Result: 53616D706C652054657874
				

JSON_AVG(json, jsonpath)

Computes the average value of a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_AVG('[1,2,3,4,5]', '$[x]');
                      -- Result: 3

                      SELECT JSON_AVG('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 3

                      SELECT JSON_AVG('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 4.5
                    

JSON_COUNT(json, jsonpath)

Returns the number of elements in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_COUNT('[1,2,3,4,5]', '$[x]');
                      -- Result: 5

                      SELECT JSON_COUNT('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 5

                      SELECT JSON_COUNT('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 2
                    

JSON_MAX(json, jsonpath)

Gets the maximum value in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_MAX('[1,2,3,4,5]', '$[x]');
                      -- Result: 5

                      SELECT JSON_MAX('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 5

                      SELECT JSON_MAX('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[..3]');
                      -- Result: 4
                    

JSON_MIN(json, jsonpath)

Gets the minimum value in a JSON array within a JSON object. The path to the array is specified in the jsonpath argument. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_MIN('[1,2,3,4,5]', '$[x]');
                      -- Result: 1

                      SELECT JSON_MIN('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 1

                      SELECT JSON_MIN('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 4
                    

JSON_SUM(json, jsonpath)

Computes the summary value in JSON according to the JSONPath expression. Return value is numeric or null.

  • json: The JSON document to compute.
  • jsonpath: The JSONPath used to select the nodes. [x], [2..], [..8], or [1..12] are accepted. [x] selects all nodes.

                      SELECT JSON_SUM('[1,2,3,4,5]', '$[x]');
                      -- Result: 15

                      SELECT JSON_SUM('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[x]');
                      -- Result: 15

                      SELECT JSON_SUM('{"test": {"data": [1,2,3,4,5]}}', '$.test.data[3..]');
                      -- Result: 9
                    

LEAST(int1,int2,....)

Returns the least of the supplied integers.

				SELECT LEAST(3,5,8,10,1)
				-- Result: 1			
				

LOG ( float_expression [, base ] )

Returns the natural logarithm of the specified float expression.

  • float_expression: The float expression.
  • base: The optional integer argument that sets the base for the logarithm.

                      SELECT LOG(7.3890560);
                      -- Result: 1.99999998661119
                    

LOG10 ( float_expression )

Returns the base-10 logarithm of the specified float expression.

  • float_expression: The expression of type float.

                      SELECT LOG10(10000);
                      -- Result: 4
                    

MOD(dividend,divisor)

Returns the integer value associated with the remainder when dividing the dividend by the divisor.

  • dividend: The number to take the modulus of.
  • divisor: The number to divide the dividend by when determining the modulus.

				SELECT MOD(10,3);
				-- Result: 1
				

NEGATE(real_number)

Returns the opposite to the real number input.

  • real_number: The real number to find the opposite of.

				SELECT NEGATE(10);
				-- Result: -10
				
				SELECT NEGATE(-12.4)
				--Result: 12.4
				

PI ( )

Returns the constant value of pi.

                  SELECT PI()
                  -- Result: 3.14159265358979 
                

POWER ( float_expression , y )

Returns the value of the specified expression raised to the specified power.

  • float_expression: The float expression.
  • y: The power to raise float_expression to.

                      SELECT POWER(2, 10);
                      -- Result: 1024

                      SELECT POWER(2, -2);
                      -- Result: 0.25
                    

RADIANS ( float_expression )

Returns the angle in radians of the angle in degrees.

  • float_expression: The degrees of the angle as a float expression.

                      SELECT RADIANS(180);
                      -- Result: 3.14159265358979
                    

RAND ( [ integer_seed ] )

Returns a pseudorandom float value from 0 through 1, exclusive.

  • seed: The optional integer expression that specifies the seed value. If seed is not specified, a seed value at random will be assigned.

                      SELECT RAND();
                      -- This result may be different, since the seed is randomized
                      -- Result: 0.873159630165044

                      SELECT RAND(1);
                      -- This result will always be the same, since the seed is constant
                      -- Result: 0.248668584157093
                    

ROUND ( numeric_expression [ ,integer_length] [ ,function ] )

Returns the numeric value rounded to the specified length or precision.

  • numeric_expression: The expression of a numeric data type.
  • length: The optional precision to round the numeric expression to. When this is omitted, the default behavior will be to round to the nearest whole number.
  • function: The optional type of operation to perform. When the function parameter is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

                      SELECT ROUND(1.3, 0);
                      -- Result: 1

                      SELECT ROUND(1.55, 1);
                      -- Result: 1.6

                      SELECT ROUND(1.7, 0, 0);
                      -- Result: 2

                      SELECT ROUND(1.7, 0, 1);
                      -- Result: 1
                      
                      SELECT ROUND (1.24);
                      -- Result: 1.0
                    

SIGN ( numeric_expression )

Returns the positive sign (1), 0, or negative sign (-1) of the specified expression.

  • numeric_expression: The expression of an indeterminate data type except for the bit data type.

                      SELECT SIGN(0);
                      -- Result: 0

                      SELECT SIGN(10);
                      -- Result: 1

                      SELECT SIGN(-10);
                      -- Result: -1
                    

SIN ( float_expression )

Returns the trigonometric sine of the angle in radians.

  • float_expression: The float expression specifying the angle in radians.

                     SELECT SIN(1);
                     -- Result: 0.841470984807897
                    

SQRT ( float_expression )

Returns the square root of the specified float value.

  • float_expression: The expression of type float.

                      SELECT SQRT(100);
                      -- Result: 10
                    

SQUARE ( float_expression )

Returns the square of the specified float value.

  • float_expression: The expression of type float.

                      SELECT SQUARE(10);
                      -- Result: 100

                      SELECT SQUARE(-10);
                      -- Result: 100
                    

TAN ( float_expression )

Returns the tangent of the input expression.

  • float_expression: The expression of type float.

                      SELECT TAN(1);
                      -- Result: 1.5574077246549
                    

TRUNC(decimal_number,precision)

Returns the supplied decimal number truncated to have the supplied decimal precision.

  • decimal_number: The decimal value to truncate.
  • precision: The number of decimal places to truncate the decimal number to.

				SELECT TRUNC(10.3423,2);
				-- Result: 10.34
				

_ROW_NUMBER_()

Returns a row index as an additional column.

				SELECT ColumnName, _ROW_NUMBER_() FROM TableName
				-- Result: ColumnData, 0
				ColumnData2, 1
				ColumnData3, 2
				

CData Python Connector for Facebook Ads

DATE Functions

CURRENT_DATE()

Returns the current date value.

                  SELECT CURRENT_DATE();
                  -- Result: 2018-02-01
                

CURRENT_TIMESTAMP()

Returns the current time stamp of the database system as a datetime value. This value is equal to GETDATE and SYSDATETIME, and is always in the local timezone.

                  SELECT CURRENT_TIMESTAMP();
                  -- Result: 2018-02-01 03:04:05
                

DATEADD (datepart , integer_number , date [, dateformat])

Returns the datetime value that results from adding the specified number (a signed integer) to the specified date part of the date.

  • datepart: The part of the date to add the specified number to. The valid values and abbreviations are
    • year (yy, yyyy)
    • quarter (qq, q)
    • month (mm, m)
    • week (wk, ww)
    • weekday (dw)
    • dayofyear (dy, y)
    • day (dd, d)
    • hour (hh)
    • minute (mi, n)
    • second (ss, s)
    • millisecond (ms)
  • number: The number to be added.
  • date: The expression of the datetime data type.
  • dateformat: The optional output date format.

                  SELECT DATEADD('d', 5, '2018-02-01');
                  -- Result: 2018-02-06

                  SELECT DATEADD('hh', 5, '2018-02-01 00:00:00');
                  -- Result: 2018-02-01 05:00:00
                

DATEDIFF ( datepart , startdate , enddate )

Returns the difference (a signed integer) of the specified time interval between the specified start date and end date.

  • datepart: The part of the date that is the time interval of the difference between the start date and end date. The valid values and abbreviations are:
    • Year (year, yyyy, yy)
    • Quarter (quarter, qq, q)
    • Month (month, mm, m)
    • Week (week, wk, ww)
    • Weekday (weekday, dw)
    • Dayofyear (dayofyear, dy, y)
    • Day (day, dd, d)
    • Hour (hour, hh)
    • Minute (minute, mi, n)
    • Second (second, ss, s)
    • Millisecond (millisecond, ms)
  • startdate: The datetime expression of the start date.
  • enddate: The datetime expression of the end date.

                  SELECT DATEDIFF('d', '2018-02-01', '2018-02-10');
                  -- Result: 9

                  SELECT DATEDIFF('hh', '2018-02-01 00:00:00', '2018-02-01 12:00:00');
                  -- Result: 12
                

DATE_FORMAT(date,format)

Returns the date or timestamp in the format specified. This function mirrors the MySQL DATE_FORMAT function.

  • date: A date or timestamp string.
  • format: The specifier string of the desired output format. The list of supported format specifiers comes from the MySQL DATE_FORMAT function (see link to MySQL documentation above).

					SELECT DATE_FORMAT('9/4/2021 3:11:53 AM','%h')
					-- Result: 03
				  

DATEFROMPARTS(integer_year, integer_month, integer_day)

Returns the datetime value for the specified year, month, and day.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.

                    SELECT DATEFROMPARTS(2018, 2, 1);
                    -- Result: 2018-02-01
                  

DATENAME(datepart , date)

Returns the character string that represents the specified date part of the specified date.

  • datepart: The part of the date to return. The valid values and abbreviations are year (yy, yyyy), quarter (qq, q), month (mm, m), dayofyear (dy, y), day (dd, d), week (wk, ww), weekday (dw), hour (hh), minute (mi, n), second (ss, s), millisecond (ms), microsecond (mcs), and nanosecond (ns).
  • date: The datetime expression.

                     SELECT DATENAME('yy', '2018-02-01');
                     -- Result: '2018'

                     SELECT DATENAME('dw', '2018-02-01');
                     -- Result: 'Thursday'
                   

DATEPART(datepart, date [,integer_datefirst])

Returns a character string that represents the specified date part of the specified date.

  • datepart: The part of the date to return. The valid values and abbreviations are year (yy, yyyy), quarter (qq, q), month (mm, m), dayofyear (dy, y), day (dd, d), week (wk, ww), weekday (dw), hour (hh), minute (mi, n), second (ss, s), millisecond (ms), microsecond (mcs), nanosecond (ns), ISODOW, ISO_WEEK (isoweek, isowk,isoww), and ISOYEAR.
  • date: The datetime string.
  • datefirst: The optional integer representing the first day of the week. The default is 7, Sunday.

                    SELECT DATEPART('yy', '2018-02-01');
                    -- Result: 2018

                    SELECT DATEPART('dw', '2018-02-01');
                    -- Result: 5
                  

DATETIMEFROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute, integer_seconds, integer_milliseconds)

Returns the datetime value for the specified date parts.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • milliseconds: The integer expression specifying the milliseconds.

                    SELECT DATETIMEFROMPARTS(2018, 2, 1, 1, 2, 3, 456);
                    -- Result: 2018-02-01 01:02:03.456
                  

DATETIME2FROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute, integer_seconds, integer_fractions, integer_precision)

Returns the datetime value for the specified date parts.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • fractions: The integer expression specifying the fractions of the second.
  • precision: The integer expression specifying the precision of the fraction.

				    SELECT DATETIME2FROMPARTS(2018, 2, 1, 1, 2, 3, 456, 3);
                    -- Result: 2018-02-01 01:02:03.456
                  

DATE_TRUNC(date, datepart)

Truncates the date to the precision of the given date part. Modeled after the Oracle TRUNC function.

  • date: The datetime string that specifies the date.
  • datepart: Refer to the Oracle documentation for valid datepart syntax.

				    SELECT DATE_TRUNC('05-04-2005', 'YY');
                    -- Result: '1/1/2005'
					
                    SELECT DATE_TRUNC('05-04-2005', 'MM');
                    -- Result: '5/1/2005'                    
                  

DATE_TRUNC2(datepart, date, [weekday])

Truncates the date to the precision of the given date part. Modeled after the PostgreSQL date_trunc function.

  • datepart: One of 'millennium', 'century', 'decade', 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute' or 'second'.
  • date: The datetime string that specifies the date.
  • weekday: The optional day of the week to use as the first day for 'week'. One of 'sunday', 'monday', etc.

                    SELECT DATE_TRUNC2('year', '2020-02-04');
                    -- Result: '2020-01-01'

                    SELECT DATE_TRUNC2('week', '2020-02-04', 'monday');
                    -- Result: '2020-02-02', which is the previous Monday
                  

DAY(date)

Returns the integer that specifies the day component of the specified date.

  • date: The datetime string that specifies the date.

                    SELECT DAY('2018-02-01');
                    -- Result: 1
                  

DAYNAME(date)

Returns the name of the day of the week of the specified date.

  • date: The datetime string that specifies the date.

                    SELECT DAYNAME('8/18/2021');
                    -- Result: Wednesday
                  

DAYOFMONTH(date)

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

				  SELECT DAYOFMONTH('04/15/2000');
				  -- Result: 15
				  

DAYOFWEEK(date)

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

				  SELECT DAYOFWEEK('04/15/2000');
				  -- Result: 7
				  

DAYOFYEAR(date)

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

				  SELECT DAYOFYEAR('04/15/2000');
				  -- Result: 106
				  

EOMONTH(date [, integer_month_to_add ]) or LAST_DAY(date)

Returns the last day of the month that contains the specified date with an optional offset.

  • date: The datetime expression specifying the date for which to return the last day of the month.
  • integer_month_to_add: The optional integer expression specifying the number of months to add to the date before calculating the end of the month.

                  SELECT EOMONTH('2018-02-01');
                  -- Result: 2018-02-28
                  
                  SELECT LAST_DAY('2018-02-01');
                  -- Result: 2018-02-28

                  SELECT EOMONTH('2018-02-01', 2);
                  -- Result: 2018-04-30
                

EXTRACT(date_part FROM date_column_name)

Returns the last day of the month that contains the specified date with an optional offset.

  • date_part: One of the following date components: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND.
  • date_column_name: The name of a date column in a table.

                  SELECT EXTRACT(YEAR FROM DateColumn)
                  -- Result: 2021
                

FDWEEK(date)

Returns the first day of the week of the given date part.
  • date: The datetime string that specifies the date.
  • weeks to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the week.

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

          SELECT FDWEEK('02-08-2018', 1)
          --Result: 02/11/2018
				  

FDMONTH(date)

Returns the first day of the month of the given date part.
  • date: The datetime string that specifies the date.
  • month to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the month.

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

          SELECT FDMONTH('02-08-2018', 1) 
          --Result: 03/01/2018
				  

FDQUARTER(date)

Returns the first day of the quarter of the given date part.
  • date: The datetime string that specifies the date.
  • quarters to add: An optional integer expression specifying the number of months to add to the date before calculating the first day of the quarter.

				  SELECT FDQUARTER('05-08-2018');
				  -- Result: 4/1/2018

          SELECT FDQUARTER('05-08-2018',1)
          --Result: 07/01/2018
				  

FILEMODIFIEDTIME(uri)

Returns the time stamp associated with the Date Modified of the relevant file.

  • uri: An absolute path pointing to a file on the local file system.

				 SELECT FILEMODIFIEDTIME('C:/Documents/myfile.txt');
				 -- Result: 6/25/2019 10:06:58 AM
				 

FROM_DAYS(datevalue)

Returns a date derived from the number of days after 1582-10-15 (based upon the Gregorian calendar). This will be equivalent to the MYSQL FROM_DAYS function.

  • datevalue: A integer value representing the number of days since 1582-10-15.

				SELECT FROM_DAYS(736000);
				-- Result: 2/6/2015
				

FROM_UNIXTIME(time, issecond)

Returns a representation of the unix_timestamp argument as a value in YYYY-MM-DD HH:MM:SS expressed in the current time zone.

  • time: The time stamp value from epoch time. Milliseconds are accepted.
  • issecond: Indicates the time stamp value is milliseconds to epoch time.

                      SELECT FROM_UNIXTIME(1540495231, 1);
                      -- Result: 2018-10-25 19:20:31

                      SELECT FROM_UNIXTIME(1540495357385, 0);
                      -- Result: 2018-10-25 19:22:37
                    

GETDATE()

Returns the current time stamp of the database system as a datetime value. This value is equal to CURRENT_TIMESTAMP and SYSDATETIME, and is always in the local timezone.

                  SELECT GETDATE();
                  -- Result: 2018-02-01 03:04:05
                

GETUTCDATE()

Returns the current time stamp of the database system formatted as a UTC datetime value. This value is equal to SYSUTCDATETIME.

In addition, GETUTCDATE can take an optional second parameter, a date and time that are converted to UTC.

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

                  SELECT GETUTCDATE('2020/08/31 13:56:00')
                  --Result: '2020-08-31 17:56:00'
                

HOUR(date)

Returns the hour component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT HOUR('02-02-2020 11:30:00');
				-- Result: 11
				

ISDATE(date, [date_format])

Returns 1 if the value is a valid date, time, or datetime value; otherwise, 0.

  • date: The datetime string.
  • date_format: The optional datetime format.

                      SELECT ISDATE('2018-02-01', 'yyyy-MM-dd');
                      -- Result: 1

                      SELECT ISDATE('Not a date');
                      -- Result: 0
                    

LAST_WEEK()

Returns a time stamp equivalent to exactly one week before the current date.

				SELECT LAST_WEEK();	//Assume the date is 3/17/2020	
			 -- Result: 3/10/2020 00:00:00
				

LAST_MONTH()

Returns a time stamp equivalent to exactly one month before the current date.

	
				SELECT LAST_MONTH(); //Assume the date is 3/17/2020
				-- Result: 2/17/2020 00:00:00
				

LAST_YEAR()

Returns a time stamp equivalent to exactly one year before the current date.

				SELECT LAST_YEAR();	//Assume the date is 3/17/2020	
				-- Result: 3/10/2019 00:00:00
				

LDWEEK(date)

Returns the last day of the provided week.

  • date: The datetime string.
  • weeks to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the week.

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

LDMONTH(date)

Returns the last day of the provided month.

  • date: The datetime string.
  • months to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the month.

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

        SELECT LDMONTH('02-08-2020', 1)
        --Result: 03/31/2020
				

LDQUARTER(date)

Returns the last day of the provided quarter.

  • date: The datetime string.
  • quarters to add: An optional integer expression specifying the number of months to add to the date before calculating the last day of the quarter.

				SELECT LDQUARTER('02-02-2020');
				-- Result: 3/31/2020

        SELECT LDQUARTER('02-02-2020',1)
        --Result: 06/30/2020
				

MAKEDATE(year, days)

Returns a date value from a year and a number of days.

  • year: The year
  • days: The number of days into the year. Value must be greater than 0.

          SELECT MAKEDATE(2020, 1);
          -- Result: 2020-01-01
        

MINUTE(date)

Returns the minute component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT MINUTE('02-02-2020 11:15:00');
				-- Result: 15
				

MONTH(date)

Returns the month component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT MONTH('02-02-2020');
				-- Result: 2
				

QUARTER(date)

Returns the quarter associated with the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT QUARTER('02-02-2020');
				-- Result: 1
				

SECOND(date)

Returns the second component from the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT SECOND('02-02-2020 11:15:23');
				-- Result: 23
				

SMALLDATETIMEFROMPARTS(integer_year, integer_month, integer_day, integer_hour, integer_minute)

Returns the datetime value for the specified date and time.

  • year: The integer expression specifying the year.
  • month: The integer expression specifying the month.
  • day: The integer expression specifying the day.
  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.

                      SELECT SMALLDATETIMEFROMPARTS(2018, 2, 1, 1, 2);
                      -- Result: 2018-02-01 01:02:00
                    

STRTODATE(string,format)

Parses the provided string value and returns the corresponding datetime.

  • string: The string value to be converted to datetime format.
  • format: A format string which describes how to interpret the first string input. A few special formats are available as well, including UNIX, UNIXMILIS, TICKS, and FILETICKS.

				SELECT STRTODATE('03*04*2020','dd*MM*yyyy');
				-- Result: 4/3/2020
				

SYSDATETIME()

Returns the current time stamp as a datetime value of the database system. It is equal to GETDATE and CURRENT_TIMESTAMP, and is always in the local timezone.

                  SELECT SYSDATETIME();
                  -- Result: 2018-02-01 03:04:05
                

SYSUTCDATETIME()

Returns the current system date and time as a UTC datetime value. It is equal to GETUTCDATE.

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

TIMEFROMPARTS(integer_hour, integer_minute, integer_seconds, integer_fractions, integer_precision)

Returns the time value for the specified time and with the specified precision.

  • hour: The integer expression specifying the hour.
  • minute: The integer expression specifying the minute.
  • seconds: The integer expression specifying the seconds.
  • fractions: The integer expression specifying the fractions of the second.
  • precision : The integer expression specifying the precision of the fraction.

                      SELECT TIMEFROMPARTS(1, 2, 3, 456, 3);
                      -- Result: 01:02:03.456
                    

TO_DAYS(date)

Returns the number of days since 0000-00-01. This will only return a value for dates on or after 1582-10-15 (based upon the Gregorian calendar). This will be equivalent to the MYSQL TO_DAYS function.

  • date: The datetime string that specifies the date.

				SELECT TO_DAYS('02-06-2015');
				-- Result: 736000
				

WEEK(date)

Returns the week (of the year) associated with the provided datetime.

  • date: The datetime string that specifies the date.

				SELECT WEEK('02-17-2020 11:15:23');
				-- Result: 8
				

YEAR(date)

Returns the integer that specifies the year of the specified date.

  • date: The datetime string.

                      SELECT YEAR('2018-02-01');
                      -- Result: 2018
                    

CData Python Connector for Facebook Ads

Date Literal Functions

The following date literal functions can be used to filter date fields using relative intervals. Note that while the <, >, and = operators are supported for these functions, <= and >= are not.

L_TODAY()

The current day.

  SELECT * FROM MyTable WHERE MyDateField = L_TODAY()

L_YESTERDAY()

The previous day.

  SELECT * FROM MyTable WHERE MyDateField = L_YESTERDAY()

L_TOMORROW()

The following day.

  SELECT * FROM MyTable WHERE MyDateField = L_TOMORROW()

L_LAST_WEEK()

Every day in the preceding week.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_WEEK()

L_THIS_WEEK()

Every day in the current week.

  SELECT * FROM MyTable WHERE MyDateField = L_THIS_WEEK()

L_NEXT_WEEK()

Every day in the following week.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_WEEK()
Also available:
  • L_LAST/L_THIS/L_NEXT MONTH
  • L_LAST/L_THIS/L_NEXT QUARTER
  • L_LAST/L_THIS/L_NEXT YEAR

L_LAST_N_DAYS(n)

The previous n days, excluding the current day.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_DAYS(3)

L_NEXT_N_DAYS(n)

The following n days, including the current day.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_DAYS(3)
Also available:
  • L_LAST/L_NEXT_90_DAYS

L_LAST_N_WEEKS(n)

Every day in every week, starting n weeks before current week, and ending in the previous week.

  SELECT * FROM MyTable WHERE MyDateField = L_LAST_N_WEEKS(3)

L_NEXT_N_WEEKS(n)

Every day in every week, starting the following week, and ending n weeks in the future.

  SELECT * FROM MyTable WHERE MyDateField = L_NEXT_N_WEEKS(3)
Also available:
  • L_LAST/L_NEXT_N_MONTHS(n)
  • L_LAST/L_NEXT_N_QUARTERS(n)
  • L_LAST/L_NEXT_N_YEARS(n)

CData Python Connector for Facebook Ads

SELECT Statements

A SELECT statement can consist of the following basic clauses.

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

SELECT Syntax

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

SELECT {
  [ TOP <numeric_literal> | DISTINCT ]
  { 
    * 
    | { 
        <expression> [ [ AS ] <column_reference> ] 
        | { <table_name> | <correlation_name> } .* 
      } [ , ... ] 
  }
  { 
    FROM <table_reference> [ [ AS ] <identifier> ] 
  } [ , ... ]
  [ [  
      INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } 
    ] JOIN <table_reference> [ ON <search_condition> ] [ [ AS ] <identifier> ] 
  ] [ ... ] 
  [ WHERE <search_condition> ]
  [ GROUP BY <column_reference> [ , ... ]
  [ HAVING <search_condition> ]
  [ UNION [ ALL ] <select_statement> ]
  [ 
    ORDER BY 
    <column_reference> [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
  ]
  [ 
    LIMIT <expression>
    [ 
      { OFFSET | , }
      <expression> 
    ]
  ] 
}

<expression> ::=
  | <column_reference>
  | @ <parameter> 
  | ?
  | COUNT( * | { [ DISTINCT ] <expression> } )
  | { AVG | MAX | MIN | SUM | COUNT } ( <expression> ) 
  | NULLIF ( <expression> , <expression> ) 
  | COALESCE ( <expression> , ... ) 
  | CASE <expression>
      WHEN { <expression> | <search_condition> } THEN { <expression> | NULL } [ ... ]
    [ ELSE { <expression> | NULL } ]
    END 
  | {RANK() | DENSE_RANK()} OVER ([PARTITION BY <column_reference>] {ORDER BY <column_reference>})
  | <literal>
  | <sql_function> 

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

Examples

  1. Return all columns:
    SELECT * FROM AdAccounts
  2. Rename a column:
    SELECT [Name] AS MY_Name FROM AdAccounts
  3. Cast a column's data as a different data type:
    SELECT CAST(AnnualRevenue AS VARCHAR) AS Str_AnnualRevenue FROM AdAccounts
  4. Search data:
    SELECT * FROM AdAccounts WHERE Name = 'Act Name'
  5. Return the number of items matching the query criteria:
    SELECT COUNT(*) AS MyCount FROM AdAccounts 
  6. Return the number of unique items matching the query criteria:
    SELECT COUNT(DISTINCT Name) FROM AdAccounts 
  7. Return the unique items matching the query criteria:
    SELECT DISTINCT Name FROM AdAccounts 
  8. Sort a result set in ascending order:
    SELECT AccountId, Name FROM AdAccounts  ORDER BY Name ASC
  9. Restrict a result set to the specified number of rows:
    SELECT AccountId, Name FROM AdAccounts LIMIT 10 
  10. Parameterize a query to pass in inputs at execution time. This enables you to create prepared statements and mitigate SQL injection attacks.
    SELECT * FROM AdAccounts WHERE Name = @param
See Explicitly Caching Data for information on using the SELECT statement in offline mode.

Pseudo Columns

Some input-only fields are available in SELECT statements. These fields, called pseudo columns, do not appear as regular columns in the results, yet may be specified as part of the WHERE clause. You can use pseudo columns to access additional features from Facebook Ads.

    SELECT * FROM AdAccounts WHERE Target = 'businessid'
    

Aggregate Functions

For SELECT examples using aggregate functions, see Aggregate Functions.

JOIN Queries

See JOIN Queries for SELECT query examples using JOINs.

Date Literal Functions

Date Literal Functions contains SELECT examples with date literal functions.

Window Functions

See Window Functions for SELECT examples containing window functions.

Table-Valued Functions

See Table-Valued Functions for SELECT examples with table-valued functions.

CData Python Connector for Facebook Ads

Aggregate Functions

COUNT

Returns the number of rows matching the query criteria.

SELECT COUNT(*) FROM AdAccounts WHERE Name = 'Act Name'

COUNT(DISTINCT)

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

SELECT COUNT(DISTINCT AccountId) AS DistinctValues FROM AdAccounts WHERE Name = 'Act Name'

AVG

Returns the average of the column values.

SELECT Name, AVG(AnnualRevenue) FROM AdAccounts WHERE Name = 'Act Name'  GROUP BY Name

MIN

Returns the minimum column value.

SELECT MIN(AnnualRevenue), Name FROM AdAccounts WHERE Name = 'Act Name' GROUP BY Name

MAX

Returns the maximum column value.

SELECT Name, MAX(AnnualRevenue) FROM AdAccounts WHERE Name = 'Act Name' GROUP BY Name

SUM

Returns the total sum of the column values.

SELECT SUM(AnnualRevenue) FROM AdAccounts WHERE Name = 'Act Name'

CData Python Connector for Facebook Ads

JOIN Queries

The CData Python Connector for Facebook Ads 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 a.Name, d.AccountStatus FROM AdAccounts a INNER JOIN Ads d ON a.Id = d.Target

Left Join

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

 SELECT a.Name, d.AccountStatus FROM AdAccounts a LEFT JOIN Ads d ON a.Id = d.Target

CData Python Connector for Facebook Ads

Window Functions

Window functions allow you to create computed fields from a group of rows (a window) that return a result for each row, as opposed to one computed result for a set of rows, as is the case with aggregate functions. The connector supports the following window function syntax.

Note: Window function support is an experimental feature of the connector. This functionality extends beyond the connector's core scope of being SQL-92 compliant. As such, performance with window functions may not be optimal.

Window Function Clauses

OVER

The OVER clause defines the window over which window functions are performed.

SELECT A, B, <window function> OVER (<window frame>) FROM TableName

The <window function> refers to any supported window function clause, and the <window frame> refers to one or more clauses that specify the logic by which the window is defined.

PARTITION BY

The PARTITION BY clause subdivides a window into sub-windows called partitions. For each unique value in the column specified in the PARTITION BY clause, every record with that value collectively forms an individual partition.

SELECT A, B, <window function> OVER (PARTITION BY A ORDER BY B) From AdAccounts

The <window function> refers to any supported window function clause.

Window Functions

The connector supports math, ranking, and analytic window functions.

Math

These window functions perform mathematical operations on the records within the window.

COUNT()

Calculates the number of records in each partition. The calculated column is of the data type "int".

In each partition, every record will display the total number of records in that partition.

SELECT Name, Role, Earnings, COUNT() OVER (PARTITION BY Role) FROM Employees

COUNT_BIG()

Calculates the number of records in each partition. The calculated column is of the data type "bigint".

In each partition, every record will display the total number of records in that partition.

SELECT Name, Role, Earnings, COUNT_BIG() OVER (PARTITION BY Role) FROM Employees

MIN(numeric_column)

Calculates the minimum value of a numerical column per partition.

In each partition, every record will display the minimum value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MIN(Earnings) OVER (PARTITION BY Role) FROM Employees

MAX(numeric_column)

Calculates the maximum value of a numerical column per partition.

In each partition, every record will display the maximum value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MAX(Earnings) OVER (PARTITION BY Role) FROM Employees

SUM(numeric_column)

Calculates the sum of a numerical column per partition.

In each partition, every record will display the sum of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, SUM(Earnings) OVER (PARTITION BY Role) FROM Employees

AVG(numeric_column)

Calculates the average value of a numerical column per partition.

In each partition, every record will display the average value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, AVG(Earnings) OVER (PARTITION BY Role) FROM Employees

MEDIAN(numeric_column)

Calculates the median value of a numerical column per partition.

In each partition, every record will display the median value of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, MEDIAN(Earnings) OVER (PARTITION BY Role) FROM Employees

STDEV(numeric_column)

Calculates the standard deviation of a numerical column per partition.

In each partition, every record will display the standard deviation of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, STDEV(Earnings) OVER (PARTITION BY Role) FROM Employees

STDEVP(numeric_column)

Calculates the population standard deviation of a numerical column per partition.

In each partition, every record will display the population standard deviation of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, STDEVP(Earnings) OVER (PARTITION BY Role) FROM Employees

VAR(numeric_column)

Calculates the statistical standard variance of a numerical column per partition.

In each partition, every record will display the statistical standard variance of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, VAR(Earnings) OVER (PARTITION BY Role) FROM Employees

VARP(numeric_column)

Calculates the variance population of a numerical column per partition.

In each partition, every record will display the variance population of numeric_column across the records in that partition.

SELECT Name, Role, Earnings, VARP(Earnings) OVER (PARTITION BY Role) FROM Employees

Ranking

These window functions rank records that fall within the window and its partitions.

RANK()

Assigns a rank number to each record in a window based on the value of the column specified in the required ORDER BY clause.

If two or more records have an equal value in the in ranked column, they all receive the same rank number and the rank count increments internally, skipping ahead one rank number for each record with a duplicate value in the ORDER BY column.

SELECT AccountId, Name, RANK() OVER (ORDER BY Name) AS Rank FROM AdAccounts

If you add a PARTITION BY clause, a separate set of ranks is calculated for each partition.

SELECT AccountId, Name, RANK() OVER (PARTITION BY AccountId ORDER BY Name) AS Rank FROM AdAccounts

DENSE_RANK()

Operates like the RANK() function, but it doesn't increment the internal rank counter for each record with a duplicate value in the ranked column.

This means that, while records with identical values in the ORDER BY column still share a rank number, the function never skips a rank number.

SELECT AccountId, Name, DENSE_RANK() OVER (PARTITION BY AccountId ORDER BY Name) AS Rank FROM AdAccounts

If you add a PARTITION BY clause, a separate set of ranks is calculated for each partition.

SELECT AccountId, Name, DENSE_RANK() OVER (PARTITION BY AccountId ORDER BY Name) AS Rank FROM AdAccounts

ROW_NUMBER()

Calculates a row number for each record. An ORDER BY clause in the OVER clause is required.

SELECT Name, Role, Earnings, ROW_NUMBER() OVER (ORDER BY Role) FROM Employees
If you define multiple partitions with PARTITION BY, a new set of row numbers are calculated for each partition.
SELECT Name, Role, Earnings, ROW_NUMBER() OVER (PARTITION BY Role ORDER BY Earnings) FROM Employees

NTILE()

Distributes rows of an ordered partition into a specified number of approximately equal groups, or buckets. It assigns each group a bucket number starting from one. For each row in a group, the NTILE() function assigns a bucket number representing the group to which the row belongs.

The syntax of NTILE() is:

NTILE(buckets) OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)
The following are paramaters that NTILE() supports:

  • buckets: The number of buckets into which the rows are divided. The buckets can be an expression or subquery that evaluates to a positive integer. It cannot be a window function.
  • PARTITION BY: distributes rows of a result set into partitions to which the NTILE() function is applied.
  • ORDER BY is clause that specifies the logical order of rows in each partition to which the NTILE() is applied.

If the number of rows is not divisible by the buckets, the NTILE() function returns groups of two sizes with the difference by one. The larger groups always precede the smaller group in the order set by ORDER BY in the OVER() clause.

If the total of rows is divisible by the number of buckets, the function divides the rows evenly among buckets. The following statement creates a new table named ntile_demo that stores 10 integers:

CREATE TABLE sales.ntile_demo (
	v INT NOT NULL
);
	
INSERT INTO sales.ntile_demo(v) 
VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);	
	
SELECT * FROM sales.ntile_demo;
This statement uses the NTILE() function to divide ten rows into three groups:
SELECT 
	v, 
	NTILE (3) OVER (
		ORDER BY v
	) buckets
FROM 
	sales.ntile_demo;

Analytical

These window functions perform analytical operations on the records within the window.

PERCENT_RANK()

Calculates the relative rank SQL Percentile of each row. It returns values greater than zero, but the maximum value is one. It does not count any NULL values. This function is nondeterministic.

The syntax of PERCENT_RANK() is:

PERCENT_RANK() OVER (
      [PARTITION BY partition_expression, ... ]
      ORDER BY sort_expression [ASC | DESC], ...
  )
  
This syntax uses the following parameters.

  • PARTITION BY: By default, SQL Server treats the whole data set as a single set. You can specify the PARTITION BY clause to divide data into multiple sets. The Percent_Rank function performs the analytical calculations on each set. This parameter is optional.
  • ORDER BY: Sorts the data in either ascending or descending order. This parameter is required.

CData Python Connector for Facebook Ads

Table-Valued Functions

Table-valued functions are functions that return a table (rowset).

Note: Table-valued function support is an experimental feature of the connector. This functionality extends beyond the connector's core scope of being SQL-92 compliant. As such, performance with these functions may not be optimal.

Table-Valued Function Clauses

CROSS APPLY

The CROSS APPLY operator is used to perform a subquery on each row of a table or resultset produced by a preceding table expression.

<table_expression_1> CROSS APPLY <table_expression_2>

The second table expression can reference results from the first table expression to create derived columns or an altered recordset via a table-valued function.

Each resulting record is an instance of the record it's splitting, with all the same column values, except for the column(s) containing the value split by the function.

WITH

The WITH clause is used alongside certain table-valued functions to match against constructs within the structure being split (keys, element names, attribute names, etc.) and/or to specify metadata for the columns generated from the function.
SELECT A.ColumnName, X.DerivedColumnName FROM TableName A CROSS APPLY <table-valued function> WITH (DerivedColumnName varchar(255)) AS X

Table-Valued Functions

STRING_SPLIT(input_text,delimiter)

Takes each record in the recordset of the preceding table expression, splits the column containing delimiters (input_text) into substrings separated by the delimiter, and returns one record per substring.

  • input_text: A column whose value you want to parse.
  • delimiter: The character used to split the value of the column specified in input_text.

Suppose there is a column called "SplitColumn" with the following content:

One-Two-Three
To unpack this value across multiple records:
SELECT A.ID, X.Value FROM [TableWithDelimitedStringField] A CROSS APPLY STRING_SPLIT(A.SplitColumn,'-') WITH (Value VARCHAR(255)) AS X

-- Results:
-----------
|ID|Value|
|1|One|
|1|Two|
|1|Three|

JSONTABLE(json_content,[jsonpath])

For each record in the recordset of the preceding table expression, returns one record for each instance of a key in a JSON array (json_content) that matches the key(s) specified in the WITH clause, at the scope specified by the "jsonpath" input.

  • json_content: A JSON "table" (array of objects). The contents can nest, but this must be a single JSON array, not any other JSON structure, at the root level.
    • The values of every instance of the key(s) provided in the WITH clause are retrievable only for substructures which are immediate children of the root-level JSON array.
  • jsonpath: An optional JSONPath query defining the scope, within the json_content array, that you want to pull content from. The JSON key(s) identified in the WITH clause must exist at the scope defined in this parameter. This defaults to the JSON root ($).

Consider a sample table with a single record, including an ID column and column with JSON content called "JSONColumn" with the following content:

[
	{
		"name": "Samuel",
		"email": "sam@gmail.com",
		"extrainfo": {
			"city": "Seattle"
		}
	},
	{
		"name": "Katherine",
		"email": "kat@gmail.com",
	},
	{
		"name": "George",
		"email": "george23@gmail.com",
	},
	{
		"name": "Carlos",
		"email": "carlos32@gmail.com",
	}
]

To extract all values for a certain key, specify the scope in the JSONTABLE function and provide the desired key(s) in the WITH clause.

SELECT A.ID, X.name FROM [TableWithJSONField] A CROSS APPLY JSONTABLE(A.JSONColumn) WITH (name VARCHAR(255)) AS X

-- Results: 
|ID|name|
---------
|1 |Samuel|
|1 |Katherine|
|1 |George|
|1 |Carlos|

XMLTABLE(xml_content,[xpath,child_type])

For each record in the resultset of the preceding table expression, returns one record for each of the elements and/or attributes in an XML structure (xml_content) that match the tag name(s) and/or attribute name(s) specified in the WITH clause, at the scope specified in the "xpath" input.

  • xml_content: A column containing an XML structure.
  • xpath: An optional XPath that specifies the scope within the XML structure at which the connector extracts content matching the tag/attribute name(s) specified in the WITH clause.
    • When extracting the content of sub-elements, the connector can retrieve all content from tags at the root level, (depth 0) immediate children of the root (depth 1), and children of those children (depth 2).
    • When extracting element attribute content, the connector can retrieve all content from tags containing the specified attribute at the root level (depth 0) and from immediate children of root-level elements (depth 1).
  • child_type: An optional parameter that specifies the part(s) of the parent element (specified in the xpath input) that the column(s) provided in the WITH clause are checked against to identify content.
    • You can supply the following values:
      • 0: The column(s) in the WITH clause are checked for matches against the parent element's attribute names and sub-element tag names.
      • 1: The column(s) in the WITH clause are checked for matches against the parent element's attribute names.
      • 2: The column(s) in the WITH clause are checked for matches against the parent element's sub-element tag names.
    • When not supplied, this defaults to 0.

Extracting Sub-Element Values

Consider a sample table with a single record, including an ID column and a column with XML content called "XMLContent" with the following content:
<shoppingList>
    <item>
        <name>Apples</name>
        <quantity>3</quantity>
        <unit>Kg</unit>
    </item>
    <item>
        <name>Bread</name>
        <quantity>2</quantity>
        <unit>Loaf</unit>
		<extrainfo>
			<Type>Whole-Grain</Type>
		</extrainfo>
    </item>
    <item>
        <name>Milk</name>
        <quantity>1</quantity>
        <unit>Carton</unit>
    </item>
    <item>
        <name>Eggs</name>
        <quantity>12</quantity>
        <unit></unit>
    </item>
</shoppingList>

To extract sub-element content, specify the scope in the XMLTABLE function and provide the desired element name(s) in the WITH clause. Note that this will not work if the XMLTABLE function's child_type input is set to 1.

SELECT A.ID, X.name FROM [TableWithXMLField] A CROSS APPLY XMLTABLE(A.XMLContent,'//*/item') WITH (name VARCHAR(255)) AS X

-- Results: 
|ID|name|
---------
|1|Apples|
|1|Bread|
|1|Milk|
|1|Eggs|

Extracting Values Using Element Tag Attributes

Suppose you have this sample table with a single record, including an ID column and a column with XML content called "XMLContent" with the following content:

<restaurant>
  <dish type="appetizer">
    <name lang="en">Caprese Salad</name>
    <chef>Chef Giovanni</chef>
    <price currency="USD">9.99</price>
  </dish>
  <dish type="main-course">
    <name lang="fr">Boeuf Bourguignon</name>
    <chef>Chef Marie</chef>
    <price currency="EUR">19.99</price>
  </dish>
  <dish type="dessert">
    <name lang="es">Tres Leches Cake</name>
    <chef>Chef Alejandro</chef>
    <price currency="MXN">89.99</price>
  </dish>
</restaurant>

To extract attribute content, specify the scope in the XMLTABLE function and provide the desired attribute name(s) in the WITH clause. Note that this will not work if the XMLTABLE function's child_type input is set to 2.

SELECT A.ID, X.type FROM [TableWithXMLField] A CROSS APPLY XMLTABLE(A.XMLContent,'//*/dish') WITH (type VARCHAR(255)) AS X

-- Results: 
|ID|type|
---------
|1|appetizer|
|1|main-course|
|1|dessert|

CSVTABLE(csv_content,[delimiter])

For each record in the resultset of the preceding table expression, reads from a column that contains a CSV table (csv_content) and for each record in that CSV table, returns one record containing the value of the CSV column(s) specified in the WITH clause.

  • csv_content: A column containing a CSV table.
  • delimiter: An optional custom delimiter (instead of a comma) which splits the CSV content contained in the csv_content input.

Consider a sample table with a single record, including an ID column and a column containing CSV table called "CSVContent" with the following content:

Name;Category;Price
Apple;Fruit;0.99
Spaghetti;Pasta;5.49
Chicken Breast;Meat;8.99
Broccoli;Vegetable;2.49

To select every value in the "Name" column and account for the custom delimiter (;):

SELECT A.ID, X.Name FROM [TableWithCSVField] A CROSS APPLY CSVTABLE(A.CSVContent,';') WITH (Name VARCHAR(255)) AS X

-- Results:
|ID|Name|
-----------
|1|Apple|
|1|Spaghetti|
|1|Chicken Breast|
|1|Broccoli|

CData Python Connector for Facebook Ads

CACHE Statements

When caching is enabled, CACHE statements provide complete control over the data that is cached and the table to which it is cached. The CACHE statement executes the SELECT statement specified and caches its results to a table with the same name in the cache database or to table specified in <cached_table_name>. The connector updates or inserts rows to the cache depending on whether or not they already exist in the cache, so the primary key, which is used to identify existing rows, must be included in the selected columns.

See Caching Data for more information on different caching strategies.

CACHE Statement Syntax

The cache statement may include the following options that alter its behavior:

CACHE [ <cached_table_name> ] [ WITH TRUNCATE | AUTOCOMMIT | SCHEMA ONLY | DROP EXISTING | ALTER SCHEMA ] <select_statement> 

WITH TRUNCATE

If this option is set, the connector removes existing rows in the cache table before adding the selected rows. Use this option if you want to refresh the entire cache table but keep its existing schema.

AUTOCOMMIT

If this option is set, the connector commits each row individually. Use this option if you want to ignore the rows that could not be cached due to some reason. By default, the entire result set is cached as a single transaction.

DROP EXISTING

If this option is set, the connector drops the existing cache table before caching the new results. Use this option if you want to refresh the entire cache table, including its schema.

SCHEMA ONLY

If this option is set, the connector creates the cache table based on the SELECT statement without executing the query.

ALTER SCHEMA

If this option is set, the connector alters the schema of the existing table in the cache if it does not match the schema of the SELECT statement. This option results in new columns or dropped columns, if the schema of the SELECT statement does not match the cached table.

Common Queries

Use the following cache statement to cache all rows of a table:

CACHE SELECT * FROM AdAccounts

Use the following cache statement to cache all rows of a table into the cache table CachedAdAccounts:

CACHE CachedAdAccounts SELECT * FROM AdAccounts

Use the following cache statement for incremental caching. The DateModified column may not exist in all tables. The cache statement shows how incremental caching would work if there were such a column. Also, notice that, in this case, the WITH TRUNCATE and DROP EXISTING options are specifically omitted, which would have deleted all existing rows.

CACHE CachedAdAccounts SELECT * FROM AdAccounts WHERE DateModified > '2013-04-04'

Use the following cache statements to create a table with all available columns that will then cache only a few of them. The sequence of statements cache only AccountId and Name even though the cache table CachedAdAccounts has all the columns in AdAccounts.

CACHE CachedAdAccounts SCHEMA ONLY SELECT * FROM AdAccounts
CACHE CachedAdAccounts SELECT AccountId, Name FROM AdAccounts

CData Python Connector for Facebook Ads

EXECUTE Statements

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

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

Stored Procedure Syntax

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

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

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

Example Statements

Reference stored procedure inputs by name:

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

Execute a parameterized stored procedure statement:

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

CData Python Connector for Facebook Ads

PIVOT and UNPIVOT

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

PIVOT

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

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

UNPIVOT

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

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

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

CData Python Connector for Facebook Ads

Data Model

The CData Python Connector for Facebook Ads models Facebook Ads APIs as relational Tables, Views, and Stored Procedures. The connector uses the Facebook Ads API to process supported filters. The connector processes other filters client-side within the connector.

Views

Views describes the available views. Two types of views are made available:

  • Base Views are statically defined to model Ad Accounts, Campaigns, Businesses, Lead Values, and more. They are used to create your custom reports instead of being used standalone. By default. these views return data from all time aggregated into a single row.
  • Predefined Report Views are a set of standard reports that mimic exactly what you see in the Facebook UI. All Predefined Report Views have "report" appended to their name. By default, these views return data from all time with a daily breakdown.

Stored Procedures

Stored Procedures are function-like interfaces to the data source. They can be used to search, update, and modify information in the data source.

Querying Facebook Ads Data

The connector supports filtering Facebook Ads views in several unique ways, such as by ad level, breakdown, time range, action collection, or action attribution. Also, many views require a target to be specified in queries. See Querying Facebook Ads Data for more information.

Insight Reports

The connector offers a selection of pre-built report views representing common reporting scenarios. Queries to these views are simpler than queries to AdInsights and AdInsightsActions. This is because querying each report view is equivalent to a more complex query containing the breakdowns and action collections associated with that reporting scenario, removing the need to specify them manually.

See Using Pre-Built Reports for a list of these pre-built reports, as well as instructions for defining additional report views.

CData Python Connector for Facebook Ads

Querying Facebook Ads Data

The ad data for Facebook Ads is represented and accessed through several tables and views exposed by the connector. There are a couple of general rules, presented below, for querying these tables and views.

See the pages for individual tables or views for additional details related to querying them.

Specifying a Target

For many views related to ads, a target must be specified when querying them in order to identify the specific ad or account object for which data should be retrieved. For example, when querying the Ads view, the Target column must be specificed as a criteria pointing to a specific ad account:
SELECT * FROM Ads WHERE Target = 'act_123456'
A Target can also be specified dynamically in a query:
SELECT * FROM Ads WHERE Target IN (SELECT ID FROM AdAccounts)
If no Target is specified in a query, and the Target connection property is not set, the AccountID connection property will be used to determine the default target for ads queries. If none of these are set, the first account id returned from Facebook Ads will be used.

Insights Views

Analytics, peformance, and reporting data for ads is accessed through the AdInsights and AdInsightsActions views. Queries to these views will require a Target as covered in the previous section, but also support more detailed query syntax for their reporting functionality.

Time Ranges

When trying to pull ad reporting and analytics, use DateStart and DateEnd or DatePreset in your query to control the time range of ads data.
SELECT DateStart, DateEnd, AdAccountId, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DateStart >= '01/01/2015' AND DateEnd <= '03/31/2015'

SELECT DateStart, DateEnd, AdAccountId, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DatePreset='last_90d' AND TimeIncrement='monthly'
When specifying a time range for ads data, use TimeIncrement to control the time span of ad data summarized in each result row. For example, if TimeIncrement is set to "monthly", each result row will correspond to a monthly roll-up of ad data.

Ad levels

The Target specified for a query will control what ad account ad data is retrieved for. Use Level to control what level of ad object results are reported at. Level can be set to ad, adset, campaign, or account.

Breakdowns

Facebook Ads offers a number of breakdowns for querying your ad insights data. These breakdowns are exposed and can be used through the AdInsights and AdInsightsActions views, such that each row returned for a query will correspond to the reporting data for one combination of the breakdowns specified in the query. The aggregated data returned for a breakdown combo will still be limited by the ad object target and ad object level specified in the query.

Facebook Ads does enforce restrictions on what breakdowns can be selected together, so by default the connector also enforces similar restrictions on breakdowns in queries supplied to it. If desired, this internal enforcement can be disabled through the IgnoreValidationException property. Setting this property to "True" bypasses internal enforcement of breakdown restrictions, and passes any supplied breakdown combination as-is to Facebook.

Please see Data Model for more info on breakdown combos.

Action Collections

The AdInsightsActions view also offers an ActionCollection column, which allows you to specify what sort of actions attributed to your ads you would like to look at.

Action Attributions

The AdInsightsActions view also offers an ActionAttributionWindows column, which allows you to control how Facebook Ads attributes actions to your ad object when it generates its report. ActionAttributionWindows are specified from a list of combinations that define action and time period combinations. For example, the default value for ActionAttributionWindows is "7d_click,1d_view", meaning that relevant actions taken within 7 days of clicking on your ad object or 1 day of viewing it are attributed to and reported on for the ad object.

CData Python Connector for Facebook Ads

Using Pre-Built Reports

There are a number of ways that you can query Facebook Ads to get ad insights data, and the AdInsights and AdInsightsActions views facilitate all of these querying methods. For a simplified datamodel and querying experience, we also offer alternatives: you can use pre-built, simplified reports that correspond to queries that you would write for AdInsights or AdInsightsActions, or you can define your own ad insights report with the CreateAdInsightsReport stored procedure.

Using the Pre-Built Reports

The driver contains the following pre-built reports:

  • AdInsights_ByActionReaction_90DayIncr
  • AdInsights_ByAge_90DayIncr
  • AdInsights_ByAgeAndGender_90DayIncr
  • AdInsights_ByCarousel_90DayIncr
  • AdInsights_ByCountry_90DayIncr
  • AdInsights_ByDevicePlatform_90DayIncr
  • AdInsights_ByDMA_90DayIncr
  • AdInsights_ByGender_90DayIncr
  • AdInsights_ByProductId_90DayIncr
  • AdInsights_ByPublisherPlatform_90DayIncr
  • AdInsights_ByRegion_90DayIncr
  • AdInsights_ByVideoSound_90DayIncr
  • AdInsights_ByVideoType_90DayIncr
  • AdInsights_TargetedLevel_90DayIncr

Queries to these views are simpler than queries to AdInsights and AdInsightsActions in that these views already define the breakdowns and action collections to query. Queries to these views still require the specification of a Target ad object, however, and can also still use the Level and ActionAttributionWindows filters.

SELECT * FROM AdInsights_ByActionReaction_90DayIncr WHERE Target='act_12345' AND Level='adset'

The naming scheme for the views defines the breakdowns queried by the view, and the default time increment used by the view. The views will attempt to query ads data as far back in time as possible. The time span and time increment for the default views can be changed by query inputs.

Defining Custom Reports with CreateAdInsightsReport

If you routinely need to request fields that are not available on the pre-built reports that ship with the connector, or you want to create a simpler ad report for your users, you may want to define your own custom ads report so that you can more easily query for the data you need. The CreateAdInsightsReport stored procedure can be used for this purpose.

The stored procedure outputs schema files, depdending on the output options supplied. Set the Location connection property to the output path of the generated reports to expose them as queryable tables in the connector.

The example stored procedure call below creates a custom ad insights report with the specified fields, breakdowns, action breakdowns, and action collections:

EXEC CreateAdInsightsReport @ReportName = 'AdInsights_CreatedReport', @Fields = 'AccountCurrency,AdAccountId', @Breakdowns = 'Country', @ActionBreakdowns='ActionType,ActionDestination',@ActionCollection='Actions,UniqueActions', @OutputDirectory='LOCATION'"
In this example, the @OutputDirectory parameter is set to the location specified for the Location connection property.

CData Python Connector for Facebook Ads

Tables

The connector models the data in Facebook Ads as a list of tables in a relational database that can be queried using standard SQL statements.

CData Python Connector for Facebook Ads Tables

Name Description
CustomAudiences Query information about custom audiences defined for your ad accounts.
CustomConversions Query information about custom conversions defined for your ad accounts.

CData Python Connector for Facebook Ads

CustomAudiences

Query information about custom audiences defined for your ad accounts.

Table Specific Information

Custom audiences in Facebook Ads represent an advertiser-defined audience to deliver ads to.

SELECT

The ExternalEventSource column is not returned by default, as it requires additional permissions for the underlying AdPixels object. To retrieve information for this column, it should be set in the query projection explicitly:

SELECT Id, Name, ExternalEventSource FROM CustomAudiences

Note: Listing CustomAudiences while selecting ExternalEventSource will only return CustomAudiences where the currently authenticated app has access to the underlying AdsPixel object.

Insert

When inserting CustomAudiences, at least a Name, Subtype, and CustomerFileSource must be specified:

INSERT INTO CustomAudiences (Name, Subtype, CustomerFileSource) VALUES ('Custom Audience', 'CUSTOM', 'USER_PROVIDED_ONLY')

Note: To insert users to a Custom Audience, the AddCustomAudienceUsers stored procedure must be used.

Update

When updating CustomAudiences, the ID of the object must be specified in the WHERE clause:

UPDATE CustomAudiences SET Name='TestCustomAudience123' WHERE ID='123abc'

Note: The Facebook Marketing API only supports updates on the following fields: Name, Description, Rule, RuleAggregation, RetentionDays, CustomerFileSource, OptOutLink, EnableFetchOrCreate, UseInCampaigns, ContentType, ClaimObjective, EventSourceGroup, ProductSetId

Delete

When deleting CustomAudiences, the Id of the object should be specified.

DELETE FROM CustomAudiences WHERE Id='123456'

Note: To delete users from a Custom Audience, the DeleteCustomAudienceUsers stored procedure must be used.

Columns

Name Type ReadOnly Description
ID [KEY] String True

The ID of the custom audience.

Target String False

The Id of the Account, Campaign, Ad Group, or Ad to retrieve custom audiences for.

Account_ID String True

The ID of the custom audience's ad account.

Name String False

The name of the custom audience.

Description String False

The description of the custom audience.

Subtype String False

The subtype of the custom audience. Valid values are: CUSTOM, PRIMARY, WEBSITE, APP, OFFLINE_CONVERSION, CLAIM, MANAGED, PARTNER, VIDEO, LOOKALIKE, ENGAGEMENT, BAG_OF_ACCOUNTS, STUDY_RULE_AUDIENCE, FOX, MEASUREMENT, REGULATED_CATEGORIES_AUDIENCE, BIDDING, SUBSCRIBER_SEGMENT, EXCLUSION

TimeCreated Datetime True

Creation time of the custom audience.

TimeUpdated Datetime True

Last updated time of the custom audience.

TimeContentUpdated Datetime True

Last update of people in this custom audience. Only supported for Customer List Custom Audiences.

Rule String False

Audience rules to be applied on the referrer URL.

RuleAggregation String False

Aggregation on top of the audience rule.

ApproximateCountLowerBound Integer True

Lower bound of the approximate number of people in this audience.

ApproximateCountUpperBound Integer True

Upper bound of the approximate number of people in this audience.

PixelID String False

ID of pixel which is collecting events for Website Custom audience.

RetentionDays Integer False

Number of days to retain user in this audience. Can be any value between 1 and 180 days. Defaults to forever if left unspecified. Only available for Customer File Custom Audience.

CustomerFileSource String False

Source of customer information in the uploaded file.

DataSource String True

JSON dictionary to indicate the method by which the custom audience was created.

DeliveryStatus String True

JSON dictionary which indicates whether an audience can be used in ads.

ExternalEventSource String True

JSON dictionary containing the pixel id whose traffic generated the custom audience. Only returned if explicitly requested.

OperationStatus String True

JSON dictionary containing status code and description of last operation.

PermissionForActions String True

JSON dictionary of permissions (string) to boolean value if the custom audience has that permission.

IsValueBased Boolean False

Whether the audience is used to seed value based lookalike.

OptOutLink String False

Opt-out URL for audience members who choose not to be targeted.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
EnableFetchOrCreate Boolean

When set to true during INSERT, this parameter causes any identical custom audience to be fetched. Prevents INSERT of duplicate audience.

UseInCampaigns Boolean

Controls whether this custom audience will be used in campaigns. Defaults to true.

Prefill Boolean

If true, website traffic recorded prior to audience creation will be used to initialize this audience. If false, only website traffic garnered after the creation of this audience will be used.

DatasetId Integer

ID of offline conversion dataset associated with this audience.

ContentType String

Specifies content type for TRAVEL claim objective. Mandatory if creating audience with TRAVEL claim objective. Valid values are: AUTOMOTIVE_MODEL, DESTINATION, FLIGHT, GENERIC, HOME_LISTING, HOTEL, JOB, LOCAL_SERVICE_BUSINESS, MEDIA_TITLE, OFFLINE_PRODUCT, PRODUCT, VEHICLE, VEHICLE_OFFER

ClaimObjective String

Specifies objective of audiences with CLAIM subtype. Valid values are: AUTOMOTIVE_MODEL, COLLABORATIVE_ADS, HOME_LISTING, MEDIA_TITLE, PRODUCT, TRAVEL, VEHICLE, VEHICLE_OFFER.

EventSourceGroup Integer

Specifies event source group if using TRAVEL claim objective.

ProductSetId Integer

Id of the Product Set to target with this audience.

OriginAudienceId Integer

Id of origin Custom Audience. Origin audience must have a minimum size of 100.

CData Python Connector for Facebook Ads

CustomConversions

Query information about custom conversions defined for your ad accounts.

Table Specific Information

Custom conversions in Facebook represent conversion events to optimize ad delivery.

Insert

When inserting CustomConversions, at least a Name must be specified:

INSERT INTO CustomConversions (Name) VALUES ('TestConversion')

If inserting to the Rule or AdvancedRule columns, the rule configuration should be specified as a JSON aggregate:

INSERT INTO CustomConversions (Name, EventSourceId, Rule, CustomEventType) 
VALUES 
 ('test',
 '871481174114636',
 '{"and":[{"event":{"eq": "Purchase"}},{"value":{"gt":100}}]}',
 'PURCHASE')

See the Facebook Marketing API documentation on CustomConversions for all available Rule configurations.

Update

When updating CustomConversions, the ID of the object must be specified in the WHERE clause:

UPDATE CustomConversions SET Name='test1' WHERE ID='123abc'

Note: The Facebook Marketing API only supports updates on the DefaultConversionValue, Name, and Description columns.

Delete

When deleting CustomConversions, the Id of the object should be specified:

DELETE FROM CustomConversions WHERE ID='123abc'

Columns

Name Type ReadOnly Description
Target String False

The Id of the Account, Campaign, Ad Group, or Ad to get insights for.

ID [KEY] String True

The ID of the custom conversion

Account_ID String True

The ID of the custom conversion's ad account

BusinessID String True

ID of business that owns the custom conversion

BusinessName String True

Name of business that owns the custom conversion

CreationTime Datetime True

Time at which the conversion was created

CustomEventType String False

The type of the conversion event

The allowed values are ADD_PAYMENT_INFO, ADD_TO_CART, ADD_TO_WISHLIST, COMPLETE_REGISTRATION, CONTENT_VIEW, INITIATED_CHECKOUT, LEAD, PURCHASE, SEARCH, CONTACT, CUSTOMIZE_PRODUCT, DONATE, FIND_LOCATION, SCHEDULE, START_TRIAL, SUBMIT_APPLICATION, SUBSCRIBE, LISTING_INTERACTION, FACEBOOK_SELECTED, OTHER.

DataSourcesId String True

ID for event sources of the custom conversion

DataSourcesName String True

Name for event sources of the custom conversion

DataSourcesSourceType String True

Source type for event sources of the custom conversion

DefaultConversionValue Decimal False

When conversion is URL based, the default conversion value associated to each conversion

Description String False

Description of the custom conversion

EventSourceType String True

Event source type of the custom conversion, e.g. pixel, app, etc.

FirstFiredTime Datetime True

Time at which the pixel was first fired

IsArchived Boolean True

Whether this conversion is archived. Archived conversions are no longer tracked in the system.

IsUnavailable Boolean True

Whether this conversion is unavailable

LastFiredTime Datetime True

Time at which the pixel was last fired

Name String False

Name of the custom conversion

OfflineConversionDataSet String True

The offline event set that contains events

PixelID String True

ID of the pixel that will send events

RetentionDays Integer True

Retention period for advanced rule

Rule String False

Rule of the custom conversion

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
EventSourceId String

Event source Id.

AdvancedRule String

Advanced ruleset for the custom conversion being created allowing multiple sources.

ActionSourceType String

Action source type the custom conversion is created from.

The allowed values are app, chat, email, other, phone_call, physical_store, system_generated, website, business_messaging.

CData Python Connector for Facebook Ads

Views

Views are similar to tables in the way that data is represented; however, views are read-only.

Queries can be executed against a view as if it were a normal table.

CData Python Connector for Facebook Ads Views

Name Description
Action_Canvas_Component_Report Ad Report focusing on clicks and ROAS, broken down by canvas component. Accessing Ad Report information requires the ads_read permission.
Action_Carousel_Card_Report Ad Report focusing on clicks and ROAS, broken down by carousel. Accessing Ad Report information requires the ads_read permission.
Action_Conversion_Device_Report Ad Report focusing on clicks and ROAS, broken down by serving device and conversion device. Accessing Ad Report information requires the ads_read permission.
Action_Product_Id_Report Ad Report focusing on clicks and ROAS, broken down by product id. Accessing Ad Report information requires the ads_read permission.
Action_Reactions_Report Ad Report focusing on clicks and ROAS, broken down by reactions. Accessing Ad Report information requires the ads_read permission.
Action_Video_Sound_Report Ad Report focusing on video consumption, broken down by sound status. Accessing Ad Report information requires the ads_read permission.
Action_Video_View_Type_Report Ad Report focusing on video consumption, broken down by video type. Accessing Ad Report information requires the ads_read permission.
AdAccounts Query the Ad Accounts available for a User. Accessing Ad Account information requires the ads_read permission.
AdCreatives Query information about an Ad Creative or the Ad Creatives on a specific Ad Account, Ad Set, or Ad. Accessing Ad Creative information requires the ads_read permission.
AdImages Images associated with an ad account
AdInsights Queries an Ad Report. Accessing Ad Report information requires the ads_read permission.
AdInsightsActions Query an Ad Report. Accessing Ad Report information requires the ads_read permission.
AdInsightsAssets Queries an Ad Report with asset breakdowns. Accessing Ad Report information requires the ads_read permission.
AdInsightsMMM Queries ad insights data for the marketing mix modeling breakdown. Accessing this information requires the ads_read permission.
AdLabels Query information about ad labels. Accessing Ad Information requires the ads_read permission.
Ads Query information about an Ad or the Ads in a specific Ad Set, Campaign, or Ad Account. Accessing Ad Information requires the ads_read permission.
AdSets Query information about an Ad Set or the Ad Sets on a specific Campaign or Ad Account. Accessing Ad Set information requires the ads_read permission.
Albums Query Albums associated with a Target. Accessing Album information typically requires the user_photos permission.
AuthorizedAdAccounts Ad Accounts authorized to run ads for your business on a specified app. This view requires that you have at least one business configured for your user id.
Basic_Ad_Report Ad Report focused on ads, broken down by action type. Accessing Ad Report information requires the ads_read permission.
Basic_Ad_Set_Report Ad Report focused on ad sets, broken down by action type. Accessing Ad Report information requires the ads_read permission.
Basic_All_Levels_Report Ad Report focused on ads, broken down by action type. Accessing Ad Report information requires the ads_read permission.
Basic_Campaign_Report Ad Report focused on ads and providing information on parent campaigns and ad sets, broken down by action type. Accessing Ad Report information requires the ads_read permission.
Businesses Query the Businesses of a Facebook user. Accessing Business information requires the business_management permission.
Campaigns Query information about a Campaign or the Campaigns on a specific Ad Account. Accessing Campaign information requires the ads_read permission.
Delivery_Device_Report Ad Report focused on campaigns, broken down by device or platform used for viewing ad. Accessing Ad Report information requires the ads_read permission.
Delivery_Platform_And_Device_Report Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.
Delivery_Platform_Report Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.
Delivery_Purchase_Roas_Report Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.
Demographic_Age_And_Gender_Report Ad Report focused on campaigns, broken down by age and gender demographics. Accessing Ad Report information requires the ads_read permission.
Demographic_Age_Report Ad Report focused on campaigns, broken down by age demographics. Accessing Ad Report information requires the ads_read permission.
Demographic_Country_Report Ad Report focused on campaigns, broken down by country demographics. Accessing Ad Report information requires the ads_read permission.
Demographic_DMA_Region_Report Ad Report focused on campaigns, broken down by Designated Market Area. Accessing Ad Report information requires the ads_read permission.
Demographic_Gender_Report Ad Report focused on campaigns, broken down by gender. Accessing Ad Report information requires the ads_read permission.
Demographic_Region_Report Ad Report focused on campaigns, broken down by sub-country geographic region. Accessing Ad Report information requires the ads_read permission.
LeadValues Query information about a lead. Accessing Lead Information requires the ads_read and either pages_manage_ads or leads_retrieval permissions.
Pages Query the Pages based on the supplied Id.
Permissions Query the Permissions the User has granted the current application.

CData Python Connector for Facebook Ads

Action_Canvas_Component_Report

Ad Report focusing on clicks and ROAS, broken down by canvas component. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
ActionCanvasComponentName String Name of a component within a Canvas ad.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Carousel_Card_Report

Ad Report focusing on clicks and ROAS, broken down by carousel. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
ActionCarouselCardId String The ID of the specific carousel card that people engaged with when they saw your ad.
ActionCarouselCardName String The specific carousel card that people engaged with when they saw your ad. The cards are identified by their headlines.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Conversion_Device_Report

Ad Report focusing on clicks and ROAS, broken down by serving device and conversion device. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
ActionDevice String The device on which the conversion event you are tracking occurred.
DevicePlatform String The device or platform used for viewing the ad. This is a breakdown column that may not be selected with other breakdown columns.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Product_Id_Report

Ad Report focusing on clicks and ROAS, broken down by product id. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
AdId String The Id of the Ad associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
ProductId String The product Id advertised in the Ad. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Reactions_Report

Ad Report focusing on clicks and ROAS, broken down by reactions. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
AdId String The Id of the Ad associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: ActionValues, MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
ActionReaction String The number of reactions on your ads or boosted posts.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Video_Sound_Report

Ad Report focusing on video consumption, broken down by sound status. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: Video30SecWatchedActions, VideoAvgTimeWatchedActions, VideoP100WatchedActions, VideoP25WatchedActions, VideoP50WatchedActions, VideoP75WatchedActions, VideoThruplayWatchedActions
ActionVideoSound String The sound status (on/off) when user watches your video ad.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Action_Video_View_Type_Report

Ad Report focusing on video consumption, broken down by video type. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionValue Integer Metric value of default attribution window.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
ActionCollection String The action collection to retrieve. The available values are: Video30SecWatchedActions, VideoAvgTimeWatchedActions, VideoP100WatchedActions, VideoP25WatchedActions, VideoP50WatchedActions, VideoP75WatchedActions, VideoThruplayWatchedActions
ActionVideoType String Video metrics breakdown.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

AdAccounts

Query the Ad Accounts available for a User. Accessing Ad Account information requires the ads_read permission.

Table Specific Information

AdAccounts in Facebook are the accounts you have available in Facebook for creating Ads on. The Ids for them are always returned in the format "act_" and when they are used as a Target in requests for other tables, the Id with the prefix "act_" must always be used.

Select

When querying AdAccounts, the Id or Target can be used to filter results. For instance:

SELECT * FROM AdAccounts WHERE Id = 'act_123456'

If you use Facebook Business Manager and manage AdAccounts for clients, all of the ad account ids your business has access to can be listed like so:

SELECT Id FROM AdAccounts WHERE Target IN (SELECT Id FROM Businesses)

Otherwise if Id is not specified, the accounts available for your user account will be listed.

Columns

Name Type Description
ID [KEY] String The Id of Ad Account.
Target String The target to get ad accounts from such as a business id.
AccountId String The Id of the Ad Account when viewed directly in Facebook.
AccountStatus Integer Status of the account. 1 = Active, 2 = Disabled, 3 = Unsettled, 7 = Pending Review, 9 = in Grace Period, 101 = temporarily unavailable, 100 = pending closure.
Age Double Amount of time the ad account has been open, in days.
AmountSpent Integer Current total amount spent by the account. This can be reset.
Balance Integer Bill amount due.
BusinessCity String City for business address.
BusinessCountryCode String Country code for the business address.
BusinessName String The business name for the account.
BusinessState String State abbreviation for business address.
BusinessStreet String First line of the business street address for the account.
BusinessStreet2 String Second line of the business street address for the account.
BusinessZip String Zip code for business address.
Capabilities String Capabilities allowed for this ad account.
CreatedTime Datetime The time the account was created.
Currency String The currency used for the account, based on the corresponding value in the account settings.
MinCampaignGroupSpendCap String The minimum campaign group spend limit.
Name String Name of the account; note that many accounts are unnamed, so this field may be empty.
OffsitePixelsTosAccepted String Indicates whether the offsite pixel Terms Of Service contract was signed.
OwnerId String Facebook ID of the owner fo the Ad Account.
SpendCap Integer The maximum that can be spent by this account after which campaigns will be paused. A value of 0 signifies no spending-cap.
TimezoneId String ID for the timezone.
TimezoneName String Name for the time zone.
TimezoneOffsetHoursUTC Double Time Zone difference from UTC.

CData Python Connector for Facebook Ads

AdCreatives

Query information about an Ad Creative or the Ad Creatives on a specific Ad Account, Ad Set, or Ad. Accessing Ad Creative information requires the ads_read permission.

Table Specific Information

AdCreatives in Facebook represent a collection of the creatives for specific Ads in Facebook.

Select

When querying ad creatives, either the Id or Target must be used to filter results. The Target may be an ad account, ad set, or ad. For instance:

SELECT * FROM AdCreatives WHERE Target = 'adid'

Columns

Name Type Description
ID [KEY] String The Id of Ad Creative.
Target String The Ad Account Id or Campaign Id to get Ad Sets of.
Name String The name of the Ad Creative.
ApplinkTreatment String Deep link fallback behavior for dynamic product ads if the app is not installed.

The allowed values are deeplink_with_web_fallback, deeplink_with_appstore_fallback, web_only.

Body String The body of the ad.
CallToActionType String The call to action button text and header text of legacy ads.

The allowed values are OPEN_LINK, LIKE_PAGE, SHOP_NOW, PLAY_GAME, INSTALL_APP, USE_APP, INSTALL_MOBILE_APP, USE_MOBILE_APP, BOOK_TRAVEL, LISTEN_MUSIC, LEARN_MORE, SIGN_UP, DOWNLOAD, WATCH_MORE, NO_BUTTON, CALL_NOW, BUY_NOW, GET_OFFER, GET_OFFER_VIEW, GET_DIRECTIONS, MESSAGE_PAGE, SUBSCRIBE, SELL_NOW, DONATE_NOW, GET_QUOTE, CONTACT_US, RECORD_NOW, VOTE_NOW, REGISTER_NOW, OPEN_MOVIES.

EffectiveInstagramMediaId String The ID of an Instagram post to use in an ad.
ImageHash String Image hash for an image you can use in creatives.
ImageUrl String A URL for the image for this creative. The image specified at this URL will be saved into the ad account's image library.
InstagramPermalinkUrl String Instagram permalink.
InstagramUserId String The ID of an Instagram user for creating ads.
LinkOgId String The Open Graph (OG) ID for the link in this creative if the landing page has OG tags.
LinkUrl String Used to identify a specific landing tab on the Page (e.g. a Page tab app) by the Page tab's URL.
ObjectId String The ID of the promoted_object or object that is relevant to the ad and ad type.
ObjectStoryId String The ID of a page post to use in an ad.
ObjectType String The type of object that is being advertised.

The allowed values are APPLICATION, DOMAIN, EVENT, OFFER, PAGE, PHOTO, SHARE, STATUS, STORE_ITEM, VIDEO, INVALID.

ObjectUrl String Destination URL for a link ads not connected to a page.
PageId String The actor ID (Page ID) of this creative.
ProductSetId String The ID of the product set for this creative.
RunStatus String The run status of this creative.

The allowed values are ACTIVE, DELETED.

SourceInstagramMediaId String The ID of an Instagram post for creating ads.
TemplateUrl String The Tracking URL for dynamic product ads.
ThumbnailUrl String The URL to a thumbnail for this creative.
Title String Title for a link ad (not connected to a Page).
UrlTags String A set of query string parameters which will replace or be appended to urls clicked from page post ads, message of the post, and canvas app install creatives only.
UsePageActorOverride Boolean If this is true, we will show the page actor for mobile app ads.
AdLabels String Ad Labels that are associated with this creative.
ObjectStorySpecLinkData String The link data to create a new unpublished page post. Will only have a value when other ObjectStorySpec columns are null.
ObjectStorySpecPhotoData String The photo data to create a new unpublished page post. Will only have a value when other ObjectStorySpec columns are null.
ObjectStorySpecVideoData String The video data to create a new unpublished page post. Will only have a value when other ObjectStorySpec columns are null.
ObjectStorySpecTextData String The text data to create a new unpublished page post. Will only have a value when other ObjectStorySpec columns are null.
ObjectStorySpecTemplateData String The template data to create a new unpublished page post. Will only have a value when other ObjectStorySpec columns are null.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
ThumbnailHeight String Rendered height of thumbnails provided in thumbnail_url, in pixels. Default 64.
ThumbnailWidth String Rendered width of thumbnails provided in thumbnail_url, in pixels. Default 64.

CData Python Connector for Facebook Ads

AdImages

Images associated with an ad account

Table Specific Information

Ad Images in Facebook represent individual images that can be used with ad creatives.

Select

When querying ad images, a Target can be specified so that ad images are queried for the correct ad account. If no Target is specified, the driver will query from the first ad account it finds for your user account:

SELECT * FROM AdImages WHERE Target = 'act_123456'

Columns

Name Type Description
ID String The Id of image.
Target String The target ad account to pull images from.
AccountId String The id of the ad account of the image.
CreatedTime Datetime The datetime the image was created.
Creatives String The name of the Ad the lead originates from.
hash String The unique hash of the image.
height Integer The height of the image.
width Integer The width of the image.
AssociatedWithCreatives Boolean Whether the image is associated with any ad creatives.
name String The filename of the image.
OriginalHeight Integer The height of the original uploaded image
OriginalWidth Integer The width of the original uploaded image
Status String The status of the image.
PermalinkUrl String The permanent URL of the image to use in ad creatives.

CData Python Connector for Facebook Ads

AdInsights

Queries an Ad Report. Accessing Ad Report information requires the ads_read permission.

Table Specific Information

Facebook AdInsights can be requested with a great amount of detail, to simulate the same sort of information that can be retrieved in a report.

Select

When requesting AdInsights, always include a Target. The Target specifies the element from which to retrieve the insights. Legal Targets are AdAccount, Campaign, AdSet, or an Ad. For example:
SELECT * FROM AdInsights WHERE Target = 'act_123456'

Columns that are always fetched by default during a SELECT * query against Adinsights:

  • Target
  • DateStart
  • DateEnd
  • AccountCurrency
  • AdAccountId
  • AdAccountName
  • Impressions
  • Spend

Metrics Columns

When running a SELECT * query on an Adinsights report, not all of the metrics columns are retrieved from Facebook. This means that certain columns may return “0” or null values if column metadata is retrieved in a prior request. To fetch this data, these columns must be included in the SELECT portion of the query, rather than using SELECT *.

Metrics columns that may display this behavior in Adinsights include:

  • BuyingType
  • Clicks
  • ConversionRateRanking
  • CostPerEstimatedAdRecallers
  • CostPerInlineLinkClick
  • CostPerInlinePostEngagement
  • CostPerUniqueClick
  • CostPerUniqueInlineLinkClick
  • CPC
  • CPM
  • CPP
  • CTR
  • EstimatedAdRecallRate
  • EstimatedAdRecallers
  • Frequency
  • Impressions
  • InlineLinkClicks
  • InlineLinkClicksCounter
  • InlinePostEngagement
  • InstantExperienceClicksToOpen
  • InstantExperienceClicksToStart
  • InstantExperienceOutboundClicks
  • Objective
  • QualityRanking
  • Reach
  • Spend
  • UniqueClicks
  • UniqueCTR
  • UniqueInLineLinkClicks
  • UniqueInLineLinkClickCounter
  • UniqueLinkClicksCounter
  • Checkins
  • EventResponses
  • LinkClicks
  • OfferSaves
  • OutboundClicks
  • PageEngagements
  • PageLikes
  • PageMentions
  • PagePhotoViews
  • PostComments
  • PostEngagements
  • PostShares
  • PostReactions
  • PageTabViews
  • Video3SecondViews

Date Presets

To specify a data range, use either DateStart and DateEnd, or DatePreset. Available values for DatePreset:

  • maximum
  • today
  • yesterday
  • this_week_sun_today
  • this_week_mon_today
  • last_week_sun_sat
  • last_week_mon_sun
  • last_3d
  • last_7d
  • last_14d
  • last_28d
  • last_30d
  • last_90d
  • this_month
  • last_month

For example:

SELECT DateStart, DateEnd, AdAccountId, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DateStart >= '01/01/2015' AND DateEnd <= '03/31/2015'

SELECT DateStart, DateEnd, AdAccountId, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DatePreset = 'last_90d'

To specify how many days should be included in each report row, use TimeIncrement. For example:

SELECT DateStart, DateEnd, AdAccountId, Age, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DatePreset = 'last_90d' AND TimeIncrement = '7'

SELECT DateStart, DateEnd, AdAccountId, Age, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND DatePreset = 'last_90d' AND TimeIncrement = 'monthly'

To specify the level at which insights should be retrieved, use the Level column. Legal values are ad, adset, campaign, or account. For example:

SELECT DateStart, DateEnd, AdAccountId, Age, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' AND Level = 'campaign'

Note: Both the DatePreset and the breakdowns are subject to frequent changes by Facebook. The lists above may be outdated due to Facebook changes. To see the most currently available breakdowns and date presets, see the documentation on Facebook for parameters and breakdowns at https://developers.facebook.com/docs/marketing-api/insights/.

Breakdown Columns

There are a number of breakdown columns. In general, only one breakdown column can be selected at a time. If you use SELECT *, no breakdown columns will be used. The available breakdown columns are:

  • Age: Can also be selected with Gender
  • Country
  • FrequencyValue
  • Gender: Can also be selected with Age
  • HStatsByAdvertiserTZ (Hourly Stats by Advertizer Timezone)
  • HStatsByAudienceTZ (Hourly Stats by Audience Timezone)
  • ImpressionDevice: Can also be selected with PublisherPlatform or both PublisherPlatform and PlatformPosition.
  • PlatformPosition: Must be selected with PublisherPlatform. Can also be selected with ImpressionDevice.
  • PublisherPlatform: Can be selected with PlatformPosition, ImpressionDevice, or both PlatformPosition and ImpressionDevice.
  • ProductId
  • Region

Most other columns not already mentioned can be used with standard SQL WHERE clause modifiers. For instance:

SELECT DateStart, DateEnd, AdAccountId, Spend, Impressions FROM AdInsights WHERE Target = 'act_123456' WHERE Impressions > 10000 AND Spend < 1000

Facebook Ads enforces restrictions on what breakdowns can be selected together, so by default the connector also enforces similar restrictions on breakdowns in queries supplied to it. If desired, you can bypass internal enforcement of breakdown restrictions by setting IgnoreValidationException to True. This passes any supplied breakdown combination to Facebook as-is.

Note: Both the DatePreset and the breakdowns are subject to frequent changes by Facebook. The lists above may be outdated due to Facebook changes. To see the most currently available breakdowns and date presets, see the documentation on Facebook for parameters and breakdowns at https://developers.facebook.com/docs/marketing-api/insights/.

Managing Query Size

Sometimes if a query is too large for Facebook to process on its end, you might receive this error: Please reduce the amount of data you're asking for, then retry your request. The error appears to be triggered by individually dense fields, and not the page size.

If the connector encounters this error when first executing certain types of queries, the driver attempts to retry the query at the next lowest level of ad object, down to the level defined in RetryLevel, as long as the query does not include the Level parameter. (If the Level parameter is specified in a query, the driver does not attempt to retry beyond the ad object level specified by Level. For further information, see RetryLevel.) Note that since spreading queries across more granular ad objects increases the number of requests executed for the query, it can decrease query performance.

If you continue to receive this error, try either reducing the date range of the query, or removing expensive columns.

A good method for finding and removing expensive columns is to use a binary search by removing half of the columns you are selecting and retrying the query. If you get the same error, reduce the remaining columns by half and try again. If you do not get an error, add back half of the columns you just removed, and try again.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range is automatically calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

AccountCurrency String The currency that is being used by the ad account.
ActionAttributionWindows String A comma separated list that determines what is the attribution window for the actions. For example, 28d_click means the API returns all actions that happened 28 days after someone clicked on the ad. The default option means [1d_view,28d_click]. Possible values include 1d_view, 7d_view, 28d_view, 1d_click, 7d_click, 28d_click, default.
AdAccountId String The Id of the Ad Account that is associated with the report row.
AdAccountName String The name of the Ad Account that is associated with the report row.
CampaignId String The Id of the Campaign that is associated with the report row.
CampaignName String The name of the Campaign that is associated with the report row.
AdSetId String The Id of the Ad Set that is associated with the report row.
AdSetName String The name of the Ad Set that is associated with the report row.
AdId String The Id of the Ad that is associated with the report row.
AdName String The name of the Ad that is associated with the report row.
AdvancedReach1DLookback String advanced_reach_1d_lookback.
AdvancedReach7DLookback String advanced_reach_7d_lookback.
AdvancedReach28DLookback String advanced_reach_28d_lookback.
AnchorEventAttributionSetting String anchor_event_attribution_setting.
AnchorEventsPerformanceIndicator String anchor_events_performance_indicator.
AttributionSetting String Default attribution window to be used when attribution result is calculated. Each ad set has its own attribution setting value. The attribution setting for campaign or account is calculated based on existing ad sets.
AuctionBid String auction_bid.
AuctionCompetitiveness String auction_competitiveness.
AuctionMaxCompetitorBid String auction_max_competitor_bid.
BuyingType String The method by which target ads are paid for in your campaigns.
CanvasAvgViewPercent Double Average percentage of the Instant Experience that Accounts Center accounts saw.
CanvasAvgViewTime Double Average total time, in seconds, that Accounts Center accounts spent viewing an Instant Experience.
Clicks Long The total number of clicks on your ad. Depending on what you're promoting, this can include Page likes, event responses or app installs. In the Facebook UI, this is the Clicks (All) field.
ConversionRateRanking String The conversion rate ranking.
CostPerDDACountByConvs Decimal cost_per_dda_countby_convs.
CostPerEstimatedAdRecallers Decimal The average cost per additional person that we estimate will recall seeing your ad if asked within 2 days.
CostPerInlineLinkClick Decimal The average cost per click on links in the ad.
CostPerInlinePostEngagement Decimal The average cost per engagement on the post.
CostPerUniqueClick Decimal The average cost per unique click for these ads, calculated as the amount spent divided by the number of unique clicks received.
CostPerUniqueInlineLinkClick Decimal The average you paid for each unique inline link click.
CostPerObjectiveResult String The average cost per objective result from your ads.
CostPerResult String The average cost per result from your ads.
CPC Decimal The average cost per click for these ads, calculated as the amount spent divided by the number of clicks received.
CPM Decimal The average cost that you've paid to have 1,000 impressions on your ad.
CPP Decimal The average cost that you've paid to have your ad served to 1,000 unique people.
CTR Double The number of clicks you received divided by the number of impressions. In the Facebook UI, this is the CTR (All) % field.
CreatedTime String created_time.
DDACountByConvs String dda_countby_convs.
DDAResults String dda_results.
EstimatedAdRecallRate Double The estimated number of people who recall your ad divided by the number of people your ad reached.
EstimatedAdRecallers Double The additional number of people that we estimate will remember seeing your ads if asked within 2 days.
Frequency Double The average number of times that your ad was served to each person.
FullViewImpressions Long The number of Full Views on your Page's posts as a result of your ad.
FullViewReach Long The number of Accounts Center accounts that performed a Full View on your Page's post as a result of your ad.
Impressions Long The number of times that your ad was served. On our mobile apps an ad is counted as served the first time it's viewed. On all other Facebook interfaces, an ad is served the first time it's placed in a person's News Feed or each time it's placed in the right column.
InlineLinkClicks Long Total number of clicks on links in the ad.
InlineLinkClicksCounter Double The click-through rate for inline clicks to link.
InlinePostEngagement Long The total number of engagements on the post.
InstagramProfileVisits Long The number of times your Instagram profile was visited.
InstagramUpcomingEventRemindersSet Long instagram_upcoming_event_reminders_set.
InstantExperienceClicksToOpen Long instant_experience_clicks_to_open
InstantExperienceClicksToStart Long instant_experience_clicks_to_start
InstantExperienceOutboundClicks Long instant_experience_outbound_clicks
LandingPageViewPerLinkClick Double landing_page_view_per_link_click.
MarketingMessagesDelivered Double The number of messages your business sent to customers that were delivered.
MarketingMessagesDeliveryRate Double The number of messages delivered divided by the number of messages sent.
MarketingMessagesReadRateBenchmark String Metric is the 75th percentile of read rates across similar businesses, representing the percentage of messages read out of total messages delivered.
MultiEventConversionAttributionSetting String multi_event_conversion_attribution_setting.
Objective String The objective you selected for your campaign. Your objective reflects the goal you want to achieve with your advertising.
ObjectiveResultRate String The number of objective results you received divided by the number of impressions.
ObjectiveResults String The number of responses you wanted to achieve from your ad campaign, based on your selected objective.
OptimizationGoal String The optimization goal you selected for your ad or ad set.
PlacePageName String The name of the place page involved in impression or click. Has to be used together with Business Locations breakdown.
ProductGroupRetailerId String product_group_retailer_id.
ProductRetailerId String product_retailer_id.
ProductViews String product_views.
PurchasePerLandingPageView String purchase_per_landing_page_view.
QualifyingQuestionQualifyAnswerRate Double qualifying_question_qualify_answer_rate.
QualityRanking String The quality ranking.
Reach Long The number of people your ad was served to.
ResultRate String The percentage of results you received out of all the views of your ads.
Results String The number of times your ad achieved an outcome, based on the objective and settings you selected.
ResultValuesPerformanceIndicator String result_values_performance_indicator.
ShopsAssistedPurchases String shops_assisted_purchases.
SocialSpend Double The total amount you've spent so far for your ads showed with social information.
Spend Decimal The total amount you've spent so far.
TotalCardView String total_card_view.
UpdatedTime String updated_time.
UniqueClicks Long The total number of unique people who have clicked on your ad. For example, if 3 people click on the same ad 5 times, it counts as 3 unique clicks.
UniqueCTR Double The number of people who clicked on your ad divided by the number of people you reached. For example, if you received 20 unique clicks and your ad was served to 1,000 unique people, your unique click-through rate would be 2%.
UniqueInlineLinkClicks Long The number of unique inline link clicks that your ad got. In the Facebook UI, this is the Unique Clicks to Link field.
UniqueInlineLinkClickCounter Double The click-through rate for unique inline clicks to link.
UniqueLinkClicksCounter Double The unique click-through rate for clicks to link. The number of people who clicked on the link in your ad that directs people off Facebook divided by the number of people you reached. Example: if you received 20 unique clicks to link and your ad was shown to 1,000 unique people, your unique click-through rate would be 2%.
TotalPostbacks String Total postbacks. Due to API limitations, this field cannot be selected with any additional fields, and therefore is not included when the query projection contains a wildcard.
TotalPostbacksDetailed String Total postbacks detailed. Due to API limitations, this field cannot be selected with any additional fields, and therefore is not included when the query projection contains a wildcard.
WishBid Double wish_bid.
Checkins Int The number of checkins attributed to the Ad.
EventResponses Int The number of event responses attributed to the Ad.
LinkClicks Int The number of link clicks attributed to the Ad.
OfferSaves Int The number of receive offers attributed to the Ad.
OutboundClicks Int The number of outbound clicks attributed to the Ad.
PageEngagements Int The number of page enagements attributed to the Ad.
PageLikes Int The number of page likes attributed to the Ad.
PageMentions Int The number of page mentions attributed to the Ad.
PagePhotoViews Int The number of photo views attributed to the Ad.
PostComments Int The number of post comments attributed to the Ad.
PostEngagements Int The number of post engagements attributed to the Ad.
PostShares Int The number of post shares attributed to the Ad.
PostReactions Int The number of post reactions attributed to the Ad.
PageTabViews Int The number of tab views attributed to the Ad.
Video3SecondViews Int The number of video views attributed to the Ad. Views count if at least 3 seconds or the entire video (if the video is less than 3 seconds) were played.
PixelAddToCart Int Pixel adds to cart.
PixelPurchase Int Pixel purchases.
Age String The age range for the metrics in this row. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ComscoreMarket String The Comscore-defined market segment associated with the ad impression, used for audience measurement and cross-media planning. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
Country String The country for the metrics in this row. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DevicePlatform String The device or platform used for viewing the ad. This is a breakdown column that may not be selected with other breakdown columns.
DMA String The designated marketing area. This is a breakdown column that may not be selected with other breakdown columns.
FlexibleFormatAssetType String The asset type (such as image or video) used in a Flexible Ad Format placement, where Facebook dynamically selects the best-performing format from the provided creative assets. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
FrequencyValue String The number of times an ad in your Reach and Frequency campaign was served to each person. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
Gender String The gender for the metrics in this row. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
HStatsByAdvertiserTZ String Time period over which the stats were taken for the advertiser. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
HStatsByAudienceTZ String Time period over which the stats were taken for the audience. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImpressionDevice String The devices used to view the Ad. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
PlacePageId String The place page used if applicable. This is a breakdown column that may not be selected with other breakdown columns.
PlatformPosition String The position on the platform.
ProductId String The product Id advertised in the Ad. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
PublisherPlatform String The platforms the ads were published on.
ReelsTrendingTopic String The trending topic category associated with the Reels placement where the ad was displayed. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
RuleSetId String The unique identifier of the rule set associated with the ad delivery, used to segment insights by specific automation or eligibility rules applied to campaigns. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
RuleSetName String The name of the rule set associated with the ad delivery, used to segment insights by specific automation or eligibility rules applied to campaigns. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
Region String The region someone viewed the Ad from. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AdFormatAsset String Ad format asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetId String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetText String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetId String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetName String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetId String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetText String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetId String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetHash String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetUrl String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetId String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetText String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetId String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetWebsiteUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetDisplayUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetThumbnailUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoName String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AppId String The ID of the application associated with the ad account or campaign requested. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacks field.
IsConversionIdModeled String Whether the conversion_bits are modeled. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacksDetailed field.
SkanCampaignId String The raw campaign ID received as a part of Skan postback from iOS 15+. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacksDetailed field.
SkanConversionId String The assigned Conversion ID of the event and or event bundle configured in the application's SKAdNetwork configuration schema. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacks field.
UserSegmentKey String User segment of Advantage+ Shopping Campaigns. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AdEffectiveStatus String An input only list of supported statuses when retrieving insights at a level lower than the Ad Account. See the values listed on AdStatus for an example of valid values.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.
DefaultSummary Boolean A boolean indicating if we should get the default summary.

CData Python Connector for Facebook Ads

AdInsightsActions

Query an Ad Report. Accessing Ad Report information requires the ads_read permission.

Table Specific Information

AdInsightsActions represents a breakdown of the Actions column from the AdInsights. See AdInsights for general information on querying AdInsights.

Select

When requesting AdInsightsActions, always include a Target. The Target specifies the element from which to retrieve the insights. Legal Targets are AdAccount, Campaign, AdSet, or an Ad. For example:
SELECT * FROM AdInsightsActions WHERE Target = 'act_123456'
Columns that are always fetched by default during a SELECT * query against Adinsightsactions:

  • Target
  • DateStart
  • DateEnd
  • AdAccountId
  • AdAccountName

Metrics Columns

When running a SELECT * query on an Adinsightsactions report, not all of the metrics columns are retrieved from Facebook. This means that certain columns may return “0” or null values if column metadata is retrieved in a prior request.

Metrics columns that may display this behavior in Adinsightsactions include:

  • ActionType
  • ActionValue
  • Action1dClick
  • Action1dView
  • Action7dClick
  • Action7dView
  • Action28dClick
  • Action28dView
  • ActionSkanView
  • ActionSkanClick
  • ActionSkanViewSecondPostback
  • ActionSkanClickSecondPostback
  • ActionSkanViewThirdPostback
  • ActionSkanClickThirdPostback
  • ActionDDA

ActionAttributionWindows

To input a comma-separated list of attribution windows, use ActionAttributionWindows. For example:
SELECT * FROM AdInsightsActions WHERE Target = 'act_123456' AND level = 'ad' AND ActionAttributionWindows = '1d_view,7d_view,28d_click'

ActionCollection

To identify a specific collection to retrieve from AdInsightsActions, use ActionCollection. If no collection is specified, the driver uses Actions by default. Each input represents an available column from AdInsights where a collection of actions would return.

To identify multiple collections, use ActionCollection with the IN clause.

For example:

SELECT * FROM AdInsightsActions WHERE Target = 'act_123456' AND ActionCollection = 'UniqueActions'

SELECT * FROM AdInsightsActions WHERE Target = 'act_123456' AND ActionCollection IN ('Actions', 'UniqueActions')

Breakdown Columns

Just as in the available selection criterias from AdInsights, breakdowns are available for the Adinsightsactions report. For further information about breakdowns, see AdInsights.

Additional breakdowns available for AdInsightsActions include:

  • ActionType
  • ActionCanvasComponentName
  • ActionCarouselCardId
  • ActionCarouselCardName
  • ActionDestination
  • ActionDevice
  • ActionLinkClickDestination
  • ActionReaction
  • ActionTargetId
  • ActionVideoSound
  • ActionVideoType
  • ComscoreMarket
  • FlexibleFormatAssetType
  • ReelsTrendingTopic
  • RuleSetId
  • RuleSetName

Managing Query Size

Sometimes if a query is too large for Facebook to process on its end, you might receive this error: Please reduce the amount of data you're asking for, then retry your request. The error appears to be triggered by individually dense fields, and not the page size.

If the connector encounters this error when first executing certain types of queries, the driver attempts to retry the query at the next lowest level of ad object, down to the level defined in RetryLevel, as long as the query does not include the Level parameter. (If the Level parameter is specified in a query, the driver does not attempt to retry beyond the ad object level specified by Level. For further information, see RetryLevel.) Note that since spreading queries across more granular ad objects increases the number of requests executed for the query, it can decrease query performance.

If you continue to receive this error, try either reducing the date range of the query, or removing expensive columns.

A good method for finding and removing expensive columns is to use a binary search by removing half of the columns you are selecting and retrying the query. If you get the same error, reduce the remaining columns by half and try again. If you do not get an error, add back half of the columns you just removed, and try again.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionAttributionWindows String A comma separated list which determines what is the attribution window for the actions. For example, 28d_click means the API returns all actions that happened 28 days after someone clicked on the ad. The default option means [1d_view,7d_click]. Possible values include 1d_view, 7d_view, 28d_view, 1d_click, 7d_click, 28d_click, skan_view, skan_click, skan_view_second_postback, skan_click_second_postback, skan_view_third_postback, skan_click_third_postback, default.
ActionCollection String The action collection to retrieve. The available values are: ActionValues, Actions, AdClickActions, AdImpressionActions, CatalogSegmentActions, CatalogSegmentValue, CatalogSegmentValueMobilePurchaseRoas, CatalogSegmentValueOmniPurchaseRoas, CatalogSegmentValueWebsitePurchaseRoas, ConversionValues, Conversions, converted_product_app_custom_event_fb_mobile_purchase, converted_product_app_custom_event_fb_mobile_purchase_value, converted_product_offline_purchase, converted_product_offline_purchase_value, converted_product_omni_purchase, converted_product_omni_purchase_values, ConvertedProductQuantity, ConvertedProductValue, converted_product_website_pixel_purchase, converted_product_website_pixel_purchase_value, converted_promoted_product_app_custom_event_fb_mobile_purchase, converted_promoted_product_app_custom_event_fb_mobile_purchase_value, converted_promoted_product_offline_purchase, converted_promoted_product_offline_purchase_value, converted_promoted_product_omni_purchase, converted_promoted_product_omni_purchase_values, converted_promoted_product_quantity, converted_promoted_product_value, CostPer15_secVideoView, converted_promoted_product_website_pixel_purchase, converted_promoted_product_website_pixel_purchase_value, CostPer2SecContinuousVideoView, CostPerActionType, CostPerAdClick, CostPerConversion, CostPerOneThousandAdImpression, CostPerOutboundClick, CostPerThruplay, CostPerUniqueActionType, CostPerUniqueConversion, CostPerUniqueOutboundClick, InteractiveComponentTap, MobileAppPurchaseRoas, OutboundClicks, OutboundClicksCtr, PurchaseRoas, UniqueActions, UniqueConversions, UniqueOutboundClicks, UniqueOutboundClicksCtr, UniqueVideoView15_sec, Video15_secWatchedActions, Video30_secWatchedActions, VideoAvgTimeWatchedActions, VideoContinuous2SecWatchedActions, VideoP100_watchedActions, VideoP25WatchedActions, VideoP50WatchedActions, VideoP75WatchedActions, VideoP95WatchedActions, VideoPlayActions, VideoPlayCurveActions, VideoPlayRetention0To15SActions, VideoPlayRetention20_to60SActions, VideoPlayRetentionGraphActions, VideoTimeWatchedActions, WebsiteCtr, WebsitePurchaseRoas

The default value is Actions.

AdAccountId String The Id of the Ad Account associated with the report row.
AdAccountName String The name of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
AdSetId String The Id of the Ad Set associated with the report row.
AdSetName String The name of the Ad Set associated with the report row.
AdId String The Id of the Ad associated with the report row.
AdName String The name of the Ad associated with the report row.
TotalPostbacks String Total postbacks. Due to API limitations, this field cannot be selected with any additional fields, and therefore is not included when the query projection contains a wildcard.
TotalPostbacksDetailed String Total postbacks detailed. Due to API limitations, this field cannot be selected with any additional fields, and therefore is not included when the query projection contains a wildcard.
ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Double Metric value of default attribution window.
Action1dClick String Metric value of attribution window 1 day after clicking the ad.
Action1dView String Metric value of attribution window 1 day after viewing the ad.
Action7dClick String Metric value of attribution window 7 days after clicking the ad.
Action7dView String Metric value of attribution window 7 days after viewing the ad.
Action28dClick String Metric value of attribution window 28 days after clicking the ad.
Action28dView String Metric value of attribution window 28 days after viewing the ad.
ActionSkanView String Metric value of SKAdNetwork attribution window after viewing the ad.
ActionSkanClick String Metric value of SKAdNetwork attribution window after clicking the ad.
ActionSkanViewSecondPostback String Metric value of SKAdNetwork attribution window after viewing the ad.
ActionSkanClickSecondPostback String Metric value of SKAdNetwork attribution window after clicking the ad.
ActionSkanViewThirdPostback String Metric value of SKAdNetwork attribution window after viewing the ad.
ActionSkanClickThirdPostback String Metric value of SKAdNetwork attribution window after clicking the ad.
ActionDDA String Metric value of attribution window which is powered by data driven model.
ActionCanvasComponentName String Name of a component within a Canvas ad.
ActionCarouselCardId String The ID of the specific carousel card that people engaged with when they saw your ad.
ActionCarouselCardName String The specific carousel card that people engaged with when they saw your ad. The cards are identified by their headlines.
ActionConvertedProductId String Converted product ids - for Collaborative Ads.
ActionDestination String The destination where people go after clicking on your ad.
ActionDevice String The device on which the conversion event you are tracking occurred.
ActionReaction String The number of reactions on your ads or boosted posts.
ActionTargetId String The id of destination where people go after clicking on your ad.
ActionVideoSound String The sound status (on/off) when user watches your video ad.
ActionVideoType String Video metrics breakdown.
ConversionDestination String Conversion destination.
SignalSourceBucket String Signal source bucket.
StandardEventContentType String Standard canvas component name.
Age String The age range for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
ComscoreMarket String The Comscore-defined market segment associated with the ad impression, used for audience measurement and cross-media planning. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
Country String The country for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
DevicePlatform String The device or platform used for viewing the ad. This is a breakdown column that may not be selected with other breakdown columns.
DMA String The designated marketing area. This is a breakdown column that may not be selected with other breakdown columns.
FlexibleFormatAssetType String The asset type (such as image or video) used in a Flexible Ad Format placement, where Facebook dynamically selects the best-performing format from the provided creative assets. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
FrequencyValue String The number of times an ad in your Reach and Frequency campaign was served to each person. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
Gender String The gender for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
HStatsByAdvertiserTZ String Time period over which the stats were taken for the advertiser. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
HStatsByAudienceTZ String Time period over which the stats were taken for the audience. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
ImpressionDevice String The devices used to view the Ad. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
PlacePageId String The place page used if applicable. This is a breakdown column that may not be selected with other breakdown columns.
PlatformPosition String The position on the platform.
ProductId String The product Id advertised in the Ad. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
PublisherPlatform String The platforms the ads were published on.
ReelsTrendingTopic String The trending topic category associated with the Reels placement where the ad was displayed. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
RuleSetId String The unique identifier of the rule set associated with the ad delivery, used to segment insights by specific automation or eligibility rules applied to campaigns. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
RuleSetName String The name of the rule set associated with the ad delivery, used to segment insights by specific automation or eligibility rules applied to campaigns. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
Region String The region someone viewed the Ad from. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
AdFormatAsset String Ad format asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetId String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetText String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetId String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetName String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetId String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetText String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetId String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetHash String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetUrl String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetId String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetText String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetId String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetWebsiteUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetDisplayUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetThumbnailUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoName String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AppId String The ID of the application associated with the ad account or campaign requested. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacks field.
IsConversionIdModeled String Whether the conversion_bits are modeled. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacksDetailed field.
SkanCampaignId String The raw campaign ID received as a part of Skan postback from iOS 15+. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacksDetailed field.
SkanConversionId String The assigned Conversion ID of the event and or event bundle configured in the application's SKAdNetwork configuration schema. This is a breakdown column and selecting this column causes results to be further broken down by this metric. Only supported by the TotalPostbacks field.
UserSegmentKey String User segment of Advantage+ Shopping Campaigns. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AdEffectiveStatus String An input only list of supported statuses when retrieving insights at a level lower than the Ad Account. See the values listed on AdStatus for an example of valid values.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

AdInsightsAssets

Queries an Ad Report with asset breakdowns. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Ad or Ad Set for which to get insights. Note that the asset breakdowns cannot target an Ad Account.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range is automatically calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

AccountCurrency String The currency that is being used by the ad account.
ActionAttributionWindows String A comma separated list that determines what is the attribution window for the actions. For example, 28d_click means the API returns all actions that happened 28 days after someone clicked on the ad. The default option means [1d_view,28d_click]. Possible values include 1d_view, 7d_view, 28d_view, 1d_click, 7d_click, 28d_click, default.
AdAccountId String The Id of the Ad Account that is associated with the report row.
AdAccountName String The name of the Ad Account that is associated with the report row.
CampaignId String The Id of the Campaign that is associated with the report row.
CampaignName String The name of the Campaign that is associated with the report row.
AdSetId String The Id of the Ad Set that is associated with the report row.
AdSetName String The name of the Ad Set that is associated with the report row.
AdId String The Id of the Ad that is associated with the report row.
AdName String The name of the Ad that is associated with the report row.
BuyingType String The method by which target ads are paid for in your campaigns.
Clicks Long The total number of clicks on your ad. Depending on what you're promoting, this can include Page likes, event responses or app installs. In the Facebook UI, this is the Clicks (All) field.
ConversionRateRanking String The conversion rate ranking.
CostPerEstimatedAdRecallers Decimal The average cost per additional person that we estimate will recall seeing your ad if asked within 2 days.
CostPerInlineLinkClick Decimal The average cost per click on links in the ad.
CostPerInlinePostEngagement Decimal The average cost per engagement on the post.
CostPerUniqueClick Decimal The average cost per unique click for these ads, calculated as the amount spent divided by the number of unique clicks received.
CostPerUniqueInlineLinkClick Decimal The average you paid for each unique inline link click.
CPC Decimal The average cost per click for these ads, calculated as the amount spent divided by the number of clicks received.
CPM Decimal The average cost that you've paid to have 1,000 impressions on your ad.
CPP Decimal The average cost that you've paid to have your ad served to 1,000 unique people.
CTR Double The number of clicks you received divided by the number of impressions. In the Facebook UI, this is the CTR (All) % field.
EstimatedAdRecallRate Double The estimated number of people who recall your ad divided by the number of people your ad reached.
EstimatedAdRecallers Double The additional number of people that we estimate will remember seeing your ads if asked within 2 days.
Frequency Double The average number of times that your ad was served to each person.
Impressions Long The number of times that your ad was served. On our mobile apps an ad is counted as served the first time it's viewed. On all other Facebook interfaces, an ad is served the first time it's placed in a person's News Feed or each time it's placed in the right column.
InlineLinkClicks Long Total number of clicks on links in the ad.
InlineLinkClicksCounter Double The click-through rate for inline clicks to link.
InlinePostEngagement Long The total number of engagements on the post.
InstantExperienceClicksToOpen Long instant_experience_clicks_to_open
InstantExperienceClicksToStart Long instant_experience_clicks_to_start
InstantExperienceOutboundClicks Long instant_experience_outbound_clicks
Objective String The objective you selected for your campaign. Your objective reflects the goal you want to achieve with your advertising.
QualityRanking String The quality ranking.
Reach Long The number of people your ad was served to.
Spend Decimal The total amount you've spent so far.
UniqueClicks Long The total number of unique people who have clicked on your ad. For example, if 3 people click on the same ad 5 times, it counts as 3 unique clicks.
UniqueCTR Double The number of people who clicked on your ad divided by the number of people you reached. For example, if you received 20 unique clicks and your ad was served to 1,000 unique people, your unique click-through rate would be 2%.
UniqueInlineLinkClicks Long The number of unique inline link clicks that your ad got. In the Facebook UI, this is the Unique Clicks to Link field.
UniqueInlineLinkClickCounter Double The click-through rate for unique inline clicks to link.
UniqueLinkClicksCounter Double The unique click-through rate for clicks to link. The number of people who clicked on the link in your ad that directs people off Facebook divided by the number of people you reached. Example: if you received 20 unique clicks to link and your ad was shown to 1,000 unique people, your unique click-through rate would be 2%.
Checkins Int The number of checkins attributed to the Ad.
EventResponses Int The number of event responses attributed to the Ad.
LinkClicks Int The number of link clicks attributed to the Ad.
OfferSaves Int The number of receive offers attributed to the Ad.
OutboundClicks Int The number of outbound clicks attributed to the Ad.
PageEngagements Int The number of page enagements attributed to the Ad.
PageLikes Int The number of page likes attributed to the Ad.
PageMentions Int The number of page mentions attributed to the Ad.
PagePhotoViews Int The number of photo views attributed to the Ad.
PostComments Int The number of post comments attributed to the Ad.
PostEngagements Int The number of post engagements attributed to the Ad.
PostShares Int The number of post shares attributed to the Ad.
PostReactions Int The number of post reactions attributed to the Ad.
PageTabViews Int The number of tab views attributed to the Ad.
Video3SecondViews Int The number of video views attributed to the Ad. Views count if at least 3 seconds or the entire video (if the video is less than 3 seconds) were played.
PixelAddToCart Int Pixel adds to cart.
PixelPurchase Int Pixel purchases.
Age String The age range for the metrics in this row. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
Gender String The gender for the metrics in this row. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetId String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
BodyAssetText String Body asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetId String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
DescriptionAssetText String Description asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetId String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetHash String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
ImageAssetUrl String Image asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetId String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
TitleAssetText String Title asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetId String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
CallToActionAssetName String Call to action asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetId String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetWebsiteUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
LinkUrlAssetDisplayUrl String Link url asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoId String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetThumbnailUrl String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
VideoAssetVideoName String Video asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AdFormatAsset String Ad format asset level breakdown. This is a breakdown column and selecting this column causes results to be further broken down by this metric.
AdEffectiveStatus String An input only list of supported statuses when retrieving insights at a level lower than the Ad Account. See the values listed on AdStatus for an example of valid values.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.
DefaultSummary Boolean A boolean indicating if we should get the default summary.

CData Python Connector for Facebook Ads

AdInsightsMMM

Queries ad insights data for the marketing mix modeling breakdown. Accessing this information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range is automatically calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

AccountId String account_id of the Marketing Mix Modeling aggregate.
CampaignId String campaign_id of the Marketing Mix Modeling aggregate.
AdSetId String adset_id of the Marketing Mix Modeling aggregate.
DateStart Date date_start of the Marketing Mix Modeling aggregate.
DateEnd Date date_stop of the Marketing Mix Modeling aggregate.
Impressions String impressions of the Marketing Mix Modeling aggregate.
Spend String spend of the Marketing Mix Modeling aggregate.
Country String country of the Marketing Mix Modeling aggregate.
Region String region of the Marketing Mix Modeling aggregate.
DMA String dma of the Marketing Mix Modeling aggregate.
DevicePlatform String device_platform of the Marketing Mix Modeling aggregate.
PlatformPosition String platform_position of the Marketing Mix Modeling aggregate.
PublisherPlatform String publisher_platform of the Marketing Mix Modeling aggregate.
CreativeMediaType String creative_media_type of the Marketing Mix Modeling aggregate.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights. Due to API limitations, the MMM breakdown must be used asynchronously so this defaults to true.

The default value is true.

CData Python Connector for Facebook Ads

AdLabels

Query information about ad labels. Accessing Ad Information requires the ads_read permission.

Table Specific Information

Ad labels associated with an ad.

Select

When querying ad labels, either the Id or Target must be used to filter results. For instance:

SELECT * FROM AdLabels WHERE Target = 'act_123456'

Additionally, UpdatedTime may be used with the > or >= operators to retrieve only records newer than a certain date. For instance:

SELECT * FROM AdLabels WHERE Target = 'act_123456' AND UpdatedTime > '01/01/2016' 

Columns

Name Type Description
ID [KEY] String The Id of Ad label.
Target String The Ad Account Id to retrieve labels from.
Name String The name of the Ad label.
CreatedTime Datetime The time when the Ad label was created.
UpdatedTime Datetime When the Ad label was last updated.

CData Python Connector for Facebook Ads

Ads

Query information about an Ad or the Ads in a specific Ad Set, Campaign, or Ad Account. Accessing Ad Information requires the ads_read permission.

Table Specific Information

Ads in Facebook represent individual ads that have been created.

Select

When querying ads, either the Id or Target must be used to filter results. For instance:

SELECT * FROM Ads WHERE Target = 'act_123456'

Additionally, UpdatedTime may be used with the > or >= operators to retrieve only records newer than a certain date. For instance:

SELECT * FROM Ads WHERE Target = 'act_123456' AND UpdatedTime > '01/01/2016' 

Columns

Name Type Description
ID [KEY] String The Id of Ad.
Target String The Ad Account Id, Campaign Id, or Ad Set Id to get Ads in.
Name String The name of the Ad.
AdStatus String The status of the Ad.

The allowed values are ACTIVE, PAUSED, CAMPAIGN_PAUSED, CAMPAIGN_GROUP_PAUSED, CREDIT_CARD_NEEDED, DISABLED, DISAPPROVED, PENDING_REVIEW, PREAPPROVED, PENDING_BILLING_INFO, ARCHIVED, DELETED.

BidInfo String The value of the bid info taken from the Ad Set.
BidType String The bid type value taken from the Ad Set.

The allowed values are CPM, CPC, MULTI_PREMIUM, ABSOLUTE_OCPM, CPA.

CampaignId String The Id of the Campaign the Ad belongs to.
AdSetId String The Id of the Ad Set the Ad belongs to.
AdCreativeId String The Id of the Ad Creative associated with the Ad.
ConfiguredStatus String The configured status of the ad. Prefer using 'status' instead of this.

The allowed values are ACTIVE, PAUSED, DELETED, ARCHIVED.

CreatedTime Datetime The time when the Ad was created.
UpdatedTime Datetime When the Ad was last updated.
ConversionSpecs String The Ad's conversion specs.
FailedDeliveryChecks String Possible checks that could have failed which will prevent the Ad from showing up.
Recommendations String If there are recommendations for this ad, this field includes them. Otherwise, this field will be null.
TrackingSpecs String The Ad's tracking specification. This field will be defaulted based on the objective, if not set to NONE, or based on the ad creative.
AdActiveTime String The time from when the ad was recently active.
AdScheduleEndTime Datetime An optional parameter that defines the end time of an individual ad. If no end time is defined, the ad will run on the campaign’s schedule.
AdScheduleStartTime Datetime An optional parameter that defines the start time of an individual ad. If no start time is defined, the ad will run on the campaign’s schedule.
BidAmount Integer Bid amount for this ad which will be used in auction.
LastUpdatedByAppId String Indicates the app used for the most recent update of the ad.
PreviewShareableLink String A link that enables users to preview ads in different placements.
SourceAdId String The source ad id that this ad is copied from.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
DateStart Date The starting date to retrieve ads.
DateEnd Date The ending date to retrieve ads.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

CData Python Connector for Facebook Ads

AdSets

Query information about an Ad Set or the Ad Sets on a specific Campaign or Ad Account. Accessing Ad Set information requires the ads_read permission.

Table Specific Information

AdSets in Facebook represent a collection of Ads in Facebook.

Select

When querying ad sets, either the Id or Target must be used to filter results. The Target may be an ad account, or a campaign. For instance:

SELECT * FROM AdSets WHERE Target = 'act_123456'

Columns

Name Type Description
ID [KEY] String The Id of Ad Set.
Target String The Ad Account Id or Campaign Id to get Ad Sets of.
Name String The name of the Ad Set.
BudgetRemaining Integer The amount of budget remaining for this Ad Set.
CampaignId String The Ad Campaign this ad set is a part of.
AdSetStatus String The status of the Ad Set.

The allowed values are ACTIVE, PAUSED, ARCHIVED, DELETED.

BillingEvent String The billing event that this adset is using: APP_INSTALLS: Pay when people install your app. CLICKS: Pay when people click anywhere in the ad. IMPRESSIONS: Pay when the ads are shown to people. LINK_CLICKS: Pay when people click on the link of the ad. OFFER_CLAIMS: Pay when people claim the offer. PAGE_LIKES: Pay when people like your page. POST_ENGAGEMENT: Pay when people engage with your post. VIDEO_VIEWS: Pay when people watch videos.
CreatedTime Datetime When the Ad Set was created.
DailyBudget Integer The daily budget of the set defined in your account currency, it is allowed only for ad sets with a duration longer than 24 hours.
LifetimeBudget Decimal The lifetime budget of the set defined in your account currency.
EndTime Datetime When the Ad Set is scheduled to end.
StartTime Datetime When the Ad Set started.
UpdatedTime Datetime The time the Ad Set was last updated.
Recommendations String If there are recommendations for this ad set, this field includes them. Otherwise, this field will be null.
TargetingGenders Integer Indicates gender-based targeting. 0=all, 1=male, 2=female.

The allowed values are 0, 1, 2.

TargetingAgeMax Integer Maximum age. If used, must be 65 or lower.
TargetingAgeMin Integer Minimum age. If used, must be 13 or higher. If omitted, will default to 18.
TargetingCountries String Values for country targeting.
TargetingLocationTypes String Values for the types of locations to target.
TargetingRegions String The state, province, or region.
TargetingCities String Cities to target with a radius and distance.
TargetingZips String The zip codes used for targeting.
TargetingCustomLocations String Any custom locations to target.
TargetingGeoMarkets String They key for the market. The destination market areas (DMA) and keys are in the format DMA:NUMBER, such as DMA:501.
TargetingInterests String Interests to target based on.
TargetingBehaviors String Behaviors to target based on.
TargetingDevicePlatforms String The device platforms to target.
TargetingPublisherPlatforms String The publisher platforms to target.
TargetingInstagramPositions String The instagram positions to target.
TargetingPageTypes String The types of pages to use when targeting. Values may include desktop, feed, desktopfeed, mobile, rightcolumn, rightcolumn-and-mobile, home, mobilefeed-and-external, desktop-and-mobile-and-external, feed-and-external, rightcolumn-and-mobile-and-external.
LearningStageInfoStatus String Learning Phase progress for the ad set.
LearningStageInfoConversions Integer Number of conversions the ad set generated since the time of its last significant edit during the learning phase.
LearningStageInfoAttributionWindows String Number of days between when a person viewed or clicked your ad and subsequently took action.
LearningStageInfoLastSigEditTime Datetime Timestamp of the last significant edit that caused ad set to reenter the learning phase.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
DateStart Date The starting date to retrieve ad sets.
DateEnd Date The ending date to retrieve ad sets.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

IsCompleted Boolean Filter by completed status.

CData Python Connector for Facebook Ads

Albums

Query Albums associated with a Target. Accessing Album information typically requires the user_photos permission.

Columns

Name Type Description
ID [KEY] String The Id of the album.
Target String The Id or username of the target you are retrieving albums from.
Name String The name of the album.
FromId String Id of the user who owns the album.
FromName String Name of the user who owns the album.
FromPicture String The picture of user the album is from.
FromCategory String The category of user the album is from. FromCategory may only be retrieved if the other From* fields are not selected.
Description String A description of the album.
Location String The location of the album.
Link String A link to this album on Facebook.
CoverPhoto String The album cover photo Id.
Privacy String The privacy settings for the album.
Count Integer The number of photos in this album.
Type String The type of the album: profile, mobile, wall, normal or album.
CommentsCount Integer The number of comments for the album.
CommentsData String An aggregate of comment data.
CreatedTime Datetime When the album was uploaded.
UpdatedTime Datetime When the album was last updated.

CData Python Connector for Facebook Ads

AuthorizedAdAccounts

Ad Accounts authorized to run ads for your business on a specified app. This view requires that you have at least one business configured for your user id.

Table Specific Information

AuthorizedAdAccounts in Facebook represent the ad accounts that have been authorized for advertising on the specified application for your Facebook business. You must have a business set up in Facebook for this view to work correctly.

Select

When querying AuthorizedAdAccounts, a Target must be specified and a business may optionally be specified. For instance:

SELECT * FROM AdAccounts WHERE Target = 'ApplicationId' AND Business = 'BusinessId'

If no business is specified, results for all of your available businesses will come back.

Columns

Name Type Description
ID [KEY] String The Id of the Ad Account.
Target String The app id to request authorized ad accounts from.
AccountId String The Id of the Ad Account when viewed directly in Facebook.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
Business String The id of the business to retrieve authorized ad accounts for.

CData Python Connector for Facebook Ads

Basic_Ad_Report

Ad Report focused on ads, broken down by action type. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
AdSetId String The Id of the Ad Set associated with the report row.
AdSetName String The name of the Ad Set associated with the report row.
AdId String The Id of the Ad associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Basic_Ad_Set_Report

Ad Report focused on ad sets, broken down by action type. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
AdSetId String The Id of the Ad Set associated with the report row.
AdSetName String The name of the Ad Set associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Basic_All_Levels_Report

Ad Report focused on ads, broken down by action type. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
AdSetId String The Id of the Ad Set associated with the report row.
AdSetName String The name of the Ad Set associated with the report row.
AdId String The Id of the Ad associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Basic_Campaign_Report

Ad Report focused on ads and providing information on parent campaigns and ad sets, broken down by action type. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Businesses

Query the Businesses of a Facebook user. Accessing Business information requires the business_management permission.

Columns

Name Type Description
ID [KEY] String The Id of the business.
Name String The name of the business.
PrimaryPage String The primary page of the business.
TimezoneId String The timezone id of the business.
Link String The link of the business.
CreatedTime Datetime When the business was added.
UpdatedTime Datetime When the business was updated.

CData Python Connector for Facebook Ads

Campaigns

Query information about a Campaign or the Campaigns on a specific Ad Account. Accessing Campaign information requires the ads_read permission.

Table Specific Information

Campaigns in Facebook represent advertising campaigns that individual Ads or AdSets may be a part of.

Select

When querying campaigns, either the Id or Target must be used to filter results. The Target must be an ad account. For instance:

SELECT * FROM Campaigns WHERE Target = 'act_123456'

Columns

Name Type Description
ID [KEY] String The Id of Campaign.
Target String The target or Ad Account Id to get Campaigns.
Name String The name of the Campaign.
BuyingType String This field will help Facebook make future optimizations to delivery, pricing, and limits. All ad sets in this campaign must match the buying type.

The allowed values are AUCTION, FIXED_CPM, RESERVED.

ConfiguredStatus String If this status is PAUSED, all its active ad sets and ads will be paused and have an effective status CAMPAIGN_PAUSED. Prefer using 'status' instead of this.

The allowed values are ACTIVE, PAUSED, DELETED, ARCHIVED.

EffectiveStatus String The effective status of this campaign. For example, when all Ad Sets beneath the campaign are paused, the effective status is ADSET_PAUSED..

The allowed values are ACTIVE, PAUSED, DELETED, PENDING_REVIEW, DISAPPROVED, PREAPPROVED, PENDING_BILLING_INFO, CAMPAIGN_PAUSED, ARCHIVED, ADSET_PAUSED.

Status String If this status is PAUSED, all its active ad sets and ads will be paused and have an effective status CAMPAIGN_PAUSED. The field returns the same value as 'configured_status', and is the suggested one to use.

The allowed values are ACTIVE, PAUSED, DELETED, ARCHIVED.

CreatedTime Datetime When the campaign was created.
Objective String Objective of this ad campaign. If it is specified the API will validate that any ad groups created under the campaign match that objective.

The allowed values are CANVAS_APP_ENGAGEMENT, CANVAS_APP_INSTALLS, EVENT_RESPONSES, MOBILE_APP_ENGAGEMENT, MOBILE_APP_INSTALLS, NONE, OFFER_CLAIMS, PAGE_LIKES, POST_ENGAGEMENT, VIDEO_VIEWS, WEBSITE_CLICKS, WEBSITE_CONVERSIONS.

SpendCap Int A spend cap for the campaign, such that it will not spend more than this cap. Expressed as integer value of the subunit in your currency.
DailyBudget Int The daily budget of the campaign.
BudgetRemaining Int The remaining budget of the campaign.
LifetimeBudget Int The lifetime budget of the campaign.
BidStrategy String The bid strategy of the campaign. May be one of LOWEST_COST_WITHOUT_CAP, LOWEST_COST_WITH_BID_CAP, COST_CAP.
StartTime Datetime When the Campaign was started.
StopTime Datetime When the Campaign was stopped.
UpdatedTime Datetime When the Campaign was last updated.
BoostedObjectId String The boosted object associated with this Campaign, if any.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
DateStart Date The starting date to retrieve campaigns.
DateEnd Date The ending date to retrieve campaigns.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

IsCompleted Boolean Filter by completed status.

CData Python Connector for Facebook Ads

Delivery_Device_Report

Ad Report focused on campaigns, broken down by device or platform used for viewing ad. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
DevicePlatform String The device or platform used for viewing the ad. This is a breakdown column that may not be selected with other breakdown columns.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Delivery_Platform_And_Device_Report

Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
PublisherPlatform String The platforms the ads were published on.
DevicePlatform String The device or platform used for viewing the ad. This is a breakdown column that may not be selected with other breakdown columns.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Delivery_Platform_Report

Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
PublisherPlatform String The platforms the ads were published on.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Delivery_Purchase_Roas_Report

Ad Report focused on campaigns, broken down by the Meta platform on which it was delivered. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: ActionValues, MobileAppPurchaseRoas, OutboundClicks, WebsitePurchaseRoas
PublisherPlatform String The platforms the ads were published on.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_Age_And_Gender_Report

Ad Report focused on campaigns, broken down by age and gender demographics. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
Age String The age range for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
Gender String The gender for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_Age_Report

Ad Report focused on campaigns, broken down by age demographics. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
Age String The age range for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_Country_Report

Ad Report focused on campaigns, broken down by country demographics. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
Country String The country for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_DMA_Region_Report

Ad Report focused on campaigns, broken down by Designated Market Area. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
DMA String The designated marketing area. This is a breakdown column that may not be selected with other breakdown columns.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_Gender_Report

Ad Report focused on campaigns, broken down by gender. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
Gender String The gender for the metrics in this row. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

Demographic_Region_Report

Ad Report focused on campaigns, broken down by sub-country geographic region. Accessing Ad Report information requires the ads_read permission.

Columns

Name Type Description
Target String The Id of the Account, Campaign, Ad Group, or Ad to get insights for.
DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

DateStart Date The starting date to retrieve insights for. In the Facebook UI, this is the Report Start field. In the Facebook UI, this is the Report Start field.
DateEnd Date The ending date to retrieve insights for. In the Facebook UI, this is the Report End field. In the Facebook UI, this is the Report End field.
TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 1.

Level String The level to represent the results at.

The allowed values are ad, adset, campaign, account.

ActionType String The kind of actions taken on your ad, Page, app or event after your ad was served to someone, even if they didn't click on it.
ActionValue Integer Metric value of default attribution window.
AdAccountId String The Id of the Ad Account associated with the report row.
CampaignId String The Id of the Campaign associated with the report row.
CampaignName String The name of the Campaign associated with the report row.
Reach Integer The number of people who saw your ads at least once.
Impressions Integer The number of times your ads were on screen.
Frequency Double The average number of times each person saw your ad. This value is estimated.
Spend Double The estimated total amount of money you've spent on your campaign, ad set or ad during its schedule. What sort of ad object is targeted depends on the Target used for the report.
Cpm Double The average cost for 1,000 impressions.
Cpc Double The average cost for each click (all).
Ctr Double The percentage of times people saw your ad and performed a click (all).
InlineLinkClicks Integer The number of clicks on links to select destinations or experiences, on or off Facebook-owned properties.
InlineLinkClickCtr Integer The percentage of time people saw your ads and performed an inline link click.
CostPerInlineLinkClick Double The average cost of each inline link click.
ActionCollection String The action collection to retrieve. The available values are: Actions, CostPerActionType
Region String The region someone viewed the Ad from. This is a breakdown column and selecting this column will cause results to be further broken down by this metric.
UseAsync Boolean A boolean indicating if an asynchronous call should be used for retrieving the insights.

CData Python Connector for Facebook Ads

LeadValues

Query information about a lead. Accessing Lead Information requires the ads_read and either pages_manage_ads or leads_retrieval permissions.

Table Specific Information

LeadValues in Facebook represent individual values available from a Lead Ad. The types of values describing a leads are varied and can range from custom information such as a car model, or something general such as name and email.

Select

When querying lead values, either the Id or Target must be used to filter results. The Id represents the id of the individual lead while the Target must be a Lead Ad. If neither filter is supplied, the Target will automatically be sliced on the Ads table.

The following columns and operators are supported server-side:

  • Id supports the '=' operator.
  • Target supports the '=', 'IN' operators.
  • CreatedTime supports the '>', '<', '<=' operators.

Sample queries:

SELECT * FROM LeadValues WHERE Target = 'lead_ad_id'

SELECT * FROM LeadValues WHERE Id = 'lead_id'

SELECT * FROM LeadValues WHERE Target IN (SELECT id FROM Ads WHERE Target = 'campaign_id')

SELECT * FROM LeadValues where Target='6043999879662' AND CreatedTime > '2026-01-01'

Note that many values may come back for a single lead id. The leads themselves are a collection on the Lead Ad, and the lead values are a collection on each individual lead.

Columns

Name Type Description
ID String The Id of Lead.
Target String The target or Ads Id to get Lead values from.
AdId String The id of the Ad the lead originates from.
AdName String The name of the Ad the lead originates from.
AdSetId String The id of the Ad Set the lead is associated with.
AdSetName String The name of the Ad Set the lead is associated with.
CampaignId String The id of the Campaign the lead is associated with.
CampaignName String The name of the Campaign the lead is associated with.
FormId String The id of the form the lead originates from.
FieldName String The name of the field of lead data.
FieldValues String The values for the given field of lead data.
IsOrganic Boolean A boolean indicating if the lead is organic.
CreatedTime Datetime The datetime the lead was created.

CData Python Connector for Facebook Ads

Pages

Query the Pages based on the supplied Id.

Table Specific Information

Pages in Facebook are pages that are created by a user and may be maintained by one or multiple users. Pages, like users, may be referred to by Id or by screen name.

Select

When querying pages, if nothing is specified then the pages you administrate will be displayed by default. Otherwise, the Id of the page can be specified. For example:

SELECT * FROM Pages WHERE Id = 'facebook'

Columns

Name Type Description
ID [KEY] String The Id of the page.
Username String The username for the page, if any.
Name String The name of the page.
Category String The category of the page.
Categories String An aggregate of categories associated with the page if multiple categories are available.
Link String A link to the page.
Picture String A link to the profile picture of the page for the page.
CoverId String Id of the cover image for the page.
CoverSource String The URL to the cover image for the page.
CoverOffsetY String The y-axis offset of the cover image for the page.
CoverOffsetX String The x-axis offset of the cover image for the page.
About String Basic information about the page.
Description String A description of the page, if available.
GeneralInfo String General information provided by the page.
LocationStreet String The street address of the page.
LocationCity String The city for the page.
LocationState String The state for the page.
LocationCountry String The country for the page.
LocationZip String The ZIP code of the page.
LocationLatitude String The latitude of the page.
LocationLongitude String The longitude of the page.
StoreNumber Integer Unique store number for this location page, if applicable.
Phone String The phone number of the page, if available.
Website String A link to the website for the page.
Likes Integer The number of people who like the page.
Checkins Integer The total number of users who have checked in to the place associated with the page.
TalkingAboutCount Integer The number of users talking about the page.
WereHereCount Integer The number of users who were at the location the page is for, if applicable.
CanPost Boolean Boolean indicating if the authenticated user can post of the page for the page.
IsPublished Boolean Boolean indicating if the page for the page has been published.
IsCommunityPage Boolean Boolean indicating if this is a community page.
PublicTransit String The public transit available for the page, if any.
ParkingStreet Boolean Boolean indicating if street parking is available.
ParkingLot Boolean Boolean indicating if a parking lot is available.
ParkingValet Boolean Boolean indicating if valet parking is available.
PromotionEligible Boolean Boosted posts eligibility status. Requires the manage_pages permission and you must be an administrator of the page.
PromotionIneligibleReason String Reason boosted posts are not eligible. Requires the manage_pages permission and you must be an administrator of the page.
Founded String When the company is founded. Applicable to companies.
Mission String The company mission. Applicable to companies.
Products String The products of this company. Applicable to companies.
Hours String An aggregate for the hours of operation. Applicable to businesses and places.
Attire String Dress code of the business. Applicable to restaurants or nightlife. Valid values are Casual, Dressy or Unspecified.
AcceptsCashOnly Boolean Whether the business accepts only cash as a payment option. Applicable to restaurants or nightlife.
AcceptsVisa Boolean Whether the business accepts Visa as a payment option. Applicable to restaurants or nightlife.
AcceptsAmericanExpress Boolean Whether the business accepts American Express as a payment option. Applicable to restaurants or nightlife.
AcceptsMasterCard Boolean Whether the business accepts MasterCard as a payment option. Applicable to restaurants or nightlife.
AcceptsDiscover Boolean Whether the business accepts Discover as a payment option. Applicable to restaurants or nightlife.
PriceRange String Price range of the business. Applicable to restaurants or nightlife. Valid values are \$ (0-10), \$\$ (10-30), \$\$\$ (30-50), \$\$\$\$ (50+), or Unspecified.
TakesReservations Boolean Whether the restaurant takes reservations. Only applicable to restaurants.
AllowsWalkins Boolean Whether the restaurant allows walk-ins. Only applicable to restaurants.
AllowsGroups Boolean Whether the restaurant accommodates groups. Only applicable to restaurants.
AllowsKids Boolean Whether the restaurant allows kids. Only applicable to restaurants.
ProvidesTakeout Boolean Whether the restaurant provides a takeout service. Only applicable to restaurants.
ProvidesDelivery Boolean Whether the restaurant provides a delivery service. Only applicable to restaurants.
ProvidesCatering Boolean Whether the restaurant provides a catering service. Only applicable to restaurants.
HasWaiters Boolean Whether the restaurant has waiters. Only applicable to restaurants.
HasOutdoorSeating Boolean Whether the restaurant has outdoor seating. Only applicable to restaurants.
ServesBreakfast Boolean Whether the restaurant serves breakfast. Only applicable to restaurants.
ServesLunch Boolean Whether the restaurant serves lunch. Only applicable to restaurants.
ServesDinner Boolean Whether the restaurant serves dinner. Only applicable to restaurants.
ServesCoffee Boolean Whether the restaurant serves coffee. Only applicable to restaurants.
ServesDrinks Boolean Whether the restaurant serves drinks. Only applicable to restaurants.
CulinaryTeam String Culinary team of the business. Applicable to restaurants or nightlife.
PharmaSafetyInfo String Pharmacy safety information. Applicable to pharmaceutical companies.
Affiliation String Affiliation of this person. Applicable to pages representing people.
Birthday String Birthday of this person. Applicable to pages representing people.
PersonalInfo String Personal information. Applicable to pages representing people.
PersonalInterests String Personal interests. Applicable to pages representing people.
ArtistsWeLike String Artists the band likes. Applicable to bands.
BandInterests String Band interests. Applicable to bands.
BandMembers String Members of the band. Applicable to bands.
Bio String Biography of the band. Applicable to bands.
BookingAgent String Booking agent of the band. Applicable to bands.
GeneralManager String General manager of the business. Applicable to restaurants or nightlife. Applicable to bands.
Hometown String Hometown of the band. Applicable to bands.
PressContact String Press contact information of the band. Applicable to bands.
RecordLabel String Record label of the band. Applicable to bands.
Awards String Awards information for the film or TV show. Applicable to films and TV shows.
DirectedBy String The director of the film or TV show. Applicable to films and TV shows.
Genre String The genre of the film or TV show. Applicable to films and TV shows.
Influences String Influences on the band. Applicable to bands.
PlotOutline String The plot outline of the film or TV show. Applicable to films and TV shows.
ProducedBy String The productor of the film. Applicable to films.
ReleaseData String The film's release data. Applicable to films and TV shows.
ScreenplayBy String The screenwriter of the film. Applicable to films and TV shows.
Starring String The cast of the film or TV show. Applicable to films and TV shows.
Studio String The studio for the film production. Applicable to films.
Network String The network the TV show airs on. Applicable to TV shows.
Schedule String The air schedule of the TV show. Applicable to TV shows.
Season String The current season of the TV show. Applicable to TV shows.
WrittenBy String The writer of the TV show. Applicable to TV shows.
Built String The information about when the vehicle was built. Applicable to vehicles.
Features String Features of the vehicle. Applicable to vehicles.
MPG String Miles per gallon for the vehicle. Applicable to vehicles.
Members String Members of this org. Applicable to pages representing team orgs.
InstagramBusinessAccountId String The business instagram account id associated with this page.

Pseudo-Columns

Pseudo column fields are used in the WHERE clause of SELECT statements and offer more granular control over the data returned from the data source.

Name Type Description
offset String Which result to begin returning results from. Used for manual paging of results.

CData Python Connector for Facebook Ads

Permissions

Query the Permissions the User has granted the current application.

Columns

Name Type Description
PermissionName [KEY] String The name of the permission.
Status String The status of the requested permission.

CData Python Connector for Facebook Ads

Stored Procedures

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

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

CData Python Connector for Facebook Ads Stored Procedures

Name Description
AddCustomAudienceUsers Updates a custom audience to add the specified users.
CreateAdInsightsReport Generates a report schema for ad insights.
CreateAdPreview Creates a schema file for an app insight.
DeleteCustomAudienceUsers Deletes a specified set of users from a custom audience.
GetOAuthAccessToken Gets an authentication token from Facebook.
GetOAuthAuthorizationURL Gets an AuthURL from Facebook. You will request the auth token from this URL.
RefreshOAuthAccessToken Refreshes the OAuth token.

CData Python Connector for Facebook Ads

AddCustomAudienceUsers

Updates a custom audience to add the specified users.

Procedure Specific Info

Configuration

Interacting with custom audience users requires configuring both a schema and payload. The PayloadSchema maps out the PII that will be represented in PayloadData.

PayloadSchema can be set as a single key, resulting in a 1-dimensional array in PayloadData:

EXECUTE AddCustomAudienceUsers 
	@CustomAudienceId='123456789123456789',
	@PayloadSchema='EMAIL_SHA256',
	@PayloadData='["31c5543c1734d25c7206f5fd591525d0295bec6fe84ff82f946a34fe970a1e66", "7df7e024c945682f00f2c6410593f407dec0e870af2a9147a62ac459db35d6b8", ...]'

PayloadSchema can also be set as a JSON array with multiple keys, resulting in a 2-dimensional array in PayloadData:

EXECUTE AddCustomAudienceUsers 
	@CustomAudienceId='120208749119170125',
	@PayloadSchema='["EMAIL", "LN"]', 
	@PayloadData='[
					[
						"example@example.com",
						"Exampleman"
					],
					[
						"example2@example.com",
						"Exampletoo"
					],
					...
				  ]'

To apply the "Limited Data Use" flag to users, it should be specified with the special "DATA_PROCESSING_OPTIONS" key in PayloadSchema, and must be provided as a nested array member in PayloadData. If using LDU and non-LDU rows in the same payload, an empty array should be used where LDU is disabled:

EXECUTE AddCustomAudienceUsers 
	@CustomAudienceId='120208749119170125',
	@PayloadSchema='["EMAIL", "DATA_PROCESSING_OPTIONS"]', 
	@PayloadData='[
					[
						"example@example.com",
						"Exampleman",
						["LDU"]
					],
					[
						"example2@example.com",
						"Exampletoo",
						[]
					],
					...
				  ]'

Session Management

Facebook Ads only allows a maximum of 10000 users to be added to a custom audience in a single request. If more than 10000 (or PageSize, if set) rows are present in PayloadData, the connector will break the provided PayloadData down into multiple requests. Note that the SessionId parameter must be set in this case.

Hashing and Normalization

Facebook Ads has strict hashing and normalization rules for Customer File Custom Audience User information submitted through the API. The connector will handle hashing data (where appropriate) if the HashData parameter is set to true, but not normalizing data. See the Facebook Ads API docs for more information on the necessary data normalization.

Note: For single-key schema, only pre-hashed datatypes (E.G. 'EMAIL_SHA256') are supported by the Facebook Ads API. The connector expects these data types to already be hashed when provided.

Input

Name Type Description
CustomAudienceId String The ID of the custom audience to add users to.
PayloadSchema String Type of information represented by PayloadData. Should be either a single string, or a JSON array with multiple key types. Supported key types are: EXTERN_ID, EMAIL, PHONE, GEN, DOBY, DOBM, DOBD, LN, FN, FI, CT, ST, ZIP, MADID, COUNTRY
PayloadData String JSON array containing keys for each user to add to custom audience. If using multiple key types in schema, should be a two-dimensional array, with each row containing multiple keys in order specified in PayloadSchema.
PayloadAppIds String JSON array of integer app IDs used by users being uploaded. Required if PayloadSchema is a Facebook UID and the IDs were collected by an app integration.
PayloadPageIds String JSON array of integer page IDs used by users being uploaded. Required if schema is a Facebook UID and the IDs were collected by a Page webhook integration.
PayloadDataSourceType String Type of the underlying custom audience. Supported values are: UNKNOWN, FILE_IMPORTED, EVENT_BASED, SEED_BASED, THIRD_PARTY_IMPORTED, COPY_PASTE, CONTACT_IMPORTER, HOUSEHOLD_AUDIENCE
PayloadDataSourceSubType String SubType of the underlying custom audience. Supported values are: ANYTHING, NOTHING, HASHES, USER_IDS, HASHES_OR_USER_IDS, MOBILE_ADVERTISER_IDS, EXTERNAL_IDS, MULTI_HASHES, TOKENS, EXTERNAL_IDS_MIX, HOUSEHOLD_EXPANSION, SUBSCRIBER_LIST, WEB_PIXEL_HITS, MOBILE_APP_EVENTS, MOBILE_APP_COMBINATION_EVENTS, VIDEO_EVENTS, WEB_PIXEL_COMBINATION_EVENTS, PLATFORM, MULTI_DATA_EVENTS, IG_BUSINESS_EVENTS, STORE_VISIT_EVENTS, INSTANT_ARTICLE_EVENTS, FB_EVENT_SIGNALS, FACEBOOK_WIFI_EVENTS, AR_EXPERIENCE_EVENTS, AR_EFFECTS_EVENTS, MESSENGER_ONSITE_SUBSCRIPTION, WHATSAPP_SUBSCRIBER_POOL, MARKETPLACE_LISTINGS, AD_CAMPAIGN, GROUP_EVENTS, ENGAGEMENT_EVENT_USERS, CUSTOM_AUDIENCE_USERS, PAGE_FANS, CONVERSION_PIXEL_HITS, APP_USERS, S_EXPR, DYNAMIC_RULE, CAMPAIGN_CONVERSIONS, WEB_PIXEL_HITS_CUSTOM_AUDIENCE_USERS, MOBILE_APP_CUSTOM_AUDIENCE_USERS, COMBINATION_CUSTOM_AUDIENCE_USERS, VIDEO_EVENT_USERS, FB_PIXEL_HITS, IG_PROMOTED_POST, PLACE_VISITS, OFFLINE_EVENT_USERS, EXPANDED_AUDIENCE, SEED_LIST, PARTNER_CATEGORY_USERS, PAGE_SMART_AUDIENCE, MULTICOUNTRY_COMBINATION, PLATFORM_USERS, MULTI_EVENT_SOURCE, SMART_AUDIENCE, LOOKALIKE_PLATFORM, SIGNAL_SOURCE, MAIL_CHIMP_EMAIL_HASHES, CONSTANT_CONTACTS_EMAIL_HASHES, COPY_PASTE_EMAIL_HASHES, CUSTOM_DATA_TARGETING, CONTACT_IMPORTER, DATA_FILE
HashData String Boolean value indicating if provider should handle hashing of data. Set to true to have the connector hash the provided data before sending to the service. Defaults to false.
SessionId String Session ID for upload involving more than 'PageSize' users (default of 10000). If PayloadData contains more than 'PageSize' records, set this value to a positive 64-bit integer.
PageSize String Number of records to include in 'PayloadData' in each request. Maximum and default of 10000.

Result Set Columns

Name Type Description
Result String Success or Failure.
NumReceived String Number of custom audience users received as reported by Facebook Marketing API.
NumInvalidEntries String Number of invalid entries in PayloadData as reported by Facebook Marketing API.
InvalidEntrySamples String JSON map representing samples of invalid entries.

CData Python Connector for Facebook Ads

CreateAdInsightsReport

Generates a report schema for ad insights.

Input

Name Type Description
ReportName String The name of the report.
Description String An optional description for the report.
Fields String Comma-delimited list of non-breakdown fields for your report. Available values: AccountCurrency,ActionValue,AdAccountId,AdAccountName,CampaignID,CampaignName,AdSetId,AdSetname,AdId,AdName,BuyingType,Clicks,ConversionRateRanking,CostPerEstimatedAdRecallers,CostPerInlineLinkClick,CostPerInlinePostEngagement,CostPerUniqueClick,CostPerUniqueInlineLinkClick,CPC,CPM,CPP,EstimatedAdRecallRate,EstimatedAdRecallers,Frequency,Impressions,InlineLinkClicks,InlineLinkClicksCounter,InlinePostEngagement,InstantExperienceClicksToOpen,InstantExperienceClicksToStart,InstantExperienceOutboundClicks,Objective,QualityRanking,Reach,Spend,UniqueClicks,UniqueCTR,UniqueInlineLinkClicks,UniqueInlineLinkClickCounter,UniqueLinkClicksCounter

The default value is AccountCurrency,AdAccountId,AdAccountName,CampaignID,CampaignName,AdSetId,AdSetname,AdId,AdName,BuyingType,Clicks,CostPerInlineLinkClick,CostPerInlinePostEngagement,CostPerUniqueClick,CostPerUniqueInlineLinkClick,CPC,CPM,CPP,Frequency,Impressions,InlineLinkClicks,InlineLinkClicksCounter,InlinePostEngagement,Reach,Spend.

Breakdowns String Breakdowns for your report. Available values: Age,Country,DevicePlatform,DMA,FrequencyValue,Gender,HStatsByAdvertiserTZ,HStatsByAudienceTZ,ImpressionDevice,PlacePageId,PlatformPosition,ProductId,PublisherPlatform,Region
ActionBreakdowns String Action breakdowns for your report. Available values: ActionCanvasComponentName,ActionCarouselCardId,ActionCarouselCardName,ActionConvertedProductId,ActionDestination,ActionDevice,ActionReaction,ActionTargetId,ActionType,ActionVideoSound,ActionVideoType
ActionCollection String Collections of ads actions stats to return for your report. The available values are: ActionValues, Actions, AdClickActions, AdImpressionActions, CatalogSegmentActions, CatalogSegmentValue, CatalogSegmentValueMobilePurchaseRoas, CatalogSegmentValueOmniPurchaseRoas, CatalogSegmentValueWebsitePurchaseRoas, ConversionValues, Conversions, ConvertedProductQuantity, ConvertedProductValue, CostPer15_secVideoView, CostPer2SecContinuousVideoView, CostPerActionType, CostPerAdClick, CostPerConversion, CostPerOneThousandAdImpression, CostPerOutboundClick, CostPerStoreVisitAction, CostPerThruplay, CostPerUniqueActionType, CostPerUniqueConversion, CostPerUniqueOutboundClick, InteractiveComponentTap, MobileAppPurchaseRoas, OutboundClicks, OutboundClicksCtr, PurchaseRoas, StoreVisitActions, UniqueActions, UniqueConversions, UniqueOutboundClicks, UniqueOutboundClicksCtr, UniqueVideoView15_sec, Video15_secWatchedActions, Video30_secWatchedActions, VideoAvgTimeWatchedActions, VideoContinuous2SecWatchedActions, VideoP100_watchedActions, VideoP25WatchedActions, VideoP50WatchedActions, VideoP75WatchedActions, VideoP95WatchedActions, VideoPlayActions, VideoPlayCurveActions, VideoPlayRetention0To15SActions, VideoPlayRetention20_to60SActions, VideoPlayRetentionGraphActions, VideoTimeWatchedActions, WebsiteCtr, WebsitePurchaseRoas

The default value is Actions.

ActionAttributionWindows String A comma separated list which determines what is the attribution window for the actions. For example, 28d_click means the API returns all actions that happened 28 days after someone clicked on the ad. The default is [1d_view,7d_click]. Possible values include 1d_view, 7d_view, 28d_view, 1d_click, 7d_click, 28d_click, default.

The default value is default.

DatePreset String An alternative to specifying the DateStart and DateEnd. A date range will automatically be calculated based on the specified preset value.

The allowed values are maximum, today, yesterday, this_week_sun_today, this_week_mon_today, last_week_sun_sat, last_week_mon_sun, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month.

The default value is maximum.

TimeIncrement String The number of days of data aggregation. An int (1-90) or one of monthly or all_days. This value splits the range or preset date into smaller increments.

The default value is 90.

OutputDirectory String The directory where the schema file will be written. If no directory is specified, the generated report will be written to the FileData output.

Result Set Columns

Name Type Description
Result String Success or Failure.
SchemaFile String The generated schema file.
Columns String The number of columns found.
FileData String The BASE64 downloaded file content. Only returned if SchemaDirectory and FileStream is not set.

CData Python Connector for Facebook Ads

CreateAdPreview

Creates a schema file for an app insight.

Input

Name Type Description
AdCreativeId String An ID of the ad creative to use for creating the preview from.
AdFormat String The format of the ad to use.

The allowed values are AUDIENCE_NETWORK_INSTREAM_VIDEO, AUDIENCE_NETWORK_INSTREAM_VIDEO_MOBILE, AUDIENCE_NETWORK_OUTSTREAM_VIDEO, AUDIENCE_NETWORK_REWARDED_VIDEO, DESKTOP_FEED_STANDARD, FACEBOOK_STORY_MOBILE, INSTAGRAM_STANDARD, INSTAGRAM_STORY, INSTANT_ARTICLE_STANDARD, INSTREAM_VIDEO_DESKTOP, INSTREAM_VIDEO_MOBILE, MARKETPLACE_MOBILE, MESSENGER_MOBILE_INBOX_MEDIA, MOBILE_BANNER, MOBILE_FEED_BASIC, MOBILE_FEED_STANDARD, MOBILE_FULLWIDTH, MOBILE_INTERSTITIAL, MOBILE_MEDIUM_RECTANGLE, MOBILE_NATIVE, RIGHT_COLUMN_STANDARD, SUGGESTED_VIDEO_DESKTOP, SUGGESTED_VIDEO_MOBILE, WATCH_FEED_MOBILE.

CreativeFeature String Name of a creative features to preview. Only applies to Marketing API versions 22.0 and above. Supported features include image_templates, image_touchups, video_auto_crop, enhance_cta, text_optimizations, image_background_gen, image_uncrop, and description_automation.
ApplyStandardEnhancements Boolean If set to true, standard enhancements are applied to automatically create multiple variations of your ad and show a personalized variation to each Account Center account based on what they're most likely to respond to. Only applies to Marketing API versions 21.0 and below.

The default value is false.

Result Set Columns

Name Type Description
Url String A url to the preview.

CData Python Connector for Facebook Ads

DeleteCustomAudienceUsers

Deletes a specified set of users from a custom audience.

Procedure Specific Info

Configuration

Interacting with custom audience users requires configuring both a schema and payload. The PayloadSchema maps out the PII that will be represented in PayloadData.

PayloadSchema can be set as a single key, resulting in a 1-dimensional array in PayloadData:

EXECUTE DeleteCustomAudienceUsers 
	@CustomAudienceId='123456789123456789',
	@PayloadSchema='EMAIL_SHA256',
	@PayloadData='["31c5543c1734d25c7206f5fd591525d0295bec6fe84ff82f946a34fe970a1e66", "7df7e024c945682f00f2c6410593f407dec0e870af2a9147a62ac459db35d6b8", ...]'

PayloadSchema can also be set as a JSON array with multiple keys, resulting in a 2-dimensional array in PayloadData:

EXECUTE DeleteCustomAudienceUsers 
	@CustomAudienceId='120208749119170125',
	@PayloadSchema='["EMAIL", "LN"]', 
	@PayloadData='[
					[
						"example@example.com",
						"Exampleman"
					],
					[
						"example2@example.com",
						"Exampletoo"
					],
					...
				  ]'

To apply the "Limited Data Use" flag to users, it should be specified with the special "DATA_PROCESSING_OPTIONS" key in PayloadSchema, and must be provided as a nested array member in PayloadData. If using LDU and non-LDU rows in the same payload, an empty array should be used where LDU is disabled:

EXECUTE DeleteCustomAudienceUsers 
	@CustomAudienceId='120208749119170125',
	@PayloadSchema='["EMAIL", "DATA_PROCESSING_OPTIONS"]', 
	@PayloadData='[
					[
						"example@example.com",
						"Exampleman",
						["LDU"]
					],
					[
						"example2@example.com",
						"Exampletoo",
						[]
					],
					...
				  ]'

Session Management

Facebook Ads only allows a maximum of 10000 users to be added to a custom audience in a single request. If more than 10000 (or PageSize, if set) rows are present in PayloadData, the connector will break the provided PayloadData down into multiple requests. Note that the SessionId parameter must be set in this case.

Hashing and Normalization

Facebook Ads has strict hashing and normalization rules for Customer File Custom Audience User information submitted through the API. The connector will handle hashing data (where appropriate) if the HashData parameter is set to true, but not normalizing data. See the Facebook Ads API docs for more information on the necessary data normalization.

Note: For single-key schema, only pre-hashed datatypes (E.G. 'EMAIL_SHA256') are supported by the Facebook Ads API. The connector expects these data types to already be hashed when provided.

Input

Name Type Description
CustomAudienceId String The ID of the custom audience to delete from.
PayloadSchema String Type of information represented by PayloadData. Should be either a single string, or a JSON array with multiple key types. Supported key types are: EXTERN_ID, EMAIL, PHONE, GEN, DOBY, DOBM, DOBD, LN, FN, FI, CT, ST, ZIP, MADID, COUNTRY
PayloadData String JSON array containing keys for each user to add to custom audience. If using multiple key types in schema, should be a two-dimensional array, with each row containing multiple keys in order specified in PayloadSchema.
PayloadAppIds String JSON array of integer app IDs used by users being uploaded. Required if PayloadSchema is a Facebook UID and the IDs were collected by an app integration.
PayloadPageIds String JSON array of integer page IDs used by users being uploaded. Required if schema is a Facebook UID and the IDs were collected by a Page webhook integration.
PayloadDataSourceType String Type of the underlying custom audience. Supported values are: UNKNOWN, FILE_IMPORTED, EVENT_BASED, SEED_BASED, THIRD_PARTY_IMPORTED, COPY_PASTE, CONTACT_IMPORTER, HOUSEHOLD_AUDIENCE
PayloadDataSourceSubType String SubType of the underlying custom audience. Supported values are: ANYTHING, NOTHING, HASHES, USER_IDS, HASHES_OR_USER_IDS, MOBILE_ADVERTISER_IDS, EXTERNAL_IDS, MULTI_HASHES, TOKENS, EXTERNAL_IDS_MIX, HOUSEHOLD_EXPANSION, SUBSCRIBER_LIST, WEB_PIXEL_HITS, MOBILE_APP_EVENTS, MOBILE_APP_COMBINATION_EVENTS, VIDEO_EVENTS, WEB_PIXEL_COMBINATION_EVENTS, PLATFORM, MULTI_DATA_EVENTS, IG_BUSINESS_EVENTS, STORE_VISIT_EVENTS, INSTANT_ARTICLE_EVENTS, FB_EVENT_SIGNALS, FACEBOOK_WIFI_EVENTS, AR_EXPERIENCE_EVENTS, AR_EFFECTS_EVENTS, MESSENGER_ONSITE_SUBSCRIPTION, WHATSAPP_SUBSCRIBER_POOL, MARKETPLACE_LISTINGS, AD_CAMPAIGN, GROUP_EVENTS, ENGAGEMENT_EVENT_USERS, CUSTOM_AUDIENCE_USERS, PAGE_FANS, CONVERSION_PIXEL_HITS, APP_USERS, S_EXPR, DYNAMIC_RULE, CAMPAIGN_CONVERSIONS, WEB_PIXEL_HITS_CUSTOM_AUDIENCE_USERS, MOBILE_APP_CUSTOM_AUDIENCE_USERS, COMBINATION_CUSTOM_AUDIENCE_USERS, VIDEO_EVENT_USERS, FB_PIXEL_HITS, IG_PROMOTED_POST, PLACE_VISITS, OFFLINE_EVENT_USERS, EXPANDED_AUDIENCE, SEED_LIST, PARTNER_CATEGORY_USERS, PAGE_SMART_AUDIENCE, MULTICOUNTRY_COMBINATION, PLATFORM_USERS, MULTI_EVENT_SOURCE, SMART_AUDIENCE, LOOKALIKE_PLATFORM, SIGNAL_SOURCE, MAIL_CHIMP_EMAIL_HASHES, CONSTANT_CONTACTS_EMAIL_HASHES, COPY_PASTE_EMAIL_HASHES, CUSTOM_DATA_TARGETING, CONTACT_IMPORTER, DATA_FILE
HashData String Boolean value indicating if provider should handle hashing of data. Set to true to have the connector hash the provided data before sending to the service. Defaults to false.
SessionId String Session ID for upload involving more than 'PageSize' users (default of 10000). If PayloadData contains more than 'PageSize' records, set this value to a positive 64-bit integer.
PageSize String Number of records to include in 'PayloadData' in each request. Maximum and default of 10000.

Result Set Columns

Name Type Description
Result String Success or Failure.
NumReceived String Number of custom audience users received as reported by Facebook Marketing API.
NumInvalidEntries String Number of invalid entries in PayloadData as reported by Facebook Marketing API.
InvalidEntrySamples String JSON map representing samples of invalid entries.

CData Python Connector for Facebook Ads

GetOAuthAccessToken

Gets an authentication token from Facebook.

Input

Name Type Description
AuthMode String The type of authentication mode to use. Select App for getting authentication tokens via a windows forms app. Select Web for getting authentication tokens via a web app.

The allowed values are APP, WEB.

The default value is APP.

Scope String A comma-separated scope of permissions to request from the user. Please check the Facebook API for scope of available permissions. Permissions that may be required depending on your use case are: read_insights,pages_manage_ads,pages_manage_metadata,pages_read_engagement,ads_read,business_management.
CallbackUrl String The URL the user will be redirected to after authorizing your application. This value must match the Site URL and App Domain you have specified in the Facebook app settings. Only needed when the Authmode parameter is Web.
Verifier String The verifier returned from Facebook after the user has authorized your app to have access to their data. This value will be returned as a parameter to the callback URL in GetAuthURL.
AuthType String An optional parameter to pass Facebook. Set the value to rerequest to request the same scope of permissions again if the user declined some of them.
State String Any value that you wish to be sent with the callback.

Result Set Columns

Name Type Description
OAuthAccessToken String The access token used for communication with Facebook.
OAuthRefreshToken String This is actually the same as the OAuthAccessToken. It can be used internally to determine if the token can be refreshed. Tokens are refreshed by Facebook automatically.
ExpiresIn String The remaining lifetime on the access token. A -1 denotes that it will not expire.

CData Python Connector for Facebook Ads

GetOAuthAuthorizationURL

Gets an AuthURL from Facebook. You will request the auth token from this URL.

Input

Name Type Description
CallbackUrl String The URL the user will be redirected to after authorizing your application. This value must match the Site URL and App Domain in the Facebook app settings.
Scope String A comma-separated scope of permissions to request from the user. Please check the Facebook API for scope of available permissions. Permissions that may be required depending on your use case are: read_insights,pages_manage_ads,pages_manage_metadata,pages_read_engagement,ads_read,business_management.
AuthType String An optional parameter to pass Facebook. Set the value to rerequest to request the same permissions again if the user declined some of them.
State String Any value that you wish to be sent with the callback.

Result Set Columns

Name Type Description
URL String The authorization URL, entered into a Web browser to obtain the verifier token and authorize your app.

CData Python Connector for Facebook Ads

RefreshOAuthAccessToken

Refreshes the OAuth token.

Input

Name Type Description
OAuthRefreshToken String The refresh token returned when the OAuth Token was first created.

Result Set Columns

Name Type Description
OAuthAccessToken String The authentication token returned from Facebook.
OAuthRefreshToken String A token that may be used to obtain a new access token.
ExpiresIn String The remaining lifetime on the access token.

CData Python Connector for Facebook Ads

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 Facebook Ads:

Data Source Tables

The following tables return information about how to connect to and query the data source:

  • sys_connection_props: Returns information on the available connection properties.
  • sys_sqlinfo: Describes the SELECT queries that the connector can offload to the data source.

Query Information Tables

The following table returns query statistics for data modification queries

  • sys_identity: Returns information about batch operations or single updates.

CData Python Connector for Facebook Ads

sys_catalogs

Lists the available databases.

The following query retrieves all databases determined by the connection string:

SELECT * FROM sys_catalogs

Columns

Name Type Description
CatalogName String The database name.

CData Python Connector for Facebook Ads

sys_schemas

Lists the available schemas.

The following query retrieves all available schemas:

          SELECT * FROM sys_schemas
          

Columns

Name Type Description
CatalogName String The database name.
SchemaName String The schema name.

CData Python Connector for Facebook Ads

sys_tables

Lists the available tables.

The following query retrieves the available tables and views:

          SELECT * FROM sys_tables
          

Columns

Name Type Description
CatalogName String The database containing the table or view.
SchemaName String The schema containing the table or view.
TableName String The name of the table or view.
TableType String The table type (table or view).
Description String A description of the table or view.
IsUpdateable Boolean Whether the table can be updated.
IsInsertable Boolean Whether the table can be inserted into.
IsDeleteable Boolean Whether rows can be deleted from the table.

CData Python Connector for Facebook Ads

sys_tablecolumns

Describes the columns of the available tables and views.

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

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

Columns

Name Type Description
CatalogName String The name of the database containing the table or view.
SchemaName String The schema containing the table or view.
TableName String The name of the table or view containing the column.
ColumnName String The column name.
DataTypeName String The data type name.
DataType Int32 An integer indicating the data type. This value is determined at run time based on the environment.
Length Int32 The storage size of the column.
DisplaySize Int32 The designated column's normal maximum width in characters.
NumericPrecision Int32 The maximum number of digits in numeric data. The column length in characters for character and date-time data.
NumericScale Int32 The column scale or number of digits to the right of the decimal point.
IsNullable Boolean Whether the column can contain null.
Description String A brief description of the column.
Ordinal Int32 The sequence number of the column.
IsAutoIncrement String Whether the column value is assigned in fixed increments.
IsGeneratedColumn String Whether the column is generated.
IsHidden Boolean Whether the column is hidden.
IsArray Boolean Whether the column is an array.
IsReadOnly Boolean Whether the column is read-only.
IsKey Boolean Indicates whether a field returned from sys_tablecolumns is the primary key of the table.
ColumnType String The role or classification of the column in the schema. Possible values include SYSTEM, LINKEDCOLUMN, NAVIGATIONKEY, REFERENCECOLUMN, and NAVIGATIONPARENTCOLUMN.
ColumnCapabilities Int32 A bit mask denoting the column's write capabilities. The value is the sum of the following: 1 if the column is required for INSERTs, 2 if the column is allowed for INSERTs, and 4 if the column is allowed for UPDATEs. A value of 0 indicates that the write capabilities of the column are unknown or that the column is read-only.

CData Python Connector for Facebook Ads

sys_procedures

Lists the available stored procedures.

The following query retrieves the available stored procedures:

          SELECT * FROM sys_procedures
          

Columns

Name Type Description
CatalogName String The database containing the stored procedure.
SchemaName String The schema containing the stored procedure.
ProcedureName String The name of the stored procedure.
Description String A description of the stored procedure.
ProcedureType String The type of the procedure, such as PROCEDURE or FUNCTION.

CData Python Connector for Facebook Ads

sys_procedureparameters

Describes stored procedure parameters.

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

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

To include result set columns in addition to the parameters, set the IncludeResultColumns pseudo column to True:

SELECT * FROM sys_procedureparameters WHERE ProcedureName = 'GetOAuthAccessToken' AND IncludeResultColumns='True'

Columns

Name Type Description
CatalogName String The name of the database containing the stored procedure.
SchemaName String The name of the schema containing the stored procedure.
ProcedureName String The name of the stored procedure containing the parameter.
ColumnName String The name of the stored procedure parameter.
Direction Int32 An integer corresponding to the type of the parameter: input (1), input/output (2), or output(4). input/output type parameters can be both input and output parameters.
DataType Int32 An integer indicating the data type. This value is determined at run time based on the environment.
DataTypeName String The name of the data type.
NumericPrecision Int32 The maximum precision for numeric data. The column length in characters for character and date-time data.
Length Int32 The number of characters allowed for character data. The number of digits allowed for numeric data.
NumericScale Int32 The number of digits to the right of the decimal point in numeric data.
IsNullable Boolean Whether the parameter can contain null.
IsRequired Boolean Whether the parameter is required for execution of the procedure.
IsArray Boolean Whether the parameter is an array.
Description String The description of the parameter.
Ordinal Int32 The index of the parameter.
Values String The values you can set in this parameter are limited to those shown in this column. Possible values are comma-separated.
SupportsStreams Boolean Whether the parameter represents a file that you can pass as either a file path or a stream.
IsPath Boolean Whether the parameter is a target path for a schema creation operation.
Default String The value used for this parameter when no value is specified.
SpecificName String A label that, when multiple stored procedures have the same name, uniquely identifies each identically-named stored procedure. If there's only one procedure with a given name, its name is simply reflected here.
IsCDataProvided Boolean Whether the procedure is added/implemented by CData, as opposed to being a native Facebook Ads procedure.

Pseudo-Columns

Name Type Description
IncludeResultColumns Boolean Whether the output should include columns from the result set in addition to parameters. Defaults to False.

CData Python Connector for Facebook Ads

sys_keycolumns

Describes the primary and foreign keys.

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

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

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
IsKey Boolean Whether the column is a primary key in the table referenced in the TableName field.
IsForeignKey Boolean Whether the column is a foreign key referenced in the TableName field.
PrimaryKeyName String The name of the primary key.
ForeignKeyName String The name of the foreign key.
ReferencedCatalogName String The database containing the primary key.
ReferencedSchemaName String The schema containing the primary key.
ReferencedTableName String The table containing the primary key.
ReferencedColumnName String The column name of the primary key.

CData Python Connector for Facebook Ads

sys_foreignkeys

Describes the foreign keys.

The following query retrieves all foreign keys which refer to other tables:

         SELECT * FROM sys_foreignkeys WHERE ForeignKeyType = 'FOREIGNKEY_TYPE_IMPORT'
          

Columns

Name Type Description
CatalogName String The name of the database containing the key.
SchemaName String The name of the schema containing the key.
TableName String The name of the table containing the key.
ColumnName String The name of the key column.
PrimaryKeyName String The name of the primary key.
ForeignKeyName String The name of the foreign key.
ReferencedCatalogName String The database containing the primary key.
ReferencedSchemaName String The schema containing the primary key.
ReferencedTableName String The table containing the primary key.
ReferencedColumnName String The column name of the primary key.
ForeignKeyType String Designates whether the foreign key is an import (points to other tables) or export (referenced from other tables) key.

CData Python Connector for Facebook Ads

sys_primarykeys

Describes the primary keys.

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

         SELECT * FROM sys_primarykeys
          

Columns

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

CData Python Connector for Facebook Ads

sys_indexes

Describes the available indexes. By filtering on indexes, you can write more selective queries with faster query response times.

The following query retrieves all indexes that are not primary keys:

          SELECT * FROM sys_indexes WHERE IsPrimary='false'
          

Columns

Name Type Description
CatalogName String The name of the database containing the index.
SchemaName String The name of the schema containing the index.
TableName String The name of the table containing the index.
IndexName String The index name.
ColumnName String The name of the column associated with the index.
IsUnique Boolean True if the index is unique. False otherwise.
IsPrimary Boolean True if the index is a primary key. False otherwise.
Type Int16 An integer value corresponding to the index type: statistic (0), clustered (1), hashed (2), or other (3).
SortOrder String The sort order: A for ascending or D for descending.
OrdinalPosition Int16 The sequence number of the column in the index.

CData Python Connector for Facebook Ads

sys_connection_props

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

The following query retrieves all connection properties that have been set in the connection string or set through a default value:

SELECT * FROM sys_connection_props WHERE Value <> ''

Columns

Name Type Description
Name String The name of the connection property.
ShortDescription String A brief description.
Type String The data type of the connection property.
Default String The default value if one is not explicitly set.
Values String A comma-separated list of possible values. A validation error is thrown if another value is specified.
Value String The value you set or a preconfigured default.
Required Boolean Whether the property is required to connect.
Category String The category of the connection property.
IsSessionProperty String Whether the property is a session property, used to save information about the current connection.
Sensitivity String The sensitivity level of the property. This informs whether the property is obfuscated in logging and authentication forms.
PropertyName String A camel-cased truncated form of the connection property name.
Ordinal Int32 The index of the parameter.
CatOrdinal Int32 The index of the parameter category.
Hierarchy String Shows dependent properties associated that need to be set alongside this one.
Visible Boolean Informs whether the property is visible in the connection UI.
ETC String Various miscellaneous information about the property.

CData Python Connector for Facebook Ads

sys_sqlinfo

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

See SQL Compliance for SQL syntax details.

Discovering the Data Source's SELECT Capabilities

Below is an example data set of SQL capabilities. Some aspects of SELECT functionality are returned in a comma-separated list if supported; otherwise, the column contains NO.

NameDescriptionPossible Values
AGGREGATE_FUNCTIONSSupported aggregation functions.AVG, COUNT, MAX, MIN, SUM, DISTINCT
COUNTWhether COUNT function is supported.YES, NO
IDENTIFIER_QUOTE_OPEN_CHARThe opening character used to escape an identifier.[
IDENTIFIER_QUOTE_CLOSE_CHARThe closing character used to escape an identifier.]
SUPPORTED_OPERATORSA list of supported SQL operators.=, >, <, >=, <=, <>, !=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, OR
GROUP_BYWhether GROUP BY is supported, and, if so, the degree of support.NO, NO_RELATION, EQUALS_SELECT, SQL_GB_COLLATE
OJ_CAPABILITIESThe supported varieties of outer joins supported.NO, LEFT, RIGHT, FULL, INNER, NOT_ORDERED, ALL_COMPARISON_OPS
OUTER_JOINSWhether outer joins are supported.YES, NO
SUBQUERIESWhether subqueries are supported, and, if so, the degree of support.NO, COMPARISON, EXISTS, IN, CORRELATED_SUBQUERIES, QUANTIFIED
STRING_FUNCTIONSSupported string functions.LENGTH, CHAR, LOCATE, REPLACE, SUBSTRING, RTRIM, LTRIM, RIGHT, LEFT, UCASE, SPACE, SOUNDEX, LCASE, CONCAT, ASCII, REPEAT, OCTET, BIT, POSITION, INSERT, TRIM, UPPER, REGEXP, LOWER, DIFFERENCE, CHARACTER, SUBSTR, STR, REVERSE, PLAN, UUIDTOSTR, TRANSLATE, TRAILING, TO, STUFF, STRTOUUID, STRING, SPLIT, SORTKEY, SIMILAR, REPLICATE, PATINDEX, LPAD, LEN, LEADING, KEY, INSTR, INSERTSTR, HTML, GRAPHICAL, CONVERT, COLLATION, CHARINDEX, BYTE
NUMERIC_FUNCTIONSSupported numeric functions.ABS, ACOS, ASIN, ATAN, ATAN2, CEILING, COS, COT, EXP, FLOOR, LOG, MOD, SIGN, SIN, SQRT, TAN, PI, RAND, DEGREES, LOG10, POWER, RADIANS, ROUND, TRUNCATE
TIMEDATE_FUNCTIONSSupported date/time functions.NOW, CURDATE, DAYOFMONTH, DAYOFWEEK, DAYOFYEAR, MONTH, QUARTER, WEEK, YEAR, CURTIME, HOUR, MINUTE, SECOND, TIMESTAMPADD, TIMESTAMPDIFF, DAYNAME, MONTHNAME, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, EXTRACT
REPLICATION_SKIP_TABLESIndicates tables skipped during replication.
REPLICATION_TIMECHECK_COLUMNSA string array containing a list of columns which will be used to check for (in the given order) to use as a modified column during replication.
IDENTIFIER_PATTERNString value indicating what string is valid for an identifier.
SUPPORT_TRANSACTIONIndicates if the provider supports transactions such as commit and rollback.YES, NO
DIALECTIndicates the SQL dialect to use.
KEY_PROPERTIESIndicates the properties which identify the uniform database.
SUPPORTS_MULTIPLE_SCHEMASIndicates if multiple schemas may exist for the provider.YES, NO
SUPPORTS_MULTIPLE_CATALOGSIndicates if multiple catalogs may exist for the provider.YES, NO
DATASYNCVERSIONThe CData Data Sync version needed to access this driver.Standard, Starter, Professional, Enterprise
DATASYNCCATEGORYThe CData Data Sync category of this driver.Source, Destination, Cloud Destination
SUPPORTSENHANCEDSQLWhether enhanced SQL functionality beyond what is offered by the API is supported.TRUE, FALSE
SUPPORTS_BATCH_OPERATIONSWhether batch operations are supported.YES, NO
SQL_CAPAll supported SQL capabilities for this driver.SELECT, INSERT, DELETE, UPDATE, TRANSACTIONS, ORDERBY, OAUTH, ASSIGNEDID, LIMIT, LIKE, BULKINSERT, COUNT, BULKDELETE, BULKUPDATE, GROUPBY, HAVING, AGGS, OFFSET, REPLICATE, COUNTDISTINCT, JOINS, DROP, CREATE, DISTINCT, INNERJOINS, SUBQUERIES, ALTER, MULTIPLESCHEMAS, GROUPBYNORELATION, OUTERJOINS, UNIONALL, UNION, UPSERT, GETDELETED, CROSSJOINS, GROUPBYCOLLATE, MULTIPLECATS, FULLOUTERJOIN, MERGE, JSONEXTRACT, BULKUPSERT, SUM, SUBQUERIESFULL, MIN, MAX, JOINSFULL, XMLEXTRACT, AVG, MULTISTATEMENTS, FOREIGNKEYS, CASE, LEFTJOINS, COMMAJOINS, WITH, LITERALS, RENAME, NESTEDTABLES, EXECUTE, BATCH, BASIC, INDEX
PREFERRED_CACHE_OPTIONSA string value specifies the preferred cacheOptions.
ENABLE_EF_ADVANCED_QUERYIndicates if the driver directly supports advanced queries coming from Entity Framework. If not, queries will be handled client side.YES, NO
PSEUDO_COLUMNSA string array indicating the available pseudo columns.
MERGE_ALWAYSIf the value is true, The Merge Mode is forcibly executed in Data Sync.TRUE, FALSE
REPLICATION_MIN_DATE_QUERYA select query to return the replicate start datetime.
REPLICATION_MIN_FUNCTIONAllows a provider to specify the formula name to use for executing a server side min.
REPLICATION_START_DATEAllows a provider to specify a replicate startdate.
REPLICATION_MAX_DATE_QUERYA select query to return the replicate end datetime.
REPLICATION_MAX_FUNCTIONAllows a provider to specify the formula name to use for executing a server side max.
IGNORE_INTERVALS_ON_INITIAL_REPLICATEA list of tables which will skip dividing the replicate into chunks on the initial replicate.
CHECKCACHE_USE_PARENTIDIndicates whether the CheckCache statement should be done against the parent key column.TRUE, FALSE
CREATE_SCHEMA_PROCEDURESIndicates stored procedures that can be used for generating schema files.

The following query retrieves the operators that can be used in the WHERE clause:

SELECT * FROM sys_sqlinfo WHERE Name = 'SUPPORTED_OPERATORS'
Note that individual tables may have different limitations or requirements on the WHERE clause; refer to the Data Model section for more information.

Columns

Name Type Description
NAME String A component of SQL syntax, or a capability that can be processed on the server.
VALUE String Detail on the supported SQL or SQL syntax.

CData Python Connector for Facebook Ads

sys_identity

Returns information about attempted modifications.

The following query retrieves the Ids of the modified rows in a batch operation:

         SELECT * FROM sys_identity
          

Columns

Name Type Description
Id String The database-generated Id returned from a data modification operation.
Batch String An identifier for the batch. 1 for a single operation.
Operation String The result of the operation in the batch: INSERTED, UPDATED, or DELETED.
Message String SUCCESS or an error message if the update in the batch failed.

CData Python Connector for Facebook Ads

sys_information

Describes the available system information.

The following query retrieves all columns:

SELECT * FROM sys_information

Columns

NameTypeDescription
ProductStringThe name of the product.
VersionStringThe version number of the product.
DatasourceStringThe name of the datasource the product connects to.
NodeIdStringThe unique identifier of the machine where the product is installed.
HelpURLStringThe URL to the product's help documentation.
LicenseStringThe license information for the product. (If this information is not available, the field may be left blank or marked as 'N/A'.)
LocationStringThe file path location where the product's library is stored.
EnvironmentStringThe version of the environment or rumtine the product is currently running under.
DataSyncVersionStringThe tier of CData Sync required to use this connector.
DataSyncCategoryStringThe category of CData Sync functionality (e.g., Source, Destination).

CData Python Connector for Facebook Ads

Connection String Options

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

For more information on establishing a connection, see Establishing a Connection.

Authentication


PropertyDescription
AccountIdThe ID of your ad account. If none is specified, we use the first ad account id returned from Facebook Ads.
AuthenticateAsPageThe name or Id of a page to authenticate as when making requests to Facebook.

OAuth


PropertyDescription
InitiateOAuthSpecifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.
OAuthClientIdSpecifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.
OAuthClientSecretSpecifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).
OAuthAccessTokenSpecifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.
OAuthSettingsLocationSpecifies the location of the settings file where OAuth values are saved.
CallbackURLIdentifies the URL users return to after authenticating to Facebook Ads via OAuth (Custom OAuth applications only).
ScopeThe scope to use when authenticating to Facebook.
OAuthVerifierSpecifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.
OAuthRefreshTokenSpecifies the OAuth refresh token used to request a new access token after the original has expired.
OAuthExpiresInSpecifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.
OAuthTokenTimestampDisplays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.

SSL


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

Firewall


PropertyDescription
FirewallTypeSpecifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.
FirewallServerIdentifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.
FirewallPortSpecifies the TCP port to be used for a proxy-based firewall.
FirewallUserIdentifies the user ID of the account authenticating to a proxy-based firewall.
FirewallPasswordSpecifies the password of the user account authenticating to a proxy-based firewall.

Proxy


PropertyDescription
ProxyAutoDetectSpecifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.
ProxyServerIdentifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.
ProxyPortIdentifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.
ProxyAuthSchemeSpecifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.
ProxyUserProvides the username of a user account registered with the proxy server specified in the ProxyServer connection property.
ProxyPasswordSpecifies the password of the user specified in the ProxyUser connection property.
ProxySSLTypeSpecifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.
ProxyExceptionsSpecifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.

Logging


PropertyDescription
LogfileSpecifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.
VerbositySpecifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.
LogModulesSpecifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.
MaxLogFileSizeSpecifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.
MaxLogFileCountSpecifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.

Schema


PropertyDescription
LocationSpecifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.
BrowsableSchemasOptional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .
TablesOptional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .
ViewsOptional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .

Caching


PropertyDescription
AutoCacheSpecifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.
CacheProviderThe namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.
CacheDriverThe driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.
CacheConnectionSpecifies the connection string for the specified cache database.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceNotes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.
OfflineGets the data from the specified cache database instead of live Facebook Ads data.
CacheMetadataDetermines whether the provider caches table metadata to a file-based cache database.

Miscellaneous


PropertyDescription
AggregateFormatThe format aggregate or collection columns should return in.
AsyncTimeoutWhen sending insights requests to Facebook Ads Async API, the value in seconds until a timeout error is thrown.
AutoDetectPageTokensControls whether the driver attempts to automatically detect the page token to use for a query targeting a page.
IgnoreValidationExceptionIgnore internal validation exception when breakdown combination is not valid.
MaxRowsSpecifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.
OtherSpecifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.
PagesizeThe maximum number of results to return per page from Facebook Ads.
PseudoColumnsSpecifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.
RetryLevelThe most granular ad object level at which the driver will try to retrieve results on retry.
RTKSpecifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.
TargetA default target if none is specified. Used for some tables, such as Comments, where a target may be specified.
TimeIncrementThe time increment used for ad and other ad object insights reporting.
TimeoutSpecifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.
UploadLinkedMediaUpload linked photos or videos before inserting a new Post.
UserDefinedViewsSpecifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.
CData Python Connector for Facebook Ads

Authentication

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


PropertyDescription
AccountIdThe ID of your ad account. If none is specified, we use the first ad account id returned from Facebook Ads.
AuthenticateAsPageThe name or Id of a page to authenticate as when making requests to Facebook.
CData Python Connector for Facebook Ads

AccountId

The ID of your ad account. If none is specified, we use the first ad account id returned from Facebook Ads.

Data Type

string

Default Value

""

Remarks

Note that the Target connection property has precedence over this connection property, and can be used to specify the id for any ad account, ad campaign, ad set, or ad. Please see Querying Facebook Ads Data for more information.

CData Python Connector for Facebook Ads

AuthenticateAsPage

The name or Id of a page to authenticate as when making requests to Facebook.

Data Type

string

Default Value

""

Remarks

The Id of a page to retrieve data from. The page must be managed by the authenticated user; you can obtain the Ids for all such pages by querying the Pages view.

CData Python Connector for Facebook Ads

OAuth

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


PropertyDescription
InitiateOAuthSpecifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.
OAuthClientIdSpecifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.
OAuthClientSecretSpecifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).
OAuthAccessTokenSpecifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.
OAuthSettingsLocationSpecifies the location of the settings file where OAuth values are saved.
CallbackURLIdentifies the URL users return to after authenticating to Facebook Ads via OAuth (Custom OAuth applications only).
ScopeThe scope to use when authenticating to Facebook.
OAuthVerifierSpecifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.
OAuthRefreshTokenSpecifies the OAuth refresh token used to request a new access token after the original has expired.
OAuthExpiresInSpecifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.
OAuthTokenTimestampDisplays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.
CData Python Connector for Facebook Ads

InitiateOAuth

Specifies the process for obtaining or refreshing the OAuth access token, which maintains user access while an authenticated, authorized user is working.

Possible Values

OFF, REFRESH, GETANDREFRESH

Data Type

string

Default Value

"OFF"

Remarks

OAuth is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service. The OAuth flow defines the method to be used for:

  • Logging in users.
  • Exchanging user credentials for an OAuth access token to be used for authentication.
  • Providing limited access to applications.

The options for initiating and maintaining OAuth access are named for the parts of that flow that the connector handles:

OFF The connector provides no automatic OAuth flow initiation. The OAuth flow is handled entirely by the user.
This means that the user must refresh the token manually, and reconnect with an updated OAuthAccessToken property when the current token expires.
GETANDREFRESH The connector handles the entire OAuth flow (both GET and REFRESH). This means that if a token already exists, the connector refreshes it when necessary; if no token currently exists, the connector obtains it by prompting the user to login.
REFRESH The user obtains the OAuth Access Token and sets up the sequence for refreshing the OAuth Access Token. (The user is never prompted to log in to authenticate.) After the user logs in, the connector handles the refresh of the OAuth Access Token.

For more information on how to set up OAuth and use this property when configuring a connection, see Establishing a Connection.

CData Python Connector for Facebook Ads

OAuthClientId

Specifies the client ID (also known as the consumer key) assigned to your custom OAuth application. This ID is required to identify the application to the OAuth authorization server during authentication.

Data Type

string

Default Value

""

Remarks

This property is required in two cases:

  • When using a custom OAuth application, such as in web-based authentication flows, service-based authentication, or certificate-based flows that require application registration.
  • If the driver does not provide embedded OAuth credentials.

(When the driver provides embedded OAuth credentials, this value may already be provided by the connector and thus not require manual entry.)

OAuthClientId is generally used alongside other OAuth-related properties such as OAuthClientSecret and OAuthSettingsLocation when configuring an authenticated connection.

OAuthClientId is one of the key connection parameters that need to be set before users can authenticate via OAuth. You can usually find this value in your identity provider’s application registration settings. Look for a field labeled Client ID, Application ID, or Consumer Key.

While the client ID is not considered a confidential value like a client secret, it is still part of your application's identity and should be handled carefully. Avoid exposing it in public repositories or shared configuration files.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for Facebook Ads

OAuthClientSecret

Specifies the client secret assigned to your custom OAuth application. This confidential value is used to authenticate the application to the OAuth authorization server. (Custom OAuth applications only.).

Data Type

string

Default Value

""

Remarks

This property (sometimes called the application secret or consumer secret) is required when using a custom OAuth application in any flow that requires secure client authentication, such as web-based OAuth, service-based connections, or certificate-based authorization flows. It is not required when using an embedded OAuth application.

The client secret is used during the token exchange step of the OAuth flow, when the driver requests an access token from the authorization server. If this value is missing or incorrect, authentication fails with either an invalid_client or an unauthorized_client error.

OAuthClientSecret is one of the key connection parameters that need to be set before users can authenticate via OAuth. You can obtain this value from your identity provider when registering the OAuth application.

Notes:

  • This value should be stored securely and never exposed in public repositories, scripts, or unsecured environments.
  • Client secrets may also expire after a set period. Be sure to monitor expiration dates and rotate secrets as needed to maintain uninterrupted access.

For more information on how this property is used when configuring a connection, see Establishing a Connection

CData Python Connector for Facebook Ads

OAuthAccessToken

Specifies the OAuth access token used to authenticate requests to the data source. This token is issued by the authorization server after a successful OAuth exchange.

Data Type

string

Default Value

""

Remarks

OAuthAccessToken is a temporary credential that authorizes access to protected resources. It is typically returned by the identity provider after the user or client application completes an OAuth authentication flow. This property is most commonly used in automated workflows or custom OAuth implementations where you want to manage token handling outside of the driver.

The OAuth access token has a server-dependent timeout, limiting user access. The timeout is set using the OAuthExpiresIn property. However, it can be reissued between requests to keep access alive as long as the user keeps working.

If InitiateOAuth is set to REFRESH, we recommend that you also set both OAuthExpiresIn and OAuthTokenTimestamp. The connector uses these properties to determine when the token expires so it can refresh most efficiently. If OAuthExpiresIn and OAuthTokenTimestamp are not specified, the connector refreshes the token immediately.

Note: Access tokens should be treated as sensitive credentials and stored securely. Avoid exposing them in logs, scripts, or configuration files that are not access-controlled.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for Facebook Ads

OAuthSettingsLocation

Specifies the location of the settings file where OAuth values are saved.

Data Type

string

Default Value

"%APPDATA%\\CData\\FacebookAds Data Provider\\OAuthSettings.txt"

Remarks

Storing OAuth settings in a central location avoids the need for users to enter OAuth connection properties manually each time they log in. It also enables credentials to be shared across connections or processes.

You can store OAuth values in a central file for shared access to those values, in either of the following ways:

  • Set InitiateOAuth to either GETANDREFRESH or REFRESH and specify a filepath to the OAuth settings file.
  • Use memory storage to load the credentials into static memory.

The following sections provide more detail on each of these methods.

Specifying the OAuthSettingsLocation Filepath

The default OAuth setting location is %APPDATA%\\CData\\FacebookAds Data Provider\\OAuthSettings.txt, with %APPDATA% set to the user's configuration directory. Default values vary, depending on the user's operating system.

  • Windows (ODBC and Power BI): registry://%DSN%
  • Windows: %APPDATA%CDataFacebookAds Data Provider\OAuthSettings.txt
  • Mac: %APPDATA%/CData/FacebookAds Data Provider/OAuthSettings.txt
  • Linux: %APPDATA%/CData/FacebookAds Data Provider/OAuthSettings.txt

Loading Credentials Via Memory Storage

Memory locations are specified by using a value starting with memory://, followed by a unique identifier for that set of credentials (for example, memory://user1). The identifier can be anything you choose, but it should be unique to the user.

Unlike file-based storage, where credentials persist across connections, memory storage loads the credentials into static memory and the credentials are shared between connections using the same identifier for the life of the process. To persist credentials outside the current process, you must manually store the credentials prior to closing the connection. This enables you to set them in the connection when the process is started again.

To retrieve OAuth property values, query the sys_connection_props system table. If there are multiple connections using the same credentials, the properties are read from the previously closed connection.

Supported Storage Types

  • memory://: Stores OAuth tokens in-memory (unique identifier, shared within same process, etc.)
  • registry://: Only supported in the Windows ODBC and Power BI editions. Stores OAuth tokens in the registry under the DSN settings. Must end in a DSN name like registry://CData Python Connector for Facebook Ads Data Source, or registry://%DSN%.
  • %DSN%: The name of the DSN you are connecting with.
  • Default (no prefix): Stores OAuth tokens within files. The value can be either an absolute path, or a path starting with %APPDATA% or %PROGRAMFILES%.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for Facebook Ads

CallbackURL

Identifies the URL users return to after authenticating to Facebook Ads via OAuth (Custom OAuth applications only).

Data Type

string

Default Value

""

Remarks

If you created a custom OAuth application, the OAuth authorization server redirects the user to this URL during the authentication process. This value must match the callback URL you specified when you configured the custom OAuth application.

CData Python Connector for Facebook Ads

Scope

The scope to use when authenticating to Facebook.

Data Type

string

Default Value

""

Remarks

The scope that are used when authenticating to Facebook give your App access to request additional information that may be required for certain tables. Individual scope may be entered in a comma separated list. Leaving it blank will use the defaults. The Scope is only used if you have specified your own OAuthClientId and OAuthClientSecret.

Requesting Additional Permissions

You may find while using the connector that Facebook returns an error stating your app does not have permissions to do a certain action. To resolve this, you will need to generate a new OAuth access token with the required scope. Set the Scope property in the authentication step for a desktop application.

Web applications need to call the GetOAuthAuthorizationURL and GetOAuthAccessToken stored procedures, which have inputs for the scope you would like to request.

Note that these are comma-separated lists of scopes, so you can request more than one per authorization request. You can find a list of available Facebook scopes here: http://developers.facebook.com/docs/authentication/permissions/.

CData Python Connector for Facebook Ads

OAuthVerifier

Specifies a verifier code returned from the OAuthAuthorizationURL . Used when authenticating to OAuth on a headless server, where a browser can't be launched. Requires both OAuthSettingsLocation and OAuthVerifier to be set.

Data Type

string

Default Value

""

Remarks

For detailed instructions about how to obtain the OAuthVerifier value, see Establishing a Connection.

CData Python Connector for Facebook Ads

OAuthRefreshToken

Specifies the OAuth refresh token used to request a new access token after the original has expired.

Data Type

string

Default Value

""

Remarks

The refresh token is used to obtain a new access token when the current one expires. It enables seamless authentication for long-running or automated workflows without requiring the user to log in again. This property is especially important in headless, CI/CD, or server-based environments where interactive authentication is not possible.

The refresh token is typically obtained during the initial OAuth exchange by calling the GetOAuthAccessToken stored procedure. After that, it can be set using this property to enable automatic token refresh, or passed to the RefreshOAuthAccessTokenproc; stored procedure if you prefer to manage the refresh manually.

When InitiateOAuth is set to REFRESH, the driver uses this token to retrieve a new access token automatically. After the first refresh, the driver saves updated tokens in the location defined by OAuthSettingsLocation, and uses those values for subsequent connections.

Note: The OAuthRefreshToken should be handled securely and stored in a trusted location. Like access tokens, refresh tokens can expire or be revoked depending on the identity provider’s policies.

For more information on how this property is used when configuring a connection, see Establishing a Connection.

CData Python Connector for Facebook Ads

OAuthExpiresIn

Specifies the duration in seconds, of an OAuth Access Token's lifetime. The token can be reissued to keep access alive as long as the user keeps working.

Data Type

string

Default Value

""

Remarks

The OAuth Access Token is assigned to an authenticated user, granting that user access to the network for a specified period of time. The access token is used in place of the user's login ID and password, which stay on the server.

An access token created by the server is only valid for a limited time. OAuthExpiresIn is the number of seconds the token is valid from when it was created. For example, a token generated at 2024-01-29 20:00:00 UTC that expires at 2024-01-29 21:00:00 UTC (an hour later) would have an OAuthExpiresIn value of 3600, no matter what the current time is.

To determine how long the user has before the Access Token will expire, check OAuthTokenTimestamp.

CData Python Connector for Facebook Ads

OAuthTokenTimestamp

Displays a Unix epoch timestamp in milliseconds that shows how long ago the current access token was created.

Data Type

string

Default Value

""

Remarks

The OAuth access token is assigned to an authenticated user, granting that user access to the network for a specified period of time. The access token is used in place of the user's login ID and password, which stay on the server.

An access token created by the server is only valid for a limited time. OAuthTokenTimestamp is the Unix timestamp when the server created the token. For example, OAuthTokenTimestamp=1706558400 indicates the OAuthAccessToken was generated by the server at 2024-01-29 20:00:00 UTC.

CData Python Connector for Facebook Ads

SSL

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


PropertyDescription
SSLServerCertSpecifies the certificate to be accepted from the server when connecting using TLS/SSL.
CData Python Connector for Facebook Ads

SSLServerCert

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

Data Type

string

Default Value

""

Remarks

If you are using a TLS/SSL connection, use this property to specify the TLS/SSL certificate to be accepted from the server. If you specify a value for this property, all other certificates that are not trusted by the machine are rejected.

This property can take the following forms:

Description Example
A full PEM Certificate (example shortened for brevity) -----BEGIN CERTIFICATE-----
MIIChTCCAe4CAQAwDQYJKoZIhv......Qw==
-----END CERTIFICATE-----
A path to a local file containing the certificate C:\cert.cer
The public key (example shortened for brevity) -----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSq......AQAB
-----END RSA PUBLIC KEY-----
The MD5 Thumbprint (hex values can also be either space- or colon-separated) ecadbdda5a1529c58a1e9e09828d70e4
The SHA1 Thumbprint (hex values can also be either space- or colon-separated) 34a929226ae0819f2ec14b4a3d904f801cbb150d

Note: It is possible to use '*' to signify that all certificates should be accepted, but due to security concerns this is not recommended.

CData Python Connector for Facebook Ads

Firewall

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


PropertyDescription
FirewallTypeSpecifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.
FirewallServerIdentifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.
FirewallPortSpecifies the TCP port to be used for a proxy-based firewall.
FirewallUserIdentifies the user ID of the account authenticating to a proxy-based firewall.
FirewallPasswordSpecifies the password of the user account authenticating to a proxy-based firewall.
CData Python Connector for Facebook Ads

FirewallType

Specifies the protocol the provider uses to tunnel traffic through a proxy-based firewall.

Possible Values

NONE, TUNNEL, SOCKS4, SOCKS5

Data Type

string

Default Value

"NONE"

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

Note: By default, the connector connects to the system proxy. To disable this behavior and connect to one of the following proxy types, set ProxyAutoDetect to false.

The following table provides port number information for each of the supported protocols.

Protocol Default Port Description
TUNNEL 80 The port where the connector opens a connection to Facebook Ads. Traffic flows back and forth via the proxy at this location.
SOCKS4 1080 The port where the connector opens a connection to Facebook Ads. SOCKS 4 then passes theFirewallUser value to the proxy, which determines whether the connection request should be granted.
SOCKS5 1080 The port where the connector sends data to Facebook Ads. If the SOCKS 5 proxy requires authentication, set FirewallUser and FirewallPassword to credentials the proxy recognizes.

To connect to HTTP proxies, use ProxyServer and ProxyPort. To authenticate to HTTP proxies, use ProxyAuthScheme, ProxyUser, and ProxyPassword.

CData Python Connector for Facebook Ads

FirewallServer

Identifies the IP address, DNS name, or host name of a proxy used to traverse a firewall and relay user queries to network resources.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for Facebook Ads

FirewallPort

Specifies the TCP port to be used for a proxy-based firewall.

Data Type

int

Default Value

0

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for Facebook Ads

FirewallUser

Identifies the user ID of the account authenticating to a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for Facebook Ads

FirewallPassword

Specifies the password of the user account authenticating to a proxy-based firewall.

Data Type

string

Default Value

""

Remarks

A proxy-based firewall (or proxy firewall) is a network security device that acts as an intermediary between user requests and the resources they access. The proxy accepts the request of an authenticated user, tunnels through the firewall, and transmits the request to the appropriate server.

Because the proxy evaluates and transfers data backets on behalf of the requesting users, the users never connect directly with the servers, only with the proxy.

CData Python Connector for Facebook Ads

Proxy

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


PropertyDescription
ProxyAutoDetectSpecifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.
ProxyServerIdentifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.
ProxyPortIdentifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.
ProxyAuthSchemeSpecifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.
ProxyUserProvides the username of a user account registered with the proxy server specified in the ProxyServer connection property.
ProxyPasswordSpecifies the password of the user specified in the ProxyUser connection property.
ProxySSLTypeSpecifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.
ProxyExceptionsSpecifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.
CData Python Connector for Facebook Ads

ProxyAutoDetect

Specifies whether the provider checks your system proxy settings for existing proxy server configurations, rather than using a manually specified proxy server.

Data Type

bool

Default Value

true

Remarks

When this connection property is set to True, the connector checks your system proxy settings for existing proxy server configurations (no need to manually supply proxy server details).

This connection property takes precedence over other proxy settings. If you want to configure the connector to connect to a specific proxy server, set ProxyAutoDetect to False.

On Windows, the connector reads the proxy settings from the Internet Options in the registry, specifically the registry key HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\. On Windows 10 and later, this corresponds to the Proxy Settings found in the Windows Settings.

Note that these settings apply only to the current user of the machine. If you're running an application as a service, the connector does not read your own user's settings. You must instead manually supply the proxy settings in the connector's connection properties.

On Mac, the connector reads proxy settings from the system-configured CFNetwork settings.

On Linux, this property is unsupported, and is set to False by default.

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

CData Python Connector for Facebook Ads

ProxyServer

Identifies the hostname or IP address of the proxy server through which you want to route HTTP traffic.

Data Type

string

Default Value

""

Remarks

The connector only routes HTTP traffic through the proxy server specified in this connection property when ProxyAutoDetect is set to False.

If ProxyAutoDetect is set to True (the default), the connector instead routes HTTP traffic through the proxy server specified in your system proxy settings.

CData Python Connector for Facebook Ads

ProxyPort

Identifies the TCP port on your specified proxy server that has been reserved for routing HTTP traffic to and from the client.

Data Type

int

Default Value

80

Remarks

The connector only routes HTTP traffic through the ProxyServer port specified in this connection property when ProxyAutoDetect is set to False.

If ProxyAutoDetect is set to True (the default), the connector instead routes HTTP traffic through the proxy server port specified in your system proxy settings.

For other proxy types, see FirewallType.

CData Python Connector for Facebook Ads

ProxyAuthScheme

Specifies the authentication method the provider uses when authenticating to the proxy server specified in the ProxyServer connection property.

Possible Values

BASIC, DIGEST, NONE, NEGOTIATE, NTLM

Data Type

string

Default Value

"BASIC"

Remarks

Note: The connector only uses this ProxyAuthScheme when ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the authentication method specified in your system proxy settings.

Supported authentication types :

  • BASIC: The connector performs HTTP basic authentication.
  • DIGEST: The connector performs HTTP digest authentication.
  • NTLM: The connector retrieves an NTLM token.
  • NEGOTIATE: The connector retrieves an NTLM or Kerberos token based on the applicable protocol for authentication.
  • NONE: Signifies that the ProxyServer does not require authentication.

For all values other than NONE, you must also set the ProxyUser and ProxyPassword connection properties.

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

CData Python Connector for Facebook Ads

ProxyUser

Provides the username of a user account registered with the proxy server specified in the ProxyServer connection property.

Data Type

string

Default Value

""

Remarks

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

After selecting one of the available authentication types in ProxyAuthScheme, set this property as follows:

ProxyAuthScheme Value Value to set for ProxyUser
BASIC The username of a user registered with the proxy server.
DIGEST The username of a user registered with the proxy server.
NEGOTIATE The username of a Windows user who is a valid user in the domain or trusted domain that the proxy server is part of, in the format user@domain or domain\user.
NTLM The username of a Windows user who is a valid user in the domain or trusted domain that the proxy server is part of, in the format user@domain or domain\user.
NONE Do not set the ProxyPassword connection property.

Note: The connector only uses this username if ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the username specified in your system proxy settings.

CData Python Connector for Facebook Ads

ProxyPassword

Specifies the password of the user specified in the ProxyUser connection property.

Data Type

string

Default Value

""

Remarks

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

After selecting one of the available authentication types in ProxyAuthScheme, set this property as follows:

ProxyAuthScheme Value Value to set for ProxyPassword
BASIC The password associated with the proxy server user specified in ProxyUser.
DIGEST The password associated with the proxy server user specified in ProxyUser.
NEGOTIATE The password associated with the Windows user account specified in ProxyUser.
NTLM The password associated with the Windows user account specified in ProxyUser.
NONE Do not set the ProxyPassword connection property.

For SOCKS 5 authentication or tunneling, see FirewallType.

Note: The connector only uses this password if ProxyAutoDetect is set to False. If ProxyAutoDetect is set to True (the default), the connector instead uses the password specified in your system proxy settings.

CData Python Connector for Facebook Ads

ProxySSLType

Specifies the SSL type to use when connecting to the proxy server specified in the ProxyServer connection property.

Possible Values

AUTO, ALWAYS, NEVER, TUNNEL

Data Type

string

Default Value

"AUTO"

Remarks

This property determines when to use SSL for the connection to the HTTP proxy specified by ProxyServer. You can set this connection property to the following values :

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

CData Python Connector for Facebook Ads

ProxyExceptions

Specifies a semicolon-separated list of destination hostnames or IPs that are exempt from connecting through the proxy server set in the ProxyServer connection property.

Data Type

string

Default Value

""

Remarks

The ProxyServer is used for all addresses, except for addresses defined in this property. Use semicolons to separate entries.

Note: The connector uses the system proxy settings by default, without further configuration needed. If you want to explicitly configure proxy exceptions for this connection, set ProxyAutoDetect to False.

CData Python Connector for Facebook Ads

Logging

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


PropertyDescription
LogfileSpecifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.
VerbositySpecifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.
LogModulesSpecifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.
MaxLogFileSizeSpecifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.
MaxLogFileCountSpecifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.
CData Python Connector for Facebook Ads

Logfile

Specifies the file path to the log file where the provider records its activities, such as authentication, query execution, and connection details.

Data Type

string

Default Value

""

Remarks

This property specifies the location and name of the log file where the connector records its operations, including authentication events, query execution, and connection details. If the specified file does not exist, the connector creates it. Ensure that the user or the service running the connector has write access to the specified path or file. Without sufficient permissions, the log file is not created.

Sensitive information from the connection string, such as passwords and tokens, is automatically masked in the logs. However, sensitive information present in the data itself may not be masked.

If you specify a relative path for Logfile, and if the Location property is set, that directory is used as the base path for the log file.

Additional properties allow you to customize logging behavior:

CData Python Connector for Facebook Ads

Verbosity

Specifies the verbosity level of the log file, which controls the amount of detail logged. Supported values range from 1 to 5.

Data Type

string

Default Value

"1"

Remarks

This property defines the level of detail the connector includes in the log file. Higher verbosity levels increase the detail of the logged information, but may also result in larger log files and slower performance due to the additional data being captured.

The default verbosity level is 1, which is recommended for regular operation. Higher verbosity levels are primarily intended for debugging purposes. For more information on each level, refer to Logging.

When combined with the LogModules property, Verbosity can refine logging to specific categories of information.

CData Python Connector for Facebook Ads

LogModules

Specifies the core modules to include in the log file. Use a semicolon-separated list of module names. By default, all modules are logged.

Data Type

string

Default Value

""

Remarks

The connector writes details about each operation it performs into the logfile specified by the Logfile connection property.

Each of these logged operations are assigned to a themed category called a module, and each module has a corresponding short code used to labels individual connector operations as belonging to that module.

When this connection property is set to a semicolon-separated list of module codes, only operations belonging to the specified modules are written to the logfile. Note that this only affects which operations are logged moving forward and doesn't retroactively alter the existing contents of the logfile. For example: INFO;EXEC;SSL;META;

By default, logged operations from all modules are included.

You can explicitly exclude a module by prefixing it with a "-". For example: -HTTP

To apply filters to submodules, identify them with the syntax <module name>.<submodule name>. For example, the following value causes the connector to only log actions belonging to the HTTP module, and further refines it to exclude actions belonging to the Res submodule of the HTTP module: HTTP;-HTTP.Res

Note that the logfile filtering triggered by the Verbosity connection property takes precedence over the filtering imposed by this connection property. This means that operations of a higher verbosity level than the level specified in the Verbosity connection property are not printed in the logfile, even if they belong to one of the modules specified in this connection property.

The available modules and submodules are:

Module Name Module Description Submodules
INFO General Information. Includes the connection string, product version (build number), and initial connection messages.
  • Connec – Information related to creating or destroying connections.
  • Messag – Generic label for messages pertaining to connections, the connection string, and product version. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
EXEC Query Execution. Includes execution messages for user-written SQL queries, parsed SQL queries, and normalized SQL queries. Success/failure messages for queries and query pages appear here as well.
  • Messag – Messages pertaining to query execution. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Normlz – Query normalization steps. Query normalization is when the product takes the user-submitted query and rewrites the query to get the same results with optimal performance.
  • Origin – This label applies to any messages recording a user's original query (the exact, unaltered, non-normalized query executed by the user).
  • Page – Messages related to query paging.
  • Parsed – Query parsing steps. Parsing is the process of converting the user-submitted query into a standardized format for easier processing.
HTTP HTTP protocol messages. Includes HTTP requests/responses (including POST messages), as well as Kerberos related messages.
  • KERB – HTTP requests related to Kerberos.
  • Messag – Messages pertaining to HTTP protocols. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • Unpack – This label applies to messages about zipped data being returned from the service API and unpacked by the product.
  • Res – Messages containing HTTP responses.
  • Req – Messages containing HTTP requests.
WSDL Messages pertaining to the generation of WSDL/XSD files.
SSL SSL certificate messages.
  • Certif – Messages pertaining to SSL certificates.
AUTH Authentication related failure/success messages.
  • Messag – Messages pertaining to authentication. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • OAuth – Messages related to OAuth authentication.
  • Krbros – Kerberos-related authentication messages.
SQL Includes SQL transactions, SQL bulk transfer messages, and SQL result set messages.
  • Bulk – Messages pertaining to bulk query execution.
  • Cache – Messages related to reading row data from and writing row data to the product's cache for better performance.
  • Messag – Messages pertaining to SQL transactions. These messages are typically specific to the connector, rather than being received and passed along directly from the service.
  • ResSet – Query resultsets.
  • Transc – Messages related to handling transactions, including information about the number of jobs executed and backup table handling.
META Metadata cache and schema messages.
  • Cache – Messages related to reading from and modifying column and table definitions in the product's cache for better performance.
  • Schema – Messages related to retrieving metadata from or modifying the service schema.
  • MemSto – Messages related to writing to or reading from in-memory metadata cache.
  • Storag – Messages relating to storing metadata on disk or in an external data store, rather than in memory.
FUNC Information related to executing SQL functions.
  • Errmsg – Error messages related to executing SQL functions.
TCP Incoming and outgoing raw bytes on TCP transport layer messages.
  • Send – Raw data sent via the TCP protocol.
  • Receiv – Raw data received via the TCP protocol.
FTP Messages pertaining to the File Transfer Protocol.
  • Info – Status messages related to communication in the FTP protocol.
  • Client – Messages related to actions taken by the FTP client (the product) during FTP communication.
  • Server – Messages related to actions taken by the FTP server during FTP communication.
SFTP Messages pertaining to the Secure File Transfer Protocol.
  • Info – Status messages related to communication in the SFTP protocol.
  • To_Server – Messages related to actions taken by the SFTP client (the product) during SFTP communication.
  • From_Server – Messages related to actions taken by the SFTP server during SFTP communication.
POP Messages pertaining to data transferred via the Post Office Protocol.
  • Client – Messages related to actions taken by the POP client (the product) during POP communication.
  • Server – Messages related to actions taken by the POP server during POP communication.
  • Status – Status messages related to communication in the POP protocol.
SMTP Messages pertaining to data transferred via the Simple Mail Transfer Protocol.
  • Client – Messages related to actions taken by the SMTP client (the product) during SMTP communication.
  • Server – Messages related to actions taken by the SMTP server during SMTP communication.
  • Status – Status messages related to communication in the SMTP protocol.
CORE Messages relating to various internal product operations not covered by other modules.
DEMN Messages related to SQL remoting.
CLJB Messages about bulk data uploads (cloud job).
  • Commit – Submissions for bulk data uploads.
SRCE Miscellaneous messages produced by the product that don't belong in any other module.
TRANCE Advanced messages concerning low-level product operations.

CData Python Connector for Facebook Ads

MaxLogFileSize

Specifies the maximum size of a single log file in bytes. For example, '10 MB'. When the file reaches the limit, the provider creates a new log file with the date and time appended to the name.

Data Type

string

Default Value

"100MB"

Remarks

For values lower than 100 KB, the connector uses 100 KB as the minimum allowable size.

To control the total number of log files retained, use the MaxLogFileCount property in conjunction with this property. Together, these properties allow you to manage the size and retention of log files effectively.

CData Python Connector for Facebook Ads

MaxLogFileCount

Specifies the maximum number of log files the provider retains. When the limit is reached, the oldest log file is deleted to make space for a new one.

Data Type

int

Default Value

-1

Remarks

Each log file name includes the date and time for easier identification.

This property accepts the following values:

  • A value of 2 or higher sets the maximum number of log files retained.
  • A value of 1 retains only one log file. When it reaches the maximum size, the file is deleted and replaced by a new one, leaving no history beyond the current log.
  • A value of 0 or negative indicates no limit on the number of log files, and logging continues indefinitely.

To manage log file size, use the MaxLogFileSize property. The two properties work together to control the size and retention of log files in the logging folder.

CData Python Connector for Facebook Ads

Schema

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


PropertyDescription
LocationSpecifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.
BrowsableSchemasOptional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .
TablesOptional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .
ViewsOptional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .
CData Python Connector for Facebook Ads

Location

Specifies the location of a directory containing schema files that define tables, views, and stored procedures. Depending on your service's requirements, this may be expressed as either an absolute path or a relative path.

Data Type

string

Default Value

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

Remarks

The Location property is only needed if you want to either customize definitions (for example, change a column name, ignore a column, etc.) or extend the data model with new tables, views, or stored procedures.

If left unspecified, the default location is %APPDATA%\\CData\\FacebookAds Data Provider\\Schema, where %APPDATA% is set to the user's configuration directory:

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

CData Python Connector for Facebook Ads

BrowsableSchemas

Optional setting that restricts the schemas reported to a subset of all available schemas. For example, BrowsableSchemas=SchemaA,SchemaB,SchemaC .

Data Type

string

Default Value

""

Remarks

Listing all available database schemas can take extra time, thus degrading performance. Providing a list of schemas in the connection string saves time and improves performance.

CData Python Connector for Facebook Ads

Tables

Optional setting that restricts the tables reported to a subset of all available tables. For example, Tables=TableA,TableB,TableC .

Data Type

string

Default Value

""

Remarks

Listing all available tables from some databases can take extra time, thus degrading performance. Providing a list of tables in the connection string saves time and improves performance.

If there are lots of tables available and you already know which ones you want to work with, you can use this property to restrict your viewing to only those tables. To do this, specify the tables you want in a comma-separated list. Each table should be a valid SQL identifier with any special characters escaped using square brackets, double-quotes or backticks. For example, Tables=TableA,[TableB/WithSlash],WithCatalog.WithSchema.`TableC With Space`.

Note: If you are connecting to a data source with multiple schemas or catalogs, you must specify each table you want to view by its fully qualified name. This avoids ambiguity between tables that may exist in multiple catalogs or schemas.

CData Python Connector for Facebook Ads

Views

Optional setting that restricts the views reported to a subset of the available tables. For example, Views=ViewA,ViewB,ViewC .

Data Type

string

Default Value

""

Remarks

Listing all available views from some databases can take extra time, thus degrading performance. Providing a list of views in the connection string saves time and improves performance.

If there are lots of views available and you already know which ones you want to work with, you can use this property to restrict your viewing to only those views. To do this, specify the views you want in a comma-separated list. Each view should be a valid SQL identifier with any special characters escaped using square brackets, double-quotes or backticks. For example, Views=ViewA,[ViewB/WithSlash],WithCatalog.WithSchema.`ViewC With Space`.

Note: If you are connecting to a data source with multiple schemas or catalogs, you must specify each view you want to examine by its fully qualified name. This avoids ambiguity between views that may exist in multiple catalogs or schemas.

CData Python Connector for Facebook Ads

Caching

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


PropertyDescription
AutoCacheSpecifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.
CacheProviderThe namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.
CacheDriverThe driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.
CacheConnectionSpecifies the connection string for the specified cache database.
CacheLocationSpecifies the path to the cache when caching to a file.
CacheToleranceNotes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.
OfflineGets the data from the specified cache database instead of live Facebook Ads data.
CacheMetadataDetermines whether the provider caches table metadata to a file-based cache database.
CData Python Connector for Facebook Ads

AutoCache

Specifies whether the content of tables targeted by SELECT queries is automatically cached to the specified cache database.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, the connector automatically caches the contents of tables targeted by SELECT queries. The content of these tables is cached to the cache database specified by the CacheConnection and CacheProvider connection properties.

See Also

For additional information, see:

  • CacheMetadata: With CacheMetadata enabled, all retrieved metadata is mirrored in the cache database. This means that any subsequent attempts by the connector to discover metadata are much faster, as this metadata is then read directly from the cache database, without needing to spend time requesting metadata from Facebook Ads.
  • Explicitly Caching Data: This topic provides examples for using AutoCache in Offline mode.
  • CACHE Statements: You can use the CACHE statement to explicitly cache the content of any table targeted by a SELECT query.

CData Python Connector for Facebook Ads

CacheProvider

The namespace of an ADO.NET provider. The specified provider is used as the target database for all caching operations.

Data Type

string

Default Value

""

Remarks

You can cache to ADO.NET providers saved in your ADO.NET global assembly cache (GAC).

CData ADO.NET providers automatically register themselves with the GAC during installation, so you don't need to do so manually.

Third-party ADO.NET providers may or may not automatically register themselves with the GAC during installation. If you want to cache to a third-party ADO.NET provider, consult the documentation for that provider to determine what steps (if any) you must take to register them with the GAC. Once they have been registered, you can supply their namespace in this connection property.

You must also set the CacheConnection connection property to provide a connection string for the specified ADO.NET provider.

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

SQLite

You can use the Microsoft ADO.NET Provider for SQLite to cache to SQLite databases.

CacheProvider=Microsoft.Data.Sqlite;CacheConnection='DataSource=C:\\Users\\Public\\cache.db;'InitiateOAuth=GETANDREFRESH;

MySQL

To cache to MySQL, you can use the CData ADO.NET Provider for MySQL:
Cache Provider=System.Data.CData.MySQL;Cache Connection='Server=localhost;Port=3306;Database=cache;User=root;Password=123456';User=myUser;Password=myPassword;Security Token=myToken;

SQL Server

You can use the Microsoft .NET Framework Provider for SQL Server, included in the .NET Framework, to cache to SQL Server:

Cache Provider=System.Data.SqlClient;Cache Connection="Server=MyMACHINE\MyInstance;Database=SQLCACHE;User Id=root;Password=admin";InitiateOAuth=GETANDREFRESH;

Oracle

To cache to Oracle, you can use the Oracle Data Provider for .NET, as shown in the following example:

Cache Provider=Oracle.DataAccess.Client;Cache Connection='User Id=scott;Password=tiger;Data Source=ORCL';InitiateOAuth=GETANDREFRESH;

The Oracle Data Provider for .NET also requires the Oracle Database Client. When you download the Oracle Database Client, ensure that its bitness matches the bitness of your machine. When you install, select either the Runtime or Administrator installation type. The Instant Client is not sufficient.

PostgreSQL

To cache to PostgreSQL, you can use the CData ADO.NET Provider for PostgreSQL:
Cache Provider=System.Data.CData.PostgreSQL;Cache Connection='Server=localhost;Port=5432;Database=cache;User=postgres;Password=123456';User=myUser;Password=myPassword;Security Token=myToken;

CData Python Connector for Facebook Ads

CacheDriver

The driver class of a JDBC driver. The specified driver is used to connect to the target database for all caching operations.

Data Type

string

Default Value

""

Remarks

You can cache to any database for which you have a JDBC driver, including CData JDBC drivers.

Note: You must add the JAR file of the specified JDBC driver to the classpath. For CData JDBC drivers, you can find this JAR file in the "lib" subfolder of that driver's installation directory.

You must also set the CacheConnection connection property to provide a connection string for the specified JDBC driver.

For Linux systems and macOS, you need to create a config.ini file on the installation path of the driver (site-packages/cdata). The config.ini file has the following format (the driver and the path of the JDBC driver):

[salesforce.cpython-38-x86_64-linux-gnu.so]
CLASSPATH = /home/usrname/Downloads/lib/cdata.jdbc.postgresql.jar

Examples

The following examples show how to cache to several major databases. For more information on the JDBC URL syntax and typical connection properties, see CacheConnection.

Derby and Java DB

Java DB is the Oracle distribution of Derby. You must add the Derby JDBC driver's JAR file, derbytools.jar, to your classpath to cache to Java DB.

The Derby JDBC driver's JAR file is bundled in db-derby-10.17.1.0-bin.zip, which you can download from this page. You can find derbytools.jar in the "lib" subfolder of this zip file.

After adding derbytools.jar to the classpath, you can cache to a Java DB database as follows:

jdbc:facebookads:CacheDriver=org.apache.derby.jdbc.EmbeddedDriver;CacheConnection='jdbc:derby:sample';InitiateOAuth=GETANDREFRESH;
To cache to an in-memory database, use a JDBC URL like the following:
jdbc:facebookads:CacheDriver=org.apache.derby.jdbc.EmbeddedDriver;CacheConnection='jdbc:derby:memory';InitiateOAuth=GETANDREFRESH;

SQLite

The following is a JDBC URL for the SQLite JDBC driver:

jdbc:facebookads:CacheDriver=org.sqlite.JDBC;CacheConnection='jdbc:sqlite:C:/Temp/sqlite.db';InitiateOAuth=GETANDREFRESH;

MySQL

The following is a JDBC URL for the CData JDBC Driver for MySQL:

  jdbc:facebookads:Cache Driver=cdata.jdbc.mysql.MySQLDriver;Cache Connection='jdbc:mysql:Server=localhost;Port=3306;Database=cache;User=root;Password=123456';InitiateOAuth=GETANDREFRESH;
  

SQL Server

The following JDBC URL uses the Microsoft JDBC Driver for SQL Server:

jdbc:facebookads:Cache Driver=com.microsoft.sqlserver.jdbc.SQLServerDriver;Cache Connection='jdbc:sqlserver://localhost\sqlexpress:7437;user=sa;password=123456;databaseName=Cache';InitiateOAuth=GETANDREFRESH;

Oracle

The following is a JDBC URL for the Oracle Thin Client:

jdbc:facebookads:Cache Driver=oracle.jdbc.OracleDriver;CacheConnection='jdbc:oracle:thin:scott/tiger@localhost:1521:orcldb';InitiateOAuth=GETANDREFRESH;
NOTE: If using a version of Oracle older than 9i, the cache driver will instead be oracle.jdbc.driver.OracleDriver .

PostgreSQL

The following JDBC URL uses the official PostgreSQL JDBC driver:

jdbc:facebookads:CacheDriver=cdata.jdbc.postgresql.PostgreSQLDriver;CacheConnection='jdbc:postgresql:User=postgres;Password=admin;Database=postgres;Server=localhost;Port=5432;';InitiateOAuth=GETANDREFRESH;

CData Python Connector for Facebook Ads

CacheConnection

Specifies the connection string for the specified cache database.

Data Type

string

Default Value

""

Remarks

The target cache database is determined by a combination of this connection property and the CacheProvider connection property. Both properties are required to use the specified cache database.

The connection string specified in this connection property is passed directly to the specified in the CacheProvider connection property. Consult the documentation for the specified for more information on its available connection properties.

Examples of common cache database settings can be found below.

SQLite

MySQL

The following are typical connection properties:

  • Server: The IP address or domain name of the server hosting the MySQL database that you want to cache to.
  • Port: The port on the specified server where your MySQL instance is running.
  • Database: The name of the MySQL database that you want to cache to. Must match the name of a MySQL database hosted on the specified server.
  • User: The username of a user registered with the selected MySQL database.
  • Password: The password associated with the specified MySQL user.

SQL Server

The following are typical SQL Server connection properties:

  • Server: The name or network address of the computer running SQL Server. To connect to a named instance instead of the default instance, specify the host name and the instance name, separated by a backslash.
  • Port: The port on the specified server where your SQL Server instance is running.
  • Database: The name of the SQL Server database you want to cache to. Must match the name of a SQL Server database hosted on the specified server.
  • Integrated Security: To use the current Windows account for authentication, set this option to True. To authenticate with User and Password instead, set this option to False.
  • User Id: The username of a user registered with the selected SQL Server database. This property is only needed if you are not using integrated security.
  • Password: The password associated with the specified SQL Server user. This property is only needed if you are not using integrated security.

Oracle

The following are typical connection properties:

  • Data Source: The connect descriptor that identifies the Oracle database. This can be a TNS connect descriptor, an Oracle Net Services name that resolves to a connect descriptor, or, after version 11g, an Easy Connect naming (the host name of the Oracle server with an optional port and service name).

  • User Id: The username of a user registered with the selected Oracle database.
  • Password: The password associated with the specified Oracle user.

PostgreSQL

The following are typical connection properties:

  • Host: The address of the server hosting the PostgreSQL database.
  • Port: The port on the specified host server where your PostgreSQL database is hosted.
  • Database: The name of the PostgreSQL database you want to cache to. Must match the name of a PostgreSQL database hosted on the specified server.
  • User name: The username of a user registered with the selected PostgreSQL database.
  • Password: The password associated with the specified user.

CData Python Connector for Facebook Ads

CacheLocation

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

Data Type

string

Default Value

"%APPDATA%\\CData\\FacebookAds Data Provider"

Remarks

The CacheLocation is a simple, file-based cache.

If left unspecified, the default location is %APPDATA%\\CData\\FacebookAds Data Provider, where %APPDATA% is set to the user's configuration directory:

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

See Also

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

CData Python Connector for Facebook Ads

CacheTolerance

Notes the tolerance, in seconds, for stale data in the specified cache database. Requires AutoCache to be set to True.

Data Type

int

Default Value

600

Remarks

When you execute a query for tables in the cache, the connector checks the time elapsed since the last update to the cache.

If the last update to the cache is older than the value of this connection property (measured in seconds), the connector refreshes the cache.

Otherwise, the connector returns data directly from the cache.

CData Python Connector for Facebook Ads

Offline

Gets the data from the specified cache database instead of live Facebook Ads data.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, all queries execute against the cache database instead of the live Facebook Ads data.

In this mode, some SQL operations like INSERT, UPDATE, DELETE, and CACHE are disabled.

CData Python Connector for Facebook Ads

CacheMetadata

Determines whether the provider caches table metadata to a file-based cache database.

Data Type

bool

Default Value

false

Remarks

When this connection property is set to True, as you execute queries, table metadata in the Facebook Ads catalog is cached to the cache database specified by CacheConnection and CacheProvider, or, if those connection properties are not set, to the user's home directory.

The location of your home directory varies by platform:

PlatformHome Directory
Windows %APPDATA%\\CData\\FacebookAds Data Provider
Mac ~/Library/Application Support/CData/FacebookAds Data Provider
Unix ~/.config/CData/FacebookAds Data Provider

A table's metadata is retrieved only once, when the table is queried for the first time.

When to Use CacheMetadata

When there are a large number of Facebook Ads tables and columns for the connector to retrieve during metadata discovery, the connector may take a while to list all table metadata.

You may experience slow metadata retrieval when:

  • Your Facebook Ads instance naturally has a large table count.
  • The connector has been configured, via its connection properties, to discover more tables than it would under its default configuration.
  • You make many short-lived connections to the connector.
With CacheMetadata enabled, all retrieved metadata is mirrored in the cache database. This means that any subsequent attempts by the connector to discover metadata are much faster, as this metadata is then read directly from the cache database, without needing to spend time requesting metadata from Facebook Ads.

When Not to Use CacheMetadata

The connector automatically persists metadata in memory for up to an hour when you first discover the metadata for a table or view, so CacheMetadata is generally not necessary.

CacheMetadata is not ideal in scenarios where you are working with volatile metadata. The first time you query a table, the connector caches its metadata to the cache database file. This cache is not dynamically updated to reflect updates to the table schema, so you must delete and rebuild the cache database file to pick up new, changed, or deleted columns.

CData Python Connector for Facebook Ads

Miscellaneous

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


PropertyDescription
AggregateFormatThe format aggregate or collection columns should return in.
AsyncTimeoutWhen sending insights requests to Facebook Ads Async API, the value in seconds until a timeout error is thrown.
AutoDetectPageTokensControls whether the driver attempts to automatically detect the page token to use for a query targeting a page.
IgnoreValidationExceptionIgnore internal validation exception when breakdown combination is not valid.
MaxRowsSpecifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.
OtherSpecifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.
PagesizeThe maximum number of results to return per page from Facebook Ads.
PseudoColumnsSpecifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.
RetryLevelThe most granular ad object level at which the driver will try to retrieve results on retry.
RTKSpecifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.
TargetA default target if none is specified. Used for some tables, such as Comments, where a target may be specified.
TimeIncrementThe time increment used for ad and other ad object insights reporting.
TimeoutSpecifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.
UploadLinkedMediaUpload linked photos or videos before inserting a new Post.
UserDefinedViewsSpecifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.
CData Python Connector for Facebook Ads

AggregateFormat

The format aggregate or collection columns should return in.

Possible Values

JSON, XML

Data Type

string

Default Value

"JSON"

Remarks

The format aggregate or collection columns should return in.

CData Python Connector for Facebook Ads

AsyncTimeout

When sending insights requests to Facebook Ads Async API, the value in seconds until a timeout error is thrown.

Data Type

string

Default Value

"300"

Remarks

The operations run until they complete successfully or until they encounter an error condition.

If AsyncTimeout expires and the operation is not yet complete, the driver throws an exception.

CData Python Connector for Facebook Ads

AutoDetectPageTokens

Controls whether the driver attempts to automatically detect the page token to use for a query targeting a page.

Data Type

bool

Default Value

true

Remarks

By default, the driver automatically detects and uses the appropriate page token for queries targeting a page. Set this property to False to disable automatic detection. When disabled, you must use the AuthenticateAsPage property to specify the ID of the page you intend to query.

CData Python Connector for Facebook Ads

IgnoreValidationException

Ignore internal validation exception when breakdown combination is not valid.

Data Type

bool

Default Value

false

Remarks

When set to "True", the supplied breakdown combination for an insights query will be passed directly to Facebook, without any internal attempts at validation by the connector. If the supplied combination is invalid, the error message from Facebook Ads will be returned directly to the user. Refer to Facebook documentation on breadown combinations for information on valid combinations.

CData Python Connector for Facebook Ads

MaxRows

Specifies the maximum number of rows returned for queries that do not include either aggregation or GROUP BY.

Data Type

int

Default Value

-1

Remarks

The default value for this property, -1, means that no row limit is enforced unless the query explicitly includes a LIMIT clause. (When a query includes a LIMIT clause, the value specified in the query takes precedence over the MaxRows setting.)

Setting MaxRows to a whole number greater than 0 ensures that queries do not return excessively large result sets by default.

This property is useful for optimizing performance and preventing excessive resource consumption when executing queries that could otherwise return very large datasets.

CData Python Connector for Facebook Ads

Other

Specifies advanced connection properties for specialized scenarios. Use this property only under the guidance of our Support team to address specific issues.

Data Type

string

Default Value

""

Remarks

This property allows advanced users to configure hidden properties for specialized situations, with the advice of our Support team. These settings are not required for normal use cases but can address unique requirements or provide additional functionality. To define multiple properties, use a semicolon-separated list.

Note: It is strongly recommended to set these properties only when advised by the Support team to address specific scenarios or issues.

Caching Configuration

PropertyDescription
CachePartial=TrueCaches only a subset of columns, which you can specify in your query.
QueryPassthrough=TruePasses the specified query to the cache database instead of using the SQL parser of the connector.

Integration and Formatting

PropertyDescription
DefaultColumnSizeSets the default length of string fields when the data source does not provide column length in the metadata. The default value is 2000.
ConvertDateTimeToGMT=TrueConverts date-time values to GMT, instead of the local time of the machine. The default value is False (use local time).
RecordToFile=filenameRecords the underlying socket data transfer to the specified file.

CData Python Connector for Facebook Ads

Pagesize

The maximum number of results to return per page from Facebook Ads.

Data Type

string

Default Value

""

Remarks

The Pagesize property affects the maximum number of results to return per page from Facebook Ads. Sometimes you may get an error asking you to request less data. The frequency of such errors can be reduced by reducing the pagesize. The maximum pagesize tends to be about 100 per page.

CData Python Connector for Facebook Ads

PseudoColumns

Specifies the pseudocolumns to expose as table columns, expressed as a string in the format 'TableName=ColumnName;TableName=ColumnName'.

Data Type

string

Default Value

""

Remarks

This property allows you to define which pseudocolumns the connector exposes as table columns.

To specify individual pseudocolumns, use the following format:

Table1=Column1;Table1=Column2;Table2=Column3

To include all pseudocolumns for all tables use:

*=*

CData Python Connector for Facebook Ads

RetryLevel

The most granular ad object level at which the driver will try to retrieve results on retry.

Possible Values

ACCOUNT, CAMPAIGN, ADSET, AD

Data Type

string

Default Value

"ACCOUNT"

Remarks

This property only applies if no Target is specified for the submitted query. The RetryLevel property limits the levels of ad objects that the driver will attempt to get data for on retry requests for certain errors. The Insights API for ad insights will return specific errors if the response for an ad insights query from the driver would return too many rows, or have to be computed over too many data points. For these errors, the driver will attempt to retry the query targeting the next most granular level of ad object, up to the level of ad object specified by RetryLevel. The driver's ad object precedence is listed below, from least granular to most granular:

  1. Account
  2. Campaign
  3. AdSet
  4. Ad
If the Level parameter is specified in a query, or if using a view that has a pre-defined value for Level, the driver will not attempt to retry beyond the ad object level specified by Level.

CData Python Connector for Facebook Ads

RTK

Specifies the runtime key for licensing the provider. If unset or invalid, the provider defaults to the standard licensing method. This property is only required in environments where the standard licensing method is unsupported or requires a runtime key.

Data Type

string

Default Value

""

Remarks

This property is typically unnecessary, as most configurations support a standard licensing mechanism.

Warning: The value of this property takes precedence over all existing licensing information. To avoid licensing errors, ensure the provided runtime key is correct.

CData Python Connector for Facebook Ads

Target

A default target if none is specified. Used for some tables, such as Comments, where a target may be specified.

Data Type

string

Default Value

""

Remarks

A default target if none is specified. Used for some tables, such as Comments, where a target may be specified.

CData Python Connector for Facebook Ads

TimeIncrement

The time increment used for ad and other ad object insights reporting.

Data Type

string

Default Value

"monthly"

Remarks

This property controls the time increment for insights reporting, which is the increment of time covered by each row in the insights result set. Valid specifications for the property are as follows:

  1. monthly
  2. all_days
  3. Any integer between 1 and 90 inclusive.
Integer values correspond to the number of days for the increment.

CData Python Connector for Facebook Ads

Timeout

Specifies the maximum time, in seconds, that the provider waits for a server response before throwing a timeout error.

Data Type

int

Default Value

60

Remarks

The timeout applies to each individual communication with the server rather than the entire query or operation. For example, a query could continue running beyond 60 seconds if each paging call completes within the timeout limit.

Timeout is set to 60 seconds by default. To disable timeouts, set this property to 0.

Disabling the timeout allows operations to run indefinitely until they succeed or fail due to other conditions such as server-side timeouts, network interruptions, or resource limits on the server.

Note: Use this property cautiously to avoid long-running operations that could degrade performance or result in unresponsive behavior.

CData Python Connector for Facebook Ads

UploadLinkedMedia

Upload linked photos or videos before inserting a new Post.

Data Type

bool

Default Value

false

Remarks

The UploadLinkedMedia determines whether to upload media before inserting a Post. If set to True, when you attempt to insert a new Post with the Link column, the driver will first attempt to resolve the URL and determine if the URL is referencing a photo or a video. If so, the photo or video will be uploaded first, then a new Post containing the media will be created. If False, then the new Post will be created as a Link Post.

CData Python Connector for Facebook Ads

UserDefinedViews

Specifies a filepath to a JSON configuration file that defines custom views. The provider automatically detects and uses the views specified in this file.

Data Type

string

Default Value

""

Remarks

UserDefinedViews allows you to define and manage custom views through a JSON-formatted configuration file called UserDefinedViews.json. These views are automatically recognized by the connector and enable you to execute custom SQL queries as if they were standard database views. The JSON file defines each view as a root element with a child element called "query", which contains the SQL query for the view.

For example:

{
	"MyView": {
		"query": "SELECT * FROM AdAccounts WHERE MyColumn = 'value'"
	},
	"MyView2": {
		"query": "SELECT * FROM MyTable WHERE Id IN (1,2,3)"
	}
}

You can use this property to define multiple views in a single file and specify the filepath. For example:

UserDefinedViews=C:\Path\To\UserDefinedViews.json
When you specify a view in UserDefinedViews, the connector only sees that view.

For further information, see User Defined Views.

CData Python Connector for Facebook Ads

Third Party Copyrights

LZMA from 7Zip LZMA SDK

LZMA SDK is placed in the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

LZMA2 from XZ SDK

Version 1.9 and older are in the public domain.

Xamarin.Forms

Xamarin SDK

The MIT License (MIT)

Copyright (c) .NET Foundation Contributors

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NSIS 3.10

Copyright (C) 1999-2025 Contributors THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS

"Contribution" means:

a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor:

i) changes to the Program, and

ii) additions to the Program;

where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.

"Contributor" means any person or entity that distributes the Program.

"Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.

2. GRANT OF RIGHTS

a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.

b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.

c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.

d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.

3. REQUIREMENTS

A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;

ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and

iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the Program.

Contributors may not remove or alter any copyright notices contained within the Program.

Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.

4. COMMERCIAL DISTRIBUTION

Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL

If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against a Contributor with respect to a patent applicable to software (including a cross-claim or counterclaim in a lawsuit), then any patent licenses granted by that Contributor to such Recipient under this Agreement shall terminate as of the date such litigation is filed. In addition, if Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. IBM is the initial Agreement Steward. IBM may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.

This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

AdoptOpenJDK / Adoptium Temurin JRE 17.0.18_8

Copyright (c) Eclipse Foundation AISBL. All Rights Reserved.

Apache License, Version 2.0

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

  1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
  2. You must cause any modified files to carry prominent notices stating that You changed the files; and
  3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
  4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

Eclipse Distribution License - v 1.0

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Eclipse Public License - v 2.0

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS "Contribution" means:

  • a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and
  • b) in the case of each subsequent Contributor:
    • i) changes to the Program, and
    • ii) additions to the Program;
    where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution "originates" from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works.
"Contributor" means any person or entity that Distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions Distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors.

"Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship.

"Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof.

"Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy.

"Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor.

2. GRANT OF RIGHTS

  • a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works.
  • b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
  • c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
  • d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
  • e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3).

3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then:

  • a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and
  • b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license:
    • i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
    • ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
    • iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and
    • iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3.
3.2 When the Program is Distributed as Source Code:
  • a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and
  • b) a copy of this Agreement must be included with each copy of the Program.
3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability (‘notices') contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices.

4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version.

Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement.

Exhibit A – Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}."

Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses.

If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.

You may add additional accurate notices of copyright ownership.

GNU Classpath

Classpath is distributed under the terms of the GNU General Public License with the following clarification and special exception.

Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination.

As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.

As such, it can be used to run, create and distribute a large class of applications and applets. When GNU Classpath is used unmodified as the core class library for a virtual machine, compiler for the java languge, or for a program written in the java programming language it does not affect the licensing for distributing those programs directly.

OpenJDK Assembly Exception

The OpenJDK source code made available by Oracle America, Inc. (Oracle) at openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2 only ("GPL2"), with the following clarification and special exception.

Linking this OpenJDK Code statically or dynamically with other code is making a combined work based on this library. Thus, the terms and conditions of GPL2 cover the whole combination.

As a special exception, Oracle gives you permission to link this OpenJDK Code with certain code licensed by Oracle as indicated at http://openjdk.java.net/legal/exception-modules-2007-05-08.html ("Designated Exception Modules") to produce an executable, regardless of the license terms of the Designated Exception Modules, and to copy and distribute the resulting executable under GPL2, provided that the Designated Exception Modules continue to be governed by the licenses under which they were offered by Oracle.

As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code to build an executable that includes those portions of necessary code that Oracle could not provide under GPL2 (or that Oracle has provided under GPL2 with the Classpath exception). If you modify or add to the OpenJDK code, that new GPL2 code may still be combined with Designated Exception Modules if the new code is made subject to this exception by its copyright holder.

Copyright (c) 2026 CData Software, Inc. - All rights reserved.
Build 26.0.9655