use super::{normalize_copy_data, normalize_table_queries, PostgresParseError};
use sqlparser::ast::Statement;
use sqlparser::dialect::PostgreSqlDialect;
use sqlparser::keywords::Keyword;
use sqlparser::parser::Parser;
use sqlparser::tokenizer::{Location, Token, TokenWithSpan};
use std::borrow::Cow;
use std::cell::{Cell, OnceCell, Ref, RefCell};
pub struct PreparedSql<'a> {
normalized: Cow<'a, str>,
source_positions_preserved: Cell<bool>,
tokens: OnceCell<Result<Vec<TokenWithSpan>, PostgresParseError>>,
functions: RefCell<Vec<super::super::SqlFunctionCallFact>>,
policy_arbiters: RefCell<Vec<super::super::source::PolicyArbiter>>,
}
impl<'a> PreparedSql<'a> {
pub fn new(sql: &'a str) -> Self {
Self {
normalized: normalize_copy_data(sql),
tokens: OnceCell::new(),
functions: RefCell::new(Vec::new()),
policy_arbiters: RefCell::new(Vec::new()),
source_positions_preserved: Cell::new(true),
}
}
pub fn normalized(&self) -> &str {
&self.normalized
}
pub fn tokens(&self) -> &[TokenWithSpan] {
self.located().map_or(&[], Vec::as_slice)
}
pub fn keyword_is_absent(&self, keyword: Keyword) -> bool {
self.located().is_ok_and(|tokens| {
!tokens.iter().any(|token| {
matches!(&token.token, Token::Word(word)
if word.quote_style.is_none() && word.keyword == keyword)
})
})
}
pub(crate) fn tokens_preserve_source_positions(&self) -> bool {
let _ = self.located();
self.source_positions_preserved.get()
}
pub(crate) fn parse(&self) -> Result<Vec<Statement>, PostgresParseError> {
self.parse_with_policy(false, None)
}
pub fn parse_policy(&self) -> Result<Vec<Statement>, PostgresParseError> {
self.parse_policy_with_locations(None)
}
pub fn parse_policy_with_locations(
&self,
locations: Option<&mut Vec<Location>>,
) -> Result<Vec<Statement>, PostgresParseError> {
self.parse_with_policy(true, locations)
}
fn parse_with_policy(
&self,
policy: bool,
locations: Option<&mut Vec<Location>>,
) -> Result<Vec<Statement>, PostgresParseError> {
self.functions.borrow_mut().clear();
self.policy_arbiters.borrow_mut().clear();
let located = self.located().map_err(Clone::clone)?;
let mut tokens = super::radix_numbers::repair(located).unwrap_or_else(|| located.clone());
normalize_table_queries(&mut tokens);
super::ddl_compat::normalize(&mut tokens);
let recursive_views = super::recursive_view::prepare(&mut tokens);
let fetch = super::fetch_expression::prepare(&mut tokens);
super::named_arguments::accept_infix(&mut tokens);
let (mut statements, functions, arbiters) = if policy {
super::super::source::parse_conflict_program(tokens, locations)
} else {
super::super::source::conceal_body_keyword(&mut tokens);
Parser::new(&PostgreSqlDialect {})
.with_tokens_with_locations(tokens)
.parse_statements()
.map(|statements| (statements, Vec::new(), Vec::new()))
}
.map_err(PostgresParseError::from)?;
super::fetch_expression::restore(&mut statements, &fetch);
for statement in &mut statements {
recursive_views.validate(statement)?;
recursive_views.restore(statement);
}
super::named_arguments::rewrite(&mut statements);
*self.functions.borrow_mut() = functions;
*self.policy_arbiters.borrow_mut() = arbiters;
Ok(statements)
}
pub fn functions(&self) -> Ref<'_, Vec<super::super::SqlFunctionCallFact>> {
self.functions.borrow()
}
pub(crate) fn policy_arbiters(&self) -> Ref<'_, Vec<super::super::source::PolicyArbiter>> {
self.policy_arbiters.borrow()
}
pub fn adopt_recovered_arbiters(&self, located: &mut [super::LocatedStatement]) {
self.policy_arbiters.borrow_mut().extend(
located
.iter_mut()
.filter_map(|statement| statement.policy_arbiter.take()),
);
}
fn located(&self) -> Result<&Vec<TokenWithSpan>, &PostgresParseError> {
self.tokens
.get_or_init(|| {
let separated = super::distinct_group::separate_distinct_grouping(&self.normalized);
self.source_positions_preserved
.set(matches!(separated, Cow::Borrowed(_)));
super::operator_boundary::tokenize_with_location(&PostgreSqlDialect {}, &separated)
.map_err(|error| PostgresParseError {
message: error.to_string(),
})
})
.as_ref()
}
}