Metadata-Version: 2.5
Name: pg-partsmith
Version: 0.5.0
Summary: PostgreSQL partition lifecycle management with extensible hooks
Project-URL: Repository, https://github.com/bedrock-python/pg-partsmith
Project-URL: Documentation, https://bedrock-python.github.io/pg-partsmith/
Project-URL: Changelog, https://github.com/bedrock-python/pg-partsmith/blob/master/CHANGELOG.md
Project-URL: Bug Tracker, https://github.com/bedrock-python/pg-partsmith/issues
Author-email: Alex Shalaev <shalaevad.alexey@gmail.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction,
        and distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity authorized by
        the copyright owner that is granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all
        other entities that control, are controlled by, or are under common
        control with that entity. For the purposes of this definition,
        "control" means (i) the power, direct or indirect, to cause the
        direction or management of such entity, whether by contract or
        otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity
        exercising permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications,
        including but not limited to software source code, documentation
        source, and configuration files.
        
        "Object" form shall mean any form resulting from mechanical
        transformation or translation of a Source form, including but
        not limited to compiled object code, generated documentation,
        and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or
        Object form, made available under the License, as indicated by a
        copyright notice that is included in or attached to the work
        (an example is provided in the Appendix below).
        
        "Derivative Works" shall mean any work, whether in Source or Object
        form, that is based on (or derived from) the Work and for which the
        editorial revisions, annotations, elaborations, or other modifications
        represent, as a whole, an original work of authorship. For the purposes
        of this License, Derivative Works shall not include works that remain
        separable from, or merely link (or bind by name) to the interfaces of,
        the Work and Derivative Works thereof.
        
        "Contribution" shall mean any work of authorship, including
        the original version of the Work and any modifications or additions
        to that Work or Derivative Works thereof, that is intentionally
        submitted to Licensor for inclusion in the Work by the copyright owner
        or by an individual or Legal Entity authorized to submit on behalf of
        the copyright owner. For the purposes of this definition, "submitted"
        means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems,
        and issue tracking systems that are managed by, or on behalf of, the
        Licensor for the purpose of discussing and improving the Work, but
        excluding communication that is conspicuously marked or otherwise
        designated in writing by the copyright owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity
        on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        copyright license to reproduce, prepare Derivative Works of,
        publicly display, publicly perform, sublicense, and distribute the
        Work and such Derivative Works in Source or Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        (except as stated in this section) patent license to make, have made,
        use, offer to sell, sell, import, and otherwise transfer the Work,
        where such license applies only to those patent claims licensable
        by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s)
        with the Work to which such Contribution(s) was submitted. If You
        institute patent litigation against any entity (including a
        cross-claim or counterclaim in a lawsuit) alleging that the Work
        or a Contribution incorporated within the Work constitutes direct
        or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate
        as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
        Work or Derivative Works thereof in any medium, with or without
        modifications, and in Source or Object form, provided that You
        meet the following conditions:
        
        (a) You must give any other recipients of the Work or
        Derivative Works a copy of this License; and
        
        (b) You must cause any modified files to carry prominent notices
        stating that You changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works
        that You distribute, all copyright, patent, trademark, and
        attribution notices from the Source form of the Work,
        excluding those notices that do not pertain to any part of
        the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its
        distribution, then any Derivative Works that You distribute must
        include a readable copy of the attribution notices contained
        within such NOTICE file, excluding those notices that do not
        pertain to any part of the Derivative Works, in at least one
        of the following places: within a NOTICE text file distributed
        as part of the Derivative Works; within the Source form or
        documentation, if provided along with the Derivative Works; or,
        within a display generated by the Derivative Works, if and
        wherever such third-party notices normally appear. The contents
        of the NOTICE file are for informational purposes only and
        do not modify the License. You may add Your own attribution
        notices within Derivative Works that You distribute, alongside
        or as an addendum to the NOTICE text from the Work, provided
        that such additional attribution notices cannot be construed
        as modifying the License.
        
        You may add Your own copyright statement to Your modifications and
        may provide additional or different license terms and conditions
        for use, reproduction, or distribution of Your modifications, or
        for any such Derivative Works as a whole, provided Your use,
        reproduction, and distribution of the Work otherwise complies with
        the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
        any Contribution intentionally submitted for inclusion in the Work
        by You to the Licensor shall be under the terms and conditions of
        this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify
        the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
        names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the
        origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
        agreed to in writing, Licensor provides the Work (and each
        Contributor provides its Contributions) on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied, including, without limitation, any warranties or conditions
        of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any
        risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
        whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly
        negligent acts) or agreed to in writing, shall any Contributor be
        liable to You for damages, including any direct, indirect, special,
        incidental, or consequential damages of any character arising as a
        result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill,
        work stoppage, computer failure or malfunction, or any and all
        other commercial damages or losses), even if such Contributor
        has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing
        the Work or Derivative Works thereof, You may choose to offer,
        and charge a fee for, acceptance of support, warranty, indemnity,
        or other liability obligations and/or rights consistent with this
        License. However, in accepting such obligations, You may act only
        on Your own behalf and on Your sole responsibility, not on behalf
        of any other Contributor, and only if You agree to indemnify,
        defend, and hold each Contributor harmless for any liability
        incurred by, or claims asserted against, such Contributor by reason
        of your accepting any such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following
        boilerplate notice, with the fields enclosed by brackets "[]"
        replaced with your own identifying information. (Don't include
        the brackets!) The text should be enclosed in the appropriate
        comment syntax for the file format. We also recommend that a
        file or class name and description of purpose be included on the
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
        
        Copyright 2026 Alex Shalaev
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Keywords: asyncio,database,partition-management,partitioning,postgresql
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic<3.0.0,>=2.0.0
Requires-Dist: python-dateutil<3.0.0,>=2.7.0
Requires-Dist: sqlalchemy[asyncio]<3.0.0,>=2.0.0
Provides-Extra: pydantic-settings
Requires-Dist: pydantic-settings<3.0.0,>=2.0.0; extra == 'pydantic-settings'
Provides-Extra: redis-locks
Requires-Dist: redis>=4.2.0; extra == 'redis-locks'
Description-Content-Type: text/markdown

