Executar consultas parametrizadas

O BigQuery suporta parâmetros de consulta para ajudar a evitar a injeção SQL quando as consultas são criadas através da introdução do utilizador. Esta funcionalidade só está disponível com a sintaxe GoogleSQL. Os parâmetros de consulta podem ser usados como substitutos de expressões arbitrárias. Não é possível usar parâmetros como substitutos de identificadores, nomes de colunas, nomes de tabelas ou outras partes da consulta.

Para especificar um parâmetro com nome, use o caráter @ seguido de um identificador, como @param_name. Em alternativa, use o valor do marcador de posição ? para especificar um parâmetro posicional. Tenha em atenção que uma consulta pode usar parâmetros posicionais ou com nome, mas não ambos.

Quando usa um parâmetro, o valor fornecido em si não é registado nos registos do BigQuery para proteger informações potencialmente confidenciais.

Pode executar uma consulta parametrizada no BigQuery das seguintes formas:

  • O comando bq query da ferramenta de linhas de comando bq
  • a API
  • as bibliotecas cliente

O exemplo seguinte mostra como transmitir valores de parâmetros a uma consulta parametrizada:

Consola

As consultas parametrizadas não são suportadas pela consola Trusted Cloud .

bq

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Use --parameter para fornecer valores para parâmetros no formato name:type:value. Um nome vazio produz um parâmetro posicional. O tipo pode ser omitido para assumir STRING.

    A flag --parameter tem de ser usada em conjunto com a flag --use_legacy_sql=false para especificar a sintaxe do GoogleSQL.

    (Opcional) Especifique a sua localização através da flag --location.

    bq query \
       --use_legacy_sql=false \
       --parameter=corpus::romeoandjuliet \
       --parameter=min_word_count:INT64:250 \
       'SELECT
         word,
         word_count
       FROM
         `bigquery-public-data.samples.shakespeare`
       WHERE
         corpus = @corpus
       AND
         word_count >= @min_word_count
       ORDER BY
         word_count DESC;'
  3. API

    Para usar parâmetros com nome, defina parameterMode como NAMED na configuração da tarefa query.

    Preencha queryParameters com a lista de parâmetros na configuração do trabalho query. Defina o name de cada parâmetro com o @param_name usado na consulta.

    Ative a sintaxe GoogleSQL definindo useLegacySql como false.

    {
      "query": "SELECT word, word_count FROM `bigquery-public-data.samples.shakespeare` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC;",
      "queryParameters": [
        {
          "parameterType": {
            "type": "STRING"
          },
          "parameterValue": {
            "value": "romeoandjuliet"
          },
          "name": "corpus"
        },
        {
          "parameterType": {
            "type": "INT64"
          },
          "parameterValue": {
            "value": "250"
          },
          "name": "min_word_count"
        }
      ],
      "useLegacySql": false,
      "parameterMode": "NAMED"
    }
    

    Experimente no Explorador de APIs Google.

    Para usar parâmetros posicionais, defina parameterMode como POSITIONAL na configuração da tarefa query.

    C#

    Antes de experimentar este exemplo, siga as C#instruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API C# BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros com nome:
    
    using Google.Cloud.BigQuery.V2;
    using System;
    
    public class BigQueryQueryWithNamedParameters
    {
        public void QueryWithNamedParameters(string projectId = "your-project-id")
        {
            var corpus = "romeoandjuliet";
            var minWordCount = 250;
    
            // Note: Standard SQL is required to use query parameters.
            var query = @"
                SELECT word, word_count
                FROM `bigquery-public-data.samples.shakespeare`
                WHERE corpus = @corpus
                AND word_count >= @min_word_count
                ORDER BY word_count DESC";
    
            // Initialize client that will be used to send requests.
            var client = BigQueryClient.Create(projectId);
    
            var parameters = new BigQueryParameter[]
            {
                new BigQueryParameter("corpus", BigQueryDbType.String, corpus),
                new BigQueryParameter("min_word_count", BigQueryDbType.Int64, minWordCount)
            };
    
            var job = client.CreateQueryJob(
                sql: query,
                parameters: parameters,
                options: new QueryOptions { UseQueryCache = false });
            // Wait for the job to complete.
            job = job.PollUntilCompleted().ThrowOnAnyError();
            // Display the results
            foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
            {
                Console.WriteLine($"{row["word"]}: {row["word_count"]}");
            }
        }
    }

    Antes de experimentar este exemplo, siga as C#instruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API C# BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros posicionais:
    
    using Google.Cloud.BigQuery.V2;
    using System;
    
    public class BigQueryQueryWithPositionalParameters
    {
        public void QueryWithPositionalParameters(string projectId = "project-id")
        {
            var corpus = "romeoandjuliet";
            var minWordCount = 250;
    
            // Note: Standard SQL is required to use query parameters.
            var query = @"
                    SELECT word, word_count
                    FROM `bigquery-public-data.samples.shakespeare`
                    WHERE corpus = ?
                    AND word_count >= ?
                    ORDER BY word_count DESC;";
    
            // Initialize client that will be used to send requests.
            var client = BigQueryClient.Create(projectId);
    
            // Set the name to None to use positional parameters.
            // Note that you cannot mix named and positional parameters.
            var parameters = new BigQueryParameter[]
            {
                new BigQueryParameter(null, BigQueryDbType.String, corpus),
                new BigQueryParameter(null, BigQueryDbType.Int64, minWordCount)
            };
    
            var job = client.CreateQueryJob(
                sql: query,
                parameters: parameters,
                options: new QueryOptions
                {
                    UseQueryCache = false,
                    ParameterMode = BigQueryParameterMode.Positional
                });
            // Wait for the job to complete.
            job = job.PollUntilCompleted().ThrowOnAnyError();
            // Display the results
            foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
            {
                Console.WriteLine($"{row["word"]}: {row["word_count"]}");
            }
        }
    }

    Go

    Antes de experimentar este exemplo, siga as Goinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Go BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros com nome:
    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/bigquery"
    	"google.golang.org/api/iterator"
    )
    
    // queryWithNamedParams demonstrate issuing a query using named query parameters.
    func queryWithNamedParams(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	q := client.Query(
    		`SELECT word, word_count
            FROM ` + "`bigquery-public-data.samples.shakespeare`" + `
            WHERE corpus = @corpus
            AND word_count >= @min_word_count
            ORDER BY word_count DESC;`)
    	q.Parameters = []bigquery.QueryParameter{
    		{
    			Name:  "corpus",
    			Value: "romeoandjuliet",
    		},
    		{
    			Name:  "min_word_count",
    			Value: 250,
    		},
    	}
    	// Run the query and print results when the query job is completed.
    	job, err := q.Run(ctx)
    	if err != nil {
    		return err
    	}
    	status, err := job.Wait(ctx)
    	if err != nil {
    		return err
    	}
    	if err := status.Err(); err != nil {
    		return err
    	}
    	it, err := job.Read(ctx)
    	for {
    		var row []bigquery.Value
    		err := it.Next(&row)
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Fprintln(w, row)
    	}
    	return nil
    }
    

    Para usar parâmetros posicionais:
    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/bigquery"
    	"google.golang.org/api/iterator"
    )
    
    // queryWithPostionalParams demonstrate issuing a query using positional query parameters.
    func queryWithPositionalParams(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	q := client.Query(
    		`SELECT word, word_count
            FROM ` + "`bigquery-public-data.samples.shakespeare`" + `
            WHERE corpus = ?
            AND word_count >= ?
            ORDER BY word_count DESC;`)
    	q.Parameters = []bigquery.QueryParameter{
    		{
    			Value: "romeoandjuliet",
    		},
    		{
    			Value: 250,
    		},
    	}
    	// Run the query and print results when the query job is completed.
    	job, err := q.Run(ctx)
    	if err != nil {
    		return err
    	}
    	status, err := job.Wait(ctx)
    	if err != nil {
    		return err
    	}
    	if err := status.Err(); err != nil {
    		return err
    	}
    	it, err := job.Read(ctx)
    	for {
    		var row []bigquery.Value
    		err := it.Next(&row)
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Fprintln(w, row)
    	}
    	return nil
    }
    

    Java

    Antes de experimentar este exemplo, siga as Javainstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Java BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros com nome:
    import com.google.cloud.bigquery.BigQuery;
    import com.google.cloud.bigquery.BigQueryException;
    import com.google.cloud.bigquery.BigQueryOptions;
    import com.google.cloud.bigquery.QueryJobConfiguration;
    import com.google.cloud.bigquery.QueryParameterValue;
    import com.google.cloud.bigquery.TableResult;
    
    public class QueryWithNamedParameters {
    
      public static void queryWithNamedParameters() {
        try {
          // Initialize client that will be used to send requests. This client only needs to be created
          // once, and can be reused for multiple requests.
          BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    
          String corpus = "romeoandjuliet";
          long minWordCount = 250;
          String query =
              "SELECT word, word_count\n"
                  + "FROM `bigquery-public-data.samples.shakespeare`\n"
                  + "WHERE corpus = @corpus\n"
                  + "AND word_count >= @min_word_count\n"
                  + "ORDER BY word_count DESC";
    
          // Note: Standard SQL is required to use query parameters.
          QueryJobConfiguration queryConfig =
              QueryJobConfiguration.newBuilder(query)
                  .addNamedParameter("corpus", QueryParameterValue.string(corpus))
                  .addNamedParameter("min_word_count", QueryParameterValue.int64(minWordCount))
                  .build();
    
          TableResult results = bigquery.query(queryConfig);
    
          results
              .iterateAll()
              .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
    
          System.out.println("Query with named parameters performed successfully.");
        } catch (BigQueryException | InterruptedException e) {
          System.out.println("Query not performed \n" + e.toString());
        }
      }
    }

    Para usar parâmetros posicionais:
    import com.google.cloud.bigquery.BigQuery;
    import com.google.cloud.bigquery.BigQueryException;
    import com.google.cloud.bigquery.BigQueryOptions;
    import com.google.cloud.bigquery.QueryJobConfiguration;
    import com.google.cloud.bigquery.QueryParameterValue;
    import com.google.cloud.bigquery.TableResult;
    
    public class QueryWithPositionalParameters {
      public static void queryWithPositionalParameters() {
        try {
          // Initialize client that will be used to send requests. This client only needs to be created
          // once, and can be reused for multiple requests.
          BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    
          String corpus = "romeoandjuliet";
          long minWordCount = 250;
          String query =
              "SELECT word, word_count\n"
                  + "FROM `bigquery-public-data.samples.shakespeare`\n"
                  + "WHERE corpus = ?\n"
                  + "AND word_count >= ?\n"
                  + "ORDER BY word_count DESC";
    
          // Note: Standard SQL is required to use query parameters.
          QueryJobConfiguration queryConfig =
              QueryJobConfiguration.newBuilder(query)
                  .addPositionalParameter(QueryParameterValue.string(corpus))
                  .addPositionalParameter(QueryParameterValue.int64(minWordCount))
                  .build();
    
          TableResult results = bigquery.query(queryConfig);
    
          results
              .iterateAll()
              .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
    
          System.out.println("Query with positional parameters performed successfully.");
        } catch (BigQueryException | InterruptedException e) {
          System.out.println("Query not performed \n" + e.toString());
        }
      }
    }

    Node.js

    Antes de experimentar este exemplo, siga as Node.jsinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Node.js BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros com nome:
    // Run a query using named query parameters
    
    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    async function queryParamsNamed() {
      // The SQL query to run
      const sqlQuery = `SELECT word, word_count
            FROM \`bigquery-public-data.samples.shakespeare\`
            WHERE corpus = @corpus
            AND word_count >= @min_word_count
            ORDER BY word_count DESC`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: {corpus: 'romeoandjuliet', min_word_count: 250},
      };
    
      // Run the query
      const [rows] = await bigquery.query(options);
    
      console.log('Rows:');
      rows.forEach(row => console.log(row));
    }

    Para usar parâmetros posicionais:
    // Run a query using positional query parameters
    
    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    async function queryParamsPositional() {
      // The SQL query to run
      const sqlQuery = `SELECT word, word_count
            FROM \`bigquery-public-data.samples.shakespeare\`
            WHERE corpus = ?
            AND word_count >= ?
            ORDER BY word_count DESC`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: ['romeoandjuliet', 250],
      };
    
      // Run the query
      const [rows] = await bigquery.query(options);
    
      console.log('Rows:');
      rows.forEach(row => console.log(row));
    }

    Python

    Antes de experimentar este exemplo, siga as Pythoninstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Python BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    Para usar parâmetros com nome:
    from google.cloud import bigquery
    
    # Construct a BigQuery client object.
    client = bigquery.Client()
    
    query = """
        SELECT word, word_count
        FROM `bigquery-public-data.samples.shakespeare`
        WHERE corpus = @corpus
        AND word_count >= @min_word_count
        ORDER BY word_count DESC;
    """
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter("corpus", "STRING", "romeoandjuliet"),
            bigquery.ScalarQueryParameter("min_word_count", "INT64", 250),
        ]
    )
    results = client.query_and_wait(
        query, job_config=job_config
    )  # Make an API request.
    
    for row in results:
        print("{}: \t{}".format(row.word, row.word_count))

    Para usar parâmetros posicionais:
    from google.cloud import bigquery
    
    # Construct a BigQuery client object.
    client = bigquery.Client()
    
    query = """
        SELECT word, word_count
        FROM `bigquery-public-data.samples.shakespeare`
        WHERE corpus = ?
        AND word_count >= ?
        ORDER BY word_count DESC;
    """
    # Set the name to None to use positional parameters.
    # Note that you cannot mix named and positional parameters.
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter(None, "STRING", "romeoandjuliet"),
            bigquery.ScalarQueryParameter(None, "INT64", 250),
        ]
    )
    results = client.query_and_wait(
        query, job_config=job_config
    )  # Make an API request.
    
    for row in results:
        print("{}: \t{}".format(row.word, row.word_count))

