Skip to content

Commit a47da28

Browse files
feat: add pg_partsmith.sync — synchronous mirror of the aio package (#13)
* feat: add pg_partsmith.sync — synchronous mirror of the aio package Same class names, file layout, and public API as pg_partsmith.aio, built on the sync SQLAlchemy Engine. Differences: ddl_timeout_seconds is enforced server-side via PostgreSQL statement_timeout, the Redis lock renews its TTL from a daemon thread, and KeyboardInterrupt/SystemExit replace CancelledError in error handling. Mirrored unit and integration test suites included. * ci: upload unit-test coverage to codecov Codecov previously received coverage only from the integration job, so unit-test-only coverage (mock-based branches) never counted toward the patch status. Upload the unit run's coverage as well (from the 3.11 matrix entry) so the merged report reflects the whole suite.
1 parent 11640c2 commit a47da28

45 files changed

Lines changed: 7892 additions & 5 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,13 @@ jobs:
3232
with:
3333
python-version: ${{ matrix.python-version }}
3434
- run: uv sync --group dev --extra pydantic-settings
35-
- run: uv run pytest -m unit
35+
- run: uv run pytest -m unit --cov=pg_partsmith --cov-report=xml
36+
- uses: codecov/codecov-action@v5
37+
if: matrix.python-version == '3.11'
38+
with:
39+
token: ${{ secrets.CODECOV_TOKEN }}
40+
files: coverage.xml
41+
continue-on-error: true
3642

3743
test-integration:
3844
name: Integration tests

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased]
9+
10+
### Added
11+
12+
- `pg_partsmith.sync` — synchronous mirror of `pg_partsmith.aio` with the same class
13+
names and API, built on the sync SQLAlchemy `Engine`: `PartitionLifecycleService`,
14+
`PartitionMaintainer`, `maintain_partitions`, `PostgresPartitionRepository`,
15+
`PostgresMetadataProvider`, `PostgresAdvisoryLockManager`, `RedisDistributedLockManager`,
16+
sync `PartitionLifecycleHooks` / `BasePartitionLifecycleHooks`, and sync protocols.
17+
Differences from the async package: `ddl_timeout_seconds` is enforced server-side via
18+
PostgreSQL `statement_timeout` (per statement), and the Redis lock renews its TTL from a
19+
background thread that logs (but cannot cancel maintenance) on renewal failure.
20+
821
## [0.1.0] - 2026-05-08
922

1023
First public release of `pg-partsmith`.

‎CONTRIBUTING.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,19 @@ make test-integration
7272

7373
## Adding a lock manager
7474

75-
1. Implement the `LockManager` protocol from `pg_partsmith.aio.protocols`
76-
2. Add it to `pg_partsmith/aio/__init__.py` exports (optional extra if it has deps)
75+
1. Implement the `LockManager` protocol from `pg_partsmith.aio.protocols` (async)
76+
and/or `pg_partsmith.sync.protocols` (sync)
77+
2. Add it to `pg_partsmith/aio/__init__.py` / `pg_partsmith/sync/__init__.py` exports
78+
(optional extra if it has deps)
7779
3. Document it in `docs/guide/locks.md`
7880

81+
## Keeping aio and sync in sync
82+
83+
`pg_partsmith/sync` is a hand-maintained mirror of `pg_partsmith/aio` (same files, same
84+
class names, plain methods instead of coroutines). Any behavioural change to one package
85+
must be applied to the other, along with the mirrored tests in `tests/unit/sync/` and
86+
`tests/integration/sync/`.
87+
7988
## Releasing (maintainers only)
8089

8190
1. Move `[Unreleased]` section in `CHANGELOG.md` to `[x.y.z] - YYYY-MM-DD`

‎README.md‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ A single library that covers the full PostgreSQL partition lifecycle: creating p
1313

1414
## Features
1515

