use crate::errors::{BigQueryInvalidParametersError, BigQueryInvalidParametersPublicDetails};
use std::fmt::{Display, Formatter};
use std::str::FromStr;
pub(crate) fn quote_identifier(name: &str) -> String {
let mut out = String::with_capacity(name.len() + 2);
out.push('`');
escape_into(&mut out, name, '`');
out.push('`');
out
}
pub(crate) fn escape_into(out: &mut String, text: &str, quote: char) {
for c in text.chars() {
match c {
'\\' => out.push_str("\\\\"),
c if c == quote => {
out.push('\\');
out.push(c);
}
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() || is_invisible(c) => {
let code = u32::from(c);
if code < 0x80 {
out.push_str(&format!("\\x{code:02x}"));
} else if code <= 0xFFFF {
out.push_str(&format!("\\u{code:04x}"));
} else {
out.push_str(&format!("\\U{code:08x}"));
}
}
c => out.push(c),
}
}
}
fn is_invisible(c: char) -> bool {
matches!(c,
'\u{00AD}'
| '\u{061C}'
| '\u{180E}'
| '\u{200B}'..='\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{2060}'..='\u{206F}'
| '\u{FEFF}'
| '\u{FFF9}'..='\u{FFFB}'
| '\u{E0000}'..='\u{E007F}')
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ColumnPath {
segments: Vec<String>,
}
impl ColumnPath {
pub(crate) fn sql(&self) -> String {
self.segments
.iter()
.map(|s| quote_identifier(s))
.collect::<Vec<_>>()
.join(".")
}
}
pub(crate) fn column_segment_violation(segment: &str) -> Option<String> {
if segment.is_empty() {
return Some("is empty".into());
}
segment
.chars()
.find(|character| character.is_control())
.map(|character| format!("holds the control character {character:?}"))
}
pub(crate) fn dotted_path(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_string()
} else {
format!("{prefix}.{name}")
}
}
impl FromStr for ColumnPath {
type Err = BigQueryInvalidParametersError;
fn from_str(path: &str) -> Result<Self, Self::Err> {
let segments: Vec<String> = path.split('.').map(String::from).collect();
if let Some(violation) = segments
.iter()
.find_map(|segment| column_segment_violation(segment))
{
return Err(BigQueryInvalidParametersError::new(
BigQueryInvalidParametersPublicDetails::new(
path.to_string(),
format!("the column path {path:?} has a segment that {violation}"),
),
));
}
Ok(Self { segments })
}
}
impl Display for ColumnPath {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.segments.join("."))
}
}