use bumpalo::collections::Vec as BumpVec;
use vibesql_ast::arena::{
Assignment, ConflictClause, InsertSource, InsertStmt, OnConflictAction, OnConflictClause,
Symbol,
};
use super::ArenaParser;
use crate::{keywords::Keyword, token::Token, ParseError};
struct TableRefParts {
schema_name: Option<Symbol>,
schema_quoted: bool,
table_name: Symbol,
table_quoted: bool,
}
impl<'arena> ArenaParser<'arena> {
fn parse_insert_table_ref(&mut self) -> Result<TableRefParts, ParseError> {
let (first_part, first_quoted) = match self.peek() {
Token::Identifier(name) => {
let name = name.clone();
self.advance();
(self.intern(&name), false)
}
Token::DelimitedIdentifier(name) => {
let name = name.clone();
self.advance();
(self.intern(&name), true)
}
_ => {
return Err(ParseError { message: "Expected table name".to_string() });
}
};
if self.try_consume(&Token::Symbol('.')) {
let (second_part, second_quoted) = match self.peek() {
Token::Identifier(name) => {
let name = name.clone();
self.advance();
(self.intern(&name), false)
}
Token::DelimitedIdentifier(name) => {
let name = name.clone();
self.advance();
(self.intern(&name), true)
}
_ => {
return Err(ParseError {
message: "Expected identifier after '.'".to_string(),
});
}
};
Ok(TableRefParts {
schema_name: Some(first_part),
schema_quoted: first_quoted,
table_name: second_part,
table_quoted: second_quoted,
})
} else {
Ok(TableRefParts {
schema_name: None,
schema_quoted: false,
table_name: first_part,
table_quoted: first_quoted,
})
}
}
pub(crate) fn parse_insert_statement(
&mut self,
) -> Result<&'arena InsertStmt<'arena>, ParseError> {
self.consume_keyword(Keyword::Insert)?;
let conflict_clause = if self.try_consume_keyword(Keyword::Or) {
if self.try_consume_keyword(Keyword::Replace) {
Some(ConflictClause::Replace)
} else if self.try_consume_keyword(Keyword::Ignore) {
Some(ConflictClause::Ignore)
} else if self.try_consume_keyword(Keyword::Abort) {
Some(ConflictClause::Abort)
} else if self.try_consume_keyword(Keyword::Rollback) {
Some(ConflictClause::Rollback)
} else if self.try_consume_keyword(Keyword::Fail) {
Some(ConflictClause::Fail)
} else {
return Err(ParseError {
message: "Expected REPLACE, IGNORE, ABORT, ROLLBACK, or FAIL after INSERT OR"
.to_string(),
});
}
} else {
None
};
self.consume_keyword(Keyword::Into)?;
let table_ref = self.parse_insert_table_ref()?;
let columns = if self.try_consume(&Token::LParen) {
let cols = self.parse_identifier_list()?;
self.expect_token(Token::RParen)?;
cols
} else {
BumpVec::new_in(self.arena)
};
let source = if self.try_consume_keyword(Keyword::Default) {
self.consume_keyword(Keyword::Values)?;
InsertSource::DefaultValues
} else if self.try_consume_keyword(Keyword::Values) {
let values = self.parse_values_clause()?;
InsertSource::Values(values)
} else if self.peek_keyword(Keyword::Select) || self.peek_keyword(Keyword::With) {
let query = self.parse_select_statement()?;
InsertSource::Select(query)
} else {
return Err(ParseError {
message: "Expected VALUES or SELECT after INSERT".to_string(),
});
};
let (on_conflict, on_duplicate_key_update) = self.parse_on_clause_for_insert()?;
let returning = if self.try_consume_keyword(Keyword::Returning) {
Some(self.parse_select_list()?)
} else {
None
};
self.expect_statement_end()?;
let stmt = InsertStmt {
with_clause: None,
schema_name: table_ref.schema_name,
schema_quoted: table_ref.schema_quoted,
table_name: table_ref.table_name,
table_quoted: table_ref.table_quoted,
columns,
source,
conflict_clause,
on_conflict,
on_duplicate_key_update,
returning,
};
Ok(self.arena.alloc(stmt))
}
pub(crate) fn parse_replace_statement(
&mut self,
) -> Result<&'arena InsertStmt<'arena>, ParseError> {
self.consume_keyword(Keyword::Replace)?;
self.consume_keyword(Keyword::Into)?;
let table_ref = self.parse_insert_table_ref()?;
let columns = if self.try_consume(&Token::LParen) {
let cols = self.parse_identifier_list()?;
self.expect_token(Token::RParen)?;
cols
} else {
BumpVec::new_in(self.arena)
};
let source = if self.try_consume_keyword(Keyword::Default) {
self.consume_keyword(Keyword::Values)?;
InsertSource::DefaultValues
} else if self.try_consume_keyword(Keyword::Values) {
let values = self.parse_values_clause()?;
InsertSource::Values(values)
} else if self.peek_keyword(Keyword::Select) || self.peek_keyword(Keyword::With) {
let query = self.parse_select_statement()?;
InsertSource::Select(query)
} else {
return Err(ParseError {
message: "Expected VALUES or SELECT after REPLACE".to_string(),
});
};
let (on_conflict, on_duplicate_key_update) = self.parse_on_clause_for_insert()?;
let returning = if self.try_consume_keyword(Keyword::Returning) {
Some(self.parse_select_list()?)
} else {
None
};
self.expect_statement_end()?;
let stmt = InsertStmt {
with_clause: None,
schema_name: table_ref.schema_name,
schema_quoted: table_ref.schema_quoted,
table_name: table_ref.table_name,
table_quoted: table_ref.table_quoted,
columns,
source,
conflict_clause: Some(ConflictClause::Replace),
on_conflict,
on_duplicate_key_update,
returning,
};
Ok(self.arena.alloc(stmt))
}
fn parse_values_clause(
&mut self,
) -> Result<BumpVec<'arena, BumpVec<'arena, vibesql_ast::arena::Expression<'arena>>>, ParseError>
{
let mut rows = BumpVec::new_in(self.arena);
loop {
self.expect_token(Token::LParen)?;
let row = self.parse_expression_list()?;
self.expect_token(Token::RParen)?;
rows.push(row);
if !self.try_consume(&Token::Comma) {
break;
}
}
Ok(rows)
}
fn parse_on_clause_for_insert(
&mut self,
) -> Result<
(Option<OnConflictClause<'arena>>, Option<BumpVec<'arena, Assignment<'arena>>>),
ParseError,
> {
if !self.try_consume_keyword(Keyword::On) {
return Ok((None, None));
}
if self.try_consume_keyword(Keyword::Conflict) {
let conflict_target = if self.try_consume(&Token::LParen) {
let cols = self.parse_identifier_list()?;
self.expect_token(Token::RParen)?;
let mut items = BumpVec::new_in(self.arena);
for col in cols {
items.push(vibesql_ast::arena::ConflictTargetItem::Column(col));
}
Some(items)
} else {
None
};
self.consume_keyword(Keyword::Do)?;
let action = if self.try_consume_keyword(Keyword::Nothing) {
OnConflictAction::DoNothing
} else if self.try_consume_keyword(Keyword::Update) {
self.consume_keyword(Keyword::Set)?;
let assignments = self.parse_assignments()?;
let where_clause = if self.try_consume_keyword(Keyword::Where) {
Some(self.parse_expression()?)
} else {
None
};
OnConflictAction::DoUpdate { assignments, where_clause }
} else {
return Err(ParseError {
message: "Expected NOTHING or UPDATE after DO".to_string(),
});
};
Ok((
Some(OnConflictClause {
conflict_target,
target_where: None,
target_inexact: false,
action,
}),
None,
))
} else if self.try_consume_keyword(Keyword::Duplicate) {
self.consume_keyword(Keyword::Key)?;
self.consume_keyword(Keyword::Update)?;
let assignments = self.parse_assignments()?;
Ok((None, Some(assignments)))
} else {
Err(ParseError { message: "Expected CONFLICT or DUPLICATE after ON".to_string() })
}
}
}