use sqlparser::tokenizer::Location;
pub(super) struct Cursor<'a> {
pub(super) sql: &'a str,
pub(super) at: usize,
pub(super) location: Location,
}
impl Cursor<'_> {
pub(super) fn identifier_before(&self) -> bool {
self.sql[..self.at]
.chars()
.next_back()
.is_some_and(|previous| {
previous.is_alphanumeric() || matches!(previous, '_' | '$') || !previous.is_ascii()
})
}
pub(super) fn peek(&self) -> Option<char> {
self.sql[self.at..].chars().next()
}
pub(super) fn starts(&self, prefix: &str) -> bool {
self.sql[self.at..].starts_with(prefix)
}
pub(super) fn next(&mut self) -> Option<char> {
let character = self.peek()?;
self.at += character.len_utf8();
if character == '\n' {
self.location.line += 1;
self.location.column = 1;
} else {
self.location.column += 1;
}
Some(character)
}
pub(super) fn line_comment(&mut self) -> bool {
while let Some(character) = self.next() {
if character == '\n' {
return true;
}
}
false
}
pub(super) fn block_comment(&mut self) {
self.next();
self.next();
let mut depth = 1;
while self.peek().is_some() {
if self.starts("/*") {
self.next();
self.next();
depth += 1;
} else if self.starts("*/") {
self.next();
self.next();
depth -= 1;
if depth == 0 {
break;
}
} else {
self.next();
}
}
}
pub(super) fn dollar_body(&mut self) -> bool {
let remaining = &self.sql[self.at + 1..];
let Some(end) = remaining.find('$') else {
return false;
};
let tag = &remaining[..end];
if !tag.is_empty()
&& (!tag
.chars()
.next()
.is_some_and(|c| c.is_alphabetic() || c == '_' || !c.is_ascii())
|| !tag
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()))
{
return false;
}
let delimiter = &self.sql[self.at..self.at + end + 2];
let after = self.at + delimiter.len();
let finish = self.sql[after..]
.find(delimiter)
.map_or(self.sql.len(), |end| after + end + delimiter.len());
while self.at < finish {
self.next();
}
true
}
pub(super) fn quoted(
&mut self,
quote: char,
escaped: bool,
mask: bool,
output: &mut [u8],
) -> Option<usize> {
self.next();
while let Some(character) = self.peek() {
let at = self.at;
self.next();
if escaped && character == '\\' {
if mask {
output[at] = b'_';
if matches!(self.peek(), Some('\'' | '\\')) {
output[self.at] = b'_';
}
}
self.next();
} else if character == quote {
if self.peek() == Some(quote) {
self.next();
} else {
return Some(at);
}
}
}
None
}
}