Skip to main content
Yanked

This release has been yanked by its maintainers, and will be ignored by installers, except when explicitly specified.
Consider using release 2.0.0b2 instead.
Reason given by maintainers: Published prematurely, pending design review. Use 2.0.0b1 or later betas.

Salesforce Data Cloud Python Connector

codecov

The official Salesforce Data Cloud Python connector — a DB-API 2.0 compliant driver for querying Salesforce Data Cloud using the Query API. Designed for use from Jupyter notebooks, pandas pipelines, ETL scripts, and any other Python data tooling.

This package (salesforce-datacloud-connector) supersedes the salesforce-cdp-connector package. New projects should adopt this package; existing salesforce-cdp-connector users should plan to migrate.

Current version: 2.0.0b2 (beta 2, off-core Query v3 migration)

Python Version License

Important: this is a beta release

salesforce-datacloud-connector is currently published as version 2.0.0b2 (beta 2) on PyPI. This release replatforms query execution onto the off-core Query v3 REST API. The public DB-API 2.0 surface is stable, but the package is still in beta to allow for adjustments based on field feedback.

  • Install with the --pre flag — pip will not pick up pre-releases otherwise:

    pip install --pre salesforce-datacloud-connector
    
  • Pin your version explicitly in production code and your dependency manifests:

    salesforce-datacloud-connector==2.0.0b2
    

    This protects you from accidental upgrades to a later beta or release candidate that may include breaking changes.

Features

  • DB-API 2.0 compliant — standard Python database interface.
  • Five auth flows — JWT Bearer Token, Refresh Token, Client Credentials, Username/Password, and Salesforce CLI (local/dev).
  • Pandas integration — works with pandas.read_sql() and cursor.fetch_df() (under the [pandas] extra).
  • Notebook-ready — interactive exploration and visualization in Jupyter.
  • Parameterized queries — safe SQL execution with named parameters (:param).
  • Efficient pagination — chunked, low-memory fetching for large result sets.
  • Type conversion — Data Cloud types map to native Python types (str, int, Decimal, float, bool, datetime.date, datetime.datetime).
  • Comprehensive error hierarchy — full DB-API 2.0 exception tree.

Installation

# Basic installation (always include --pre during the beta)
pip install --pre salesforce-datacloud-connector

# With pandas + pyarrow support (recommended for analytics use)
pip install --pre "salesforce-datacloud-connector[pandas]"

Requirements

  • Python 3.8 or newer.
  • requests >= 2.31.0
  • cryptography >= 41.0.0
  • pyjwt >= 2.8.0
  • python-dateutil >= 2.8.0

Optional (under [pandas] extra):

  • pandas >= 2.0.0
  • pyarrow >= 14.0.0

Quickstart

The connector uses OAuth for authentication. JWT bearer token is the recommended flow for production and demo environments:

import salesforce_datacloud_connector as sfdc

# Read private key from file (PEM format)
with open("private_key.pem", "r") as f:
    private_key = f.read()

conn = sfdc.connect(
    login_url="https://login.salesforce.com",
    auth_type="jwt",
    username="your_user@example.com",
    client_id="YOUR_CONNECTED_APP_CLIENT_ID",
    jwt_private_key=private_key,
)

cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM Account")
(count,) = cursor.fetchone()
print(f"Total accounts: {count}")

cursor.close()
conn.close()

The connector also supports context managers — both the connection and the cursor close cleanly when their with blocks exit:

import salesforce_datacloud_connector as sfdc

with sfdc.connect(...) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT COUNT(*) FROM Account")
        (count,) = cursor.fetchone()
        print(f"Total accounts: {count}")

Authentication

The connector ships five auth flows, all driven through sfdc.connect(...) via the auth_type keyword.

JWT bearer token is the recommended flow for production services and demos. It requires a connected app configured with a certificate and the api, cdpquery, and refresh_token offline_access scopes.

import salesforce_datacloud_connector as sfdc

with open("private_key.pem", "r") as f:
    private_key = f.read()

conn = sfdc.connect(
    login_url="https://login.salesforce.com",
    auth_type="jwt",
    username="user@example.com",
    client_id="your_connected_app_client_id",
    jwt_private_key=private_key,
)

Setup:

  1. Create a connected app in Salesforce Setup → App Manager
  2. Enable OAuth Settings, configure callback URL, add api, cdpquery, refresh_token offline_access scopes
  3. Enable "Use digital signatures" and upload a certificate (self-signed is fine for dev)
  4. Extract the private key to a PEM file: openssl pkcs12 -in cert.p12 -nocerts -nodes -out private_key.pem
import os

import salesforce_datacloud_connector as sfdc

conn = sfdc.connect(
    login_url=os.environ["SFDC_LOGIN_URL"],
    auth_type="refresh_token",
    client_id=os.environ["SFDC_CLIENT_ID"],
    client_secret=os.environ["SFDC_CLIENT_SECRET"],
    refresh_token=os.environ["SFDC_REFRESH_TOKEN"],
)

Client Credentials

Client Credentials is a server-to-server flow with no user context — the connected app itself is the principal. It requires only a client ID and secret, and the connected app must be configured to allow the client credentials flow.

