pgttl 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pgttl/__init__.py +87 -0
- pgttl/django/__init__.py +38 -0
- pgttl/django/apps.py +12 -0
- pgttl/django/checks.py +83 -0
- pgttl/django/migrations.py +37 -0
- pgttl-0.1.0.dist-info/METADATA +137 -0
- pgttl-0.1.0.dist-info/RECORD +9 -0
- pgttl-0.1.0.dist-info/WHEEL +5 -0
- pgttl-0.1.0.dist-info/top_level.txt +1 -0
pgttl/__init__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Thin synchronous psycopg bindings for the pg_ttl server extension."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TTLUnavailableError(RuntimeError):
|
|
9
|
+
"""The pg_ttl server extension is missing or incompatible."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _version(value):
|
|
13
|
+
if not isinstance(value, str) or not re.fullmatch(r"\d+\.\d+\.\d+", value):
|
|
14
|
+
raise ValueError(f"invalid pg_ttl version: {value!r}")
|
|
15
|
+
return tuple(map(int, value.split(".")))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def require(connection, min_version=None):
|
|
19
|
+
"""Check the installed extension version without changing the server."""
|
|
20
|
+
required = __version__ if min_version is None else min_version
|
|
21
|
+
minimum = _version(required)
|
|
22
|
+
row = connection.execute(
|
|
23
|
+
"SELECT extversion FROM pg_catalog.pg_extension WHERE extname = 'pg_ttl'"
|
|
24
|
+
).fetchone()
|
|
25
|
+
if row is None:
|
|
26
|
+
raise TTLUnavailableError("pg_ttl is not installed in this database")
|
|
27
|
+
try:
|
|
28
|
+
installed = _version(row[0])
|
|
29
|
+
except ValueError as exc:
|
|
30
|
+
raise TTLUnavailableError(str(exc)) from exc
|
|
31
|
+
if installed < minimum:
|
|
32
|
+
raise TTLUnavailableError(
|
|
33
|
+
f"pg_ttl {row[0]} is older than required version {required}"
|
|
34
|
+
)
|
|
35
|
+
return row[0]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def enable(connection, table):
|
|
39
|
+
"""Register an ordinary table."""
|
|
40
|
+
return connection.execute("SELECT pgttl.ttl_enable(%s::regclass)", (table,)).fetchone()[0]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def disable(connection, table):
|
|
44
|
+
"""Unregister a table and discard its deadlines."""
|
|
45
|
+
return connection.execute("SELECT pgttl.ttl_disable(%s::regclass)", (table,)).fetchone()[0]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def set_ttl(connection, table, id, seconds):
|
|
49
|
+
"""Schedule or renew expiration of an existing row."""
|
|
50
|
+
if not isinstance(seconds, int):
|
|
51
|
+
raise TypeError("TTL seconds must be an integer")
|
|
52
|
+
return connection.execute(
|
|
53
|
+
"SELECT pgttl.ttl_set(%s::regclass, %s::text, %s::bigint)", (table, id, seconds)
|
|
54
|
+
).fetchone()[0]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def clear_ttl(connection, table, id):
|
|
58
|
+
"""Clear a scheduled expiration."""
|
|
59
|
+
return connection.execute(
|
|
60
|
+
"SELECT pgttl.ttl_clear(%s::regclass, %s::text)", (table, id)
|
|
61
|
+
).fetchone()[0]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def configure(connection, name, value):
|
|
65
|
+
"""Configure persisted native maintenance settings."""
|
|
66
|
+
if not isinstance(value, int):
|
|
67
|
+
raise TypeError("TTL configuration value must be an integer")
|
|
68
|
+
return connection.execute(
|
|
69
|
+
"SELECT pgttl.ttl_config(%s, %s::integer)", (name, value)
|
|
70
|
+
).fetchone()[0]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def status(connection):
|
|
74
|
+
"""Return maintenance health as a dictionary."""
|
|
75
|
+
return connection.execute("SELECT pgttl.ttl_status()").fetchone()[0]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def validate(connection):
|
|
79
|
+
"""Return schema validation results as (table_name, status, detail) tuples."""
|
|
80
|
+
return connection.execute("SELECT * FROM pgttl.ttl_validate()").fetchall()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def accept_schema(connection, table):
|
|
84
|
+
"""Accept the current table definition if its registration is still valid."""
|
|
85
|
+
return connection.execute(
|
|
86
|
+
"SELECT pgttl.ttl_accept_schema(%s::regclass)", (table,)
|
|
87
|
+
).fetchone()[0]
|
pgttl/django/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Optional Django helpers for a server with pg_ttl installed."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _instance_key(instance, using):
|
|
5
|
+
from django.db import connections
|
|
6
|
+
|
|
7
|
+
if instance._state.adding or instance.pk is None:
|
|
8
|
+
raise ValueError("TTL requires a saved model instance")
|
|
9
|
+
alias = instance._state.db if using is None else using
|
|
10
|
+
if alias is None:
|
|
11
|
+
raise ValueError("TTL requires a saved model instance with a database alias")
|
|
12
|
+
db = connections[alias]
|
|
13
|
+
if db.vendor != "postgresql":
|
|
14
|
+
raise ValueError("TTL requires a PostgreSQL database")
|
|
15
|
+
if len(instance._meta.pk_fields) != 1:
|
|
16
|
+
raise ValueError("TTL requires a single-column primary key")
|
|
17
|
+
table = db.ops.quote_name(instance._meta.db_table)
|
|
18
|
+
key = instance._meta.pk.get_db_prep_value(instance.pk, db)
|
|
19
|
+
return db, table, key
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def set_ttl(instance, seconds, using=None):
|
|
23
|
+
"""Schedule expiration of a saved instance in its current transaction."""
|
|
24
|
+
if not isinstance(seconds, int):
|
|
25
|
+
raise TypeError("TTL seconds must be an integer")
|
|
26
|
+
db, table, key = _instance_key(instance, using)
|
|
27
|
+
with db.cursor() as cursor:
|
|
28
|
+
cursor.execute("SELECT pgttl.ttl_set(%s::regclass, %s::text, %s::bigint)",
|
|
29
|
+
[table, key, seconds])
|
|
30
|
+
return cursor.fetchone()[0]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def clear_ttl(instance, using=None):
|
|
34
|
+
"""Remove expiration of a saved instance in its current transaction."""
|
|
35
|
+
db, table, key = _instance_key(instance, using)
|
|
36
|
+
with db.cursor() as cursor:
|
|
37
|
+
cursor.execute("SELECT pgttl.ttl_clear(%s::regclass, %s::text)", [table, key])
|
|
38
|
+
return cursor.fetchone()[0]
|
pgttl/django/apps.py
ADDED
pgttl/django/checks.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Check TTL registrations and actual foreign keys without changing schema."""
|
|
2
|
+
|
|
3
|
+
from django.apps import apps
|
|
4
|
+
from django.core.checks import Error, Warning, Tags, register
|
|
5
|
+
from django.db import DatabaseError, connections, models, router
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _relation_warnings(alias, cursor, registered, app_configs):
|
|
9
|
+
db = connections[alias]
|
|
10
|
+
selected = None if app_configs is None else set(app_configs)
|
|
11
|
+
for model in apps.get_models(include_auto_created=True):
|
|
12
|
+
if selected is not None and model._meta.app_config not in selected:
|
|
13
|
+
continue
|
|
14
|
+
if model._meta.proxy or not router.allow_migrate_model(alias, model):
|
|
15
|
+
continue
|
|
16
|
+
cursor.execute("SELECT pg_catalog.to_regclass(%s)::oid",
|
|
17
|
+
[db.ops.quote_name(model._meta.db_table)])
|
|
18
|
+
oid = cursor.fetchone()[0]
|
|
19
|
+
if oid is None:
|
|
20
|
+
continue
|
|
21
|
+
cursor.execute(
|
|
22
|
+
"SELECT p.confrelid, a.attname, p.confdeltype "
|
|
23
|
+
"FROM pg_catalog.pg_constraint p JOIN pg_catalog.pg_attribute a "
|
|
24
|
+
"ON a.attrelid=p.conrelid AND a.attnum=p.conkey[1] "
|
|
25
|
+
"WHERE p.conrelid=%s AND p.contype='f' AND cardinality(p.conkey)=1",
|
|
26
|
+
[oid],
|
|
27
|
+
)
|
|
28
|
+
actual = {(target, column): action for target, column, action in cursor.fetchall()}
|
|
29
|
+
for field in model._meta.local_fields:
|
|
30
|
+
if not isinstance(field, models.ForeignKey):
|
|
31
|
+
continue
|
|
32
|
+
target_table = field.remote_field.model._meta.db_table
|
|
33
|
+
cursor.execute("SELECT pg_catalog.to_regclass(%s)::oid",
|
|
34
|
+
[db.ops.quote_name(target_table)])
|
|
35
|
+
target = cursor.fetchone()[0]
|
|
36
|
+
if target not in registered:
|
|
37
|
+
continue
|
|
38
|
+
action = actual.get((target, field.column))
|
|
39
|
+
on_delete = field.remote_field.on_delete
|
|
40
|
+
native = any(on_delete is getattr(models, name, None)
|
|
41
|
+
for name in ("DB_CASCADE", "DB_SET_NULL", "DB_SET_DEFAULT"))
|
|
42
|
+
if action in ("c", "n", "d") and (native or on_delete is models.DO_NOTHING):
|
|
43
|
+
continue
|
|
44
|
+
yield Warning(
|
|
45
|
+
f"TTL expiration of {target_table!r} bypasses Django deletion behavior "
|
|
46
|
+
f"for {model._meta.label}.{field.name} on database {alias!r}.",
|
|
47
|
+
hint="Use compatible database constraints. TTL never calls Django's deletion collector.",
|
|
48
|
+
obj=field,
|
|
49
|
+
id="pgttl.W002",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@register(Tags.database)
|
|
54
|
+
def check_ttl(app_configs, **kwargs):
|
|
55
|
+
issues = []
|
|
56
|
+
for alias in kwargs.get("databases") or ():
|
|
57
|
+
db = connections[alias]
|
|
58
|
+
if db.vendor != "postgresql":
|
|
59
|
+
continue
|
|
60
|
+
try:
|
|
61
|
+
with db.cursor() as cursor:
|
|
62
|
+
cursor.execute("SELECT 1 FROM pg_catalog.pg_extension WHERE extname='pg_ttl'")
|
|
63
|
+
if cursor.fetchone() is None:
|
|
64
|
+
continue
|
|
65
|
+
cursor.execute("SELECT * FROM pgttl.ttl_validate()")
|
|
66
|
+
for table, status, detail in cursor.fetchall():
|
|
67
|
+
if status == "ok":
|
|
68
|
+
continue
|
|
69
|
+
cls = Error if status == "error" else Warning
|
|
70
|
+
issues.append(cls(
|
|
71
|
+
f"TTL table {table!r} on database {alias!r}: {detail}",
|
|
72
|
+
hint="Inspect the table registration; explicitly accept a compatible schema.",
|
|
73
|
+
id="pgttl.E001" if status == "error" else "pgttl.W001",
|
|
74
|
+
))
|
|
75
|
+
cursor.execute("SELECT relid FROM pgttl._ttl_tables")
|
|
76
|
+
registered = {row[0] for row in cursor.fetchall()}
|
|
77
|
+
issues.extend(_relation_warnings(alias, cursor, registered, app_configs))
|
|
78
|
+
except (DatabaseError, ValueError, TypeError) as exc:
|
|
79
|
+
issues.append(Error(
|
|
80
|
+
f"Cannot validate TTL registrations on database {alias!r}: {exc}",
|
|
81
|
+
id="pgttl.E002",
|
|
82
|
+
))
|
|
83
|
+
return issues
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Explicit TTL registration in Django migrations."""
|
|
2
|
+
|
|
3
|
+
from django.db.migrations.operations.base import Operation
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class EnableTTL(Operation):
|
|
7
|
+
"""Register a model table; reversing discards its pending deadlines."""
|
|
8
|
+
|
|
9
|
+
reversible = True
|
|
10
|
+
reduces_to_sql = True
|
|
11
|
+
|
|
12
|
+
def __init__(self, model_name):
|
|
13
|
+
self.model_name = model_name
|
|
14
|
+
|
|
15
|
+
def state_forwards(self, app_label, state):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
|
19
|
+
model = to_state.apps.get_model(app_label, self.model_name)
|
|
20
|
+
db = schema_editor.connection
|
|
21
|
+
if db.vendor == "postgresql" and self.allow_migrate_model(db.alias, model):
|
|
22
|
+
schema_editor.execute("SELECT pgttl.ttl_enable(%s::regclass)",
|
|
23
|
+
[db.ops.quote_name(model._meta.db_table)])
|
|
24
|
+
|
|
25
|
+
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
|
26
|
+
model = from_state.apps.get_model(app_label, self.model_name)
|
|
27
|
+
db = schema_editor.connection
|
|
28
|
+
if db.vendor == "postgresql" and self.allow_migrate_model(db.alias, model):
|
|
29
|
+
schema_editor.execute("SELECT pgttl.ttl_disable(%s::regclass)",
|
|
30
|
+
[db.ops.quote_name(model._meta.db_table)])
|
|
31
|
+
|
|
32
|
+
def describe(self):
|
|
33
|
+
return f"Enable TTL on {self.model_name}"
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def migration_name_fragment(self):
|
|
37
|
+
return f"enable_ttl_{self.model_name.lower()}"
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pgttl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python bindings for the PostgreSQL TTL extension
|
|
5
|
+
Author: Grant Jenks
|
|
6
|
+
Classifier: Development Status :: 4 - Beta
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Topic :: Database
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: psycopg>=3
|
|
12
|
+
Provides-Extra: django
|
|
13
|
+
Requires-Dist: Django>=5.2; extra == "django"
|
|
14
|
+
|
|
15
|
+
# PostgreSQL TTL: Automatic Row Expiration
|
|
16
|
+
|
|
17
|
+
`pg_ttl` is a PostgreSQL extension that supports time-to-live (TTL) on rows
|
|
18
|
+
in ordinary tables.
|
|
19
|
+
|
|
20
|
+
PostgreSQL is excellent at managing its own storage. Wouldn't it be nice
|
|
21
|
+
if applications could tell the database how long to keep individual rows
|
|
22
|
+
and then forget about expiration?
|
|
23
|
+
|
|
24
|
+
The design follows [SQLite TTL](https://github.com/grantjenks/sqlite-ttl):
|
|
25
|
+
the application sets a deadline on a row, and a native worker removes it
|
|
26
|
+
after the deadline. Existing table columns, indexes, and queries need not
|
|
27
|
+
change.
|
|
28
|
+
|
|
29
|
+
**Status:** Early development. Tested with PostgreSQL 16 and psycopg 3. This
|
|
30
|
+
is soft TTL, not a security deadline.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
Build the server extension using the matching PostgreSQL headers and PGXS:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
make PG_CONFIG=/path/to/pg_config
|
|
38
|
+
make PG_CONFIG=/path/to/pg_config install
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Configure these settings in `postgresql.conf` and restart PostgreSQL:
|
|
42
|
+
|
|
43
|
+
```conf
|
|
44
|
+
shared_preload_libraries = 'pg_ttl'
|
|
45
|
+
pg_ttl.databases = 'example'
|
|
46
|
+
pg_ttl.role = 'ttl_owner'
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Create the named database and non-superuser maintenance role first. Install
|
|
50
|
+
the extension and grant access to the trusted role as described in
|
|
51
|
+
[Installation and Deployment](docs/installation.md).
|
|
52
|
+
Workers start automatically for the configured databases on server startup.
|
|
53
|
+
|
|
54
|
+
## Quickstart
|
|
55
|
+
|
|
56
|
+
Connect to the configured database as the trusted table-owner role.
|
|
57
|
+
The extension's SQL functions live in the `pgttl` schema:
|
|
58
|
+
|
|
59
|
+
```sql
|
|
60
|
+
SET search_path = public, pgttl;
|
|
61
|
+
|
|
62
|
+
CREATE TABLE sessions (
|
|
63
|
+
id bigint PRIMARY KEY,
|
|
64
|
+
data text
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
SELECT ttl_enable('sessions');
|
|
68
|
+
|
|
69
|
+
BEGIN;
|
|
70
|
+
INSERT INTO sessions VALUES (42, 'temporary');
|
|
71
|
+
SELECT ttl_set('sessions', 42, 5);
|
|
72
|
+
COMMIT;
|
|
73
|
+
|
|
74
|
+
SELECT * FROM sessions;
|
|
75
|
+
-- 42 | temporary
|
|
76
|
+
|
|
77
|
+
-- Wait for expiration and maintenance.
|
|
78
|
+
SELECT * FROM sessions;
|
|
79
|
+
-- No rows.
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Renew a deadline by calling `ttl_set` again or remove it with `ttl_clear`.
|
|
83
|
+
Rows without a scheduled expiration remain in the table.
|
|
84
|
+
|
|
85
|
+
## Python Bindings
|
|
86
|
+
|
|
87
|
+
Install the Python bindings with pip:
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
pip install pgttl
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
The native extension must be installed and configured on the PostgreSQL
|
|
94
|
+
server. Use an existing psycopg connection:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import psycopg
|
|
98
|
+
import pgttl
|
|
99
|
+
|
|
100
|
+
with psycopg.connect("dbname=example user=ttl_owner", autocommit=True) as db:
|
|
101
|
+
pgttl.require(db)
|
|
102
|
+
db.execute("CREATE TABLE sessions (id bigint PRIMARY KEY, data text)")
|
|
103
|
+
pgttl.enable(db, "sessions")
|
|
104
|
+
with db.transaction():
|
|
105
|
+
db.execute("INSERT INTO sessions VALUES (%s, %s)", (42, "temporary"))
|
|
106
|
+
pgttl.set_ttl(db, "sessions", 42, 5)
|
|
107
|
+
|
|
108
|
+
print(pgttl.status(db))
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
No Python maintenance thread is needed. PostgreSQL owns expiration even
|
|
112
|
+
after the connection is closed.
|
|
113
|
+
|
|
114
|
+
## Features
|
|
115
|
+
|
|
116
|
+
- Automatic expiration on ordinary tables with integer, text or UUID keys.
|
|
117
|
+
- Transactional scheduling, renewal and clearing.
|
|
118
|
+
- Native deletion with ordinary SQL constraints and triggers.
|
|
119
|
+
- Bounded maintenance and health reporting.
|
|
120
|
+
- Explicit schema validation and acceptance.
|
|
121
|
+
- Optional transactional audit log with automatic retention.
|
|
122
|
+
- Optional Django instance helpers, migrations and system checks.
|
|
123
|
+
|
|
124
|
+
## Documentation
|
|
125
|
+
|
|
126
|
+
- [Installation and Deployment](docs/installation.md)
|
|
127
|
+
- [SQL API](docs/design.md)
|
|
128
|
+
- [Implementation Details](docs/implementation.md)
|
|
129
|
+
- [Python Bindings](docs/python.md)
|
|
130
|
+
|
|
131
|
+
## Related Work
|
|
132
|
+
|
|
133
|
+
[pg_ttl_index](https://pgxn.org/dist/pg_ttl_index/) offers automatic
|
|
134
|
+
expiration using a timestamp column and a configured retention interval.
|
|
135
|
+
[pg_cron](https://github.com/citusdata/pg_cron) can run scheduled DELETE
|
|
136
|
+
statements. [pg_partman](https://github.com/pgpartman/pg_partman) can remove
|
|
137
|
+
old time partitions efficiently.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
pgttl/__init__.py,sha256=n_hwGhe_DO7zpv2OSOIEnLAq73yTtc7-QP-oou2roNw,2966
|
|
2
|
+
pgttl/django/__init__.py,sha256=f8DdSuXbr_OmAPwEkEKN_mX4zpXH9LtOqNBji_-VqJs,1599
|
|
3
|
+
pgttl/django/apps.py,sha256=YfaZ5D3JbqnPLOEJZARoGGnfJnDMzWHEofZVkbhPLvg,255
|
|
4
|
+
pgttl/django/checks.py,sha256=0RYSnAf2Exv1aBCAhBDMx8_dRdIulB5FnDCw6p4LP7w,3988
|
|
5
|
+
pgttl/django/migrations.py,sha256=Gaug6HEjW7RYaH0vPHoiE1ANYZ33UiecOJmO765db7I,1441
|
|
6
|
+
pgttl-0.1.0.dist-info/METADATA,sha256=Yywd0AmMzfxGYL0rPsf6_ZDM7mnZdThJkATIOOZI_Jw,4031
|
|
7
|
+
pgttl-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
pgttl-0.1.0.dist-info/top_level.txt,sha256=qhVN_0MHEJYZrK0pBpB7Aamo39HDikBY52hPgmEBs7c,6
|
|
9
|
+
pgttl-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pgttl
|