**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


query_info.prewhere_info->alias_actions = std::make_shared<ExpressionActions>(prewhere_info->alias_actions);
            if (prewhere_info->remove_columns_actions)
                query_info.prewhere_info->remove_columns_actions = std::make_shared<ExpressionActions>(prewhere_info->remove_columns_actions);
            query_info.prewhere_info->remove_prewhere_column = prewhere_info->remove_prewhere_column;
            query_info.prewhere_info->need_filter = prewhere_info->need_filter;
        }
        
        
        if (analysis_result.optimize_read_in_order || analysis_result.optimize_aggregation_in_order)
        {
            if (analysis_result.optimize_read_in_order)
                query_info.order_optimizer = std::make_shared<ReadInOrderOptimizer>(
                    analysis_result.order_by_elements_actions,
                    getSortDescription(query, *context),
                    query_info.syntax_analyzer_result);
            else
                query_info.order_optimizer = std::make_shared<ReadInOrderOptimizer>(
                    analysis_result.group_by_elements_actions,
                    getSortDescriptionFromGroupBy(query),
                    query_info.syntax_analyzer_result);
            query_info.input_order_info = query_info.order_optimizer->getInputOrder(metadata_snapshot, *context);
        }
        StreamLocalLimits limits;
        SizeLimits leaf_limits;
        std::shared_ptr<const EnabledQuota> quota;
        
        if (!options.ignore_limits)
        {
            limits = getLimitsForStorage(settings, options);
            leaf_limits = SizeLimits(settings.max_rows_to_read_leaf, settings.max_bytes_to_read_leaf,