Usar matrizes em consultas parametrizadas

Para usar um tipo de matriz num parâmetro de consulta, defina o tipo como ARRAY<T>, onde T é o tipo dos elementos na matriz. Construa o valor como uma lista separada por vírgulas de elementos incluídos entre parênteses retos, como [1, 2, 3].

Consulte a referência de tipos de dados para mais informações sobre o tipo de matriz.

Consola

As consultas parametrizadas não são suportadas pela consola Trusted Cloud .

bq

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Esta consulta seleciona os nomes mais populares de rapazes recém-nascidos nos estados dos EUA que começam pela letra W:

    bq query \
       --use_legacy_sql=false \
       --parameter='gender::M' \
       --parameter='states:ARRAY<STRING>:["WA", "WI", "WV", "WY"]' \
       'SELECT
         name,
         SUM(number) AS count
       FROM
         `bigquery-public-data.usa_names.usa_1910_2013`
       WHERE
         gender = @gender
         AND state IN UNNEST(@states)
       GROUP BY
         name
       ORDER BY
         count DESC
       LIMIT
         10;'

    Tenha cuidado para incluir a declaração do tipo de matriz entre aspas simples, para que o resultado do comando não seja redirecionado acidentalmente para um ficheiro pelo caráter >.

  3. API

    Para usar um parâmetro com valor de matriz, defina o parameterType como ARRAY na configuração da tarefa query.

    Se os valores da matriz forem escalares, defina parameterType para o tipo dos valores, como STRING. Se os valores da matriz forem estruturas, defina este campo como STRUCT e adicione as definições de campo necessárias a structTypes.

    Por exemplo, esta consulta seleciona os nomes mais populares de rapazes recém-nascidos nos estados dos EUA que começam pela letra W.

    {
     "query": "SELECT name, sum(number) as count\nFROM `bigquery-public-data.usa_names.usa_1910_2013`\nWHERE gender = @gender\nAND state IN UNNEST(@states)\nGROUP BY name\nORDER BY count DESC\nLIMIT 10;",
     "queryParameters": [
      {
       "parameterType": {
        "type": "STRING"
       },
       "parameterValue": {
        "value": "M"
       },
       "name": "gender"
      },
      {
       "parameterType": {
        "type": "ARRAY",
        "arrayType": {
         "type": "STRING"
        }
       },
       "parameterValue": {
        "arrayValues": [
         {
          "value": "WA"
         },
         {
          "value": "WI"
         },
         {
          "value": "WV"
         },
         {
          "value": "WY"
         }
        ]
       },
       "name": "states"
      }
     ],
     "useLegacySql": false,
     "parameterMode": "NAMED"
    }
    

    Experimente no Explorador de APIs Google.

    C#

    Antes de experimentar este exemplo, siga as C#instruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API C# BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    
    using Google.Cloud.BigQuery.V2;
    using System;
    
    public class BigQueryQueryWithArrayParameters
    {
        public void QueryWithArrayParameters(string projectId = "your-project-id")
        {
            var gender = "M";
            string[] states = { "WA", "WI", "WV", "WY" };
    
            // Note: Standard SQL is required to use query parameters.
            var query = @"
                SELECT name, sum(number) as count
                FROM `bigquery-public-data.usa_names.usa_1910_2013`
                WHERE gender = @gender
                AND state IN UNNEST(@states)
                GROUP BY name
                ORDER BY count DESC
                LIMIT 10;";
    
            // Initialize client that will be used to send requests.
            var client = BigQueryClient.Create(projectId);
    
            var parameters = new BigQueryParameter[]
            {
                new BigQueryParameter("gender", BigQueryDbType.String, gender),
                new BigQueryParameter("states", BigQueryDbType.Array, states)
            };
    
            var job = client.CreateQueryJob(
                sql: query,
                parameters: parameters,
                options: new QueryOptions { UseQueryCache = false });
            // Wait for the job to complete.
            job = job.PollUntilCompleted().ThrowOnAnyError();
            // Display the results
            foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
            {
                Console.WriteLine($"{row["name"]}: {row["count"]}");
            }
        }
    }

    Go

    Antes de experimentar este exemplo, siga as Goinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Go BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/bigquery"
    	"google.golang.org/api/iterator"
    )
    
    // queryWithArrayParams demonstrates issuing a query and specifying query parameters that include an
    // array of strings.
    func queryWithArrayParams(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	q := client.Query(
    		`SELECT
    			name,
    			sum(number) as count 
            FROM ` + "`bigquery-public-data.usa_names.usa_1910_2013`" + `
    		WHERE
    			gender = @gender
            	AND state IN UNNEST(@states)
    		GROUP BY
    			name
    		ORDER BY
    			count DESC
    		LIMIT 10;`)
    	q.Parameters = []bigquery.QueryParameter{
    		{
    			Name:  "gender",
    			Value: "M",
    		},
    		{
    			Name:  "states",
    			Value: []string{"WA", "WI", "WV", "WY"},
    		},
    	}
    	// Run the query and print results when the query job is completed.
    	job, err := q.Run(ctx)
    	if err != nil {
    		return err
    	}
    	status, err := job.Wait(ctx)
    	if err != nil {
    		return err
    	}
    	if err := status.Err(); err != nil {
    		return err
    	}
    	it, err := job.Read(ctx)
    	for {
    		var row []bigquery.Value
    		err := it.Next(&row)
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Fprintln(w, row)
    	}
    	return nil
    }
    

    Java

    Antes de experimentar este exemplo, siga as Javainstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Java BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import com.google.cloud.bigquery.BigQuery;
    import com.google.cloud.bigquery.BigQueryException;
    import com.google.cloud.bigquery.BigQueryOptions;
    import com.google.cloud.bigquery.QueryJobConfiguration;
    import com.google.cloud.bigquery.QueryParameterValue;
    import com.google.cloud.bigquery.TableResult;
    
    // Sample to running a query with array query parameters.
    public class QueryWithArrayParameters {
    
      public static void runQueryWithArrayParameters() {
        String gender = "M";
        String[] states = {"WA", "WI", "WV", "WY"};
        String query =
            "SELECT name, sum(number) as count\n"
                + "FROM `bigquery-public-data.usa_names.usa_1910_2013`\n"
                + "WHERE gender = @gender\n"
                + "AND state IN UNNEST(@states)\n"
                + "GROUP BY name\n"
                + "ORDER BY count DESC\n"
                + "LIMIT 10;";
        queryWithArrayParameters(query, gender, states);
      }
    
      public static void queryWithArrayParameters(String query, String gender, String[] states) {
        try {
          // Initialize client that will be used to send requests. This client only needs to be created
          // once, and can be reused for multiple requests.
          BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    
          // Note: Standard SQL is required to use query parameters.
          QueryJobConfiguration queryConfig =
              QueryJobConfiguration.newBuilder(query)
                  .addNamedParameter("gender", QueryParameterValue.string(gender))
                  .addNamedParameter("states", QueryParameterValue.array(states, String.class))
                  .build();
    
          TableResult results = bigquery.query(queryConfig);
    
          // Print the results.
          results
              .iterateAll()
              .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
          System.out.println("Query with arrays parameters performed successfully");
        } catch (BigQueryException | InterruptedException e) {
          System.out.println("Query not performed \n" + e.toString());
        }
      }
    }

    Node.js

    Antes de experimentar este exemplo, siga as Node.jsinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Node.js BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    // Run a query using array query parameters
    
    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    async function queryParamsArrays() {
      // The SQL query to run
      const sqlQuery = `SELECT name, sum(number) as count
      FROM \`bigquery-public-data.usa_names.usa_1910_2013\`
      WHERE gender = @gender
      AND state IN UNNEST(@states)
      GROUP BY name
      ORDER BY count DESC
      LIMIT 10;`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: {gender: 'M', states: ['WA', 'WI', 'WV', 'WY']},
      };
    
      // Run the query
      const [rows] = await bigquery.query(options);
    
      console.log('Rows:');
      rows.forEach(row => console.log(row));
    }

    Python

    Antes de experimentar este exemplo, siga as Pythoninstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Python BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    from google.cloud import bigquery
    
    # Construct a BigQuery client object.
    client = bigquery.Client()
    
    query = """
        SELECT name, sum(number) as count
        FROM `bigquery-public-data.usa_names.usa_1910_2013`
        WHERE gender = @gender
        AND state IN UNNEST(@states)
        GROUP BY name
        ORDER BY count DESC
        LIMIT 10;
    """
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter("gender", "STRING", "M"),
            bigquery.ArrayQueryParameter("states", "STRING", ["WA", "WI", "WV", "WY"]),
        ]
    )
    rows = client.query_and_wait(query, job_config=job_config)  # Make an API request.
    
    for row in rows:
        print("{}: \t{}".format(row.name, row.count))

