use text_size::TextSize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Context {
DotOf {
alias: String,
},
Table,
Projection,
Predicate,
Statement,
AlterTableAction,
General,
}
pub fn detect(source: &str, offset: TextSize) -> Context {
let pos: usize = offset.into();
let before = &source[..pos.min(source.len())];
if let Some(ctx) = dot_context(before) {
return ctx;
}
if after_alter_table_name(before) {
return Context::AlterTableAction;
}
if is_after_keyword(before, &["FROM", "JOIN", "INTO", "UPDATE", "TABLE", "INSERT INTO", "ALTER TABLE"]) {
return Context::Table;
}
if is_after_keyword(before, &["ON", "WHERE", "HAVING", "AND", "OR"]) {
return Context::Predicate;
}
if in_projection_list(before) {
return Context::Projection;
}
if at_statement_start(before) {
return Context::Statement;
}
Context::General
}
fn dot_context(before: &str) -> Option<Context> {
let dot_idx = before.rfind('.')?;
let after_dot = &before[dot_idx + 1..];
if !after_dot.chars().all(|c| c.is_alphanumeric() || c == '_') {
return None;
}
let pre_dot = &before[..dot_idx];
let alias: String =
pre_dot.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>().chars().rev().collect();
if alias.is_empty() {
return None;
}
Some(Context::DotOf { alias })
}
fn is_after_keyword(before: &str, keywords: &[&str]) -> bool {
let cur = before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>();
let cut = before.len() - cur.len();
let trimmed_upper = before[..cut].trim_end().to_uppercase();
keywords.iter().any(|kw| trimmed_upper.ends_with(kw))
}
fn in_projection_list(before: &str) -> bool {
let upper = before.to_uppercase();
let select_idx = upper.rfind("SELECT");
let Some(sel) = select_idx else {
return false;
};
if let Some(from) = upper[sel + 6..].find("FROM") {
let from_abs = sel + 6 + from;
if upper[from_abs..].rfind("SELECT").is_none() {
return false;
}
}
true
}
fn after_alter_table_name(before: &str) -> bool {
let cur: String =
before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>().chars().rev().collect();
let cut = before.len() - cur.len();
let head = before[..cut].trim_end();
let table_chars: String = head
.chars()
.rev()
.take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '"' || *c == '.')
.collect::<String>()
.chars()
.rev()
.collect();
if table_chars.is_empty() {
return false;
}
let cut2 = head.len() - table_chars.len();
let head2 = head[..cut2].trim_end().to_ascii_uppercase();
let head2 = head2.trim_end_matches("IF EXISTS").trim_end();
let head2 = head2.trim_end_matches("ONLY").trim_end();
head2.ends_with("ALTER TABLE")
}
fn at_statement_start(before: &str) -> bool {
let cur = before.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>();
let cut = before.len() - cur.len();
let head = before[..cut].trim_end();
head.is_empty() || head.ends_with(';')
}