use bson::{Bson, Document};
use super::{MongoFields, MongoSubjects, subject::sort_key};
use crate::{
OrderTerm, RecordAddress, TermName, Walk,
comparison::mongo::Mongo,
query::{ColumnNotStored, Unpushable, partition},
};
const ASC: i32 = 1;
const DESC: i32 = -1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MongoOrder<'a> {
terms: &'a [OrderTerm],
}
impl<'a> MongoOrder<'a> {
pub fn new(terms: &'a [OrderTerm]) -> Result<Self, MongoSortError> {
if terms.is_empty() {
return Err(MongoSortError::Empty);
}
if let Some(refused) = terms
.iter()
.find(|term| !term.order().is_empty() || term.leaf().is_some())
{
return Err(MongoSortError::Semantic(refused.identity()));
}
let partition = partition::<Mongo>(terms);
let Some(refused) = partition.remainder().first() else {
return Ok(Self { terms });
};
let term = refused.identity();
Err(match partition.cause() {
Some(Unpushable::NotStored) => MongoSortError::NotStored(ColumnNotStored::new(
term,
refused
.subject()
.absent_from()
.expect("a term refused as unstored names the dialect that has not got it"),
)),
Some(
Unpushable::CollectionSemantics
| Unpushable::CollectionTable
| Unpushable::CollectionShadow,
) => MongoSortError::Collection(term),
_ => MongoSortError::Repeated(term),
})
}
#[inline]
#[must_use]
pub const fn terms(&self) -> &'a [OrderTerm] {
self.terms
}
#[must_use]
pub fn sort(&self, at: &RecordAddress, walk: Walk) -> Document {
self.sort_with(at, walk, &MongoFields)
}
#[must_use]
pub fn sort_with<S: MongoSubjects + ?Sized>(
&self,
at: &RecordAddress,
walk: Walk,
subjects: &S,
) -> Document {
let mut sort = Document::new();
for (level, term) in self.terms.iter().enumerate() {
let direction = walk.direction(term.direction());
let value = if direction.is_descending() { DESC } else { ASC };
sort.insert(
sort_key(at, self.terms, level, subjects),
Bson::Int32(value),
);
}
sort
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoSortError {
NotStored(ColumnNotStored),
Empty,
Repeated(&'static TermName),
Collection(&'static TermName),
Semantic(&'static TermName),
}
impl core::fmt::Display for MongoSortError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Empty => f.write_str("an order over no terms has no spelling"),
Self::NotStored(why) => write!(f, "{why}"),
Self::Repeated(term) => {
let term: &str = term;
write!(
f,
"`{term}` is named twice and a `$sort` document holds one entry per field"
)
}
Self::Collection(term) => {
let term: &str = term;
write!(
f,
"`{term}` is a collection, and `$sort` orders one by its smallest element ascending and \
its largest descending rather than element by element"
)
}
Self::Semantic(term) => {
let term: &str = term;
write!(
f,
"`{term}` states a semantic order over its own columns, and this backend sorts a nested \
citizen as one sub-document rather than by that sequence"
)
}
}
}
}
impl core::error::Error for MongoSortError {}
#[cfg(test)]
mod tests;