|
| 1 | +# |
| 2 | +# MIT License |
| 3 | +# |
| 4 | +# Copyright (c) 2020 Airbyte |
| 5 | +# |
| 6 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +# of this software and associated documentation files (the "Software"), to deal |
| 8 | +# in the Software without restriction, including without limitation the rights |
| 9 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +# copies of the Software, and to permit persons to whom the Software is |
| 11 | +# furnished to do so, subject to the following conditions: |
| 12 | +# |
| 13 | +# The above copyright notice and this permission notice shall be included in all |
| 14 | +# copies or substantial portions of the Software. |
| 15 | +# |
| 16 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +# SOFTWARE. |
| 23 | +# |
| 24 | + |
| 25 | +import re |
| 26 | +from functools import lru_cache |
| 27 | +from typing import Any, Dict, List, Mapping |
| 28 | + |
| 29 | +from .streams import IncrementalGoogleAdsStream |
| 30 | + |
| 31 | + |
| 32 | +class CustomQuery(IncrementalGoogleAdsStream): |
| 33 | + def __init__(self, custom_query_config, **kwargs): |
| 34 | + self.custom_query_config = custom_query_config |
| 35 | + self.user_defined_query = custom_query_config["query"] |
| 36 | + super().__init__(**kwargs) |
| 37 | + |
| 38 | + @property |
| 39 | + def primary_key(self) -> str: |
| 40 | + """ |
| 41 | + The primary_key option is disabled. Config should not provide the primary key. |
| 42 | + It will be ignored if provided. |
| 43 | + If you need to enable it, uncomment the next line instead of `return None` and modify your config |
| 44 | + """ |
| 45 | + # return self.custom_query_config.get("primary_key") or None |
| 46 | + return None |
| 47 | + |
| 48 | + @property |
| 49 | + def name(self): |
| 50 | + return self.custom_query_config["table_name"] |
| 51 | + |
| 52 | + def get_query(self, stream_slice: Mapping[str, Any] = None) -> str: |
| 53 | + start_date, end_date = self.get_date_params(stream_slice, self.cursor_field) |
| 54 | + return self.insert_segments_date_expr(self.user_defined_query, start_date, end_date) |
| 55 | + |
| 56 | + # IncrementalGoogleAdsStream uses get_json_schema a lot while parsing |
| 57 | + # responses, caching plaing crucial role for performance here. |
| 58 | + @lru_cache() |
| 59 | + def get_json_schema(self) -> Dict[str, Any]: |
| 60 | + """ |
| 61 | + Compose json schema based on user defined query. |
| 62 | + :return Dict object representing jsonschema |
| 63 | + """ |
| 64 | + |
| 65 | + local_json_schema = { |
| 66 | + "$schema": "http://json-schema.org/draft-07/schema#", |
| 67 | + "type": "object", |
| 68 | + "properties": {}, |
| 69 | + "additionalProperties": True, |
| 70 | + } |
| 71 | + # full list {'ENUM', 'STRING', 'DATE', 'DOUBLE', 'RESOURCE_NAME', 'INT32', 'INT64', 'BOOLEAN', 'MESSAGE'} |
| 72 | + |
| 73 | + google_datatype_mapping = { |
| 74 | + "INT64": "integer", |
| 75 | + "INT32": "integer", |
| 76 | + "DOUBLE": "number", |
| 77 | + "STRING": "string", |
| 78 | + "BOOLEAN": "boolean", |
| 79 | + "DATE": "string", |
| 80 | + } |
| 81 | + fields = CustomQuery.get_query_fields(self.user_defined_query) |
| 82 | + fields.append(self.cursor_field) |
| 83 | + google_schema = self.google_ads_client.get_fields_metadata(fields) |
| 84 | + |
| 85 | + for field in fields: |
| 86 | + node = google_schema.get(field) |
| 87 | + # Data type return in enum format: "GoogleAdsFieldDataType.<data_type>" |
| 88 | + google_data_type = str(node.data_type).replace("GoogleAdsFieldDataType.", "") |
| 89 | + if google_data_type == "ENUM": |
| 90 | + field_value = {"type": "string", "enum": list(node.enum_values)} |
| 91 | + elif google_data_type == "MESSAGE": |
| 92 | + # Represents protobuf message and could be anything, set custom |
| 93 | + # attribute "protobuf_message" to convert it to a string (or |
| 94 | + # array of strings) later. |
| 95 | + # https://developers.google.com/google-ads/api/reference/rpc/v8/GoogleAdsFieldDataTypeEnum.GoogleAdsFieldDataType?hl=en#message |
| 96 | + if node.is_repeated: |
| 97 | + output_type = ["array", "null"] |
| 98 | + else: |
| 99 | + output_type = ["string", "null"] |
| 100 | + field_value = {"type": output_type, "protobuf_message": True} |
| 101 | + else: |
| 102 | + output_type = [google_datatype_mapping.get(google_data_type, "string"), "null"] |
| 103 | + field_value = {"type": output_type} |
| 104 | + local_json_schema["properties"][field] = field_value |
| 105 | + |
| 106 | + return local_json_schema |
| 107 | + |
| 108 | + # Regexp flags for parsing GAQL query |
| 109 | + RE_FLAGS = re.DOTALL | re.MULTILINE | re.IGNORECASE |
| 110 | + # Regexp for getting query columns |
| 111 | + SELECT_EXPR = re.compile("select(.*)from", flags=RE_FLAGS) |
| 112 | + WHERE_EXPR = re.compile("where.*", flags=RE_FLAGS) |
| 113 | + # list of keywords that can come after WHERE clause, |
| 114 | + # according to https://developers.google.com/google-ads/api/docs/query/grammar |
| 115 | + KEYWORDS_EXPR = re.compile("(order by|limit|parameters)", flags=RE_FLAGS) |
| 116 | + |
| 117 | + @staticmethod |
| 118 | + def get_query_fields(query: str) -> List[str]: |
| 119 | + fields = CustomQuery.SELECT_EXPR.search(query) |
| 120 | + if not fields: |
| 121 | + return [] |
| 122 | + fields = fields.group(1) |
| 123 | + return [f.strip() for f in fields.split(",")] |
| 124 | + |
| 125 | + @staticmethod |
| 126 | + def insert_segments_date_expr(query: str, start_date: str, end_date: str) -> str: |
| 127 | + """ |
| 128 | + Insert segments.date condition to break query into slices for incremental stream. |
| 129 | + :param query Origin user defined query |
| 130 | + :param start_date start date for metric (inclusive) |
| 131 | + :param end_date end date for metric (inclusive) |
| 132 | + :return Modified query with date window condition included |
| 133 | + """ |
| 134 | + # insert segments.date field |
| 135 | + columns = CustomQuery.SELECT_EXPR.search(query) |
| 136 | + if not columns: |
| 137 | + raise Exception("Not valid GAQL expression") |
| 138 | + columns = columns.group(1) |
| 139 | + new_columns = columns + ", segments.date\n" |
| 140 | + result_query = query.replace(columns, new_columns) |
| 141 | + |
| 142 | + # Modify/insert where condition |
| 143 | + where_cond = CustomQuery.WHERE_EXPR.search(result_query) |
| 144 | + if not where_cond: |
| 145 | + # There is no where condition, insert new one |
| 146 | + where_location = len(result_query) |
| 147 | + keywords = CustomQuery.KEYWORDS_EXPR.search(result_query) |
| 148 | + if keywords: |
| 149 | + # where condition is not at the end of expression, insert new condition before keyword begins. |
| 150 | + where_location = keywords.start() |
| 151 | + result_query = ( |
| 152 | + result_query[0:where_location] |
| 153 | + + f"\nWHERE segments.date BETWEEN '{start_date}' AND '{end_date}'\n" |
| 154 | + + result_query[where_location:] |
| 155 | + ) |
| 156 | + return result_query |
| 157 | + # There is already where condition, add segments.date expression |
| 158 | + where_cond = where_cond.group(0) |
| 159 | + keywords = CustomQuery.KEYWORDS_EXPR.search(where_cond) |
| 160 | + if keywords: |
| 161 | + # There is some keywords after WHERE condition |
| 162 | + where_cond = where_cond[0 : keywords.start()] |
| 163 | + new_where_cond = where_cond + f" AND segments.date BETWEEN '{start_date}' AND '{end_date}'\n" |
| 164 | + result_query = result_query.replace(where_cond, new_where_cond) |
| 165 | + return result_query |
0 commit comments