sless-primer/POSTGRES/code/pg-delete-old/pg_delete_old.py
2026-03-22 17:08:18 +04:00

34 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 2026-03-21 — pg-delete-old: удаляет строки старше N минут (default 60).
# Тестирует: DELETE с RETURNING, идемпотентность (повторный вызов = 0 удалений если нет старых).
import os, psycopg2, psycopg2.extras
def delete_old(event):
older_than_min = max(int(event.get("older_than_min", 60)), 1)
prefix_filter = event.get("prefix", "")
conn = psycopg2.connect(
host=os.environ["PGHOST"], port=int(os.environ.get("PGPORT", 5432)),
dbname=os.environ["PGDATABASE"], user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"], sslmode=os.environ.get("PGSSLMODE", "require"),
)
try:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
if prefix_filter:
cur.execute(
"DELETE FROM terraform_demo_table "
"WHERE created_at < now() - interval '1 minute' * %s "
"AND title LIKE %s RETURNING id, title",
(older_than_min, f"{prefix_filter}%"),
)
else:
cur.execute(
"DELETE FROM terraform_demo_table "
"WHERE created_at < now() - interval '1 minute' * %s RETURNING id, title",
(older_than_min,),
)
deleted = [dict(r) for r in cur.fetchall()]
conn.commit()
return {"deleted": len(deleted), "older_than_min": older_than_min, "sample": deleted[:5]}
finally:
conn.close()