lexeme_form_query.py 2.18 KB
# -*- coding: utf-8 -*-

FROM_CLAUSES = '''
from leksemy l
join odmieniasie o on l.id = o.l_id
join wzory w on (o.w_id = w.id)
join tables_tabletemplate tt
    on tt.id = %%s
join tables_tabletemplate_pattern_types tt_pt
    on (w.typ = tt_pt.patterntype_id and tt.id = tt_pt.tabletemplate_id)
join tables_tabletemplate_parts_of_speech tt_pos
    on (tt.id = tt_pos.tabletemplate_id and
        l.pos = tt_pos.partofspeech_id)
join tables_%(type)scell cell
    on tt.id = cell.table_template_id
join tables_%(type)scell_pattern_types cell_pt
    on (cell.id = cell_pt.%(type)scell_id and w.typ = cell_pt.patterntype_id)
left join tables_%(type)scell_genders cell_g
    on cell.id = cell_g.%(type)scell_id
join zakonczenia z
    on (o.w_id = z.w_id and cell.base_form_label_id = z.efobaz)
'''

TABLE_FROM_CLAUSES = FROM_CLAUSES % {'type': 'table'}

EXPORT_FROM_CLAUSES = FROM_CLAUSES % {'type': 'export'}

WHERE_CLAUSES = '(not tt.takes_gender or cell_g.gender_id = o.gender_id)'


def value_combinations(attributes, attr_vals=None):
    if len(attributes) == 0:
        yield ()
        return
    combinations1 = value_combinations(attributes[1:])
    attr_values = attributes[0].values.all()
    for c in combinations1:
        for val in attr_values:
            if attr_vals is None or val in attr_vals:
                yield (val.id,) + c


def attr_clauses_combinations(tt):
    tt_attrs = list(tt.attributes.all())
    tt_attr_vals = set(tt.attribute_values.all())
    cell_attrs = list(tt.cell_attributes.all())
    tt_attr_combinations = value_combinations(tt_attrs, tt_attr_vals)
    cell_attr_combinations = value_combinations(cell_attrs)
    attr_clauses = [
        '''%s in (select lav.attribute_value_id from dictionary_lexemeav lav
        where lav.lexeme_id = l.id)'''
        for i in xrange(len(tt_attrs) + len(cell_attrs))]
    attr_clauses += [
        '''%%s in (select lexemeattributevalue_id from
        tables_%(type)scell_attribute_values cell_attr_val
        where cell_attr_val.%(type)scell_id = cell.id)''' %
        {'type': tt.variant.type}
        for i in cell_attrs]
    if not attr_clauses:
        attr_clauses = ['true']
    return attr_clauses, list(cell_attr_combinations), tt_attr_combinations