16-
- **Async-first** — built on `asyncio` and SQLAlchemy async engine
16+
- **Async and sync** — `pg_partsmith.aio` on the SQLAlchemy async engine, `pg_partsmith.sync` on the classic sync engine
1717
- **Full lifecycle** — create ahead, detach expired, drop orphans in one call
1818
- **Extensible hooks** — 6 hook points (`before`/`after` create, detach, drop)
1919
- **Multiple strategies** — daily, weekly, monthly, yearly + fully custom
@@ -93,6 +93,43 @@ async def run_maintenance(engine: AsyncEngine) -> None:
9393
> **Cancellation semantics** — `run_maintenance_safe()` (and `maintain_partitions()`)
9494
> always returns `MaintenanceResult`, including on `asyncio.CancelledError`.
9595
96+
## Sync usage
97+
98+
Every class in `pg_partsmith.aio` has a synchronous twin in `pg_partsmith.sync` with the
99+
same name and API — built on the classic SQLAlchemy `Engine` instead of `AsyncEngine`:
100+
101+
```python
102+
from sqlalchemy import create_engine
103+
104+
from pg_partsmith import MonthPeriodCalculator
105+
from pg_partsmith.sync import (
106+
PartitionLifecycleService,
107+
PartitionMaintainer,
108+
PostgresAdvisoryLockManager,
109+
PostgresMetadataProvider,
110+
PostgresPartitionRepository,
111+
)
112+
113+
engine = create_engine("postgresql+psycopg2://user:pass@host/db")
114+
115+
service = PartitionLifecycleService(
116+
repo=PostgresPartitionRepository(engine),
117+
metadata=PostgresMetadataProvider(engine),
118+
locks=PostgresAdvisoryLockManager(engine),
119+
period_calculator=MonthPeriodCalculator(),
120+
)
121+
maintainer = PartitionMaintainer(service)
122+
result = maintainer.run_maintenance_safe(config)
123+
```
124+
125+
Hooks and custom lock managers implement the sync protocols from `pg_partsmith.sync`
126+
(plain methods instead of coroutines). Two behavioural differences from the async package:
127+
128+
- `ddl_timeout_seconds` is enforced server-side via PostgreSQL `statement_timeout`
129+
(per statement) rather than client-side around the whole operation.
130+
- The Redis lock renews its TTL from a background thread; on renewal failure it logs a
131+
warning but cannot cancel the running maintenance (the TTL bounds a stale holder).
132+
96133
## Multi-schema databases
97134

