"""
Practice: indexes. Lab 04's arithmetic for script 03_indexes.py: how much faster an index made
a query, what it cost inserts, what the single costs predict when indexes are kept together,
and the rules that decide whether an index can serve a query (column order, sort order,
covering).

Fill in the TODOs, then run the tests:
    pytest test_index_practice.py        (locally)
or press "Run tests" on the chapter page.
"""


def speedup(base_ms, ms):
    """How many times faster `ms` is than `base_ms` (the time with no index).
    Below 1 means the index made the query slower."""
    return base_ms / ms


def table_mb(pages, page_bytes=8192):
    """A table's size in MB (1 MB = 1,000,000 bytes) from its page count."""
    return pages * page_bytes / 1e6


def insert_cost(base_rate, rate):
    """The change in inserts a second an index caused, as a fraction of the no-index rate:
    rate / base_rate - 1 (negative: fewer inserts a second)."""
    return rate / base_rate - 1


def added_up_rate(base_rate, single_rates):
    """Inserts a second you'd expect with several indexes at once if their costs simply added up.
    Each index alone adds (1 / its rate - 1 / base_rate) seconds to every insert; add those extra
    times to one insert's base time (1 / base_rate) and turn the total back into a rate."""
    per_insert = 1 / base_rate + sum(1 / r - 1 / base_rate for r in single_rates)
    return 1 / per_insert


def narrowing_columns(index_cols, equals, range_col=None):
    """How many of the index's leading columns narrow the search for a query that matches the
    columns in `equals` exactly and (optionally) asks for a range of `range_col`.
    Walk the index columns in order: each column in `equals` counts and the walk continues;
    `range_col` counts and the walk stops (the entries after a range aren't grouped any more);
    any other column stops the walk."""
    n = 0
    for col in index_cols:
        if col in equals:
            n += 1
        elif col == range_col:
            return n + 1
        else:
            break
    return n


def gives_order(index_cols, equals, sort_col):
    """True if, after jumping to the rows that match `equals`, the index hands them back already
    sorted by `sort_col`: the first index column not in `equals` is `sort_col`."""
    for col in index_cols:
        if col not in equals:
            return col == sort_col
    return False


def covers(index_cols, included, needed):
    """True if every column the query needs is in the index (its key columns or its INCLUDE
    columns), so Postgres can answer from the index alone (an Index Only Scan)."""
    return set(needed) <= set(index_cols) | set(included)


def fastest(times):
    """The name of the fastest index in a dict {index name: median ms}."""
    return min(times, key=times.get)
