use crate::column_types::main::warehouse_type::warehouse_type;
use crate::column_types::models::{ColumnType, Warehouse};
use crate::write_sql::models::TableName;
fn is_plain(name: &str) -> bool {
name.chars()
.next()
.is_some_and(|first| first.is_ascii_lowercase() || first == '_')
&& name.chars().all(|character| {
character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_'
})
}
pub(crate) fn quote(name: &str, warehouse: Warehouse) -> String {
let stored = match warehouse {
Warehouse::Snowflake if is_plain(name) => name.to_ascii_uppercase(),
_ => name.to_owned(),
};
format!("\"{}\"", stored.replace('"', "\"\""))
}
pub(crate) fn qualified(table: &TableName, warehouse: Warehouse) -> String {
let schema_and_table = format!(
"{}.{}",
quote(&table.schema, warehouse),
quote(&table.table, warehouse)
);
match &table.database {
Some(database) => format!("{}.{schema_and_table}", quote(database, warehouse)),
None => schema_and_table,
}
}
pub(crate) fn with_suffix(table: &TableName, suffix: &str) -> TableName {
TableName {
table: format!("{}{suffix}", table.table),
..table.clone()
}
}
pub(crate) fn literal(text: &str, warehouse: Warehouse) -> String {
let escaped = match warehouse {
Warehouse::Snowflake => text.replace('\\', "\\\\"),
_ => text.to_owned(),
};
format!("'{}'", escaped.replace('\'', "''"))
}
pub(crate) fn staging_type(column_type: &ColumnType, warehouse: Warehouse) -> String {
match column_type {
ColumnType::Json | ColumnType::Uuid => warehouse_type(&ColumnType::Text, warehouse).sql,
other => warehouse_type(other, warehouse).sql,
}
}
pub(crate) fn from_staging(name: &str, column_type: &ColumnType, warehouse: Warehouse) -> String {
let column = quote(name, warehouse);
match (column_type, warehouse) {
(ColumnType::Json, Warehouse::Snowflake) => format!("PARSE_JSON({column})"),
(ColumnType::Json | ColumnType::Uuid, _) => {
format!(
"CAST({column} AS {})",
warehouse_type(column_type, warehouse).sql
)
}
_ => column,
}
}
pub(crate) fn quote_live(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\""))
}