lexeme_form_query.py 2.46 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 dictionary_tabletemplate tt
    on tt.id = %s
join dictionary_tabletemplate_pattern_types tt_pt
    on (w.typ = tt_pt.patterntype_id and tt.id = tt_pt.tabletemplate_id)
join dictionary_tabletemplate_parts_of_speech tt_pos
    on (tt.id = tt_pos.tabletemplate_id and
        l.pos = tt_pos.partofspeech_id)'''

TABLE_CLAUSES = '''
join dictionary_tablecell cell
    on tt.id = cell.table_template_id
join dictionary_tablecell_pattern_types cell_pt
    on (cell.id = cell_pt.tablecell_id and w.typ = cell_pt.patterntype_id)
left join dictionary_tablecell_genders cell_g
    on cell.id = cell_g.tablecell_id
join zakonczenia z
    on (o.w_id = z.w_id and cell.base_form_label_id = z.efobaz)
'''

EXPORT_CLAUSES = '''
join dictionary_exportcell cell
    on tt.id = cell.table_template_id
join dictionary_exportcell_pattern_types cell_pt
    on (cell.id = cell_pt.exportcell_id and w.typ = cell_pt.patterntype_id)
left join dictionary_exportcell_genders cell_g
    on cell.id = cell_g.exportcell_id
join zakonczenia z
    on (o.w_id = z.w_id and cell.base_form_label_id = z.efobaz)
'''

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 _ in xrange(len(tt_attrs) + len(cell_attrs))]
    attr_clauses += ['''
            %s in (select lexemeattributevalue_id from
            dictionary_tablecell_attribute_values cell_attr_val
            where cell_attr_val.tablecell_id = cell.id)'''
        for _ in cell_attrs]
    if not attr_clauses:
        attr_clauses = ['true']
    return attr_clauses, cell_attr_combinations, tt_attr_combinations