use std::sync::Arc;
use bson::{Bson, Document, doc};
use super::{
MongoExtract, MongoHop, MongoNesting, MongoOrdering, MongoQuery, MongoSubjects, MongoTypeError,
MongoWrite, field,
};
use crate::{
ComplexComparison, CursorValue, FieldName, Identifiable, OrderDirection, OrderTerm, Record,
RecordAddress, TermName, Transformer,
comparison::{
At, Backend, CollapsibleComparison,
mongo::{Mongo, MongoCarrier, MongoRefComparison, MongoRelatedDocument, MongoScalarComparison},
},
query::{CrossingError, mongo::MongoExtractionError},
};
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Shot {
pub(super) media: i64,
pub(super) id: i64,
pub(super) title: String,
pub(super) score: Option<f64>,
pub(super) cover: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ShotKey {
media: i64,
id: i64,
}
impl Identifiable for Shot {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Shot {
type Key = ShotKey;
type Lineage = i64;
type Record = Self;
type Graphql = ();
fn key(&self) -> ShotKey {
ShotKey {
media: self.media,
id: self.id,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ShotMongo {
pub(super) media: i64,
pub(super) id: i64,
pub(super) title: String,
pub(super) score: Option<f64>,
pub(super) cover: Option<i64>,
}
#[derive(Debug, Default)]
pub(super) struct KeyframeFilter {
pub(super) title: MongoScalarComparison<String>,
}
impl ComplexComparison<Mongo> for KeyframeFilter {
fn conjuncts(&self) -> usize {
self.title.conjuncts()
}
fn apply<'q>(
&'q self,
at: At<'_>,
builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
let title = at.frame(FieldName::new("title"));
self.title.apply(title.at(), builder)
}
}
impl CollapsibleComparison<Mongo> for KeyframeFilter {
type Id = MongoScalarComparison<i64>;
fn only_id(&self) -> Option<&MongoScalarComparison<i64>> {
None
}
}
const KEYFRAME: MongoRelatedDocument = MongoRelatedDocument::new(
RecordAddress::new(FieldName::new("keyframe"), &[FieldName::new("id")]),
&[
"__ig_keyframe_0__",
"__ig_keyframe_1__",
"__ig_keyframe_2__",
"__ig_keyframe_3__",
"__ig_keyframe_4__",
"__ig_keyframe_5__",
"__ig_keyframe_6__",
"__ig_keyframe_7__",
],
);
const STRIP: MongoRelatedDocument = MongoRelatedDocument::new(
RecordAddress::new(FieldName::new("strip"), &[FieldName::new("id")]),
&[
"__ig_strip_0__",
"__ig_strip_1__",
"__ig_strip_2__",
"__ig_strip_3__",
"__ig_strip_4__",
"__ig_strip_5__",
"__ig_strip_6__",
"__ig_strip_7__",
],
);
#[derive(Debug)]
pub(super) struct ShotFilter {
pub(super) title: MongoScalarComparison<String>,
pub(super) score: MongoScalarComparison<f64>,
pub(super) cover: MongoRefComparison<KeyframeFilter>,
}
impl Default for ShotFilter {
fn default() -> Self {
Self {
title: MongoScalarComparison::new(),
score: MongoScalarComparison::new(),
cover: MongoRefComparison::new(KEYFRAME, KeyframeFilter::default()),
}
}
}
impl ComplexComparison<Mongo> for ShotFilter {
fn conjuncts(&self) -> usize {
self.title.conjuncts() + self.score.conjuncts() + ComplexComparison::conjuncts(&self.cover)
}
fn apply<'q>(
&'q self,
at: At<'_>,
builder: <Mongo as Backend>::Builder<'q>,
) -> Result<<Mongo as Backend>::Builder<'q>, <Mongo as Backend>::Error> {
let title = at.frame(FieldName::new("title"));
let builder = self.title.apply(title.at(), builder)?;
let score = at.frame(FieldName::new("score"));
let builder = self.score.apply(score.at(), builder)?;
let cover = at.frame(FieldName::new("cover_id"));
self.cover.apply(cover.at(), builder)
}
}
impl Record<Mongo> for Shot {
type Row = ShotMongo;
type Comparison = ShotFilter;
type OrderBy = ShotOrder;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum ShotOrder {
Title(OrderDirection),
Score(OrderDirection),
Id(OrderDirection),
Cover(Arc<KeyframeOrder>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum KeyframeOrder {
Title(OrderDirection),
Strip(Arc<StripOrder>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum StripOrder {
Label(OrderDirection),
}
const VIA_COVER: MongoHop = MongoHop::new(KEYFRAME, FieldName::new("cover_id"));
const VIA_STRIP: MongoHop = MongoHop::new(STRIP, FieldName::new("strip_id"));
impl ShotOrder {
fn term(&self) -> OrderTerm {
match self {
Self::Title(direction) => {
OrderTerm::new(TermName::new("title"), FieldName::new("title"), *direction)
}
Self::Score(direction) => {
OrderTerm::nullable(TermName::new("score"), FieldName::new("score"), *direction)
}
Self::Id(direction) => OrderTerm::new(TermName::new("id"), FieldName::new("id"), *direction),
Self::Cover(target) => {
let (identity, direction) = match &**target {
KeyframeOrder::Title(direction) => ("cover_id.title", *direction),
KeyframeOrder::Strip(strip) => match &**strip {
StripOrder::Label(direction) => ("cover_id.strip_id.label", *direction),
},
};
OrderTerm::nullable(
TermName::new(identity),
FieldName::new("cover_id"),
direction,
)
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(super) struct ShotSubjects(Vec<Option<MongoNesting>>);
impl MongoSubjects for ShotSubjects {
fn nesting(&self, _: &[OrderTerm], level: usize) -> Option<&MongoNesting> {
self.0[level].as_ref()
}
}
fn nesting(order: &ShotOrder) -> Option<MongoNesting> {
let ShotOrder::Cover(target) = order else {
return None;
};
Some(match &**target {
KeyframeOrder::Title(_) => MongoNesting::new(VIA_COVER, FieldName::new("title")),
KeyframeOrder::Strip(strip) => match &**strip {
StripOrder::Label(_) => MongoNesting::new(VIA_STRIP, FieldName::new("label")).via(VIA_COVER),
},
})
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum ShotCursor {
Title(String),
Score(f64),
Id(i64),
CoverTitle(String),
CoverStripLabel(String),
}
impl MongoCarrier for ShotCursor {
fn to_bson(&self) -> Bson {
match self {
Self::Title(value) | Self::CoverTitle(value) | Self::CoverStripLabel(value) => {
value.to_bson()
}
Self::Score(value) => value.to_bson(),
Self::Id(value) => value.to_bson(),
}
}
}
impl CursorValue for ShotCursor {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Title(value) => {
out.push(0);
value.write_cursor(out);
}
Self::Score(value) => {
out.push(1);
value.write_cursor(out);
}
Self::Id(value) => {
out.push(2);
value.write_cursor(out);
}
Self::CoverTitle(value) => {
out.push(3);
value.write_cursor(out);
}
Self::CoverStripLabel(value) => {
out.push(4);
value.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match *tag {
0 => String::read_cursor(rest).map(Self::Title),
1 => f64::read_cursor(rest).map(Self::Score),
2 => i64::read_cursor(rest).map(Self::Id),
3 => String::read_cursor(rest).map(Self::CoverTitle),
4 => String::read_cursor(rest).map(Self::CoverStripLabel),
_ => None,
}
}
}
impl MongoQuery for ShotMongo {
type Record = Shot;
const ADDRESS: RecordAddress =
RecordAddress::new(FieldName::new("shot"), &[FieldName::new("id")]);
const ALIASES: &'static [&'static str] = &[
"__ig_shot_0__",
"__ig_shot_1__",
"__ig_shot_2__",
"__ig_shot_3__",
"__ig_shot_4__",
"__ig_shot_5__",
"__ig_shot_6__",
"__ig_shot_7__",
];
const FIELDS: &'static [&'static FieldName] = &[
FieldName::new("media"),
FieldName::new("id"),
FieldName::new("title"),
FieldName::new("score"),
FieldName::new("cover_id"),
];
fn id(id: &i64) -> Result<Bson, CrossingError> {
Ok(id.to_bson())
}
fn from_document(document: &Document) -> Result<Self, MongoExtractionError> {
Ok(Self {
media: field(document, "media")?,
id: field(document, "_id")?,
title: field(document, "title")?,
score: field(document, "score")?,
cover: field(document, "cover_id")?,
})
}
fn record(self) -> Result<Shot, CrossingError> {
Ok(Shot {
media: self.media,
id: self.id,
title: self.title,
score: self.score,
cover: self.cover,
})
}
}
impl MongoWrite for ShotMongo {
fn row(record: Shot) -> Result<Self, CrossingError> {
Ok(Self {
media: record.media,
id: record.id,
title: record.title,
score: record.score,
cover: record.cover,
})
}
fn document(&self) -> Document {
let mut document = Document::new();
document.insert("media", self.media.to_bson());
document.insert("_id", self.id.to_bson());
document.insert("title", self.title.to_bson());
document.insert("score", self.score.to_bson());
document.insert("cover_id", self.cover.to_bson());
document
}
}
impl MongoOrdering for ShotMongo {
type Order = ShotOrder;
type Subjects = ShotSubjects;
type Value = ShotCursor;
fn complete(written: &[ShotOrder]) -> Vec<ShotOrder> {
let mut order: Vec<ShotOrder> = written
.iter()
.filter(|term| !matches!(term, ShotOrder::Id(_)))
.cloned()
.collect();
order.push(ShotOrder::Id(OrderDirection::Asc));
order
}
fn term(order: ShotOrder) -> OrderTerm {
order.term()
}
fn subjects(order: &[ShotOrder]) -> ShotSubjects {
ShotSubjects(order.iter().map(nesting).collect())
}
fn value(
&self,
order: ShotOrder,
raw: &Document,
alias: &str,
) -> Result<Option<ShotCursor>, MongoTypeError> {
let materialized = |mint: fn(String) -> ShotCursor| {
<Option<String> as MongoExtract>::extract(raw.get(alias)).map(|value| value.map(mint))
};
match order {
ShotOrder::Title(_) => Ok(Some(ShotCursor::Title(self.title.clone()))),
ShotOrder::Score(_) => Ok(self.score.map(ShotCursor::Score)),
ShotOrder::Id(_) => Ok(Some(ShotCursor::Id(self.id))),
ShotOrder::Cover(target) => match &*target {
KeyframeOrder::Title(_) => materialized(ShotCursor::CoverTitle),
KeyframeOrder::Strip(_) => materialized(ShotCursor::CoverStripLabel),
},
}
}
}
pub(super) fn terms(written: &[ShotOrder]) -> Vec<OrderTerm> {
<ShotMongo as MongoOrdering>::complete(written)
.into_iter()
.map(<ShotMongo as MongoOrdering>::term)
.collect()
}
pub(super) fn subjects(written: &[ShotOrder]) -> ShotSubjects {
<ShotMongo as MongoOrdering>::subjects(&<ShotMongo as MongoOrdering>::complete(written))
}
pub(super) fn by_cover_title() -> [ShotOrder; 1] {
[ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
OrderDirection::Asc,
)))]
}
pub(super) fn by_cover_strip_label() -> [ShotOrder; 1] {
[ShotOrder::Cover(Arc::new(KeyframeOrder::Strip(Arc::new(
StripOrder::Label(OrderDirection::Asc),
))))]
}
pub(super) struct DeepSubjects(MongoNesting);
impl DeepSubjects {
pub(super) fn crossing(hops: usize) -> Self {
let hop = MongoHop::new(
MongoRelatedDocument::of::<ShotMongo>(),
FieldName::new("cover_id"),
);
let mut nesting = MongoNesting::new(hop, FieldName::new("title"));
for _ in 1..hops {
nesting = nesting.via(hop);
}
Self(nesting)
}
}
impl MongoSubjects for DeepSubjects {
fn nesting(&self, _: &[OrderTerm], level: usize) -> Option<&MongoNesting> {
(level == 0).then_some(&self.0)
}
}
pub(super) fn titled(title: &str) -> ShotFilter {
let mut filter = ShotFilter::default();
filter.title.eq = Some(title.to_owned());
filter
}
pub(super) fn covering(title: &str) -> ShotFilter {
let mut target = KeyframeFilter::default();
target.title.eq = Some(title.to_owned());
ShotFilter {
cover: MongoRefComparison::new(KEYFRAME, target),
..ShotFilter::default()
}
}
#[test]
fn a_related_document_reads_its_address_and_its_join_fields_off_one_binding() {
let related = MongoRelatedDocument::of::<ShotMongo>();
assert_eq!(related.address(), &<ShotMongo as MongoQuery>::ADDRESS);
assert_eq!(
<ShotMongo as MongoQuery>::ALIASES[1],
"__ig_shot_1__",
"the mint's shape is the SQL family's, under a different job"
);
let _ = related;
}
#[test]
fn the_records_own_id_renders_as_the_documents_underscore_id() {
let address = <ShotMongo as MongoQuery>::ADDRESS;
let rendered = |name| {
let frame = At::new(&address).frame(FieldName::new(name));
let mut out = String::new();
<Mongo as Backend>::write_column(frame.at(), &mut out);
out
};
assert_eq!(rendered("id"), "_id");
assert_eq!(rendered("title"), "title");
}
#[test]
fn a_nested_id_keeps_its_own_name() {
let address = <ShotMongo as MongoQuery>::ADDRESS;
let outer = At::new(&address).frame(FieldName::new("cover"));
let inner = outer.at().frame(FieldName::new("id"));
let mut out = String::new();
<Mongo as Backend>::write_column(inner.at(), &mut out);
assert_eq!(out, "cover.id");
}
#[test]
fn the_extraction_reads_a_whole_document() {
let document =
doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "score": 0.5, "cover_id": 4i64 };
assert_eq!(
ShotMongo::from_document(&document),
Ok(ShotMongo {
media: 7,
id: 12,
title: "a red car".to_owned(),
score: Some(0.5),
cover: Some(4),
})
);
let sparse = doc! { "media": 7i64, "_id": 12i64, "title": "a red car" };
assert_eq!(
ShotMongo::from_document(&sparse).map(|row| row.score),
Ok(None)
);
}
#[test]
fn a_missing_id_is_refused_under_the_key_the_document_spells() {
let document = doc! { "media": 7i64, "title": "a red car" };
let refusal = ShotMongo::from_document(&document).expect_err("no `_id`");
assert_eq!(refusal.field(), "_id");
assert_eq!(
refusal.to_string(),
"`_id` did not read: this field is not in the document"
);
}
#[test]
fn every_column_is_read_through_the_one_extraction_authority() {
let document = doc! { "media": 7i64, "_id": 12i64, "title": 3i64, "score": 0.5 };
let refusal = ShotMongo::from_document(&document).expect_err("`title` is not a string");
assert_eq!(refusal.field(), "title");
assert_eq!(
refusal.cause(),
&super::MongoTypeError::wrong_type("string", "long")
);
}
#[test]
fn a_leaf_refusal_carries_no_field_and_the_wrapper_adds_it() {
assert_eq!(
<i64 as MongoExtract>::extract(None),
Err(super::MongoTypeError::Absent)
);
assert_eq!(
field::<i64>(&doc! {}, "score").expect_err("absent").field(),
"score"
);
}
#[test]
fn a_nested_terms_cursor_value_is_read_at_the_engines_own_alias() {
let alias = super::sort_alias(0);
let order = ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc)));
let document = doc! {
"media": 7i64, "_id": 12i64, "title": "a red car", "cover_id": 4i64, "__ig_ord0__": "Autumn",
};
let row = ShotMongo::from_document(&document).expect("a whole document");
assert_eq!(
row.value(order.clone(), &document, &alias),
Ok(Some(ShotCursor::CoverTitle("Autumn".to_owned())))
);
let unjoined = doc! { "media": 7i64, "_id": 12i64, "title": "a red car" };
let row = ShotMongo::from_document(&unjoined).expect("a whole document");
assert_eq!(row.value(order, &unjoined, &alias), Ok(None));
}
#[test]
fn a_plain_terms_cursor_value_ignores_the_raw_document() {
let document =
doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "__ig_ord0__": "Autumn" };
let row = ShotMongo::from_document(&document).expect("a whole document");
assert_eq!(
row.value(
ShotOrder::Title(OrderDirection::Asc),
&doc! {},
&super::sort_alias(0)
),
Ok(Some(ShotCursor::Title("a red car".to_owned())))
);
}
#[test]
fn a_materialized_value_of_the_wrong_type_is_refused() {
let document = doc! { "media": 7i64, "_id": 12i64, "title": "a red car", "__ig_ord0__": 3i64 };
let row = ShotMongo::from_document(&document).expect("a whole document");
assert_eq!(
row.value(
ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
&document,
&super::sort_alias(0)
),
Err(MongoTypeError::wrong_type("string", "long"))
);
}
#[test]
fn a_column_spelled_the_old_way_is_the_declarations_and_stays_untouched() {
let alias = super::sort_alias(0);
let document = doc! {
"media": 7i64,
"_id": 12i64,
"title": "a red car",
"cover_id": 4i64,
"__ord_0": "the declaration's own",
"__ig_ord0__": "Autumn",
};
let row = ShotMongo::from_document(&document).expect("a whole document");
assert_eq!(
row.value(
ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
&document,
&alias
),
Ok(Some(ShotCursor::CoverTitle("Autumn".to_owned()))),
"the boundary is the engine's field, not the one the declaration owns"
);
assert_eq!(
document.get_str("__ord_0").ok(),
Some("the declaration's own"),
"and the declaration's field is still what it stored"
);
}
#[test]
fn the_order_signature_folds_no_rendered_name() {
let nested = crate::OrderSignature::of(&terms(&by_cover_title()));
assert_eq!(nested.get(), 0xa3ea_9224_7e71_33df);
}