@@ -1031,31 +1031,42 @@ def _reproject_to_table(self) -> OrderedIR:
1031
1031
1032
1032
def to_sql (
1033
1033
self ,
1034
- offset_column : typing .Optional [str ] = None ,
1035
1034
col_id_overrides : typing .Mapping [str , str ] = {},
1036
1035
sorted : bool = False ,
1037
1036
) -> str :
1038
- offsets_id = offset_column or ORDER_ID_COLUMN
1039
-
1040
1037
sql = ibis_bigquery .Backend ().compile (
1041
1038
self ._to_ibis_expr (
1042
- ordering_mode = "offset_col"
1043
- if (offset_column or sorted )
1044
- else "unordered" ,
1045
- order_col_name = offsets_id ,
1039
+ ordering_mode = "unordered" ,
1046
1040
col_id_overrides = col_id_overrides ,
1041
+ expose_hidden_cols = sorted ,
1047
1042
)
1048
1043
)
1049
1044
if sorted :
1045
+ output_columns = [
1046
+ col_id_overrides .get (col ) if (col in col_id_overrides ) else col
1047
+ for col in self .column_ids
1048
+ ]
1049
+ selection = ", " .join (map (lambda col_id : f"`{ col_id } `" , output_columns ))
1050
+ order_by_clause = self ._ordering_clause (self ._ordering .all_ordering_columns )
1051
+
1050
1052
sql = textwrap .dedent (
1051
- f"SELECT * EXCEPT (` { offsets_id } `) \n "
1053
+ f"SELECT { selection } \n "
1052
1054
"FROM (\n "
1053
1055
f"{ sql } \n "
1054
1056
")\n "
1055
- f"ORDER BY ` { offsets_id } ` \n "
1057
+ f"{ order_by_clause } \n "
1056
1058
)
1057
1059
return typing .cast (str , sql )
1058
1060
1061
+ def _ordering_clause (self , ordering : Iterable [OrderingColumnReference ]) -> str :
1062
+ parts = []
1063
+ for col_ref in ordering :
1064
+ asc_desc = "ASC" if col_ref .direction .is_ascending else "DESC"
1065
+ null_clause = "NULLS LAST" if col_ref .na_last else "NULLS FIRST"
1066
+ part = f"`{ col_ref .column_id } ` { asc_desc } { null_clause } "
1067
+ parts .append (part )
1068
+ return f"ORDER BY { ' ,' .join (parts )} "
1069
+
1059
1070
def _to_ibis_expr (
1060
1071
self ,
1061
1072
* ,
0 commit comments