|
| 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 | +# 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 | +BigQuery Annotations loader |
| 16 | +""" |
| 17 | + |
| 18 | +import argparse |
| 19 | +from concurrent import futures |
| 20 | +import logging |
| 21 | +import pathlib |
| 22 | +import sys |
| 23 | +import typing |
| 24 | +import yaml |
| 25 | + |
| 26 | +from google.cloud import bigquery |
| 27 | +from google.cloud.exceptions import NotFound |
| 28 | + |
| 29 | +sys.path.append(".") |
| 30 | +sys.path.append("./src") |
| 31 | +sys.path.append(str(pathlib.Path(__file__).parent)) |
| 32 | + |
| 33 | +# pylint:disable=wrong-import-position |
| 34 | +from common.py_libs.configs import load_config_file |
| 35 | +from common.py_libs.jinja import (apply_jinja_params_dict_to_file, |
| 36 | + initialize_jinja_from_config) |
| 37 | + |
| 38 | +_PARALLEL_THREADS = 5 |
| 39 | + |
| 40 | + |
| 41 | +def _load_table_annotations(table_annotations: typing.Dict[str, typing.Any], |
| 42 | + client: bigquery.Client): |
| 43 | + full_table_id = table_annotations["id"] |
| 44 | + table_description = table_annotations["description"] |
| 45 | + description_changed = False |
| 46 | + schema_changed = False |
| 47 | + try: |
| 48 | + table = client.get_table(full_table_id) |
| 49 | + except NotFound: |
| 50 | + logging.info("Table or view `%s` was not found. Skipping it.", |
| 51 | + full_table_id) |
| 52 | + return |
| 53 | + table_description = table.description or table_description |
| 54 | + description_changed = table_description != table.description |
| 55 | + table.description = table_description |
| 56 | + annotation_fields = { |
| 57 | + field_item["name"]: field_item["description"] |
| 58 | + for field_item in table_annotations["fields"] |
| 59 | + } |
| 60 | + |
| 61 | + schema = table.schema.copy() |
| 62 | + for index, field in enumerate(schema): |
| 63 | + description = field.description or annotation_fields.get(field.name, "") |
| 64 | + if description != field.description: |
| 65 | + schema_changed = True |
| 66 | + field_dict = field.to_api_repr() |
| 67 | + field_dict["description"] = description |
| 68 | + schema[index] = bigquery.SchemaField.from_api_repr(field_dict) |
| 69 | + changes = [] |
| 70 | + if schema_changed: |
| 71 | + table.schema = schema |
| 72 | + changes.append("schema") |
| 73 | + if description_changed: |
| 74 | + changes.append("description") |
| 75 | + if len(changes) > 0: |
| 76 | + client.update_table(table, changes) |
| 77 | + logging.info("Table/view `%s` has been updated.", full_table_id) |
| 78 | + else: |
| 79 | + logging.info("No changes in `%s`.", full_table_id) |
| 80 | + |
| 81 | + |
| 82 | +def load_annotations(jinja_dict: typing.Dict[str, typing.Any], |
| 83 | + client: bigquery.Client, annotations_file: pathlib.Path): |
| 84 | + annotations_yaml = apply_jinja_params_dict_to_file(annotations_file, |
| 85 | + jinja_dict) |
| 86 | + annotations_dict = yaml.safe_load(annotations_yaml) |
| 87 | + if not annotations_dict: |
| 88 | + logging.warning("Annotations file `%s` has no parsable content.", |
| 89 | + str(annotations_file)) |
| 90 | + return |
| 91 | + logging.info("Loading annotations from `%s`.", str(annotations_file)) |
| 92 | + |
| 93 | + threads = [] |
| 94 | + executor = futures.ThreadPoolExecutor(_PARALLEL_THREADS) |
| 95 | + |
| 96 | + for table_item in annotations_dict: |
| 97 | + threads.append( |
| 98 | + executor.submit(_load_table_annotations, table_item, client)) |
| 99 | + futures.wait(threads) |
| 100 | + |
| 101 | + |
| 102 | +def main(args: typing.Sequence[str]) -> int: |
| 103 | + """BigQuery Annotations loader main""" |
| 104 | + |
| 105 | + parser = argparse.ArgumentParser(description="BigQuery Annotations Loader") |
| 106 | + parser.add_argument("--annotations-directory", |
| 107 | + help="Annotation files directory", |
| 108 | + type=str, |
| 109 | + required=True) |
| 110 | + parser.add_argument("--debug", |
| 111 | + help="Debugging mode.", |
| 112 | + action="store_true", |
| 113 | + default=False, |
| 114 | + required=False) |
| 115 | + parser.add_argument("--config", |
| 116 | + help="Data Foundation config.json.", |
| 117 | + type=str, |
| 118 | + required=False, |
| 119 | + default="./config/config.json") |
| 120 | + options = parser.parse_args(args) |
| 121 | + logging.basicConfig( |
| 122 | + format="%(asctime)s | %(levelname)s | %(message)s", |
| 123 | + level=logging.INFO if not options.debug else logging.DEBUG, |
| 124 | + ) |
| 125 | + |
| 126 | + logging.info("Cortex Annotations Loader for BigQuery.") |
| 127 | + |
| 128 | + config = load_config_file(options.config) |
| 129 | + |
| 130 | + logging.info("Loading BigQuery Annotations.") |
| 131 | + |
| 132 | + annotations_path = pathlib.Path(options.annotations_directory) |
| 133 | + if not annotations_path.exists(): |
| 134 | + logging.fatal("Directory `%s` doesn't exist.", str(annotations_path)) |
| 135 | + return 1 |
| 136 | + |
| 137 | + client = bigquery.Client(project=config["projectIdSource"], |
| 138 | + location=config["location"]) |
| 139 | + jinja_dict = initialize_jinja_from_config(config) |
| 140 | + |
| 141 | + for annotation_file in annotations_path.iterdir(): |
| 142 | + load_annotations(jinja_dict, client, annotation_file.absolute()) |
| 143 | + logging.info("BigQuery Annotations has been loaded!") |
| 144 | + |
| 145 | + return 0 |
| 146 | + |
| 147 | + |
| 148 | +############################################################### |
| 149 | +if __name__ == "__main__": |
| 150 | + sys.exit(main(sys.argv[1:])) |
0 commit comments