98135
If your database uses multiple schemas, set `schema` in `TablePartitionConfig`. The library
@@ -278,6 +315,11 @@ scheduler.add_job(
278315

279316
**Orchestration** — `PartitionMaintainer`, `maintain_partitions`
280317

318+
### `pg_partsmith.sync`
319+
320+
Synchronous mirror of `pg_partsmith.aio` — same names, same layout, plain methods
321+
built on the sync SQLAlchemy `Engine`.
322+
281323
## Development
282324

283325
```bash

‎docs/guide/quickstart.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,33 @@ scheduler.add_job(
9696
)
9797
```
9898

99+
## Sync variant
100+
101+
Every class above has a synchronous twin in `pg_partsmith.sync` with the same name and
102+
API. Build against the classic SQLAlchemy engine and drop the `await`:
103+
104+
```python
105+
from sqlalchemy import create_engine
106+
from pg_partsmith.sync import (
107+
PartitionLifecycleService,
108+
PartitionMaintainer,
109+
PostgresAdvisoryLockManager,
110+
PostgresMetadataProvider,
111+
PostgresPartitionRepository,
112+
)
113+
114+
engine = create_engine("postgresql+psycopg2://user:pass@host/db")
115+
116+
service = PartitionLifecycleService(
117+
repo=PostgresPartitionRepository(engine),
118+
metadata=PostgresMetadataProvider(engine),
119+
locks=PostgresAdvisoryLockManager(engine),
120+
period_calculator=MonthPeriodCalculator(),
121+
)
122+
maintainer = PartitionMaintainer(service)
123+
result = maintainer.run_maintenance_safe(config)
124+
```
125+
99126
## What happens each run
100127

101128
1. **Create** — ensures partitions exist for `create_ahead_count` periods starting from now.

‎docs/reference/index.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,49 @@ Async implementations: service, maintainer, repositories, lock managers, and hoo
106106
::: pg_partsmith.aio.hooks.BasePartitionLifecycleHooks
107107
options:
108108
heading_level: 4
109+
110+
---
111+
112+
## pg_partsmith.sync
113+
114+
Synchronous mirror of `pg_partsmith.aio`: same class names and API, plain methods
115+
built on the sync SQLAlchemy `Engine`.
116+
117+
### Service and maintainer
118+
119+
::: pg_partsmith.sync.service.PartitionLifecycleService
120+
options:
121+
heading_level: 4
122+
123+
::: pg_partsmith.sync.maintainer.PartitionMaintainer
124+
options:
125+
heading_level: 4
126+
members:
127+
- run_maintenance
128+
- run_maintenance_safe
129+
130+
### PostgreSQL implementations
131+
132+
::: pg_partsmith.sync.repositories.repository.PostgresPartitionRepository
133+
options:
134+
heading_level: 4
135+
136+
::: pg_partsmith.sync.metadata.PostgresMetadataProvider
137+
options:
138+
heading_level: 4
139+
140+
### Lock managers
141+
142+
::: pg_partsmith.sync.lock.postgres.PostgresAdvisoryLockManager
143+
options:
144+
heading_level: 4
145+
146+
::: pg_partsmith.sync.lock.redis.RedisDistributedLockManager
147+
options:
148+
heading_level: 4
149+
150+
### Hooks
151+
152+
::: pg_partsmith.sync.hooks.BasePartitionLifecycleHooks
153+
options:
154+
heading_level: 4

‎pg_partsmith/sync/__init__.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""Sync implementations for partition management."""
2+
3+
from .hooks import BasePartitionLifecycleHooks, PartitionLifecycleHooks
4+
from .lock import PostgresAdvisoryLockManager, RedisDistributedLockManager
5+
from .maintainer import PartitionMaintainer, maintain_partitions
6+
from .metadata import PostgresMetadataProvider
7+
from .protocols import LockManager, PartitionMetadataProvider, PartitionRepository
8+
from .repositories import PostgresPartitionRepository
9+
from .service import PartitionLifecycleService
10+
11+
__all__ = [
12+
"BasePartitionLifecycleHooks",
13+
"LockManager",
14+
"PartitionLifecycleHooks",
15+
"PartitionLifecycleService",
16+
"PartitionMaintainer",
17+
"PartitionMetadataProvider",
18+
"PartitionRepository",
19+
"PostgresAdvisoryLockManager",
20+
"PostgresMetadataProvider",
21+
"PostgresPartitionRepository",
22+
"RedisDistributedLockManager",
23+
"maintain_partitions",
24+
]

‎pg_partsmith/sync/hooks.py‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
"""Lifecycle hooks (middleware) and protocol for partition operations.
2+
3+
Hooks let you inject custom logic at each step of the partition lifecycle -
4+
for example, exporting data before a partition is dropped, publishing events
5+
to Kafka after a partition is created, or archiving rows before detachment.
6+
7+
Usage example::
8+
9+
class KafkaExportHooks(BasePartitionLifecycleHooks):
10+
def __init__(self, producer: KafkaProducer) -> None:
11+
self._producer = producer
12+
13+
def before_drop(self, table_name: str, partition_name: str) -> None:
14+
self._producer.send("partition.before_drop", {
15+
"table": table_name,
16+
"partition": partition_name,
17+
})
18+
19+
service = PartitionLifecycleService(
20+
repo=repo,
21+
metadata=metadata,
22+
locks=locks,
23+
period_calculator=calculator,
24+
hooks=[KafkaExportHooks(producer)],
25+
)
26+
"""
27+
28+
from typing import Protocol, runtime_checkable
29+
30+
from pg_partsmith.entities import PartitionInfo, TablePartitionConfig
31+
32+
33+
@runtime_checkable
34+
class PartitionLifecycleHooks(Protocol):
35+
"""Protocol for partition lifecycle hooks.
36+
37+
Implement this protocol to inject custom logic at each step of the partition
38+
lifecycle without inheriting from a specific base class.
39+
"""
40+
41+
def before_create(
42+
self,
43+
config: TablePartitionConfig,
44+
partition_name: str,
45+
from_value: str,
46+
to_value: str,
47+
) -> None: ...
48+
49+
def after_create(
50+
self,
51+
config: TablePartitionConfig,
52+
partition: PartitionInfo,
53+
) -> None: ...
54+
55+
def before_detach(
56+
self,
57+
table_name: str,
58+
partition: PartitionInfo,
59+
) -> None: ...
60+
61+
def after_detach(
62+
self,
63+
table_name: str,
64+
partition_name: str,
65+
) -> None: ...
66+
67+
def before_drop(
68+
self,
69+
table_name: str,
70+
partition_name: str,
71+
) -> None: ...
72+
73+
def after_drop(
74+
self,
75+
table_name: str,
76+
partition_name: str,
77+
) -> None: ...
78+
79+
80+
class BasePartitionLifecycleHooks:
81+
"""No-op base implementation of partition lifecycle hooks.
82+
83+
Subclass and override only the methods you need.
84+
All methods are no-ops by default so you can selectively add behaviour
85+
without implementing every step.
86+
"""
87+
88+
def before_create(
89+
self,
90+
config: TablePartitionConfig,
91+
partition_name: str,
92+
from_value: str,
93+
to_value: str,
94+
) -> None:
95+
"""Called before a partition is created.
96+
97+
Args:
98+
config: Table partition configuration.
99+
partition_name: Name the new partition will be given.
100+
from_value: Start boundary value.
101+
to_value: End boundary value.
102+
"""
103+
104+
def after_create(
105+
self,
106+
config: TablePartitionConfig,
107+
partition: PartitionInfo,
108+
) -> None:
109+
"""Called after a partition has been created (and optionally attached).
110+
111+
Args:
112+
config: Table partition configuration.
113+
partition: Info about the newly created partition.
114+
"""
115+
116+
def before_detach(
117+
self,
118+
table_name: str,
119+
partition: PartitionInfo,
120+
) -> None:
121+
"""Called before a partition is detached from its parent table.
122+
123+
This is a good place to export or archive data while the partition
124+
is still accessible via the parent table's indexes and constraints.
125+
126+
Args:
127+
table_name: Parent table name.
128+
partition: Info about the partition being detached.
129+
"""
130+
131+
def after_detach(
132+
self,
133+
table_name: str,
134+
partition_name: str,
135+
) -> None:
136+
"""Called after a partition has been detached.
137+
138+
Args:
139+
table_name: Parent table name.
140+
partition_name: Name of the detached partition.
141+
"""
142+
143+
def before_drop(
144+
self,
145+
table_name: str,
146+
partition_name: str,
147+
) -> None:
148+
"""Called before a partition table is dropped.
149+
150+
This is the last chance to read or export data from the partition
151+
before it is permanently destroyed.
152+
153+
Args:
154+
table_name: Parent table name.
155+
partition_name: Name of the partition about to be dropped.
156+
"""
157+
158+
def after_drop(
159+
self,
160+
table_name: str,
161+
partition_name: str,
162+
) -> None:
163+
"""Called after a partition table has been dropped.
164+
165+
Args:
166+
table_name: Parent table name.
167+
partition_name: Name of the dropped partition.
168+
"""

0 commit comments

Comments
 (0)