@@ -1728,32 +1728,27 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
17281728 } else {
17291729 match ( var_names. pop ( ) , var_names. pop ( ) ) {
17301730 ( Some ( name) , Some ( relation) ) if var_names. is_empty ( ) => {
1731- match schema. field_with_qualified_name ( & relation, & name) {
1731+ match schema. field_with_qualified_name ( & relation, & name) {
17321732 Ok ( _) => {
17331733 // found an exact match on a qualified name so this is a table.column identifier
17341734 Ok ( Expr :: Column ( Column {
17351735 relation : Some ( relation) ,
17361736 name,
17371737 } ) )
17381738 } ,
1739- Err ( e) => {
1740- let search_term = format ! ( ".{}.{}" , relation, name) ;
1741- if schema. field_names ( ) . iter ( ) . any ( |name| name. as_str ( ) . ends_with ( & search_term) ) {
1742- // this could probably be improved but here we handle the case
1743- // where the qualifier is only a partial qualifier such as when
1744- // referencing "t1.foo" when the available field is "public.t1.foo"
1745- Ok ( Expr :: Column ( Column {
1746- relation : Some ( relation) ,
1747- name,
1748- } ) )
1749- } else if let Some ( field) = schema. fields ( ) . iter ( ) . find ( |f| f. name ( ) . eq ( & relation) ) {
1739+ Err ( _) => {
1740+ if let Some ( field) = schema. fields ( ) . iter ( ) . find ( |f| f. name ( ) . eq ( & relation) ) {
17501741 // Access to a field of a column which is a structure, example: SELECT my_struct.key
17511742 Ok ( Expr :: GetIndexedField {
17521743 expr : Box :: new ( Expr :: Column ( field. qualified_column ( ) ) ) ,
17531744 key : ScalarValue :: Utf8 ( Some ( name) ) ,
17541745 } )
17551746 } else {
1756- Err ( e)
1747+ // table.column identifier
1748+ Ok ( Expr :: Column ( Column {
1749+ relation : Some ( relation) ,
1750+ name,
1751+ } ) )
17571752 }
17581753 }
17591754 }
@@ -4819,6 +4814,21 @@ mod tests {
48194814 quick_test ( sql, expected) ;
48204815 }
48214816
4817+ #[ test]
4818+ fn order_by_unaliased_name ( ) {
4819+ // https://github.com/apache/arrow-datafusion/issues/3160
4820+ // This query was failing with:
4821+ // SchemaError(FieldNotFound { qualifier: Some("p"), name: "state", valid_fields: Some(["z", "q"]) })
4822+ let sql = "select p.state z, sum(age) q from person p group by p.state order by p.state" ;
4823+ let expected = "Projection: #z, #q\
4824+ \n Sort: #p.state ASC NULLS LAST\
4825+ \n Projection: #p.state AS z, #SUM(p.age) AS q, #p.state\
4826+ \n Aggregate: groupBy=[[#p.state]], aggr=[[SUM(#p.age)]]\
4827+ \n SubqueryAlias: p\
4828+ \n TableScan: person";
4829+ quick_test ( sql, expected) ;
4830+ }
4831+
48224832 #[ test]
48234833 fn test_zero_offset_with_limit ( ) {
48244834 let sql = "select id from person where person.id > 100 LIMIT 5 OFFSET 0;" ;
0 commit comments