Search code examples
google-bigqueryuser-defined-functionsgoogle-api-python-client

Upload UDF in BigQuery using Python API Client


I would like to create a UDF inside a specific dataset in BigQuery. I've tried using the create_table and other API methods from the Python Client but none seem to work.

Is there any method or way to upload a UDF (stored in a file and read it as a string) into BigQuery?


Solution

  • This is my UDF:

    $ cat test.udf
    CREATE OR REPLACE FUNCTION dataset_name.addFourAndDivideAny(x ANY TYPE, y ANY TYPE) AS ((x + 4) / y);
    

    This is my upload command ran on Cloud Shell (it will ask to authorise):

    bq query --nouse_legacy_sql  < test.udf
    

    In python:

    from google.cloud import bigquery
    
    client = bigquery.Client()
    
    with open('test.udf', 'r') as file:
         QUERY = file.read().replace('\n', '')
    
    query_job = client.query(QUERY)
    

    I have got the UDF in single line in the file, but you can use multi-lines file as well. Just make sure the QUERY string is properly constructed.