use ref_view::RefView;
#[derive(RefView)]
#[ref_view(name = TableReferenceWithoutPivot, omit(Table.pivot, Subquery.pivot))]
enum TableReference {
Table {
name: String,
alias: Option<String>,
pivot: String,
sample: Option<u8>,
},
Subquery {
query: String,
alias: Option<String>,
pivot: String,
},
}
fn format_table_reference<T: TableReferenceView>(table_ref: &T) -> String {
let mut out = String::new();
if let Some(name) = table_ref.name() {
out.push_str(name);
}
if let Some(query) = table_ref.query() {
out.push('(');
out.push_str(query);
out.push(')');
}
if let Some(alias) = table_ref.alias() {
out.push_str(" AS ");
out.push_str(alias);
}
if let Some(sample) = table_ref.sample() {
out.push_str(&format!(" SAMPLE {}", sample));
}
if let Some(pivot) = table_ref.pivot() {
out.push_str(" PIVOT ");
out.push_str(pivot);
}
out
}
fn main() {
let table = TableReference::Table {
name: "\"pivot any quoted db\".\"select\"".to_string(),
alias: Some("src".to_string()),
pivot: "SUM(amount) FOR quarter IN (ANY)".to_string(),
sample: Some(10),
};
let full = TableReferenceRef::from(&table);
let without_pivot = TableReferenceWithoutPivot::from(&table);
println!("{}", format_table_reference(&full));
println!("{}", format_table_reference(&without_pivot));
let subquery = TableReference::Subquery {
query: "SELECT * FROM sales".to_string(),
alias: Some("s".to_string()),
pivot: "SUM(amount) FOR month IN (ANY)".to_string(),
};
println!(
"{}",
format_table_reference(&TableReferenceWithoutPivot::from(&subquery))
);
}