use super::table_ref::check_project_id;
use crate::errors::BigQueryError;
use crate::{BigQueryLocation, BigQueryResult};
use gcloud_sdk::GoogleEnvironment;
use rsb_derive::Builder;
use url::Url;
pub const BIGQUERY_API_URL: &str = "https://bigquery.googleapis.com";
pub const BIGQUERY_STORAGE_API_URL: &str = "https://bigquerystorage.googleapis.com";
#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct BigQueryDbOptions {
pub google_project_id: String,
pub location: Option<BigQueryLocation>,
#[default = "3"]
pub max_retries: usize,
pub bigquery_api_url: Option<Url>,
pub bigquery_storage_api_url: Option<Url>,
}
impl BigQueryDbOptions {
pub async fn for_default_project_id() -> Option<BigQueryDbOptions> {
GoogleEnvironment::detect_google_project_id()
.await
.map(BigQueryDbOptions::new)
}
pub fn effective_bigquery_api_url(&self) -> Url {
self.bigquery_api_url.clone().unwrap_or_else(|| {
Url::parse(BIGQUERY_API_URL).expect("BIGQUERY_API_URL is an absolute https URL")
})
}
pub fn effective_bigquery_storage_api_url(&self) -> Url {
self.bigquery_storage_api_url.clone().unwrap_or_else(|| {
Url::parse(BIGQUERY_STORAGE_API_URL)
.expect("BIGQUERY_STORAGE_API_URL is an absolute https URL")
})
}
pub(crate) fn check(&self) -> BigQueryResult<()> {
check_project_id("google_project_id", &self.google_project_id)?;
check_grpc_endpoint("bigquery_api_url", &self.effective_bigquery_api_url())?;
check_grpc_endpoint(
"bigquery_storage_api_url",
&self.effective_bigquery_storage_api_url(),
)
}
}
fn check_grpc_endpoint(field: &'static str, url: &Url) -> BigQueryResult<()> {
if !matches!(url.scheme(), "http" | "https") {
return Err(BigQueryError::invalid_parameters(
field,
format!("must start with http:// or https://, was \"{url}\""),
));
}
if url.host_str().is_none_or(str::is_empty) {
return Err(BigQueryError::invalid_parameters(
field,
format!("must name a host, was \"{url}\""),
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_endpoints_are_the_two_google_hosts() {
let options = BigQueryDbOptions::new("acme-prod".to_string());
assert_eq!(
options.effective_bigquery_api_url().host_str(),
Some("bigquery.googleapis.com")
);
assert_eq!(
options.effective_bigquery_storage_api_url().host_str(),
Some("bigquerystorage.googleapis.com")
);
}
}