I think you are reading that wrong. That section identifies 4 broad things that may be used as an orderby_item. Specifically on point here are the last 2:
3. A general_identification_variable that evaluates to the same map field of the same entity or embeddable abstract schema type as a general_identification_variable in the SELECT clause
4. A result_variable that refers to an orderable item in the SELECT clause for which the same result_variable has been specified. This may be the result of an aggregate_expression, a scalar_expression, or a state_field_path_expression in the SELECT clause.
(4) talks about a from clause alias. (3) talks about a select clause alias. Both are valid options as an orderBY_item.
select a from A as a order by a
select a.something+1 as b from A as a order by b
No where in this "Query Language" chapter (that I have ever seen) does it talk about collisions.
Now we could just "pick one" to take precedence. But the bottom line is that queries that have such alias collisions are ambiguous. That's what this issue is about right now... to discuss our options. But it flat out is ambiguous.
And btw, its not just limited to order-by. I think y'all are just being reactive to specific queries I happen to use to illustrate the problems this causes. Stop and think about the bigger picture of interpreting the meaning of these queries.
As I see it we can either allow the collision (so long as it does not occur within the same clause) or throw an exception. Andrea's linked PR takes the stance of don't allow it and throw an exception. The alternative to that is to allow it (possibly after a warning) but that means resolving the ambiguity. There are 2 strategies for that:
-
Pick a precedence. The most likely would seem to be to prefer any select-clause aliases. Think of this as a Map. Since we process the from-clause first, those become the base values (with the alias as the key). As we process the select clause any "collisions" would simply overwrite the previous entry.
-
Apply a more contextual resolution. This one is harder to explain. For order-by, I think we'd still just prefer the select alias if one. For usage in predicates... this is where it gets harder. Imagine a query like:
select a.something as a from A a where a+1 = 2
Obviously the a in a+1 more likely refers to the select clause alias since we can safely assume that "some entity plus 1" probably makes no sense.
To me that "contextual resolution" is just asking for problems. Ultimately, I see the workable solutions as: 1) Don't allow collisions. Throw an exception. This is what Andrea's PR does. 2) Maintain a select-clause-scoped alias registry that is preferred for resolving simple IDENTIFIER expressions. Here we'd allow the collisions, but have an explicit "precedence" for resolving the ambiguity (select clause alias would win).
Let's just vote? Unless someone has another compelling strategy I may be missing.
|