Skip to main content

pg_helper

A simple and robust helper package for PostgreSQL operations. This package provides an easy-to-use interface for connecting to PostgreSQL databases, executing queries, and handling results with various fetching modes.

Features

  • Connection Management: Supports both managed (context manager) and unmanaged connection modes with configurable auto-commit.
  • Flexible Querying: Execute SQL queries with support for parameterized queries.
  • Row Styles: Fetch results as dictionaries or tuples.
  • Advanced Fetching: Multiple fetch modes including column extraction, key-value pairs, grouping, and more.
  • Bulk Operations: Efficiently execute the same query multiple times with different parameters using execute_many.
  • Transaction Control: Manual commit and rollback support.

Installation

Install the package using pip:

pip install pg_helper

Requirements

  • Python >= 3.8
  • psycopg[binary] >= 3.1

Usage

Basic Connection and Querying

from pg_helper import DBHelper, RowStyle

# Using environment variable POSTGRESQL_URL for connection string
with DBHelper() as db:
    result = db.query("SELECT * FROM users WHERE active = %s", (True,))
    for user in result:
        print(user['name'])  # Assuming RowStyle.DICT (default)

# Or pass connection string directly
db = DBHelper("postgresql://user:password@localhost/dbname")
try:
    result = db.query("SELECT id, name FROM products", style=RowStyle.TUPLE)
    products = result.fetch_all()
    print(products)
finally:
    db.close()

Fetching Modes

from pg_helper import DBHelper, FetchMode

with DBHelper() as db:
    result = db.query("SELECT category, name, price FROM products")

    # Get all categories as a list
    categories = result.fetch_all(FetchMode.COLUMN, key_column='category')

    # Get products grouped by category
    products_by_category = result.fetch_all(FetchMode.GROUP, key_column='category')

    # Get price mapping by product name
    price_map = result.fetch_all(FetchMode.KEY_PAIR, key_column='name', value_column='price')

Bulk Insert

from pg_helper import DBHelper

users_data = [
    ('Alice', 'alice@example.com'),
    ('Bob', 'bob@example.com'),
    ('Charlie', 'charlie@example.com')
]

with DBHelper() as db:
    affected_rows = db.execute_many(
        "INSERT INTO users (name, email) VALUES (%s, %s)",
        users_data
    )
    print(f"Inserted {affected_rows} users")

API Reference

DBHelper

The main class for database operations.

  • __init__(conn_str=None, autocommit=False): Initialize with optional connection string and auto-commit mode.
  • query(query, params=None, style=RowStyle.DICT): Execute a query and return a QueryResult object.
  • execute_many(query, param_list): Execute a query multiple times with different parameters.
  • commit(): Manually commit the current transaction.
  • rollback(): Manually roll back the current transaction.
  • close(): Close the database connection.

QueryResult

An iterable container for query results.

  • fetch(style=None): Fetch the next row.
  • fetch_all(mode=None, key_column=0, value_column=1): Fetch all remaining rows with optional mode.
  • row_count: Property returning the number of affected rows.

Enums

  • RowStyle: DICT, TUPLE
  • FetchMode: COLUMN, KEY_PAIR, KEY_PAIR_LIST, GROUP, GROUP_COLUMN

Metadata

Release files for pg-helper 1.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 pg-helper 1.0.0
File Size Uploaded Provenance
pg_helper-1.0.0.tar.gz 4.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for pg-helper 1.0.0
File Interpreter ABI Platform
pg_helper-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 10.2 kB

Release files / pg_helper-1.0.0.tar.gz

Download URL pg_helper-1.0.0.tar.gz
Size 4.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b7a406f5da9ebdb5cf4da2530af300729578277ee481dce4ec66820704373a47
BLAKE2b-256 checksum
How to use checksums
f460b7693cf464b9b810d4a89f492c2e66a29ca6ef828176c8b341c06fbcb694
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.8

Release files / pg_helper-1.0.0-py3-none-any.whl

Download URL pg_helper-1.0.0-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c624cbef1a811fea6e3677483ff50636f91d143bc81faf5c90f4b03d669a30e
BLAKE2b-256 checksum
How to use checksums
6a2d9674c014496f87adbcdc7ee1eaccade21c4d621a05559db27b1ba6404052
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.8

Security for pg-helper 1.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.

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No 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