Skip to main content

sql_file

Macro sql_file 

Source
macro_rules! sql_file {
    ($path:literal $(, $parameter:ident)* $(,)?) => { ... };
}
Expand description

Embeds a GoogleSQL file as a BigQuerySql and checks, as the calling crate compiles, that the names listed after the path are exactly the file’s @name parameters.

The path is relative to the file that calls the macro, as for include_str!, and Cargo rebuilds the crate when the .sql file changes. Pass the result to query and bind each value with .param, as for a query written inline:

use bigquery::*;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct WordCount {
    word: String,
    word_count: i64,
}

let top_words: Vec<WordCount> = db
    .fluent()
    .query(bigquery::sql_file!("sql/top_words.sql", corpus, min_count))
    .param("corpus", "hamlet")
    .param("min_count", 100)
    .obj()
    .query()
    .await?;

A parameter the file uses but the list leaves out fails the build:

ⓘ
let _ = bigquery::sql_file!("sql/top_words.sql", corpus);

So does a listed name the file never uses:

ⓘ
let _ = bigquery::sql_file!("sql/top_words.sql", corpus, min_count, limit);

The compiler cannot see which names the .param calls bind, so the query checks them when it runs: a terminal fails with InvalidParametersError, naming the parameter, before any request is sent if a listed name is not bound or a bound name is not listed.

The file is read with GoogleSQL’s lexical rules, so an @ inside a string or bytes literal, a backtick-quoted identifier or a comment is not a parameter, and neither is a @@name system variable. Whitespace and comments may stand between @ and the name, and the name may be backtick-quoted: @`corpus` lists as corpus. An unquoted name ends at the first character that cannot be part of an identifier: @window.earliest reads the field earliest of the STRUCT parameter window, and lists as window. Names are compared ignoring ASCII case, as BigQuery compares them, so @Corpus lists as corpus.