Skip to main content

datus-postgresql

PostgreSQL database adapter for Datus.

Timeouts

timeout_seconds must be positive and now bounds driver I/O as well as pool checkout where applicable. Long operations may need a larger value. Server execution deadlines and supported overrides are described in the shared timeout policy and real-database validation. A socket/RPC timeout is distinct from an overall operation deadline.

Amazon Aurora PostgreSQL

Aurora uses this adapter with the PostgreSQL dialect. Set aurora=True and provide sslrootcert; the adapter requires sslmode=verify-full. Password authentication needs no AWS SDK. Install pip install 'datus-postgresql[aws]' for IAM or Secrets Manager.

import os
from datus_postgresql import PostgreSQLConnector

connector = PostgreSQLConnector({
    "host": os.environ["AURORA_POSTGRESQL_ENDPOINT"],
    "username": os.environ["AURORA_DB_USER"],
    "database": os.environ["AURORA_DATABASE"],
    "aurora": True,
    "auth_mode": "iam",
    "aws": {"region": os.environ["AWS_REGION"]},
    "sslrootcert": os.environ["AURORA_CA_BUNDLE"],
})
try:
    result = connector.execute_query("SELECT 1", result_format="list")
    assert result.success, result.error
finally:
    connector.close()

TLS and dynamic credentials apply to the base engine and every cached database engine. See Aurora authentication and lifecycle for the full contract, IAM permissions/user setup, Role profiles, Secret rotation and pending cloud acceptance. From the workspace root, uv run --no-project python -m ci.run_tls_integration_tests postgresql runs verified TLS, multiple databases, shared contracts and wrong-CA/hostname rejection.

Overview

This adapter provides PostgreSQL connectivity for Datus, supporting full SQL operations, metadata discovery, schema management, and materialized views via the standard PostgreSQL protocol.

Installation

pip install datus-postgresql

This will automatically install the required dependencies:

  • datus-agent
  • datus-sqlalchemy (which includes SQLAlchemy and psycopg2)

Usage

The adapter is automatically registered with Datus when installed. Configure your database connection:

namespace:
  postgresql_prod:
    type: postgresql
    host: localhost
    port: 5432
    username: postgres
    password: your_password
    database: mydb
    schema: public

Or use programmatically:

from datus_postgresql import PostgreSQLConnector, PostgreSQLConfig

# Using config object
config = PostgreSQLConfig(
    host="localhost",
    port=5432,
    username="postgres",
    password="password",
    database="mydb",
    schema_name="public",
)

connector = PostgreSQLConnector(config)

# Or using dict
connector = PostgreSQLConnector({
    "host": "localhost",
    "port": 5432,
    "username": "postgres",
    "password": "password",
    "database": "mydb",
})

# Use context manager for automatic cleanup
with connector:
    # Test connection
    connector.test_connection()

    # Execute queries
    result = connector.execute({"sql_query": "SELECT * FROM users LIMIT 10"})
    print(result.sql_return)

    # Get tables
    tables = connector.get_tables(schema_name="public")
    print(f"Tables: {tables}")

    # Get table schema
    columns = connector.get_schema(schema_name="public", table_name="users")
    for col in columns:
        print(f"  {col['name']}: {col['type']}")

    # Get materialized views
    mvs = connector.get_materialized_views(schema_name="public")
    print(f"Materialized Views: {mvs}")

Configuration Options

Option Type Default Description
host str "127.0.0.1" PostgreSQL server host
port int 5432 PostgreSQL server port
username str required PostgreSQL username
password str "" PostgreSQL password
database str None Default database name
schema_name str "public" Default schema name
sslmode str "prefer" SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
timeout_seconds int 30 Connection timeout in seconds

Features

  • Full SQL Support: Execute queries, DDL, DML operations
  • Metadata Discovery: Automatic discovery of databases, schemas, tables, views, and materialized views
  • DDL Generation: Reconstruct CREATE TABLE / VIEW / MATERIALIZED VIEW statements
  • Schema Management: Switch between schemas seamlessly
  • Sample Data: Extract sample rows for data profiling
  • Connection Management: SQLAlchemy-based connection pooling with SSL support
  • Multiple Result Formats: pandas, arrow, csv, list

Code Structure

