45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
"""add account-name and audit-target query indexes
|
|
|
|
Production slow-query review found:
|
|
- account lookups by username scanned the accounts table;
|
|
- audit timeline lookups by target scanned audit_logs.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlalchemy as sa
|
|
from alembic import op
|
|
|
|
revision: str = "20261120_0102"
|
|
down_revision: str | None = "20261120_0101"
|
|
branch_labels: str | None = None
|
|
depends_on: str | None = None
|
|
|
|
INDEXES: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
|
("ix_accounts_username_id", "accounts", ("username", "id")),
|
|
("ix_audit_logs_target_id", "audit_logs", ("target", "id")),
|
|
)
|
|
|
|
|
|
def _indexes(table: str) -> set[str]:
|
|
inspector = sa.inspect(op.get_bind())
|
|
if not inspector.has_table(table):
|
|
return set()
|
|
return {
|
|
str(index["name"])
|
|
for index in inspector.get_indexes(table)
|
|
if index.get("name")
|
|
}
|
|
|
|
|
|
def upgrade() -> None:
|
|
for name, table, columns in INDEXES:
|
|
if name not in _indexes(table):
|
|
op.create_index(name, table, list(columns), unique=False)
|
|
|
|
|
|
def downgrade() -> None:
|
|
for name, table, _columns in reversed(INDEXES):
|
|
if name in _indexes(table):
|
|
op.drop_index(name, table_name=table)
|