Usar datas/horas nas consultas parametrizadas

Para usar uma data/hora num parâmetro de consulta, a API REST subjacente aceita um valor do tipo TIMESTAMP no formato YYYY-MM-DD HH:MM:SS.DDDDDD time_zone. Se estiver a usar as bibliotecas cliente, cria um objeto de data incorporado nesse idioma, e a biblioteca converte-o no formato correto. Para mais informações, consulte os seguintes exemplos específicos de cada idioma.

Para mais informações sobre o tipo TIMESTAMP, consulte a referência de tipos de dados.

Consola

As consultas parametrizadas não são suportadas pela consola Trusted Cloud .

bq

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Esta consulta adiciona uma hora ao valor do parâmetro de indicação de tempo:

    bq query \
       --use_legacy_sql=false \
       --parameter='ts_value:TIMESTAMP:2016-12-07 08:00:00' \
       'SELECT
         TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);'
  3. API

    Para usar um parâmetro de data/hora, defina o elemento parameterType como TIMESTAMP na configuração da tarefa de consulta.

    Esta consulta adiciona uma hora ao valor do parâmetro de indicação de tempo.

    {
      "query": "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);",
      "queryParameters": [
        {
          "name": "ts_value",
          "parameterType": {
            "type": "TIMESTAMP"
          },
          "parameterValue": {
            "value": "2016-12-07 08:00:00"
          }
        }
      ],
      "useLegacySql": false,
      "parameterMode": "NAMED"
    }
    

    Experimente no Explorador de APIs Google.

    C#

    Antes de experimentar este exemplo, siga as C#instruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API C# BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    
    using Google.Cloud.BigQuery.V2;
    using System;
    
    public class BigQueryQueryWithTimestampParameters
    {
        public void QueryWithTimestampParameters(string projectId = "project-id")
        {
            var timestamp = new DateTime(2016, 12, 7, 8, 0, 0, DateTimeKind.Utc);
    
            // Note: Standard SQL is required to use query parameters.
            var query = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
    
            // Initialize client that will be used to send requests.
            var client = BigQueryClient.Create(projectId);
    
            var parameters = new BigQueryParameter[]
            {
                new BigQueryParameter("ts_value", BigQueryDbType.Timestamp, timestamp),
            };
    
            var job = client.CreateQueryJob(
                sql: query,
                parameters: parameters,
                options: new QueryOptions { UseQueryCache = false });
            // Wait for the job to complete.
            job = job.PollUntilCompleted().ThrowOnAnyError();
            // Display the results
            foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
            {
                Console.WriteLine(row[0]);
            }
        }
    }

    Go

    Antes de experimentar este exemplo, siga as Goinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Go BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"
    
    	"cloud.google.com/go/bigquery"
    	"google.golang.org/api/iterator"
    )
    
    // queryWithTimestampParam demonstrates issuing a query and supplying a timestamp query parameter.
    func queryWithTimestampParam(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	q := client.Query(
    		`SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);`)
    	q.Parameters = []bigquery.QueryParameter{
    		{
    			Name:  "ts_value",
    			Value: time.Date(2016, 12, 7, 8, 0, 0, 0, time.UTC),
    		},
    	}
    	// Run the query and print results when the query job is completed.
    	job, err := q.Run(ctx)
    	if err != nil {
    		return err
    	}
    	status, err := job.Wait(ctx)
    	if err != nil {
    		return err
    	}
    	if err := status.Err(); err != nil {
    		return err
    	}
    	it, err := job.Read(ctx)
    	for {
    		var row []bigquery.Value
    		err := it.Next(&row)
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Fprintln(w, row)
    	}
    	return nil
    }
    

    Java

    Antes de experimentar este exemplo, siga as Javainstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Java BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import com.google.cloud.bigquery.BigQuery;
    import com.google.cloud.bigquery.BigQueryException;
    import com.google.cloud.bigquery.BigQueryOptions;
    import com.google.cloud.bigquery.QueryJobConfiguration;
    import com.google.cloud.bigquery.QueryParameterValue;
    import com.google.cloud.bigquery.TableResult;
    import org.threeten.bp.LocalDateTime;
    import org.threeten.bp.ZoneOffset;
    import org.threeten.bp.ZonedDateTime;
    
    // Sample to running a query with timestamp query parameters.
    public class QueryWithTimestampParameters {
    
      public static void runQueryWithTimestampParameters() {
        queryWithTimestampParameters();
      }
    
      public static void queryWithTimestampParameters() {
        try {
          // Initialize client that will be used to send requests. This client only needs to be created
          // once, and can be reused for multiple requests.
          BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    
          ZonedDateTime timestamp = LocalDateTime.of(2016, 12, 7, 8, 0, 0).atZone(ZoneOffset.UTC);
          String query = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
          // Note: Standard SQL is required to use query parameters.
          QueryJobConfiguration queryConfig =
              QueryJobConfiguration.newBuilder(query)
                  .addNamedParameter(
                      "ts_value",
                      QueryParameterValue.timestamp(
                          // Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
                          timestamp.toInstant().toEpochMilli() * 1000))
                  .build();
    
          TableResult results = bigquery.query(queryConfig);
    
          results
              .iterateAll()
              .forEach(row -> row.forEach(val -> System.out.printf("%s", val.toString())));
    
          System.out.println("Query with timestamp parameter performed successfully.");
        } catch (BigQueryException | InterruptedException e) {
          System.out.println("Query not performed \n" + e.toString());
        }
      }
    }

    Node.js

    Antes de experimentar este exemplo, siga as Node.jsinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Node.js BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    // Run a query using timestamp parameters
    
    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    async function queryParamsTimestamps() {
      // The SQL query to run
      const sqlQuery = `SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: {ts_value: new Date()},
      };
    
      // Run the query
      const [rows] = await bigquery.query(options);
    
      console.log('Rows:');
      rows.forEach(row => console.log(row.f0_));
    }

    Python

    Antes de experimentar este exemplo, siga as Pythoninstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Python BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import datetime
    
    from google.cloud import bigquery
    
    # Construct a BigQuery client object.
    client = bigquery.Client()
    
    query = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);"
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter(
                "ts_value",
                "TIMESTAMP",
                datetime.datetime(2016, 12, 7, 8, 0, tzinfo=datetime.timezone.utc),
            )
        ]
    )
    results = client.query_and_wait(
        query, job_config=job_config
    )  # Make an API request.
    
    for row in results:
        print(row)

Usar structs em consultas parametrizadas

Para usar uma struct num parâmetro de consulta, defina o tipo como STRUCT<T>, em que T define os campos e os tipos na struct. As definições dos campos são separadas por vírgulas e têm o formato field_name TF, em que TF é o tipo do campo. Por exemplo, STRUCT<x INT64, y STRING> define uma struct com um campo denominado x do tipo INT64 e um segundo campo denominado y do tipo STRING.

Para mais informações sobre o tipo STRUCT, consulte a referência de tipos de dados .

Consola

As consultas parametrizadas não são suportadas pela consola Trusted Cloud .

bq

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Esta consulta trivial demonstra a utilização de tipos estruturados devolvendo o valor do parâmetro:

    bq query \
       --use_legacy_sql=false \
       --parameter='struct_value:STRUCT<x INT64, y STRING>:{"x": 1, "y": "foo"}' \
       'SELECT
         @struct_value AS s;'
  3. API

    Para usar um parâmetro struct, defina parameterType como STRUCT na configuração da tarefa de consulta.

    Adicione um objeto para cada campo da struct a structTypes no queryParameters da tarefa. Se os valores struct forem escalares, defina o elemento type para o tipo dos valores, como STRING. Se os valores struct forem matrizes, defina este campo como ARRAY e defina o campo arrayType aninhado para o tipo adequado. Se os valores struct forem estruturas, defina type como STRUCT e adicione o structTypes necessário.

    Esta consulta trivial demonstra a utilização de tipos estruturados devolvendo o valor do parâmetro.

    {
      "query": "SELECT @struct_value AS s;",
      "queryParameters": [
        {
          "name": "struct_value",
          "parameterType": {
            "type": "STRUCT",
            "structTypes": [
              {
                "name": "x",
                "type": {
                  "type": "INT64"
                }
              },
              {
                "name": "y",
                "type": {
                  "type": "STRING"
                }
              }
            ]
          },
          "parameterValue": {
            "structValues": {
              "x": {
                "value": "1"
              },
              "y": {
                "value": "foo"
              }
            }
          }
        }
      ],
      "useLegacySql": false,
      "parameterMode": "NAMED"
    }
    

    Experimente no Explorador de APIs Google.

    C#

    A biblioteca de cliente do BigQuery para .NET não suporta parâmetros struct.

    Go

    Antes de experimentar este exemplo, siga as Goinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Go BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/bigquery"
    	"google.golang.org/api/iterator"
    )
    
    // queryWithStructParam demonstrates running a query and providing query parameters that include struct
    // types.
    func queryWithStructParam(w io.Writer, projectID string) error {
    	// projectID := "my-project-id"
    	ctx := context.Background()
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %v", err)
    	}
    	defer client.Close()
    
    	type MyStruct struct {
    		X int64
    		Y string
    	}
    	q := client.Query(
    		`SELECT @struct_value as s;`)
    	q.Parameters = []bigquery.QueryParameter{
    		{
    			Name:  "struct_value",
    			Value: MyStruct{X: 1, Y: "foo"},
    		},
    	}
    	// Run the query and print results when the query job is completed.
    	job, err := q.Run(ctx)
    	if err != nil {
    		return err
    	}
    	status, err := job.Wait(ctx)
    	if err != nil {
    		return err
    	}
    	if err := status.Err(); err != nil {
    		return err
    	}
    	it, err := job.Read(ctx)
    	for {
    		var row []bigquery.Value
    		err := it.Next(&row)
    		if err == iterator.Done {
    			break
    		}
    		if err != nil {
    			return err
    		}
    		fmt.Fprintln(w, row)
    	}
    	return nil
    }
    

    Java

    Antes de experimentar este exemplo, siga as Javainstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Java BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    import com.google.cloud.bigquery.BigQuery;
    import com.google.cloud.bigquery.BigQueryException;
    import com.google.cloud.bigquery.BigQueryOptions;
    import com.google.cloud.bigquery.QueryJobConfiguration;
    import com.google.cloud.bigquery.QueryParameterValue;
    import com.google.cloud.bigquery.TableResult;
    import java.util.HashMap;
    import java.util.Map;
    
    public class QueryWithStructsParameters {
    
      public static void queryWithStructsParameters() {
        try {
          // Initialize client that will be used to send requests. This client only needs to be created
          // once, and can be reused for multiple requests.
          BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    
          // Create struct
          Map<String, QueryParameterValue> struct = new HashMap<>();
          struct.put("booleanField", QueryParameterValue.bool(true));
          struct.put("integerField", QueryParameterValue.string("test-stringField"));
          struct.put("stringField", QueryParameterValue.int64(10));
          QueryParameterValue recordValue = QueryParameterValue.struct(struct);
    
          String query = "SELECT STRUCT(@recordField) AS record";
          QueryJobConfiguration queryConfig =
              QueryJobConfiguration.newBuilder(query)
                  .setUseLegacySql(false)
                  .addNamedParameter("recordField", recordValue)
                  .build();
    
          TableResult results = bigquery.query(queryConfig);
    
          results
              .iterateAll()
              .forEach(row -> row.forEach(val -> System.out.printf("%s", val.toString())));
    
          System.out.println("Query with struct parameter performed successfully.");
        } catch (BigQueryException | InterruptedException e) {
          System.out.println("Query not performed \n" + e.toString());
        }
      }
    }

    Node.js

    Antes de experimentar este exemplo, siga as Node.jsinstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Node.js BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    // Run a query using struct query parameters
    
    // Import the Google Cloud client library
    const {BigQuery} = require('@google-cloud/bigquery');
    const bigquery = new BigQuery();
    
    async function queryParamsStructs() {
      // The SQL query to run
      const sqlQuery = `SELECT @struct_value AS struct_obj;`;
    
      const options = {
        query: sqlQuery,
        // Location must match that of the dataset(s) referenced in the query.
        location: 'US',
        params: {struct_value: {x: 1, y: 'foo'}},
      };
    
      // Run the query
      const [rows] = await bigquery.query(options);
    
      console.log('Rows:');
      rows.forEach(row => console.log(row.struct_obj.y));
    }

    Python

    Antes de experimentar este exemplo, siga as Pythoninstruções de configuração no início rápido do BigQuery com bibliotecas cliente. Para mais informações, consulte a API Python BigQuery documentação de referência.

    Para se autenticar no BigQuery, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

    Antes de executar exemplos de código, defina a variável GOOGLE_CLOUD_UNIVERSE_DOMAIN environment como s3nsapis.fr.

    from google.cloud import bigquery
    
    # Construct a BigQuery client object.
    client = bigquery.Client()
    
    query = "SELECT @struct_value AS s;"
    job_config = bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.StructQueryParameter(
                "struct_value",
                bigquery.ScalarQueryParameter("x", "INT64", 1),
                bigquery.ScalarQueryParameter("y", "STRING", "foo"),
            )
        ]
    )
    results = client.query_and_wait(
        query, job_config=job_config
    )  # Make an API request and waits for results.
    
    for row in results:
        print(row.s)