• Oleg Smirnov's avatar
    MDEV-29681 Server crashes when optimizing SQL with ORDER BY · 28cdbab1
    Oleg Smirnov authored
    When parsing statements like (SELECT .. FROM ..) ORDER BY <expr>,
    there is a step LEX::add_tail_to_query_expression_body_ext_parens()
    which calls LEX::wrap_unit_into_derived(). After that the statement
    looks like SELECT * FROM (SELECT .. FROM ..), and parser's
    Lex_order_limit_lock structure (ORDER BY <expr>) is assigned to
    the new SELECT. But what is missing here is that Items in
    Lex_order_limit_lock are left with their original name resolution
    contexts, and fix_fields() later resolves the names incorrectly.
    
    For example, when processing
      (SELECT * FROM t1 JOIN t2 ON a=b) ORDER BY a
    Item_field 'a' in the ORDER BY clause is left with the name resolution
    context of the derived table (first_name_resolution_table='t1'), so
    it is resolved to 't1.a', which is incorrect.
    After LEX::wrap_unit_into_derived() the statement looks like
      SELECT * FROM (SELECT * FROM t1 JOIN t2 ON a=b) AS '__2' ORDER BY a,
    and the name resolution context for Item_field 'a' in the ORDER BY
    must be set to the wrapping SELECT's one.
    
    This commit fixes the issue by changing context for Items in
    Lex_order_limit_lock after LEX::wrap_unit_into_derived().
    28cdbab1
order_by.result 98.2 KB