Metadata-Version: 2.4
Name: raccoontools-db
Version: 1.0.0
Summary: A collection of utilities to be used with databases.
Author-email: Breno RdV <hello@raccoon.ninja>
Maintainer-email: Breno RdV <hello@raccoon.ninja>
License: Copyright (c) 2024 Breno RdV
        
        Permission is hereby granted, free of charge, to any person obtaining
        a copy of this software and associated documentation files (the
        "Software"), to deal in the Software without restriction, including
        without limitation the rights to use, copy, modify, merge, publish,
        distribute, sublicense, and/or sell copies of the Software, and to
        permit persons to whom the Software is furnished to do so, subject to
        the following conditions:
        
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
        MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
        NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
        LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
        OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
        WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Project-URL: Homepage, https://github.com/brenordv/pypi-raccoon-tools
Project-URL: Source, https://github.com/brenordv/pypi-raccoon-tools
Project-URL: Bug Tracker, https://github.com/brenordv/pypi-raccoon-tools/issues
Project-URL: Changelog, https://github.com/brenordv/pypi-raccoon-tools/blob/master/raccoontools-db/CHANGELOG.md
Project-URL: Author, https://raccoon.ninja
Keywords: database,db,utilities,tools,helpers,python
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: psycopg[binary,pool]~=3.3.4
Requires-Dist: simple-log-factory==1.0.0
Provides-Extra: otel
Requires-Dist: simple-log-factory-ext-otel[psycopg]==1.5.0; extra == "otel"
Provides-Extra: fastapi
Requires-Dist: simple-log-factory-ext-otel[fastapi]==1.5.0; extra == "fastapi"
Provides-Extra: all
Requires-Dist: simple-log-factory-ext-otel[fastapi,psycopg]==1.5.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-mock>=3.12; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# Raccoon Tools DB
A managed PostgreSQL connection pool (via `psycopg 3`) with opt-in FastAPI and OpenTelemetry integrations.

[![vet OSS Components](https://github.com/brenordv/pypi-raccoon-tools/actions/workflows/raccoontools-db-vet.yml/badge.svg)](https://github.com/brenordv/pypi-raccoon-tools/actions/workflows/raccoontools-db-vet.yml)

# Installation

**Base install:**
```bash
uv add raccoontools-db
```

**With OpenTelemetry instrumentation:**
```bash
uv add raccoontools-db[otel]
```

**With FastAPI OTEL instrumentation:**
```bash
uv add raccoontools-db[fastapi]
```

**All extras:**
```bash
uv add raccoontools-db[all]
```

# Functionalities

## Connection Pool (`raccoontools_db.pool`)

Provides a module-level singleton connection pool with a simple create/get/close lifecycle.

### `PoolConfig`
Configuration dataclass for the connection pool.

**Fields:**
- `conn_info` *(str)*: PostgreSQL connection string.
- `min_size` *(int)*: Minimum connections in pool (default: 2).
- `max_size` *(int)*: Maximum connections in pool (default: 10).
- `use_otel` *(bool)*: Enable OpenTelemetry tracing (default: False).
- `otel_service_name` *(str)*: Service name for OTEL (required when `use_otel=True`).
- `otel_exporter_endpoint` *(str)*: OTLP exporter endpoint (required when `use_otel=True`).
- `otel_use_http` *(bool)*: Use HTTP protocol for OTLP (default: True).

### `create_pool(config: PoolConfig) -> None`
Creates and opens the global connection pool. Raises `RuntimeError` if a pool already exists.

### `get_pool() -> ConnectionPool`
Returns the active pool. Raises `RuntimeError` if the pool has not been created.

### `close_pool() -> None`
Closes the pool and resets state. Safe to call if already closed or never created.

### Example: Plain usage (no FastAPI, no OTEL)
```python
from raccoontools_db.pool import PoolConfig, create_pool, get_pool, close_pool

config = PoolConfig(conn_info="postgresql://user:pass@localhost:5432/mydb")
create_pool(config)

pool = get_pool()
with pool.connection() as conn:
    with conn.cursor() as cur:
        cur.execute("SELECT 1")
        print(cur.fetchone())

close_pool()
```

### Example: With OpenTelemetry
```python
from raccoontools_db.pool import PoolConfig, create_pool, get_pool, close_pool

config = PoolConfig(
    conn_info="postgresql://user:pass@localhost:5432/mydb",
    use_otel=True,
    otel_service_name="my-service",
    otel_exporter_endpoint="http://localhost:4318",
)
create_pool(config)

pool = get_pool()
# Use pool as normal — logging is handled via OTEL tracing
```

## FastAPI Integration (`raccoontools_db.fastapi`)

### `create_lifespan(config: PoolConfig)`
An async context manager that ties the pool lifecycle to FastAPI's startup/shutdown.

### Example: With FastAPI
```python
from fastapi import FastAPI
from raccoontools_db.fastapi import create_lifespan
from raccoontools_db.pool import PoolConfig, get_pool

config = PoolConfig(conn_info="postgresql://user:pass@localhost:5432/mydb")
app = FastAPI(lifespan=create_lifespan(config))

@app.get("/health")
def health():
    pool = get_pool()
    with pool.connection() as conn:
        conn.execute("SELECT 1")
    return {"status": "ok"}
```

### Example: With FastAPI + OpenTelemetry
```python
from fastapi import FastAPI
from raccoontools_db.fastapi import create_lifespan
from raccoontools_db.pool import PoolConfig, get_pool

config = PoolConfig(
    conn_info="postgresql://user:pass@localhost:5432/mydb",
    use_otel=True,
    otel_service_name="my-service",
    otel_exporter_endpoint="http://localhost:4318",
)
app = FastAPI(lifespan=create_lifespan(config))
```

# Changelog
- [Check the changelog here.](CHANGELOG.md)
