|
| 1 | +# Copyright 2022 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 | + |
| 16 | +def get_table_make_schema(table_id: str, schema_path: str) -> None: |
| 17 | + orig_table_id = table_id |
| 18 | + orig_schema_path = schema_path |
| 19 | + # [START bigquery_schema_file_get] |
| 20 | + from google.cloud import bigquery |
| 21 | + |
| 22 | + client = bigquery.Client() |
| 23 | + |
| 24 | + # TODO(dev): Change the table_id variable to the full name of the |
| 25 | + # table you want to get schema from. |
| 26 | + table_id = "your-project.your_dataset.your_table_name" |
| 27 | + |
| 28 | + # TODO(dev): Change schema_path variable to the path |
| 29 | + # of your schema file. |
| 30 | + schema_path = "path/to/schema.json" |
| 31 | + # [END bigquery_schema_file_get] |
| 32 | + table_id = orig_table_id |
| 33 | + schema_path = orig_schema_path |
| 34 | + # [START bigquery_schema_file_get] |
| 35 | + table = client.get_table(table_id) # Make an API request. |
| 36 | + |
| 37 | + # Write a schema file to schema_path with the schema_to_json method. |
| 38 | + client.schema_to_json(table.schema, schema_path) |
| 39 | + |
| 40 | + with open(schema_path, "r", encoding="utf-8") as schema_file: |
| 41 | + schema_contents = schema_file.read() |
| 42 | + |
| 43 | + # View table properties |
| 44 | + print(f"Got table '{table.project}.{table.dataset_id}.{table.table_id}'.") |
| 45 | + print(f"Table schema: {schema_contents}") |
| 46 | + |
| 47 | + # [END bigquery_schema_file_get] |
0 commit comments