|
| 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 | +from google.cloud import bigquery |
| 16 | + |
| 17 | + |
| 18 | +def relax_column(table_id: str) -> bigquery.Table: |
| 19 | + orig_table_id = table_id |
| 20 | + |
| 21 | + # [START bigquery_relax_column] |
| 22 | + from google.cloud import bigquery |
| 23 | + |
| 24 | + client = bigquery.Client() |
| 25 | + |
| 26 | + # TODO(dev): Change table_id to full name of the table you want to create. |
| 27 | + table_id = "your-project.your_dataset.your_table" |
| 28 | + |
| 29 | + # [END bigquery_relax_column] |
| 30 | + table_id = orig_table_id |
| 31 | + |
| 32 | + # [START bigquery_relax_column] |
| 33 | + table = client.get_table(table_id) |
| 34 | + new_schema = [] |
| 35 | + for field in table.schema: |
| 36 | + if field.mode != "REQUIRED": |
| 37 | + new_schema.append(field) |
| 38 | + else: |
| 39 | + # SchemaField properties cannot be edited after initialization. |
| 40 | + # To make changes, construct new SchemaField objects. |
| 41 | + new_field = field.to_api_repr() |
| 42 | + new_field["mode"] = "NULLABLE" |
| 43 | + relaxed_field = bigquery.SchemaField.from_api_repr(new_field) |
| 44 | + new_schema.append(relaxed_field) |
| 45 | + |
| 46 | + table.schema = new_schema |
| 47 | + table = client.update_table(table, ["schema"]) |
| 48 | + |
| 49 | + print(f"Updated {table_id} schema: {table.schema}.") |
| 50 | + |
| 51 | + # [END bigquery_relax_column] |
| 52 | + return table |
0 commit comments