import os

import salesforce_datacloud_connector as sfdc

conn = sfdc.connect(
    login_url="https://login.salesforce.com",
    auth_type="client_credentials",
    client_id=os.environ["SFDC_CLIENT_ID"],
    client_secret=os.environ["SFDC_CLIENT_SECRET"],
)

The sf_cli flow reuses whatever org the Salesforce CLI is already authenticated against — no connected app, client secret, or JWT key required. It's the fastest way to point the connector at an org during local development:

sf org login web --alias my-org --scopes "api cdpquery refresh_token offline_access"

The --scopes flag matters: without it, the CLI's session may not carry the cdpquery scope, and the Data Cloud token exchange fails with invalid_scope. If it does, re-run sf org login web with --scopes as shown above (add --instance-url for sandboxes or non-default pods).

import salesforce_datacloud_connector as sfdc

conn = sfdc.connect(
    auth_type="sf_cli",
    target_org="my-org",  # alias or username; omit to use the CLI's default org
)

Each call to sfdc.connect(...) shells out to sf org display and sf org auth show-access-token to fetch a fresh token — the CLI handles its own token refresh, so there's nothing to configure or rotate. Requires the sf executable to be on PATH.

Pre-minted Data Cloud token

If another service already minted a Data Cloud (CDP) access token, pass it directly together with the tenant endpoint. OAuth login and the token exchange are skipped (mirrors the JDBC driver's cdpToken / tenantUrl properties):

conn = sfdc.connect(
    auth_type="cdp_token",
    cdp_token=cdp_jwt,
    tenant_endpoint="tenant.c360a.salesforce.com",
    dataspace="default",
)

The token must be a JWT with an exp claim; connect() raises immediately if it is malformed or already expired. It cannot be refreshed: once it expires, queries fail with an error and you must create a new connection with a fresh token.

Username/Password (deprecated)

Username/password authentication is deprecated and will be removed in a future release. Use JWT bearer token or refresh token flows instead.

import salesforce_datacloud_connector as sfdc

conn = sfdc.connect(
    login_url="https://login.salesforce.com",
    auth_type="username_password",
    username="user@example.com",
    password="your_password",
    client_id="your_connected_app_client_id",
    client_secret="your_connected_app_client_secret",
)

Credential hygiene

Never hardcode credentials in source. Load them from environment variables (local development) or your platform's secret manager (production). Rotate credentials regularly and avoid using production credentials for development.

Usage

Parameterized queries

cursor.execute(
    """
    SELECT Id, Name, Email
    FROM Contact
    WHERE Status = :status AND CreatedDate > :min_date
    LIMIT :limit
    """,
    {
        "status": "Active",
        "min_date": "2024-01-01",
        "limit": 100,
    },
)

Pandas integration

import pandas as pd
import salesforce_datacloud_connector as sfdc

conn = sfdc.connect(...)

# Method 1 — pandas.read_sql
df = pd.read_sql("SELECT * FROM Account LIMIT 1000", conn)

# Method 2 — cursor.fetch_df
cursor = conn.cursor()
cursor.execute("SELECT Id, Name, Industry FROM Account")
df = cursor.fetch_df()

print(df.describe())
print(df.groupby("Industry").size())

cursor.fetch_df() lazily imports pandas. Calling it without the [pandas] extra installed raises ImportError with installation guidance.

Fetch methods

row = cursor.fetchone()       # one row
rows = cursor.fetchmany(100)  # multiple rows
all_rows = cursor.fetchall()  # all remaining rows

for row in cursor:            # iteration
    process(row)

Configuration: dataspace and workload

conn = sfdc.connect(
    ...,
    dataspace="custom_dataspace",  # optional; defaults to the org default
    workload="my_application",     # optional; surfaced in observability
)

Query settings

Connection-wide defaults, applied to every query on the connection:

conn = sfdc.connect(
    ...,
    query_settings={"time_zone": "UTC"},
)

Per-call settings, merged over the connection-level defaults (per-call wins on key collision):

cursor.execute("SELECT ...", settings={"time_zone": "America/Los_Angeles"})

See the Hyper connection settings reference for available keys. Values must be strings.

Cursor array size

cursor = conn.cursor()
cursor.arraysize = 1000  # default fetch size for fetchmany()

Type mapping

Data Cloud type Python type Notes
Varchar str
Numeric int, Decimal int when scale is 0; Decimal otherwise
Integer, BigInt int
Float, Double float
Boolean bool
Date datetime.date
TimestampTZ datetime.datetime timezone-aware

API reference

DB-API 2.0 surface

This connector follows PEP 249 — Python Database API Specification v2.0.

  • API level: 2.0
  • Thread safety: 1 (threads may share the module, but not connections)
  • Parameter style: named (:param)

Connection

  • cursor() — create a new cursor.
  • close() — close the connection.
  • commit() — no-op (read-only driver).
  • rollback() — no-op (read-only driver).

Cursor

  • execute(operation, parameters=None) — execute a query.
  • executemany(operation, seq_of_parameters) — execute the same query multiple times.
  • fetchone() — fetch the next row.
  • fetchmany(size=cursor.arraysize) — fetch up to size rows.
  • fetchall() — fetch all remaining rows.
  • close() — close the cursor.
  • cancel() — cancel a running query (extension).
  • fetch_df() — fetch results as a pandas DataFrame (extension; requires the [pandas] extra).

Cursor attributes

  • description — column metadata.
  • rowcount — total rows in the result set, reported by the server after execute() (-1 before any query is executed).
  • arraysize — default fetch size for fetchmany().

Exception hierarchy

Exception
└── Warning
└── Error
    ├── InterfaceError
    └── DatabaseError
        ├── DataError
        ├── OperationalError      (auth failures, network errors)
        ├── IntegrityError
        ├── InternalError         (server errors)
        ├── ProgrammingError      (SQL syntax errors)
        └── NotSupportedError     (unsupported operations)
import salesforce_datacloud_connector as sfdc

try:
    cursor.execute("SELECT * FROM NonexistentTable")
except sfdc.ProgrammingError as e:
    print(f"SQL error: {e}")

try:
    cursor.execute("INSERT INTO Account VALUES (...)")
except sfdc.NotSupportedError as e:
    print(f"Operation not supported: {e}")

fetch_df() extension

cursor.fetch_df() returns a pandas.DataFrame containing all remaining rows of the most recent query. It is available only when the [pandas] extra is installed:

pip install --pre "salesforce-datacloud-connector[pandas]"
cursor.execute("SELECT Id, Name, Industry FROM Account LIMIT 5000")
df = cursor.fetch_df()

If pandas is missing, fetch_df() raises an ImportError with the install command above.

Beta-period limitations

2.0.0b2 is intentionally scoped:

  1. Read-only — no INSERT, UPDATE, DELETE, or DDL operations.
  2. No streaming — results buffer in memory (chunked pagination keeps memory bounded but does not stream row-by-row).
  3. Synchronous API only — async client is on the V2 roadmap.
  4. No connection pooling — create new connections as needed.
  5. No prepared statements — parameters bind on each execution.
  6. No SQLAlchemy dialect — direct DB-API usage only.
  7. In-memory token cache — tokens are not persisted across runs.

These constraints will be reconsidered as the package moves from beta to GA.

Development

The repository uses uv for dependency management and hatchling as the build backend.

Setup

# From the repo root
cd salesforce_datacloud_connector

# Install everything (runtime + pandas extra + dev dependency group)
uv sync --all-extras --dev

Run tests

# Unit + integration tests (skips live-org E2E)
uv run pytest -m "not e2e"

# Include the live-org E2E suite (requires real Salesforce credentials —
# see tests/test_e2e_real_datacloud.py for the env vars it expects)
uv run pytest

Lint

uv run ruff check salesforce_datacloud_connector tests --statistics

Build

uv build
# produces dist/salesforce_datacloud_connector-<version>-py3-none-any.whl
# and  dist/salesforce_datacloud_connector-<version>.tar.gz

Repo layout

The repository publishes two PyPI packages from one branch — see the repo-root README for the full layout. This package's source lives under salesforce_datacloud_connector/salesforce_datacloud_connector/, its tests under salesforce_datacloud_connector/tests/, and its build config under salesforce_datacloud_connector/pyproject.toml.

Contributing

Contributions are welcome. Please open an issue before starting on a large change. PRs should include tests for new functionality and pass ruff check and pytest -m "not e2e" locally.

See CONTRIBUTING.md at the repo root for the full contribution guide.

License

BSD-3-Clause. See LICENSE.txt at the repo root.

Metadata

Release files for salesforce-datacloud-connector 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for salesforce-datacloud-connector 2.0.0
File Size Uploaded Provenance Actions
salesforce_datacloud_connector-2.0.0.tar.gz 239.8 kB With provenance Details for salesforce_datacloud_connector-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for salesforce-datacloud-connector 2.0.0
File Interpreter ABI Platform Actions
salesforce_datacloud_connector-2.0.0-py3-none-any.whl Python 3 none any Details for salesforce_datacloud_connector-2.0.0-py3-none-any.whl

Total release size: 291.3 kB

Release files / salesforce_datacloud_connector-2.0.0.tar.gz

Download URL salesforce_datacloud_connector-2.0.0.tar.gz
Size 239.8 kB
Tags Source
SHA-256 checksum
How to use checksums
be4190be0ab59b42a9253585e7f8a66392e2e1bebbe5b02852e065e8bacb7c92
BLAKE2b-256 checksum
How to use checksums
c99feed0bf5df866994c39fe71a44a8dae3de3ef27543d913473daf521bb2fd1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Release files / salesforce_datacloud_connector-2.0.0-py3-none-any.whl

Download URL salesforce_datacloud_connector-2.0.0-py3-none-any.whl
Size 51.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e5e094ced943cab1bc359fe1138609d42a7c8fb568e1422d1fd07d390dce70db
BLAKE2b-256 checksum
How to use checksums
ff5648c550eae51c8347457d0d88f2d1451075e71fd1bec60216897da26f07a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Security for salesforce-datacloud-connector 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for salesforce_datacloud_connector-2.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page