Skip to main content

A simple and robust helper package for PostgreSQL operations.

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pg_helper-1.0.0.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pg_helper-1.0.0-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file pg_helper-1.0.0.tar.gz.

File metadata

  • Download URL: pg_helper-1.0.0.tar.gz
  • Upload date:
  • Size: 4.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.8

File hashes

Hashes for pg_helper-1.0.0.tar.gz
Algorithm Hash digest
SHA256 b7a406f5da9ebdb5cf4da2530af300729578277ee481dce4ec66820704373a47
MD5 aacaf60cccb2e1cb1373b0c90e365750
BLAKE2b-256 f460b7693cf464b9b810d4a89f492c2e66a29ca6ef828176c8b341c06fbcb694

See more details on using hashes here.

File details

Details for the file pg_helper-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: pg_helper-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.8

File hashes

Hashes for pg_helper-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0c624cbef1a811fea6e3677483ff50636f91d143bc81faf5c90f4b03d669a30e
MD5 8f180557e2be80743da90902d92b3962
BLAKE2b-256 6a2d9674c014496f87adbcdc7ee1eaccade21c4d621a05559db27b1ba6404052

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page