Skip to main content

A Python package that seamlessly integrates PostgreSQL, Jinja templating, and Pydantic for type-safe database queries

Project description

pgjinja

A Python library that combines PostgreSQL with Jinja2 templates to create dynamic SQL queries with a clean, async interface.

Description

pgjinja simplifies database interactions by allowing you to:

  • Keep SQL queries in separate template files
  • Use Jinja2 templating for dynamic query generation
  • Execute queries asynchronously
  • Automatically map query results to Pydantic models

This approach helps separate SQL logic from application code, making your database interactions more maintainable and testable.

Installation

pip install pgjinja

Usage Example

Here's a simple example of how to use pgjinja to query merchants from a database:

# src/my_db.py
from functools import cache

from src.models.merchant import Merchant

from pgjinja import PgJinja


# Create a PostgreSQL connection
@cache
def get_postgres():
    return PgJinja(
        user="user",
        password="password",
        host="dev.postgres",
        template_dir="template",
        dbname="dbname",
    )


# Query using a template with parameters
async def select_merchant(limit: int = 3) -> list[Merchant]:
    params = dict(limit=limit)
    template = "select_merchant.sql.jinja"
    return await get_postgres().query(template, params, Merchant)

# Add other database operations here
# ...
# main.py
import asyncio

import src.my_db as db


# Example usage
async def main():
    merchants = await db.select_merchant(limit=5)  # clean and very readable
    # Even with a more complex query, the interface is still the same

    print(merchants)


if __name__ == "__main__":
    asyncio.run(main())

SQL Template Example

Create a file template/select_merchant.sql.jinja:

SELECT id, name
FROM merchants
WHERE active = true
ORDER BY name
LIMIT {{ limit }}

Configuration

The PgJinja class accepts the following configuration parameters:

Parameter Description Default
user PostgreSQL user (Required)
password PostgreSQL password (Required)
host Database host localhost
port Database port 5432
dbname Database name public
template_dir Directory containing SQL templates Current directory
template_extension File extension to append to template names Empty string

Asynchronous Execution and Connection Pooling

pgjinja leverages modern Python's async capabilities and PostgreSQL connection pooling for optimal performance:

  • Async/await pattern: All database operations use the async/await pattern for non-blocking execution
  • Connection pooling: Built-in connection pooling via psycopg_pool reduces connection overhead
  • Resource management: Connections are automatically returned to the pool after query execution
  • Concurrent queries: Multiple queries can be executed concurrently without blocking the main thread

This approach is particularly beneficial for web applications and API services where database operations should not block the event loop while waiting for results.

Dependencies

  • asyncio - For asynchronous operations
  • pydantic - For data validation and model mapping
  • jinjasql2 - For SQL templating with Jinja2
  • psycopg - PostgreSQL database adapter for Python
  • psycopg_pool - Connection pooling for psycopg

Development and Testing

Setting Up Development Environment

  1. Clone the repository:

    git clone https://github.com/tungph/pgjinja.git
    cd pgjinja
    
  2. Create and activate a virtual environment:

    uv venv
    . .venv/bin/activate
    
  3. Install development dependencies:

    uv pip install pytest pytest-asyncio pytest-cov
    pip install -e .
    

Running Tests

To run the test suite:

make test

This will:

  • Set up a virtual environment
  • Install necessary test dependencies
  • Run the tests with code coverage reporting

License

MIT License

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

pgjinja-1.0.0.tar.gz (15.9 kB view details)

Uploaded Source

Built Distribution

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

pgjinja-1.0.0-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pgjinja-1.0.0.tar.gz
  • Upload date:
  • Size: 15.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for pgjinja-1.0.0.tar.gz
Algorithm Hash digest
SHA256 30394b412b6f5f7ce04cbda50d8b88a08e78ad67158a0952a9786113778044f2
MD5 c81b1875d6813ea64135ad90fda5e2f0
BLAKE2b-256 71619c8b48bb99fc9e4f517013bbfc23e55f7e5e7c36d317520f897d7c7ca5d4

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pgjinja-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.11

File hashes

Hashes for pgjinja-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d3e20648bd61fa5c9e054442f0681d05a674908a7f077fd1230fc5d632b3120b
MD5 0128efcd069f65415c2bc9be3f5749a4
BLAKE2b-256 efb1dd78e61789b3ce7d0f45c288f11118c6fda92ae143145c56b55d2f79a6ab

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