Realizar consultas con parámetros

BigQuery admite parámetros de consulta para ayudar a evitar la inyección de SQL cuando las consultas se crean con entradas de usuario. Esta función solo está disponible con la sintaxis de GoogleSQL. Los parámetros de consulta se pueden usar como sustitutos de expresiones arbitrarias. Los parámetros no se pueden usar como sustitutos de identificadores, nombres de columnas, nombres de tablas u otras partes de la consulta.

Para especificar un parámetro con nombre, usa el carácter @ seguido de un identificador, como @param_name. También puedes usar el valor de marcador de posición ? para especificar un parámetro posicional. Ten en cuenta que una consulta puede usar parámetros posicionales o con nombre, pero no ambos.

Cuando se usa un parámetro, el valor proporcionado no se registra en los registros de BigQuery para proteger la información potencialmente sensible.

Puedes ejecutar una consulta con parámetros en BigQuery de las siguientes formas:

  • el comando bq query de la herramienta de línea de comandos bq
  • la API
  • las bibliotecas de cliente

En el siguiente ejemplo se muestra cómo transferir valores de parámetros a una consulta parametrizada:

Consola

La consola Google Cloud no admite consultas parametrizadas.

bq

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

    Activate Cloud Shell

    At the bottom of the Google 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. Usa --parameter para proporcionar valores de parámetros con el formato name:type:value. Si el nombre está vacío, se genera un parámetro posicional. El tipo se puede omitir para asumir STRING.

    La marca --parameter debe usarse junto con la marca --use_legacy_sql=false para especificar la sintaxis de GoogleSQL.

    (Opcional) Especifica tu ubicación con la marca --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 con nombre, asigna el valor NAMED a parameterMode en la configuración del trabajo query.

    Rellena queryParameters con la lista de parámetros del trabajo query. Asigna el name de cada parámetro con el @param_name usado en la consulta.

    Habilita la sintaxis de GoogleSQL definiendo 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"
    }
    

    Pruébalo en el Explorador de APIs de Google.

    Para usar parámetros posicionales, asigna el valor POSITIONAL a parameterMode en la configuración del trabajo query.

    C#

    Antes de probar este ejemplo, sigue las C#instrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros con nombre, sigue estos pasos:
    
    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 probar este ejemplo, sigue las C#instrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros posicionales, sigue estos pasos:
    
    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 probar este ejemplo, sigue las Goinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros con nombre, sigue estos pasos:
    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 posicionales, sigue estos pasos:
    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 probar este ejemplo, sigue las Javainstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros con nombre, sigue estos pasos:
    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 posicionales, sigue estos pasos:
    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 probar este ejemplo, sigue las Node.jsinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros con nombre, sigue estos pasos:
    // 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 posicionales, sigue estos pasos:
    // 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 probar este ejemplo, sigue las Pythoninstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    Para usar parámetros con nombre, sigue estos pasos:
    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 posicionales, sigue estos pasos:
    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 matrices en consultas con parámetros

Para usar un tipo de array en un parámetro de consulta, define el tipo como ARRAY<T>, donde T es el tipo de los elementos del array. Crea el valor como una lista de elementos separados por comas y entre corchetes, como [1, 2, 3].

Consulta la referencia de tipos de datos para obtener más información sobre el tipo de matriz.

Consola

La consola Google Cloud no admite consultas parametrizadas.

bq

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

    Activate Cloud Shell

    At the bottom of the Google 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 selecciona los nombres más populares de los niños nacidos en estados de EE. UU. que empiezan por la 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;'

    Asegúrate de incluir la declaración del tipo de matriz entre comillas simples para que el carácter > no redirija accidentalmente la salida del comando a un archivo.

  3. API

    Para usar un parámetro con valor de array, define parameterType como ARRAY en la configuración de la tarea query.

    Si los valores de la matriz son escalares, defina parameterType como el tipo de los valores, como STRING. Si los valores de la matriz son estructuras, asigna el valor STRUCT y añade las definiciones de campo necesarias a structTypes.

    Por ejemplo, esta consulta selecciona los nombres más populares de niños nacidos en estados de EE. UU. que empiezan por la 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"
    }
    

    Pruébalo en el Explorador de APIs de Google.

    C#

    Antes de probar este ejemplo, sigue las C#instrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    
    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 probar este ejemplo, sigue las Goinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Javainstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Node.jsinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    // 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 probar este ejemplo, sigue las Pythoninstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 marcas de tiempo en consultas con parámetros

Para usar una marca de tiempo en un parámetro de consulta, la API REST subyacente toma un valor de tipo TIMESTAMP en el formato YYYY-MM-DD HH:MM:SS.DDDDDD time_zone. Si usas las bibliotecas de cliente, crea un objeto de fecha integrado en ese lenguaje y la biblioteca lo convierte al formato correcto. Para obtener más información, consulta los siguientes ejemplos específicos de cada idioma.

Para obtener más información sobre el tipo TIMESTAMP, consulta la referencia de tipos de datos.

Consola

La consola Google Cloud no admite consultas parametrizadas.

bq

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

    Activate Cloud Shell

    At the bottom of the Google 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 añade una hora al valor del parámetro de marca de tiempo:

    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 un parámetro de marca de tiempo, define parameterType como TIMESTAMP en la configuración de la tarea de consulta.

    Esta consulta añade una hora al valor del parámetro de marca de tiempo.

    {
      "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"
    }
    

    Pruébalo en el Explorador de APIs de Google.

    C#

    Antes de probar este ejemplo, sigue las C#instrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    
    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 probar este ejemplo, sigue las Goinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Javainstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Node.jsinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    // 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 probar este ejemplo, sigue las Pythoninstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 en consultas con parámetros

Para usar una estructura en un parámetro de consulta, define el tipo como STRUCT<T>, donde T define los campos y los tipos de la estructura. Las definiciones de los campos se separan con comas y tienen el formato field_name TF, donde TF es el tipo del campo. Por ejemplo, STRUCT<x INT64, y STRING> define una estructura con un campo llamado x de tipo INT64 y un segundo campo llamado y de tipo STRING.

Para obtener más información sobre el tipo STRUCT, consulta la referencia de tipos de datos .

Consola

La consola Google Cloud no admite consultas parametrizadas.

bq

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

    Activate Cloud Shell

    At the bottom of the Google 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 muestra el uso de tipos estructurados devolviendo el valor del 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 un parámetro struct, define parameterType como STRUCT en la configuración de la tarea de consulta.

    Añade un objeto por cada campo de la struct a structTypes en el queryParameters del trabajo. Si los valores de struct son escalares, define type como el tipo de los valores, como STRING. Si los valores de struct son arrays, asigna el valor ARRAY a este campo y asigna el tipo adecuado al campo arrayType anidado. Si los valores de struct son estructuras, asigna el valor type a STRUCT y añade el structTypes necesario.

    Esta consulta trivial muestra el uso de tipos estructurados devolviendo el valor del 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"
    }
    

    Pruébalo en el Explorador de APIs de Google.

    C#

    La biblioteca cliente de BigQuery para .NET no admite parámetros struct.

    Go

    Antes de probar este ejemplo, sigue las Goinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Javainstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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 probar este ejemplo, sigue las Node.jsinstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    // 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 probar este ejemplo, sigue las Pythoninstrucciones de configuración de la guía de inicio rápido de BigQuery con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de BigQuery.

    Para autenticarte en BigQuery, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación para bibliotecas de cliente.

    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)