Created
February 23, 2024 13:03
-
-
Save salvadorgascon/aa1d6a95ca8c014d838cb68eee00d3fa to your computer and use it in GitHub Desktop.
Truncate table in Google Cloud BigQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from google.cloud import bigquery | |
from google.cloud.exceptions import NotFound | |
from google.api_core.exceptions import Conflict | |
from shared.loaders.bigquery_constants import BIGQUERY_PROJECT_NAME | |
print(f'Contando registros en {BIGQUERY_PROJECT_NAME}.{bigquery_dataset_name}.{bigquery_table_name}') | |
query_count = f'SELECT COUNT(*) as record_count FROM {BIGQUERY_PROJECT_NAME}.{bigquery_dataset_name}.{bigquery_table_name}' | |
query_count_job = bigquery_client.query(query_count) | |
dataframe_count = query_count_job.result().to_dataframe() | |
record_count = dataframe_count.iloc[0]['record_count'] | |
if record_count > 0: | |
print(f'Truncating rows {BIGQUERY_PROJECT_NAME}.{bigquery_dataset_name}.{bigquery_table_name}') | |
delete_rows_job = bigquery_client.query(f'TRUNCATE TABLE {BIGQUERY_PROJECT_NAME}.{bigquery_dataset_name}.{bigquery_table_name}') | |
delete_rows_job.result() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment