<commit_before># encoding: utf8
"""Small wrapper for access to the pokedex library's database."""
from __future__ import absolute_import

import os.path
import re

import pokedex.db
from pokedex.db import tables
from sqlalchemy.sql import func
from sqlalchemy import and_, or_, not_
from pylons import tmpl_context as c

from spline.lib.base import SQLATimerProxy


pokedex_session = None
pokedex_lookup = None

def connect(config):
    """Instantiates the `pokedex_session` and `pokedex_lookup` objects."""
    # DB session for everyone to use.
    # This uses the same timer proxy as the main engine, so Pokédex queries are
    # counted towards the db time in the footer
    global pokedex_session
    prefix = 'spline-pokedex.sqlalchemy.'
    config[prefix + 'proxy'] = config['spline._sqlalchemy_proxy']
    pokedex_session = pokedex.db.connect(
        engine_args=config, engine_prefix=prefix,
    )

    # Lookup object
    global pokedex_lookup
    pokedex_lookup = pokedex.lookup.PokedexLookup(
        # Keep our own whoosh index in the /data dir
        directory=os.path.join(config['pylons.cache_dir'],
                              'pokedex-index'),
        session=pokedex_session,
    )
    if not pokedex_lookup.index:
        pokedex_lookup.rebuild_index()


# Quick access to a few database objects
def get_by_identifier_query(table, identifier, query=None):
    """Returns a query to find a single row in the given table by identifier.

    Don't use this for Pokémon!  Use `pokemon_query(use_identifier=True)`,
    as it knows about forms.
    """

    identifier = identifier.lower()
    identifier = re.sub(u'[ _]+', u'-', identifier)
    identifier = re.sub(u'[\'.]', u'', identifier)

    query = pokedex_session.query(table).filter(
                table.identifier == identifier)

    return query

def get_by_name_query(table, name, query=None):
    """Returns a query to find a single row in the given table by name,
    ignoring case.

    Don't use this for Pokémon!  Use `pokemon_query()`, as it knows about
    forms.

    If query is given, it will be extended joined with table.name_table,
    otherwise table will be queried.
    """

    name = name.lower()

    if query is None:
        query = pokedex_session.query(table)

    query = query.join(table.names_table) \
        .filter(func.lower(table.names_table.name) == name)

    return query

def pokemon_query(name, form=None):
    """Returns a query that will look for the named Pokémon."""

    q = get_by_name_query(tables.Pokemon, name)

    if form:
        # If a form has been specified, it must match
        q = q.join(tables.Pokemon.unique_form) \
            .filter(tables.PokemonForm.form == form)
    else:
        # If there's NOT a form, just make sure we get a form base Pokémon
        # TODO wtf is this any() for?<commit_msg>Crashfix: Another pre-i18n condition lying around.<commit_after># encoding: utf8
"""Small wrapper for access to the pokedex library's database."""
from __future__ import absolute_import

import os.path
import re

import pokedex.db
from pokedex.db import tables
from sqlalchemy.sql import func
from sqlalchemy import and_, or_, not_
from pylons import tmpl_context as c

from spline.lib.base import SQLATimerProxy


pokedex_session = None
pokedex_lookup = None

def connect(config):
    """Instantiates the `pokedex_session` and `pokedex_lookup` objects."""
    # DB session for everyone to use.
    # This uses the same timer proxy as the main engine, so Pokédex queries are
    # counted towards the db time in the footer
    global pokedex_session
    prefix = 'spline-pokedex.sqlalchemy.'
    config[prefix + 'proxy'] = config['spline._sqlalchemy_proxy']
    pokedex_session = pokedex.db.connect(
        engine_args=config, engine_prefix=prefix,
    )

    # Lookup object
    global pokedex_lookup
    pokedex_lookup = pokedex.lookup.PokedexLookup(
        # Keep our own whoosh index in the /data dir
        directory=os.path.join(config['pylons.cache_dir'],
                              'pokedex-index'),
        session=pokedex_session,
    )
    if not pokedex_lookup.index:
        pokedex_lookup.rebuild_index()


# Quick access to a few database objects
def get_by_identifier_query(table, identifier, query=None):
    """Returns a query to find a single row in the given table by identifier.

    Don't use this for Pokémon!  Use `pokemon_query(use_identifier=True)`,
    as it knows about forms.
    """

    identifier = identifier.lower()
    identifier = re.sub(u'[ _]+', u'-', identifier)
    identifier = re.sub(u'[\'.]', u'', identifier)

    query = pokedex_session.query(table).filter(
                table.identifier == identifier)

    return query

def get_by_name_query(table, name, query=None):
    """Returns a query to find a single row in the given table by name,
    ignoring case.

    Don't use this for Pokémon!  Use `pokemon_query()`, as it knows about
    forms.

    If query is given, it will be extended joined with table.name_table,
    otherwise table will be queried.
    """

    name = name.lower()

    if query is None:
        query = pokedex_session.query(table)

    query = query.join(table.names_table) \
        .filter(func.lower(table.names_table.name) == name)

    return query

def pokemon_query(name, form=None):
    """Returns a query that will look for the named Pokémon."""

    q = get_by_name_query(tables.Pokemon, name)

    if form:
        # If a form has been specified, it must match
        q = q.join(tables.Pokemon.unique_form) \
            .join(tables.PokemonForm.names_local) \
            .filter(func.lower(tables.PokemonForm.names_table.name) == form)
    else:
        # If there's NOT a form, just make sure we get a form base Pokémon
        # TODO wtf is this any() for?
{'fraction_non_alphanumeric': 0.0909404659188956, 'fraction_numerical': 0.0006902502157031924, 'mean_word_length': 3.0588235294117645, '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': '1840465', 'n_tokens_mistral': 1814, 'n_tokens_neox': 1742, 'n_words': 577}