sless-primer/POSTGRES/code/pg-counter/pg_counter.py
2026-03-22 17:08:18 +04:00

24 lines
1.1 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-counter: считает строки по prefix, возвращает статистику.
# Тестирует: SELECT COUNT с WHERE LIKE, агрегация, concurrent reads.
import os, psycopg2
def count(event):
prefix = 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() as cur:
if prefix:
cur.execute("SELECT COUNT(*) FROM terraform_demo_table WHERE title LIKE %s", (f"{prefix}%",))
else:
cur.execute("SELECT COUNT(*) FROM terraform_demo_table")
total = cur.fetchone()[0]
cur.execute("SELECT COUNT(*) FROM terraform_demo_table WHERE created_at > now() - interval '1 hour'")
last_hour = cur.fetchone()[0]
return {"total": total, "last_hour": last_hour, "prefix": prefix or "*"}
finally:
conn.close()