datus-postgresql/
├── datus_postgresql/
│   ├── __init__.py          # Package exports
│   ├── config.py            # PostgreSQLConfig (Pydantic model)
│   └── connector.py         # PostgreSQLConnector implementation
├── tests/
│   ├── unit/                # Unit tests with mocks (no database needed)
│   └── integration/         # Integration tests (requires PostgreSQL)
│       ├── conftest.py      # Test fixtures and TPC-H data setup
│       ├── test_integration.py  # General integration tests
│       └── test_tpch.py     # TPC-H benchmark data tests
├── scripts/
│   └── init_tpch_data.py    # TPC-H data initialization script
├── docker-compose.yml       # PostgreSQL test container
├── pyproject.toml
└── README.md

Testing

Quick Start

# 1. Start PostgreSQL test container
docker-compose up -d

# 2. Run tests
pytest tests/unit/ -v              # Unit tests (no database needed)
pytest tests/integration/ -v       # Integration tests (requires PostgreSQL)
pytest tests/ -v                   # All tests

Test Types

  • Unit tests: Configuration and connector logic with mocks (no database needed)
  • Integration tests: Real database operations (SQL, metadata, schema)
  • TPC-H tests: Analytical query tests using TPC-H benchmark data

TPC-H Integration Tests

The adapter includes TPC-H benchmark data tests for validating analytical query capabilities.

TPC-H Tables

Table Rows Description
tpch_region 5 World regions
tpch_nation 25 Countries with region references
tpch_supplier 5 Suppliers with nation references
tpch_customer 10 Customers with nation references
tpch_orders 15 Orders with customer references

Running TPC-H Tests

# Start PostgreSQL container
docker-compose up -d

# Run TPC-H integration tests
pytest tests/integration/test_tpch.py -v

# Initialize TPC-H data manually (for ad-hoc testing)
python scripts/init_tpch_data.py \
    --host localhost --port 5432 \
    --username test_user --password test_password \
    --database test --schema public

# Drop and recreate TPC-H tables
python scripts/init_tpch_data.py --drop

Environment Variables

Tests use these default values (matching docker-compose.yml):

Variable Default Description
POSTGRESQL_HOST localhost PostgreSQL server host
POSTGRESQL_PORT 5432 PostgreSQL server port
POSTGRESQL_USER test_user PostgreSQL username
POSTGRESQL_PASSWORD test_password PostgreSQL password
POSTGRESQL_DATABASE test Database name
POSTGRESQL_SCHEMA public Schema name

Requirements

  • Python >= 3.12
  • PostgreSQL >= 12
  • datus-agent >= 0.2.1
  • datus-sqlalchemy >= 0.1.0

License

Apache License 2.0

  • datus-sqlalchemy - SQLAlchemy base connector
  • datus-mysql - MySQL adapter
  • datus-redshift - Amazon Redshift adapter
  • datus-snowflake - Snowflake adapter

Metadata

Release files for datus-postgresql 0.1.11

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

Source distribution (sdist)

Source distribution for datus-postgresql 0.1.11
File Size Uploaded Provenance Actions
datus_postgresql-0.1.11.tar.gz 39.6 kB Without provenance Details for datus_postgresql-0.1.11.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for datus-postgresql 0.1.11
File Interpreter ABI Platform Actions
datus_postgresql-0.1.11-py3-none-any.whl Python 3 none any Details for datus_postgresql-0.1.11-py3-none-any.whl

Total release size: 59.6 kB

Release files / datus_postgresql-0.1.11.tar.gz

Download URL datus_postgresql-0.1.11.tar.gz
Size 39.6 kB
Tags Source
SHA-256 checksum
How to use checksums
91117a27ed954e45180ab176afd0ed5011510a5155f7b0908bb2be0509d7dfa5
BLAKE2b-256 checksum
How to use checksums
0ce886bfdc55369f1414ec926dd8b8c87c87cc891feb2e937fcb81f357a8185f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Release files / datus_postgresql-0.1.11-py3-none-any.whl

Download URL datus_postgresql-0.1.11-py3-none-any.whl
Size 20.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
40356a1444841a4031a70e2b1e39f271e91d7ab5ddf1935a964a671d2e651444
BLAKE2b-256 checksum
How to use checksums
84325d4df41f88d2b78d4e812e9f590de255dee87326dfb9de7bb4b6ed7a9299
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for datus-postgresql 0.1.11

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

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