use crate::databricks_source::constants::{BINARY_COLLATION, COLLATE};
use crate::databricks_source::models::DatabricksReadRequest;
use crate::postgres_source::models::SourceTable;
pub(crate) fn quote_identifier(name: &str) -> String {
format!("`{}`", name.replace('`', "``"))
}
pub(crate) fn quote_text(name: &str) -> String {
format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
}
fn from_item(catalog: &str, (table, sql): (&SourceTable, Option<&str>)) -> String {
match sql {
Some(sql) => subquery(sql),
None => [catalog, &table.schema, &table.name]
.map(quote_identifier)
.join("."),
}
}
pub(crate) fn select_query(catalog: &str, request: &DatabricksReadRequest<'_>) -> String {
let columns: Vec<String> = request
.columns
.iter()
.map(|column| selected(&column.expression))
.collect();
let filter = request
.filter
.map(|filter| format!(" WHERE {filter}"))
.unwrap_or_default();
format!(
"SELECT {} FROM {}{filter}",
columns.join(", "),
from_item(catalog, (request.table, request.sql))
)
}
fn selected(expression: &str) -> String {
match expression.strip_suffix(&format!("{COLLATE}{BINARY_COLLATION}")) {
Some(name) => format!("{expression} AS {name}"),
None => expression.to_owned(),
}
}
pub(crate) fn count_query(
catalog: &str,
(table, sql): (&SourceTable, Option<&str>),
filter: &str,
) -> String {
format!(
"SELECT COUNT(*) FROM {} WHERE {filter}",
from_item(catalog, (table, sql))
)
}
pub(crate) fn subquery(sql: &str) -> String {
let body = sql
.trim_start()
.trim_end_matches(|character: char| character == ';' || character.is_whitespace());
format!("({body}\n)")
}