Daniel Wyatt
Daniel Wyatt

Reputation: 1151

Check if bigquery query was successful or not in python

I am trying to test whether the result of my create or replace query in python was successful or not. I have written code like the following

    PROJECT = project_id
    DATASET = dataset
    FINAL_TABLE = final_table
    MAIN_TABLE = main_table
    main_query = \
    f'CREATE OR REPLACE TABLE `{PROJECT}.{DATASET}.{FINAL_TABLE}` AS \
    (SELECT * FROM `{PROJECT}.{DATASET}.{MAIN_TABLE}` WHERE region="us")'
    result = BQ.query(main_query)
    if result.errors():
        raise Exception('Table was not successfullly refreshed in bigQuery')

However the result.errors() syntax doesn't work properly. What is the syntax to try and achieve this?

Upvotes: 0

Views: 3809

Answers (1)

itroulli
itroulli

Reputation: 2094

The result.errors() syntax doesn't work because result.errors is actually an attribute of the QueryJob and not a method. It is a list of the errors that may have occurred. However, if no errors occur result.errors is None (See also: errors API Reference).

So by just removing the parentheses, your code should work:

PROJECT = project_id
DATASET = dataset
FINAL_TABLE = final_table
MAIN_TABLE = main_table
main_query = \
f'CREATE OR REPLACE TABLE `{PROJECT}.{DATASET}.{FINAL_TABLE}` AS \
(SELECT * FROM `{PROJECT}.{DATASET}.{MAIN_TABLE}` WHERE region="us")'
result = BQ.query(main_query)
if result.errors:
    raise Exception('Table was not successfullly refreshed in bigQuery')

Upvotes: 2

Related Questions