forked from mtusi2026/mtusi2026lab2
66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Seed ≥10k messages and print EXPLAIN (ANALYZE, BUFFERS) for keyset page query."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
# Allow running against a live API + direct DB for EXPLAIN.
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from app.config import settings # noqa: E402
|
|
from app.db import Database # noqa: E402
|
|
from app.models import Chat, Message, User # noqa: E402
|
|
from app.password import hash_password # noqa: E402
|
|
from app.timefmt import now_utc # noqa: E402
|
|
|
|
|
|
def main() -> int:
|
|
count = int(os.environ.get("EXPLAIN_MESSAGES", "10000"))
|
|
db = Database()
|
|
db.open()
|
|
user = User(
|
|
id=str(uuid.uuid4()),
|
|
username="explain_" + uuid.uuid4().hex[:10],
|
|
display_name="Explain",
|
|
created_at=now_utc(),
|
|
password_hash=hash_password("Explain-password-12"),
|
|
)
|
|
db.add_user(user)
|
|
chat = Chat(
|
|
id=str(uuid.uuid4()),
|
|
title="EXPLAIN chat",
|
|
member_ids=[user.id],
|
|
created_at=now_utc(),
|
|
)
|
|
db.add_chat(chat)
|
|
for i in range(count):
|
|
db.add_message(
|
|
Message(
|
|
id=str(uuid.uuid4()),
|
|
chat_id=chat.id,
|
|
sender_id=user.id,
|
|
text="bulk-%d" % i,
|
|
created_at=now_utc(),
|
|
)
|
|
)
|
|
if (i + 1) % 2000 == 0:
|
|
print("inserted", i + 1, flush=True)
|
|
plan = db.explain_messages_page(chat.id, limit=50)
|
|
out = ROOT / "evidence" / "explain.txt"
|
|
out.write_text(
|
|
"chat_id=%s messages=%d\n\n%s\n" % (chat.id, count, plan),
|
|
encoding="utf-8",
|
|
)
|
|
print(plan)
|
|
print("wrote", out)
|
|
db.close()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|