Amazon Redshift Dialect for SQLAlchemy

0.8.14 · active · verified Thu Apr 09

sqlalchemy-redshift is an active project that provides an Amazon Redshift dialect for SQLAlchemy. It extends SQLAlchemy to support Redshift-specific syntax and operations, allowing Python applications to interact seamlessly with Amazon Redshift data warehouses. The library maintains a regular release schedule, with version 0.8.14 being the latest as of April 2023, indicating frequent patch and minor updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an Amazon Redshift database using `sqlalchemy-redshift` and perform a simple query. It uses environment variables for credentials and connects via the `psycopg2` driver. Remember to install an underlying DBAPI driver like `psycopg2-binary` or `redshift_connector` alongside `sqlalchemy-redshift`.

import sqlalchemy as sa
import os

# Ensure either 'redshift_connector' or 'psycopg2' is installed
# e.g., pip install sqlalchemy-redshift psycopg2-binary

# Redshift connection details from environment variables
REDSHIFT_USER = os.environ.get("REDSHIFT_USER", "your_username")
REDSHIFT_PASSWORD = os.environ.get("REDSHIFT_PASSWORD", "your_password")
REDSHIFT_HOST = os.environ.get("REDSHIFT_HOST", "your_redshift_host.amazonaws.com")
REDSHIFT_PORT = os.environ.get("REDSHIFT_PORT", "5439")
REDSHIFT_DB = os.environ.get("REDSHIFT_DB", "your_database_name")

# Construct connection string using psycopg2 driver (can be 'redshift_connector')
connection_string = (
    f"redshift+psycopg2://{REDSHIFT_USER}:{REDSHIFT_PASSWORD}@"
    f"{REDSHIFT_HOST}:{REDSHIFT_PORT}/{REDSHIFT_DB}"
)

try:
    engine = sa.create_engine(connection_string)
    with engine.connect() as connection:
        # Perform a simple query to verify connection
        result = connection.execute(sa.text("SELECT 1 as id, 'hello' as message")).fetchone()
        if result:
            print(f"Connection successful! Result: ID={result.id}, Message='{result.message}'")
        else:
            print("Connection successful, but no result returned for test query.")
except Exception as e:
    print(f"Error connecting to Redshift: {e}")

view raw JSON →