# pg-partsmith

PostgreSQL partition lifecycle management with extensible hooks.

[![PyPI](https://img.shields.io/pypi/v/pg-partsmith?color=blue)](https://pypi.org/project/pg-partsmith/)
[![Python](https://img.shields.io/pypi/pyversions/pg-partsmith)](https://pypi.org/project/pg-partsmith/)
[![License](https://img.shields.io/github/license/bedrock-python/pg-partsmith)](LICENSE)
[![CI](https://github.com/bedrock-python/pg-partsmith/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/bedrock-python/pg-partsmith/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/bedrock-python/pg-partsmith/graph/badge.svg)](https://codecov.io/gh/bedrock-python/pg-partsmith)
[![Docs](https://img.shields.io/badge/docs-online-blue)](https://bedrock-python.github.io/pg-partsmith/)

A single library that covers the full PostgreSQL partition lifecycle: creating partitions ahead of time, detaching expired ones, and dropping orphans — with a middleware system for injecting custom logic at each step.

## Features

- **Async and sync** — `pg_partsmith.aio` on the SQLAlchemy async engine, `pg_partsmith.sync` on the classic sync engine
- **Full lifecycle** — create ahead, detach expired, drop orphans in one call
- **Nested partitioning** — `RANGE(time) → HASH(column)` and `→ LIST(column)` trees, reconciled towards the configured shape on every run
- **Time-free tables** — HASH or LIST roots with a fixed partition set, managed by the same reconciler
- **Composite keys** — multi-column partition keys, with trailing columns bounded by `MINVALUE`
- **Encoded partition keys** — partition by time even when the key is a UUIDv7 or another sortable id
- **Extensible hooks** — 6 hook points (`before`/`after` create, detach, drop)
- **Multiple strategies** — hourly, daily, weekly, monthly, quarterly, yearly + fully custom
- **Distributed locking** — PostgreSQL advisory locks (built-in) or Redis
- **Schema-aware** — multi-schema support, independent of `search_path`
- **Safe by default** — refuses to drop tables not managed by this library
- **Type-safe** — full mypy compliance with Pydantic models
- **Well-tested** — 90%+ coverage with real PostgreSQL via testcontainers

## Installation

```bash
pip install pg-partsmith

# With Redis distributed locks
pip install "pg-partsmith[redis-locks]"
```

**Requirements:** Python 3.11+, PostgreSQL 15+

## Quick start

```python
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine

from pg_partsmith import (
    MonthPeriodCalculator,
    PartitionGranularity,
    PartitionStrategy,
    PartitionType,
    TablePartitionConfig,
)
from pg_partsmith.aio import (
    PartitionLifecycleService,
    PartitionMaintainer,
    PostgresAdvisoryLockManager,
    PostgresMetadataProvider,
    PostgresPartitionRepository,
)

engine = create_async_engine("postgresql+asyncpg://user:pass@host/db")

config = TablePartitionConfig(
    schema="public",
    table_name="events",
    partition_type=PartitionType.RANGE,
    partition_strategy=PartitionStrategy.TIME_BASED,
    partition_column="created_at",
    granularity=PartitionGranularity.MONTH,
    create_ahead_count=3,  # current month + next 2
    retention_count=12,
)


async def run_maintenance(engine: AsyncEngine) -> None:
    service = PartitionLifecycleService(
        repo=PostgresPartitionRepository(engine),
        metadata=PostgresMetadataProvider(engine),
        locks=PostgresAdvisoryLockManager(engine),
        period_calculator=MonthPeriodCalculator(),
    )
    maintainer = PartitionMaintainer(service)
    result = await maintainer.run_maintenance_safe(config)
    if result.success:
        print(
            f"created={result.created_count} "
            f"detached={result.detached_count} "
            f"dropped={result.dropped_count}"
        )
    else:
        print(f"error={result.error}")
```

> **Transaction semantics** — every DDL operation (CREATE, ATTACH, DETACH, DROP)
> runs in its own connection and commits immediately. Use `AsyncEngine`, not `AsyncSession`.
> A subpartitioned branch is built detached and attached last, so an interrupted run leaves
> an unreachable table rather than a live partition that cannot route part of its keyspace.

> **Timezones** — everything is UTC by default. For calendar partitions in a business
> timezone pass the same zone to both sides: `MonthPeriodCalculator(tz=ZoneInfo("Europe/Moscow"))`
> and `PostgresPartitionRepository(engine, ddl_timezone="Europe/Moscow")` — the service
> refuses a mismatched pair, so names and real bounds cannot silently drift apart.
> Hourly granularity is UTC-only (DST makes local hour names ambiguous).

> **Cancellation semantics** — `run_maintenance_safe()` (and `maintain_partitions()`)
> always returns `MaintenanceResult`, including on `asyncio.CancelledError`.

## Sync usage

Every class in `pg_partsmith.aio` has a synchronous twin in `pg_partsmith.sync` with the
same name and API — built on the classic SQLAlchemy `Engine` instead of `AsyncEngine`:

```python
from sqlalchemy import create_engine

from pg_partsmith import MonthPeriodCalculator
from pg_partsmith.sync import (
    PartitionLifecycleService,
    PartitionMaintainer,
    PostgresAdvisoryLockManager,
    PostgresMetadataProvider,
    PostgresPartitionRepository,
)

engine = create_engine("postgresql+psycopg2://user:pass@host/db")

service = PartitionLifecycleService(
    repo=PostgresPartitionRepository(engine),
    metadata=PostgresMetadataProvider(engine),
    locks=PostgresAdvisoryLockManager(engine),
    period_calculator=MonthPeriodCalculator(),
)
maintainer = PartitionMaintainer(service)
result = maintainer.run_maintenance_safe(config)
```

Hooks and custom lock managers implement the sync protocols from `pg_partsmith.sync`
(plain methods instead of coroutines). Two behavioural differences from the async package:

- `ddl_timeout_seconds` is enforced server-side via PostgreSQL `statement_timeout`
  (per statement) rather than client-side around the whole operation.
- The Redis lock renews its TTL from a background thread; on renewal failure it logs a
  warning but cannot cancel the running maintenance (the TTL bounds a stale holder).

## Nested partitioning

A time partition can itself be a partitioned table. Add a `subpartition` spec and each
period is split along a second dimension:

```python
from pg_partsmith import HashSubpartitionSpec

config = TablePartitionConfig(
    schema="public",
    table_name="events",
    partition_type=PartitionType.RANGE,
    partition_strategy=PartitionStrategy.TIME_BASED,
    partition_column="created_at",
    granularity=PartitionGranularity.WEEK,
    create_ahead_count=3,
    retention_count=12,
    subpartition=HashSubpartitionSpec(column="tenant_id", modulus=4),
)
```

```text
events
├── events__2026_w35            PARTITION BY HASH (tenant_id)
│   ├── events__2026_w35__h0
│   ├── events__2026_w35__h1
│   ├── events__2026_w35__h2
│   └── events__2026_w35__h3
└── events__2026_w36 …
```

The two dimensions stay separate: **time is the lifecycle dimension** (create-ahead,
retention, detach, drop, hooks all operate on the whole week) and the nested one is the
distribution dimension. `retention_count=12` keeps twelve weeks, not twelve leaves.

`ListSubpartitionSpec` splits a period into named value sets instead
(`RANGE(time) → LIST(region)`), with an optional DEFAULT catch-all; the strategies also
nest into each other.

Maintenance converges the actual tree towards the configured one on every run: missing
buckets are created, a converged tree costs **zero DDL**, and anything that cannot be
repaired safely — a bucket set at an older modulus, a partition from a previous policy, a
shape the config does not describe — is left intact and reported through
`MaintenanceResult.issues`. See the
[subpartitioning guide](https://bedrock-python.github.io/pg-partsmith/guide/subpartitioning/).

## Tables partitioned without a time dimension

A table divided only by tenant or region has a fixed set of partitions — nothing
is created ahead and nothing ages out. Configure it with `root_layout`:

```python
config = TablePartitionConfig(
    table_name="issue_index",
    partition_type=PartitionType.HASH,
    partition_strategy=PartitionStrategy.HASH_BASED,
    partition_column="organization_id",
    root_layout=HashSubpartitionSpec(column="organization_id", modulus=16),
)
```

Such a table needs no period calculator, and maintenance is purely
reconciliation: missing partitions are created, nothing is ever pruned.

## Partitioning by an encoded key

When the partition key is a time-sortable identifier rather than a timestamp — a UUIDv7, a
ULID, an epoch bigint — a boundary codec keeps the lifecycle reasoning in calendar periods
while the DDL speaks the key's own language:

```python
from pg_partsmith.boundaries import UUIDv7BoundaryCodec

codec = UUIDv7BoundaryCodec()

service = PartitionLifecycleService(
    repo=PostgresPartitionRepository(engine),
    metadata=PostgresMetadataProvider(engine, boundary_codec=codec),
    locks=PostgresAdvisoryLockManager(engine),
    period_calculator=WeekPeriodCalculator(boundary_codec=codec),
)
```

Partition names, create-ahead, and retention are unchanged; only the `FOR VALUES FROM … TO
…` literals become UUIDs. Codecs are bidirectional, so retention and `is_partition_closed`
keep working. See the
[boundary codec guide](https://bedrock-python.github.io/pg-partsmith/guide/boundary-codecs/).

## Multi-schema databases

If your database uses multiple schemas, set `schema` in `TablePartitionConfig`. The library
schema-qualifies all catalog queries, DDL statements, and lock namespaces — behaviour
becomes independent of `search_path`.

## Orphan partitions

After detach, the repository writes a `COMMENT` marker on the detached table.
Only marker-tagged tables are eligible for dropping, making cleanup safe even if the
database contains similarly named tables not managed by this library.

Set `marker_prefix` explicitly on both `PostgresPartitionRepository` and
`PostgresMetadataProvider` to ensure consistent orphan marker recognition across deployments.

> **Marker semantics** — the `COMMENT` marker means "this library owns cleanup of this
> table". It survives `pg_dump`/restore (comments are dumped by default), so a restored
> copy of a marked table is again eligible for dropping. When repurposing such a table,
> clear its comment (`COMMENT ON TABLE ... IS NULL`) or restore with `--no-comments`.

## DEFAULT partition reconciliation

When creating a new partition, if the DEFAULT partition contains rows belonging to the
new range, pg-partsmith automatically:

1. Detects the conflict (`CheckViolationError 23514`)
2. Moves conflicting rows from DEFAULT to the new partition
3. Retries `ATTACH PARTITION`

The reconciliation is atomic and logged at `INFO` level.

## TIMESTAMPTZ boundary semantics

For `TIMESTAMP WITH TIME ZONE` partition keys, `PostgresPartitionRepository` runs
`SET LOCAL TimeZone='UTC'` before `ATTACH PARTITION` (`ddl_timezone="UTC"` default).
Set `ddl_timezone=None` to disable this enforcement.

## Safe drops

`drop_partition()` refuses to drop tables not tagged as orphans. To override:
```python
repo = PostgresPartitionRepository(engine, drop_allow_unmanaged=True)
```
An attempt to drop an unmanaged table raises `UnmanagedPartitionDropError`.

## Hooks (middleware)

```python
from pg_partsmith.aio import BasePartitionLifecycleHooks, PartitionLifecycleService
from pg_partsmith.entities import PartitionInfo, TablePartitionConfig


class KafkaNotifyHooks(BasePartitionLifecycleHooks):
    def __init__(self, producer: KafkaProducer) -> None:
        self._producer = producer

    async def after_create(self, config: TablePartitionConfig, partition: PartitionInfo) -> None:
        await self._producer.send("partition.created", {"name": partition.name})

    async def before_drop(self, table_name: str, partition_name: str) -> None:
        await export_to_cold_storage(table_name, partition_name)


service = PartitionLifecycleService(
    repo=repo,
    metadata=metadata,
    locks=locks,
    period_calculator=calculator,
    hooks=[KafkaNotifyHooks(producer)],
)
```

### Hook points

| Method | When |
|--------|------|
| `before_create(config, partition_name, from_value, to_value)` | Before partition is created |
| `after_create(config, partition)` | After creation |
| `before_detach(table_name, partition)` | Before detach |
| `after_detach(table_name, partition_name)` | After successful detach |
| `before_drop(table_name, partition_name)` | Before drop — last chance to read data |
| `after_drop(table_name, partition_name)` | After drop |

`before_*` exceptions abort the operation. `after_*` exceptions are logged but do not affect `result.success`.

## Extensibility

```python
from pg_partsmith.aio import PostgresPartitionRepository


class AuditedPartitionRepository(PostgresPartitionRepository):
    async def drop_partition(self, partition_name: str) -> None:
        await self._audit_log.record("drop", partition_name)
        await super().drop_partition(partition_name)
```

## Lock managers

### PostgreSQL advisory locks (default)

```python
from pg_partsmith.aio import PostgresAdvisoryLockManager

locks = PostgresAdvisoryLockManager(engine, prefix="myapp")
```

> **Pool sizing** — advisory locks hold a dedicated connection for the duration of
> maintenance. Ensure your pool has spare capacity, or use a separate `AsyncEngine`
> for the lock manager (a pool of 1 will deadlock).

### Redis distributed locks

```bash
pip install "pg-partsmith[redis-locks]"
```

```python
from redis.asyncio import Redis
from pg_partsmith.aio import RedisDistributedLockManager

locks = RedisDistributedLockManager(
    redis_client=Redis.from_url("redis://localhost"),
    prefix="myapp:partitioner",
    ttl_seconds=300,
)
```

## Period strategies

| Class | Granularity | Example |
|-------|-------------|---------|
| `HourPeriodCalculator` | Hourly (UTC) | `events__2024_01_15_09` |
| `DayPeriodCalculator` | Daily | `events__2024_01_15` |
| `WeekPeriodCalculator` | ISO weekly | `events__2024_w03` |
| `MonthPeriodCalculator` | Monthly | `events__2024_01` |
| `QuarterPeriodCalculator` | Quarterly | `events__2024_q1` |
| `YearPeriodCalculator` | Yearly | `events__2024` |

```python
from pg_partsmith.strategies import BasePeriodCalculator
from pg_partsmith.entities import Period


class QuarterPeriodCalculator(BasePeriodCalculator):
    def current_period(self) -> Period: ...
    def format_partition_name(self, table_name: str, period: Period) -> str: ...
    def parse_partition_name(self, partition_name: str) -> Period | None: ...
    def get_boundaries(self, period: Period) -> tuple[str, str]: ...
```

## Scheduler integration

```python
from pg_partsmith.aio import maintain_partitions

scheduler.add_job(
    maintain_partitions,
    "cron",
    hour=2,
    kwargs={"maintainer": maintainer, "config": config},
)
```

## API reference

### `pg_partsmith`

**Entities** — `Period`, `PartitionInfo`, `TablePartitionConfig`, `MaintenanceResult`, `MaintenanceIssue`, `MaintenanceIssueStep`

**Topology** — `HashSubpartitionSpec`, `ListSubpartitionSpec`, `ListGroup`, `SubpartitionSpec`, `PartitionNode`, `RangeBounds`, `HashBounds`, `ListBounds`, `DefaultBounds`, `PartitionBounds`, `SubpartitionBounds`

**Reconciliation** — `SubpartitionPlan`, `SubpartitionAction`, `SubpartitionReconcileResult`, `TopologyFinding`, `TopologyReason`, `plan_subpartitions`

**Boundary codecs** — `RangeBoundaryCodec`, `UUIDv7BoundaryCodec`

**Helpers** — `qualify`, `split_qualified_name`

**Enums** — `PartitionType`, `PartitionGranularity`, `PartitionStrategy`

**Exceptions** — `PartitionError`, `PartitionAlreadyExistsError`, `PartitionNotFoundError`, `PartitionAttachedError`, `PartitionDetachInProgressError`, `InvalidPartitionConfigError`, `LockAcquisitionError`, `DropRetryExhaustedError`, `UnmanagedPartitionDropError`, `PartitionTopologyError`, `UnsupportedCapabilityError`

**Protocols** — `PeriodCalculator`, `TimezoneAwareCalculator`, `DdlTimezoneAware`, `BoundaryDecoder`

**Strategies** — `BasePeriodCalculator`, `HourPeriodCalculator`, `DayPeriodCalculator`, `WeekPeriodCalculator`, `MonthPeriodCalculator`, `QuarterPeriodCalculator`, `YearPeriodCalculator`, `get_period_calculator`

### `pg_partsmith.aio`

**Protocols** — `PartitionRepository`, `PartitionMetadataProvider`, `LockManager`, `SubpartitionRepository`, `NestedPartitionMetadata`, `CompositeKeyRepository`, `CompositeKeyMetadata`

**Hooks** — `BasePartitionLifecycleHooks`

**Service** — `PartitionLifecycleService`

**PostgreSQL** — `PostgresPartitionRepository`, `PostgresMetadataProvider`

**Lock managers** — `PostgresAdvisoryLockManager`, `RedisDistributedLockManager`

**Orchestration** — `PartitionMaintainer`, `maintain_partitions`

### `pg_partsmith.sync`

Synchronous mirror of `pg_partsmith.aio` — same names, same layout, plain methods
built on the sync SQLAlchemy `Engine`.

## Migrating from a hand-rolled partitioner

The [migration guide](https://bedrock-python.github.io/pg-partsmith/guide/migration/)
covers the traps: retention is a **count**, not a distance (`old_distance + 1`); legacy
detached partitions are adopted with `repo.adopt_partition(...)` instead of disabling
safe-drop via `drop_allow_unmanaged`; writers that need one specific partition use
`service.ensure_partition(config, period)`; scheduled ticks isolate step failures with
`maintain_lifecycle(..., continue_on_error=True)` → `result.issues`; export pipelines
check `metadata.is_partition_closed(name, settle_seconds=...)` before finalizing; data that
predates the create-ahead window gets partitions via
`service.ensure_partitions(config, periods)`.

For a worked example of adopting a `RANGE(UUIDv7) → HASH(tenant)` event store — including a
non-uniform bucket history and custom partition names — see
[Example: an event store with TIME → HASH](https://bedrock-python.github.io/pg-partsmith/guide/nested-migration/).

## Development

```bash
make install          # uv sync --group dev
make check            # ruff + mypy
make test-unit        # unit tests (no Docker)
make test-integration # integration tests (Docker required)
make test             # all tests with coverage
make docs-serve       # local docs preview
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.

## License

[Apache 2.0](LICENSE)
