<commit_before>from __future__ import absolute_import
from __future__ import unicode_literals

from corehq.apps.locations.models import LocationType, SQLLocation


def build_location_filters(location_id):
    try:
        location = SQLLocation.objects.get(location_id=location_id)
    except SQLLocation.DoesNotExist:
        return {'state_id': 'ALL'}

    location_ancestors = location.get_ancestors(include_self=True)

    filters = {
        "{}_id".format(ancestor.location_type.code): ancestor.location_id
        for ancestor in location_ancestors
    }

    location_type = location.location_type
    child_location_type = LocationType.objects.filter(domain=location_type.domain, parent_type=location_type)
    filters["{}_id".format(child_location_type.code)] = 'All'

    return filters<commit_msg>Create easy explanations for aggregation queries<commit_after>from __future__ import absolute_import
from __future__ import unicode_literals

from django.db import connections

from corehq.apps.locations.models import LocationType, SQLLocation
from custom.aaa.models import AggAwc, AggVillage, CcsRecord, Child, Woman


def build_location_filters(location_id):
    try:
        location = SQLLocation.objects.get(location_id=location_id)
    except SQLLocation.DoesNotExist:
        return {'state_id': 'ALL'}

    location_ancestors = location.get_ancestors(include_self=True)

    filters = {
        "{}_id".format(ancestor.location_type.code): ancestor.location_id
        for ancestor in location_ancestors
    }

    location_type = location.location_type
    child_location_type = LocationType.objects.filter(domain=location_type.domain, parent_type=location_type)
    filters["{}_id".format(child_location_type.code)] = 'All'

    return filters


def explain_aggregation_queries(domain, window_start, window_end):
    queries = {}
    for cls in (AggAwc, AggVillage, CcsRecord, Child, Woman):
        for agg_query in cls.aggregation_queries:
            explanation = _explain_query(cls, agg_query, domain, window_start, window_end)
            queries[explanation[0]] = explanation[1]

    return queries


def _explain_query(cls, method, domain, window_start, window_end):
    agg_query, agg_params = method(domain, window_start, window_end)
    with connections['aaa-data'].cursor() as cursor:
        cursor.execute('explain ' + agg_query, agg_params)
        return cls.__name__ + method.__name__, cursor.fetchall()
{'fraction_non_alphanumeric': 0.08692086920869209, 'fraction_numerical': 0.0008200082000820008, 'mean_word_length': 4.5580865603644645, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1832109', 'n_tokens_mistral': 742, 'n_tokens_neox': 723, 'n_words': 147}