"""EXPLAIN the actual ORM history query on 10,000 rows, then roll back fixtures.""" from uuid import uuid4 from sqlalchemy import select from sqlalchemy.orm import Session from src.database import create_db_engine from src.models import User, Chat, Message from src.store import history_query from .fixtures import seed_messages def main(): engine = create_db_engine() try: with Session(engine) as session: user = User(username='explain_' + uuid4().hex[:12], display_name='Explain', password_hash='unused') session.add(user) session.flush() chat = Chat(title='Explain') session.add(chat) session.flush() seed_messages(session, chat.id, user.id) conn = session.connection() conn.exec_driver_sql('ANALYZE messages') boundary = session.execute(select(Message.created_at, Message.id).where( Message.chat_id == chat.id).order_by(Message.created_at, Message.id).offset(8999).limit(1)).one() after = (boundary.created_at.isoformat(), boundary.id) compiled = history_query(chat.id, 50, after).compile(dialect=engine.dialect) print('Dataset: 10000 messages; page after message 9000; ORM query; limit 51') for row in conn.exec_driver_sql('EXPLAIN (ANALYZE, BUFFERS) ' + str(compiled), compiled.params): print(row[0]) session.rollback() print('Synthetic data rolled back.') finally: engine.dispose() if __name__ == '__main__': main()