use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use crate::core::pattern::{AfterMatchSkip, Pattern, RowsPerMatch, Symbol};
pub type MatchRecognizeSpecResult<T> = Result<T, MatchRecognizeSpecError>;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeSpec<E> {
pub partition_by: Vec<E>,
pub order_by: Vec<MatchRecognizeSortExpr<E>>,
pub source_rows_per_match: RowsPerMatch,
pub after_match_skip: AfterMatchSkip,
pub pattern: Pattern,
pub symbols: Vec<String>,
pub definitions: Vec<MatchRecognizeDefinition<E>>,
pub measures: Vec<MatchRecognizeMeasure<E>>,
pub output: MatchRecognizeOutputContract<E>,
}
impl<E> MatchRecognizeSpec<E> {
pub fn try_new(self) -> MatchRecognizeSpecResult<Self> {
self.validate()?;
Ok(self)
}
pub fn validate(&self) -> MatchRecognizeSpecResult<()> {
let symbols = symbol_map(&self.symbols)?;
validate_pattern_symbols(&self.pattern, &symbols)?;
validate_definitions(&self.definitions, &symbols)?;
validate_skip_target(&self.after_match_skip, &symbols)?;
validate_measures(&self.measures)?;
self.output.validate()?;
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeSortExpr<E> {
pub expr: E,
pub direction: MatchRecognizeSortDirection,
pub null_ordering: MatchRecognizeNullOrdering,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeSortDirection {
Asc,
Desc,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeNullOrdering {
First,
Last,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeDefinition<E> {
pub symbol: String,
pub predicate: E,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeMeasure<E> {
pub name: Option<String>,
pub expression: E,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeOutputContract<E> {
Derived,
ExplicitNamedExpressions(Vec<MatchRecognizeNamedExpression<E>>),
}
impl<E> MatchRecognizeOutputContract<E> {
fn validate(&self) -> Result<(), MatchRecognizeSpecError> {
match self {
Self::Derived => Ok(()),
Self::ExplicitNamedExpressions(expressions) => {
let mut seen = BTreeSet::new();
for expr in expressions {
let key = normalize_name(&expr.name);
if !seen.insert(key) {
return Err(MatchRecognizeSpecError::DuplicateOutputName {
name: expr.name.clone(),
});
}
}
Ok(())
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeNamedExpression<E> {
pub name: String,
pub expression: E,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MatchRecognizeSpecError {
DuplicateSymbol {
symbol: String,
},
DuplicatePatternSymbol {
symbol: String,
previous: String,
},
PatternSymbolsMismatch {
missing_from_pattern: Vec<String>,
unknown_in_pattern: Vec<String>,
},
DuplicateDefinition {
symbol: String,
},
UnknownDefinition {
symbol: String,
},
UnknownSkipTarget {
symbol: String,
},
MissingMeasureName,
DuplicateMeasureName {
name: String,
},
DuplicateOutputName {
name: String,
},
}
impl Display for MatchRecognizeSpecError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateSymbol { symbol } => {
write!(f, "duplicate MATCH_RECOGNIZE symbol: {symbol}")
}
Self::DuplicatePatternSymbol { symbol, previous } => write!(
f,
"MATCH_RECOGNIZE pattern symbol {symbol} conflicts with symbol {previous} by case-insensitive name"
),
Self::PatternSymbolsMismatch {
missing_from_pattern,
unknown_in_pattern,
} => write!(
f,
"pattern symbols do not match declared symbols: missing_from_pattern={missing_from_pattern:?}, unknown_in_pattern={unknown_in_pattern:?}"
),
Self::DuplicateDefinition { symbol } => {
write!(f, "duplicate DEFINE entry for symbol: {symbol}")
}
Self::UnknownDefinition { symbol } => {
write!(f, "DEFINE entry references unknown symbol: {symbol}")
}
Self::UnknownSkipTarget { symbol } => {
write!(f, "AFTER MATCH SKIP references unknown symbol: {symbol}")
}
Self::MissingMeasureName => {
write!(f, "MEASURES expression requires a name")
}
Self::DuplicateMeasureName { name } => {
write!(f, "duplicate MEASURES name: {name}")
}
Self::DuplicateOutputName { name } => {
write!(f, "duplicate explicit output name: {name}")
}
}
}
}
impl Error for MatchRecognizeSpecError {}
fn symbol_map(symbols: &[String]) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
let mut seen = BTreeMap::new();
for symbol in symbols {
let key = normalize_name(symbol);
if seen.insert(key, symbol.clone()).is_some() {
return Err(MatchRecognizeSpecError::DuplicateSymbol {
symbol: symbol.clone(),
});
}
}
Ok(seen)
}
fn validate_pattern_symbols(
pattern: &Pattern,
symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
let pattern_symbols = pattern_symbol_map(pattern)?;
let missing_from_pattern = symbols
.iter()
.filter(|(key, _)| !pattern_symbols.contains_key(*key))
.map(|(_, symbol)| symbol.clone())
.collect::<Vec<_>>();
let unknown_in_pattern = pattern_symbols
.iter()
.filter(|(key, _)| !symbols.contains_key(*key))
.map(|(_, symbol)| symbol.clone())
.collect::<Vec<_>>();
if missing_from_pattern.is_empty() && unknown_in_pattern.is_empty() {
Ok(())
} else {
Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
missing_from_pattern,
unknown_in_pattern,
})
}
}
fn validate_definitions<E>(
definitions: &[MatchRecognizeDefinition<E>],
symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
let mut seen = BTreeSet::new();
for definition in definitions {
let key = normalize_name(&definition.symbol);
if !symbols.contains_key(&key) {
return Err(MatchRecognizeSpecError::UnknownDefinition {
symbol: definition.symbol.clone(),
});
}
if !seen.insert(key) {
return Err(MatchRecognizeSpecError::DuplicateDefinition {
symbol: definition.symbol.clone(),
});
}
}
Ok(())
}
fn validate_skip_target(
after_match_skip: &AfterMatchSkip,
symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
let target = match after_match_skip {
AfterMatchSkip::ToFirst(symbol) | AfterMatchSkip::ToLast(symbol) => symbol,
AfterMatchSkip::PastLastRow | AfterMatchSkip::ToNextRow => return Ok(()),
};
if symbols.contains_key(&normalize_name(target)) {
Ok(())
} else {
Err(MatchRecognizeSpecError::UnknownSkipTarget {
symbol: target.clone(),
})
}
}
fn validate_measures<E>(
measures: &[MatchRecognizeMeasure<E>],
) -> MatchRecognizeSpecResult<()> {
let mut seen = BTreeSet::new();
for measure in measures {
let Some(name) = &measure.name else {
return Err(MatchRecognizeSpecError::MissingMeasureName);
};
let key = normalize_name(name);
if !seen.insert(key) {
return Err(MatchRecognizeSpecError::DuplicateMeasureName {
name: name.clone(),
});
}
}
Ok(())
}
fn pattern_symbol_map(
pattern: &Pattern,
) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
let mut pending = vec![pattern];
let mut symbols: BTreeMap<String, String> = BTreeMap::new();
while let Some(node) = pending.pop() {
let leaf_symbols = match node {
Pattern::Symbol(symbol) | Pattern::Exclude(symbol) => {
std::slice::from_ref(symbol)
}
Pattern::Permute(permuted) => permuted.as_slice(),
Pattern::Concat(parts) | Pattern::Alternation(parts) => {
pending.extend(parts.iter().rev());
continue;
}
Pattern::Group(inner) | Pattern::Repetition(inner, _) => {
pending.push(inner);
continue;
}
};
for symbol in leaf_symbols {
if let Symbol::Named(name) = symbol {
let key = normalize_name(name);
if let Some(previous) = symbols.get(&key) {
if previous != name {
return Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
symbol: name.clone(),
previous: previous.clone(),
});
}
} else {
symbols.insert(key, name.clone());
}
}
}
}
Ok(symbols)
}
fn normalize_name(name: &str) -> String {
name.to_ascii_lowercase()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::pattern::{EmptyMatchesMode, RepetitionQuantifier};
type TestSpec = MatchRecognizeSpec<&'static str>;
fn valid_spec() -> TestSpec {
MatchRecognizeSpec {
partition_by: vec!["account_id"],
order_by: vec![MatchRecognizeSortExpr {
expr: "event_time",
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
after_match_skip: AfterMatchSkip::ToLast("B".to_string()),
pattern: Pattern::Concat(vec![
Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
RepetitionQuantifier::OneOrMore,
),
Pattern::Symbol(Symbol::Named("B".to_string())),
]),
symbols: vec!["A".to_string(), "B".to_string()],
definitions: vec![
MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: "price > 0",
},
MatchRecognizeDefinition {
symbol: "B".to_string(),
predicate: "price < prev(price)",
},
],
measures: vec![MatchRecognizeMeasure {
name: Some("last_price".to_string()),
expression: "last(price)",
}],
output: MatchRecognizeOutputContract::Derived,
}
}
#[test]
fn validate_rejects_case_insensitive_duplicate_symbols() {
let mut spec = valid_spec();
spec.symbols = vec!["A".to_string(), "a".to_string()];
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::DuplicateSymbol {
symbol: "a".to_string()
})
);
}
#[test]
fn validate_requires_pattern_symbols_to_match_declared_symbols() {
let mut spec = valid_spec();
spec.symbols = vec!["A".to_string(), "C".to_string()];
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
missing_from_pattern: vec!["C".to_string()],
unknown_in_pattern: vec!["B".to_string()],
})
);
}
#[test]
fn validate_allows_repeated_pattern_symbol_occurrences() {
let mut spec = valid_spec();
spec.pattern = Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".to_string())),
Pattern::Symbol(Symbol::Named("B".to_string())),
Pattern::Symbol(Symbol::Named("A".to_string())),
]);
assert_eq!(spec.validate(), Ok(()));
}
#[test]
fn validate_rejects_case_insensitive_pattern_symbol_conflicts() {
let mut spec = valid_spec();
spec.pattern = Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("a".to_string())),
Pattern::Symbol(Symbol::Named("A".to_string())),
Pattern::Symbol(Symbol::Named("B".to_string())),
]);
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
symbol: "A".to_string(),
previous: "a".to_string(),
})
);
}
#[test]
fn validate_rejects_duplicate_definitions() {
let mut spec = valid_spec();
spec.definitions.push(MatchRecognizeDefinition {
symbol: "a".to_string(),
predicate: "volume > 10",
});
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::DuplicateDefinition {
symbol: "a".to_string()
})
);
}
#[test]
fn validate_rejects_unknown_definition_symbol() {
let mut spec = valid_spec();
spec.definitions.push(MatchRecognizeDefinition {
symbol: "C".to_string(),
predicate: "volume > 10",
});
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::UnknownDefinition {
symbol: "C".to_string()
})
);
}
#[test]
fn validate_rejects_unknown_skip_target() {
let mut spec = valid_spec();
spec.after_match_skip = AfterMatchSkip::ToFirst("C".to_string());
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::UnknownSkipTarget {
symbol: "C".to_string()
})
);
}
#[test]
fn validate_rejects_missing_measure_name_when_required() {
let mut spec = valid_spec();
spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
MatchRecognizeNamedExpression {
name: "out_price".to_string(),
expression: "last_price",
},
]);
spec.measures = vec![MatchRecognizeMeasure {
name: None,
expression: "last(price)",
}];
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::MissingMeasureName)
);
}
#[test]
fn specification_rejects_duplicate_measure_and_explicit_output_names() {
let named = |name: &str, expression| MatchRecognizeNamedExpression {
name: name.into(),
expression,
};
for output in [
MatchRecognizeOutputContract::Derived,
MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![named(
"out_price",
"last_price",
)]),
] {
let mut spec = valid_spec();
spec.output = output;
spec.measures = vec![
MatchRecognizeMeasure {
name: Some("m".into()),
expression: "last(price)",
},
MatchRecognizeMeasure {
name: Some("M".into()),
expression: "first(price)",
},
];
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::DuplicateMeasureName { name: "M".into() })
);
}
let mut spec = valid_spec();
spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
named("out_price", "last_price"),
named("OUT_PRICE", "first_price"),
]);
assert_eq!(
spec.validate(),
Err(MatchRecognizeSpecError::DuplicateOutputName {
name: "OUT_PRICE".into()
})
);
}
}