|
| 1 | +# Copyright 2019 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 client_query_add_column(client, table_id): |
| 17 | + |
| 18 | + # [START bigquery_add_column_query_append] |
| 19 | + from google.cloud import bigquery |
| 20 | + |
| 21 | + # TODO(developer): Construct a BigQuery client object. |
| 22 | + # client = bigquery.Client() |
| 23 | + |
| 24 | + # TODO(developer): Set table_id to the ID of the destination table. |
| 25 | + # table_id = "your-project.your_dataset.your_table_name" |
| 26 | + |
| 27 | + # Retrieves the destination table and checks the length of the schema. |
| 28 | + table = client.get_table(table_id) # Make an API request. |
| 29 | + print("Table {} contains {} columns".format(table_id, len(table.schema))) |
| 30 | + |
| 31 | + # Configures the query to append the results to a destination table, |
| 32 | + # allowing field addition. |
| 33 | + job_config = bigquery.QueryJobConfig(destination=table_id) |
| 34 | + job_config.schema_update_options = [ |
| 35 | + bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION |
| 36 | + ] |
| 37 | + job_config.write_disposition = bigquery.WriteDisposition.WRITE_APPEND |
| 38 | + |
| 39 | + # Start the query, passing in the extra configuration. |
| 40 | + query_job = client.query( |
| 41 | + # In this example, the existing table contains only the 'full_name' and |
| 42 | + # 'age' columns, while the results of this query will contain an |
| 43 | + # additional 'favorite_color' column. |
| 44 | + 'SELECT "Timmy" as full_name, 85 as age, "Blue" as favorite_color;', |
| 45 | + job_config=job_config, |
| 46 | + ) # Make an API request. |
| 47 | + query_job.result() # Wait for the job to complete. |
| 48 | + |
| 49 | + # Checks the updated length of the schema. |
| 50 | + table = client.get_table(table_id) # Make an API request. |
| 51 | + print("Table {} now contains {} columns".format(table_id, len(table.schema))) |
| 52 | + # [END bigquery_add_column_query_append] |
0 commit comments