|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import dataclasses |
| 17 | +import functools |
| 18 | +import typing |
| 19 | + |
| 20 | +import google.cloud.bigquery as bigquery |
| 21 | +import sqlglot.expressions as sge |
| 22 | + |
| 23 | +from bigframes.core import expression, nodes, rewrite |
| 24 | +from bigframes.core.compile import configs |
| 25 | +from bigframes.core.compile.sqlglot import sql_gen |
| 26 | +import bigframes.core.ordering as bf_ordering |
| 27 | + |
| 28 | + |
| 29 | +@dataclasses.dataclass(frozen=True) |
| 30 | +class SQLGlotCompiler: |
| 31 | + """Compiles BigFrame nodes into SQL using SQLGlot.""" |
| 32 | + |
| 33 | + sql_gen = sql_gen.SQLGen() |
| 34 | + |
| 35 | + def compile( |
| 36 | + self, |
| 37 | + node: nodes.BigFrameNode, |
| 38 | + *, |
| 39 | + ordered: bool = True, |
| 40 | + limit: typing.Optional[int] = None, |
| 41 | + ) -> str: |
| 42 | + """Compile node into sql where rows are sorted with ORDER BY.""" |
| 43 | + request = configs.CompileRequest(node, sort_rows=ordered, peek_count=limit) |
| 44 | + return self._compile_sql(request).sql |
| 45 | + |
| 46 | + def compile_raw( |
| 47 | + self, |
| 48 | + node: nodes.BigFrameNode, |
| 49 | + ) -> typing.Tuple[ |
| 50 | + str, typing.Sequence[bigquery.SchemaField], bf_ordering.RowOrdering |
| 51 | + ]: |
| 52 | + """Compile node into sql that exposes all columns, including hidden |
| 53 | + ordering-only columns.""" |
| 54 | + request = configs.CompileRequest( |
| 55 | + node, sort_rows=False, materialize_all_order_keys=True |
| 56 | + ) |
| 57 | + result = self._compile_sql(request) |
| 58 | + assert result.row_order is not None |
| 59 | + return result.sql, result.sql_schema, result.row_order |
| 60 | + |
| 61 | + def _compile_sql(self, request: configs.CompileRequest) -> configs.CompileResult: |
| 62 | + output_names = tuple( |
| 63 | + (expression.DerefOp(id), id.sql) for id in request.node.ids |
| 64 | + ) |
| 65 | + result_node = nodes.ResultNode( |
| 66 | + request.node, |
| 67 | + output_cols=output_names, |
| 68 | + limit=request.peek_count, |
| 69 | + ) |
| 70 | + if request.sort_rows: |
| 71 | + # Can only pullup slice if we are doing ORDER BY in outermost SELECT |
| 72 | + # Need to do this before replacing unsupported ops, as that will rewrite slice ops |
| 73 | + result_node = rewrite.pull_up_limits(result_node) |
| 74 | + result_node = _replace_unsupported_ops(result_node) |
| 75 | + # prune before pulling up order to avoid unnnecessary row_number() ops |
| 76 | + result_node = typing.cast(nodes.ResultNode, rewrite.column_pruning(result_node)) |
| 77 | + result_node = rewrite.defer_order( |
| 78 | + result_node, output_hidden_row_keys=request.materialize_all_order_keys |
| 79 | + ) |
| 80 | + if request.sort_rows: |
| 81 | + result_node = typing.cast( |
| 82 | + nodes.ResultNode, rewrite.column_pruning(result_node) |
| 83 | + ) |
| 84 | + sql = self._compile_result_node(result_node) |
| 85 | + return configs.CompileResult( |
| 86 | + sql, result_node.schema.to_bigquery(), result_node.order_by |
| 87 | + ) |
| 88 | + |
| 89 | + ordering: typing.Optional[bf_ordering.RowOrdering] = result_node.order_by |
| 90 | + result_node = dataclasses.replace(result_node, order_by=None) |
| 91 | + result_node = typing.cast(nodes.ResultNode, rewrite.column_pruning(result_node)) |
| 92 | + sql = self._compile_result_node(result_node) |
| 93 | + # Return the ordering iff no extra columns are needed to define the row order |
| 94 | + if ordering is not None: |
| 95 | + output_order = ( |
| 96 | + ordering |
| 97 | + if ordering.referenced_columns.issubset(result_node.ids) |
| 98 | + else None |
| 99 | + ) |
| 100 | + assert (not request.materialize_all_order_keys) or (output_order is not None) |
| 101 | + return configs.CompileResult( |
| 102 | + sql, result_node.schema.to_bigquery(), output_order |
| 103 | + ) |
| 104 | + |
| 105 | + def _compile_result_node(self, root: nodes.ResultNode) -> str: |
| 106 | + sqlglot_expr = compile_node(root.child) |
| 107 | + # TODO: add order_by, limit, and selections to sqlglot_expr |
| 108 | + return self.sql_gen.sql(sqlglot_expr) |
| 109 | + |
| 110 | + |
| 111 | +def _replace_unsupported_ops(node: nodes.BigFrameNode): |
| 112 | + node = nodes.bottom_up(node, rewrite.rewrite_slice) |
| 113 | + node = nodes.bottom_up(node, rewrite.rewrite_timedelta_expressions) |
| 114 | + node = nodes.bottom_up(node, rewrite.rewrite_range_rolling) |
| 115 | + return node |
| 116 | + |
| 117 | + |
| 118 | +@functools.lru_cache(maxsize=5000) |
| 119 | +def compile_node(node: nodes.BigFrameNode) -> sge.Expression: |
| 120 | + """Compile node into CompileArrayValue. Caches result.""" |
| 121 | + return node.reduce_up(lambda node, children: _compile_node(node, *children)) |
| 122 | + |
| 123 | + |
| 124 | +@functools.singledispatch |
| 125 | +def _compile_node( |
| 126 | + node: nodes.BigFrameNode, *compiled_children: sge.Expression |
| 127 | +) -> sge.Expression: |
| 128 | + """Defines transformation but isn't cached, always use compile_node instead""" |
| 129 | + raise ValueError(f"Can't compile unrecognized node: {node}") |
| 130 | + |
| 131 | + |
| 132 | +@_compile_node.register |
| 133 | +def compile_readlocal(node: nodes.ReadLocalNode, *args) -> sge.Expression: |
| 134 | + # TODO: add support for reading from local files |
| 135 | + return sge.select() |
| 136 | + |
| 137 | + |
| 138 | +@_compile_node.register |
| 139 | +def compile_selection(node: nodes.SelectionNode, child: sge.Expression): |
| 140 | + # TODO: add support for selection |
| 141 | + return child |
0 commit comments