|
| 1 | +# Copyright 2018 Google Inc. All Rights Reserved. |
| 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 | + |
| 15 | +"""Sanitizes BigQuery schema and field according to BigQuery restrictions.""" |
| 16 | + |
| 17 | +import math |
| 18 | +import re |
| 19 | +import sys |
| 20 | +from typing import List, Optional # pylint: disable=unused-import |
| 21 | + |
| 22 | +from gcp_variant_transforms.beam_io import vcfio |
| 23 | + |
| 24 | +# Prefix to use when the first character of the field name is not [a-zA-Z] |
| 25 | +# as required by BigQuery. |
| 26 | +_FALLBACK_FIELD_NAME_PREFIX = 'field_' |
| 27 | + |
| 28 | +# A big number to represent infinite float values. The division by 10 is to |
| 29 | +# prevent unintentional overflows when doing subsequent operations. |
| 30 | +_INF_FLOAT_VALUE = sys.float_info.max / 10 |
| 31 | +_DEFAULT_NULL_NUMERIC_VALUE_REPLACEMENT = -2 ^ 31 |
| 32 | + |
| 33 | + |
| 34 | +class SchemaSanitizer(object): |
| 35 | + """Class to sanitize BigQuery schema according to BigQuery restrictions.""" |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def get_sanitized_string(input_str): |
| 39 | + # type: (str) -> unicode |
| 40 | + """Returns a unicode as BigQuery API does not support UTF-8 strings.""" |
| 41 | + return _decode_utf8_string(input_str) |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def get_sanitized_field_name(field_name): |
| 45 | + # type: (str) -> str |
| 46 | + """Returns the sanitized field name according to BigQuery restrictions. |
| 47 | +
|
| 48 | + BigQuery field names must follow `[a-zA-Z][a-zA-Z0-9_]*`. This method |
| 49 | + converts any unsupported characters to an underscore. Also, if the first |
| 50 | + character does not match `[a-zA-Z]`, it prepends |
| 51 | + `_FALLBACK_FIELD_NAME_PREFIX` to the name. |
| 52 | +
|
| 53 | + Args: |
| 54 | + field_name: Name of the field to sanitize. |
| 55 | + Returns: |
| 56 | + Sanitized field name with unsupported characters replaced with an |
| 57 | + underscore. It also prepends the name with `_FALLBACK_FIELD_NAME_PREFIX` |
| 58 | + if the first character does not match `[a-zA-Z]`. |
| 59 | + """ |
| 60 | + assert field_name # field_name must not be empty by this stage. |
| 61 | + if not re.match('[a-zA-Z]', field_name[0]): |
| 62 | + field_name = _FALLBACK_FIELD_NAME_PREFIX + field_name |
| 63 | + return re.sub('[^a-zA-Z0-9_]', '_', field_name) |
| 64 | + |
| 65 | + |
| 66 | +class FieldSanitizer(object): |
| 67 | + """Class to sanitize field values according to BigQuery restrictions.""" |
| 68 | + |
| 69 | + def __init__(self, null_numeric_value_replacement): |
| 70 | + # type: (Optional[int]) -> None |
| 71 | + """Initializes a `BigQueryFieldSanitizer`. |
| 72 | +
|
| 73 | + Args: |
| 74 | + null_numeric_value_replacement: Value to use instead of null for |
| 75 | + numeric (float/int/long) lists. For instance, [0, None, 1] will become |
| 76 | + [0, `null_numeric_value_replacement`, 1]. |
| 77 | + """ |
| 78 | + self._null_numeric_value_replacement = ( |
| 79 | + null_numeric_value_replacement or |
| 80 | + _DEFAULT_NULL_NUMERIC_VALUE_REPLACEMENT) |
| 81 | + |
| 82 | + def get_sanitized_field(self, field): |
| 83 | + # type: (Any) -> Any |
| 84 | + """Returns sanitized field according to BigQuery restrictions. |
| 85 | +
|
| 86 | + This method only sanitizes lists and strings. It returns the same `field` |
| 87 | + for all other types (including None). |
| 88 | +
|
| 89 | + For lists, null values are replaced with reasonable defaults since the |
| 90 | + BigQuery API does not allow null values in lists (note that the entire |
| 91 | + list is allowed to be null). For instance, [0, None, 1] becomes |
| 92 | + [0, `null_numeric_value_replacement`, 1]. |
| 93 | + Null value replacements are: |
| 94 | + - `False` for bool. |
| 95 | + - `.` for string (null string values should not exist in Variants parsed |
| 96 | + using PyVCF though). |
| 97 | + - `null_numeric_value_replacement` for float/int/long. |
| 98 | +
|
| 99 | + For strings, it returns its unicode representation. The BigQuery API does |
| 100 | + not support strings that are UTF-8 encoded. |
| 101 | +
|
| 102 | + Args: |
| 103 | + field: Field to sanitize. It can be of any type. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + ValueError: If the field could not be sanitized (e.g. unsupported types in |
| 107 | + lists). |
| 108 | + """ |
| 109 | + if not field: |
| 110 | + return field |
| 111 | + if isinstance(field, basestring): |
| 112 | + return self._get_sanitized_string(field) |
| 113 | + elif isinstance(field, float): |
| 114 | + return self._get_sanitized_float(field) |
| 115 | + elif isinstance(field, list): |
| 116 | + return self._get_sanitized_list(field) |
| 117 | + else: |
| 118 | + return field |
| 119 | + |
| 120 | + def _get_sanitized_list(self, input_list): |
| 121 | + # type: (List) -> List |
| 122 | + """Returns sanitized list according to BigQuery restrictions. |
| 123 | +
|
| 124 | + Null values are replaced with reasonable defaults since the |
| 125 | + BigQuery API does not allow null values in lists (note that the entire |
| 126 | + list is allowed to be null). For instance, [0, None, 1] becomes |
| 127 | + [0, `null_numeric_value_replacement`, 1]. |
| 128 | + Null value replacements are: |
| 129 | + - `False` for bool. |
| 130 | + - `.` for string (null string values should not exist in Variants parsed |
| 131 | + using PyVCF though). |
| 132 | + - `null_numeric_value_replacement` for float/int/long. |
| 133 | + Lists that contain strings are also sanitized according to the |
| 134 | + `_get_sanitized_string` method. |
| 135 | +
|
| 136 | + Args: |
| 137 | + input_list: List to sanitize. |
| 138 | +
|
| 139 | + Raises: |
| 140 | + ValueError: If a list contains unsupported values. Supported types are |
| 141 | + basestring, bool, int, long, and float. |
| 142 | + """ |
| 143 | + null_replacement_value = None |
| 144 | + for i in input_list: |
| 145 | + if i is None: |
| 146 | + continue |
| 147 | + if isinstance(i, basestring): |
| 148 | + null_replacement_value = vcfio.MISSING_FIELD_VALUE |
| 149 | + elif isinstance(i, bool): |
| 150 | + null_replacement_value = False |
| 151 | + elif isinstance(i, (int, long, float)): |
| 152 | + null_replacement_value = self._null_numeric_value_replacement |
| 153 | + else: |
| 154 | + raise ValueError('Unsupported value for input: %s' % str(i)) |
| 155 | + break # Assumption is that all fields have the same type. |
| 156 | + if null_replacement_value is None: # Implies everything was None. |
| 157 | + return [] |
| 158 | + sanitized_list = [] |
| 159 | + for i in input_list: |
| 160 | + if i is None: |
| 161 | + i = null_replacement_value |
| 162 | + elif isinstance(i, basestring): |
| 163 | + i = self._get_sanitized_string(i) |
| 164 | + elif isinstance(i, float): |
| 165 | + sanitized_float = self._get_sanitized_float(i) |
| 166 | + i = (sanitized_float if sanitized_float is not None |
| 167 | + else null_replacement_value) |
| 168 | + sanitized_list.append(i) |
| 169 | + return sanitized_list |
| 170 | + |
| 171 | + def _get_sanitized_float(self, input_float): |
| 172 | + """Returns a sanitized float for BigQuery. |
| 173 | +
|
| 174 | + This method replaces INF and -INF with positive and negative numbers with |
| 175 | + huge absolute values, and replaces NaN with None. It returns the same value |
| 176 | + for all other values. |
| 177 | + """ |
| 178 | + if input_float == float('inf'): |
| 179 | + return _INF_FLOAT_VALUE |
| 180 | + elif input_float == float('-inf'): |
| 181 | + return -_INF_FLOAT_VALUE |
| 182 | + elif math.isnan(input_float): |
| 183 | + return None |
| 184 | + else: |
| 185 | + return input_float |
| 186 | + |
| 187 | + def _get_sanitized_string(self, input_str): |
| 188 | + # type: (str) -> unicode |
| 189 | + """Returns a unicode as BigQuery API does not support UTF-8 strings.""" |
| 190 | + return _decode_utf8_string(input_str) |
| 191 | + |
| 192 | + |
| 193 | +def _decode_utf8_string(input_str): |
| 194 | + # type: (str) -> unicode |
| 195 | + try: |
| 196 | + return (input_str if isinstance(input_str, unicode) |
| 197 | + else input_str.decode('utf-8')) |
| 198 | + except UnicodeDecodeError: |
| 199 | + raise ValueError('input_str is not UTF-8: %s ' % (input_str)) |
0 commit comments