use std::{fmt, str::FromStr};
use crate::common::*;
use crate::drivers::bigquery_shared::{BqColumn, BqTable, TableName, Usage};
#[derive(Clone, Debug)]
pub struct BigQuerySchemaLocator {
path: PathOrStdio,
}
impl fmt::Display for BigQuerySchemaLocator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.path.fmt_locator_helper(Self::scheme(), f)
}
}
impl FromStr for BigQuerySchemaLocator {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let path = PathOrStdio::from_str_locator_helper(Self::scheme(), s)?;
Ok(BigQuerySchemaLocator { path })
}
}
impl Locator for BigQuerySchemaLocator {
fn as_any(&self) -> &dyn Any {
self
}
fn schema(&self, ctx: Context) -> BoxFuture<Option<Table>> {
schema_helper(ctx, self.to_owned()).boxed()
}
fn write_schema(
&self,
ctx: Context,
table: Table,
if_exists: IfExists,
) -> BoxFuture<()> {
write_schema_helper(ctx, self.to_owned(), table, if_exists).boxed()
}
}
impl LocatorStatic for BigQuerySchemaLocator {
fn scheme() -> &'static str {
"bigquery-schema:"
}
fn features() -> Features {
Features {
locator: LocatorFeatures::Schema | LocatorFeatures::WriteSchema,
write_schema_if_exists: IfExistsFeatures::no_append(),
source_args: EnumSet::empty(),
dest_args: EnumSet::empty(),
dest_if_exists: EnumSet::empty(),
_placeholder: (),
}
}
}
async fn schema_helper(
_ctx: Context,
source: BigQuerySchemaLocator,
) -> Result<Option<Table>> {
let input = source.path.open_async().await?;
let data = async_read_to_end(input)
.await
.with_context(|_| format!("error reading {}", source.path))?;
let columns: Vec<BqColumn> = serde_json::from_slice(&data)
.with_context(|_| format!("error parsing {}", source.path))?;
let arbitrary_name = TableName::from_str(&"unused:unused.unused")?;
let bq_table = BqTable {
name: arbitrary_name,
columns,
};
let mut table = bq_table.to_table()?;
table.name = "unnamed".to_owned();
Ok(Some(table))
}
async fn write_schema_helper(
ctx: Context,
dest: BigQuerySchemaLocator,
table: Table,
if_exists: IfExists,
) -> Result<()> {
let arbitrary_name = TableName::from_str(&"unused:unused.unused")?;
let bq_table = BqTable::for_table_name_and_columns(
arbitrary_name,
&table.columns,
Usage::FinalTable,
)?;
let f = dest.path.create_async(ctx, if_exists).await?;
buffer_sync_write_and_copy_to_async(f, |buff| bq_table.write_json_schema(buff))
.await
.with_context(|_| format!("error writing to {}", dest.path))?;
Ok(())
}