|
| 1 | +# Copyright 2026 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 | +# https://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 | + |
| 15 | +import contextlib |
| 16 | + |
| 17 | +from garf.core import query_editor |
| 18 | +from garf.executors import exceptions, execution_context |
| 19 | + |
| 20 | + |
| 21 | +def process_gquery( |
| 22 | + context: execution_context.ExecutionContext, |
| 23 | +) -> execution_context.ExecutionContext: |
| 24 | + for k, v in context.fetcher_parameters.items(): |
| 25 | + if isinstance(v, str) and v.startswith('gquery'): |
| 26 | + no_writer_context = context.model_copy(update={'writer': None}) |
| 27 | + try: |
| 28 | + _, alias, query = v.split(':', maxsplit=3) |
| 29 | + except ValueError: |
| 30 | + raise exceptions.GarfExecutorError( |
| 31 | + f'Incorrect gquery format, should be gquery:alias:query, got {v}' |
| 32 | + ) |
| 33 | + if alias == 'sqldb': |
| 34 | + from garf.executors import sql_executor |
| 35 | + |
| 36 | + gquery_executor = sql_executor.SqlAlchemyQueryExecutor( |
| 37 | + **context.fetcher_parameters |
| 38 | + ) |
| 39 | + elif alias == 'bq': |
| 40 | + from garf.executors import bq_executor |
| 41 | + |
| 42 | + gquery_executor = bq_executor.BigQueryExecutor( |
| 43 | + **context.fetcher_parameters |
| 44 | + ) |
| 45 | + else: |
| 46 | + raise exceptions.GarfExecutorError( |
| 47 | + f'Unsupported alias for gquery: {alias}' |
| 48 | + ) |
| 49 | + with contextlib.suppress(query_editor.GarfResourceError): |
| 50 | + query_spec = query_editor.QuerySpecification( |
| 51 | + text=query, args=context.query_parameters |
| 52 | + ).generate() |
| 53 | + if len(columns := [c for c in query_spec.column_names if c != '_']) > 1: |
| 54 | + raise exceptions.GarfExecutorError( |
| 55 | + f'Multiple columns in gquery: {columns}' |
| 56 | + ) |
| 57 | + res = gquery_executor.execute( |
| 58 | + query=query, title='gquery', context=no_writer_context |
| 59 | + ) |
| 60 | + context.fetcher_parameters[k] = res.to_list(row_type='scalar') |
| 61 | + return context |
0 commit comments