use std::rc::Rc;
use hamelin_lib::err::TranslationErrors;
use hamelin_lib::types::Type;
use hamelin_lib::{
antlr::hamelinparser::{SortExpressionContextAll, SortExpressionContextAttrs},
sql::expression::{Direction, OrderByExpression},
};
use crate::ast::expression::HamelinExpression;
use crate::ast::ExpressionTranslationContext;
#[derive(Clone)]
pub struct HamelinSortExpression {
ctx: Vec<Rc<SortExpressionContextAll<'static>>>,
context: Rc<ExpressionTranslationContext>,
}
impl HamelinSortExpression {
pub fn new(
ctx: Vec<Rc<SortExpressionContextAll<'static>>>,
context: Rc<ExpressionTranslationContext>,
) -> Self {
Self { ctx, context }
}
pub fn translate(&self) -> Result<(Vec<OrderByExpression>, Vec<Type>), TranslationErrors> {
let translated = TranslationErrors::from_vec(
self.ctx
.iter()
.map(|se| {
HamelinExpression::new(
TranslationErrors::expect(se.as_ref(), se.expression())?,
self.context.clone(),
)
.translate()
})
.collect(),
)?;
let res = translated
.into_iter()
.zip(self.ctx.iter())
.map(|(t, se)| {
(
OrderByExpression::new(
t.sql,
if se.DESC().is_some() {
Direction::DESC
} else {
Direction::ASC
},
),
t.typ,
)
})
.collect();
Ok(res)
}
}