cache_form_qualifiers.py 2.35 KB
# -*- coding: utf-8 -*-

from django.db import connection, transaction
from django.core.management.base import BaseCommand
from common.util import uniprint
from dictionary.lexeme_form_query import WHERE_CLAUSES, \
    attr_clauses_combinations, TABLE_FROM_CLAUSES
from dictionary.models import TableTemplate


class Command(BaseCommand):
    help = 'Cache form qualifiers for filtering'

    def handle(self, **options):
        create_forms()

VARIANT = '1'


def create_forms():
    cursor = connection.cursor()

    transaction.commit_unless_managed()
    transaction.enter_transaction_management()
    transaction.managed()

    cursor.execute('''truncate dictionary_lexemeformqualifier''')
    tts = TableTemplate.objects.filter(variant_id=VARIANT).prefetch_related(
        'attributes__values', 'cell_attributes__values')
    for tt in tts:
        uniprint('caching ending qualifiers for: %s' % tt.name)
        attr_clauses, cell_attr_combinations, tt_attr_combinations = \
            attr_clauses_combinations(tt)
        for tt_c in tt_attr_combinations:
            for cell_c in cell_attr_combinations:
                select_query = '''
                    select distinct l.id as lexeme_id,
                        kz.qualifier_id as qualifier_id
                    %s join kwalifikatory_zakonczen kz
                        on (z.id = kz.ending_id)
                    where %s and ''' % (TABLE_FROM_CLAUSES, WHERE_CLAUSES)
                select_query += ' and '.join(attr_clauses)
                cursor.execute('''
                    insert into dictionary_lexemeformqualifier
                        (lexeme_id, qualifier_id) (%s)''' % select_query,
                    (tt.id,) + tt_c + cell_c + cell_c)

    print 'caching other qualifiers'
    select_query = '''
        select l.id as lexeme_id, kl.qualifier_id as qualifier_id
        from leksemy l
            join kwalifikatory_leksemow kl on l.id = kl.lexeme_id
        union
        select o.l_id as lexeme_id, ko.qualifier_id as qualifier_id
        from odmieniasie o
            join kwalifikatory_odmieniasiow ko
                on o.id = ko.lexemeinflectionpattern_id
    '''
    cursor.execute('''
        insert into dictionary_lexemeformqualifier (lexeme_id, qualifier_id)
        (%s)''' % select_query)

    print 'commiting to database'
    transaction.commit()
    transaction.leave_transaction_management()