|
23 | 23 | import bigframes_vendored.ibis.expr.datatypes as ibis_dtypes |
24 | 24 | import bigframes_vendored.ibis.expr.operations as ibis_ops |
25 | 25 | import bigframes_vendored.ibis.expr.types as ibis_types |
| 26 | +import bigframes_vendored.sqlglot.expressions as sge |
26 | 27 | from google.cloud import bigquery |
27 | 28 | import pyarrow as pa |
28 | 29 |
|
29 | 30 | from bigframes.core import agg_expressions, rewrite |
30 | 31 | import bigframes.core.agg_expressions as ex_types |
31 | | -import bigframes.core.compile.googlesql |
32 | 32 | import bigframes.core.compile.ibis_compiler.aggregate_compiler as agg_compiler |
33 | 33 | import bigframes.core.compile.ibis_compiler.scalar_op_compiler as op_compilers |
34 | 34 | import bigframes.core.compile.ibis_types |
| 35 | +import bigframes.core.compile.sqlglot.sqlglot_ir as sqlglot |
35 | 36 | import bigframes.core.expression as ex |
36 | 37 | from bigframes.core.ordering import OrderingExpression |
37 | 38 | import bigframes.core.sql |
@@ -82,13 +83,21 @@ def to_sql( |
82 | 83 | ) |
83 | 84 |
|
84 | 85 | if order_by or limit or not is_noop_selection: |
85 | | - sql = ibis_bigquery.Backend().compile(ibis_table) |
86 | | - sql = ( |
87 | | - bigframes.core.compile.googlesql.Select() |
88 | | - .from_(sql) |
89 | | - .select(selection_strings) |
90 | | - .sql() |
91 | | - ) |
| 86 | + # selections are (ref.id.sql, name) where ref.id.sql is escaped identifier |
| 87 | + to_select = [ |
| 88 | + sge.Alias( |
| 89 | + this=sge.to_identifier(src, quoted=False), |
| 90 | + alias=sge.to_identifier(alias, quoted=True), |
| 91 | + ) |
| 92 | + if src != alias |
| 93 | + else sge.to_identifier(src, quoted=False) |
| 94 | + for src, alias in selection_strings |
| 95 | + ] |
| 96 | + # Use string formatting for FROM clause to avoid re-parsing potentially complex SQL (like ARRAY<STRUCT<...>>) |
| 97 | + # that sqlglot might not handle perfectly when parsing BigQuery dialect strings. |
| 98 | + select_sql = sge.Select().select(*to_select).sql(dialect="bigquery") |
| 99 | + ibis_sql = ibis_bigquery.Backend().compile(ibis_table) |
| 100 | + sql = f"{select_sql} FROM ({ibis_sql}) AS `t`" |
92 | 101 |
|
93 | 102 | # Single row frames may not have any ordering columns |
94 | 103 | if len(order_by) > 0: |
|
0 commit comments