use happenstance_core::{Query, QueryItem};
#[derive(Debug, Clone)]
pub(crate) struct Predicate {
sql: String,
params: Vec<Param>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Param {
EventType(String),
Tags(Vec<String>),
}
impl Predicate {
pub(crate) fn sql(&self) -> &str {
&self.sql
}
pub(crate) fn params(&self) -> &[Param] {
&self.params
}
}
pub(crate) fn predicate(query: &Query, next: &mut usize) -> Predicate {
let Some(items) = query.items() else {
return Predicate {
sql: "TRUE".to_owned(),
params: Vec::new(),
};
};
if items.is_empty() {
return Predicate {
sql: "FALSE".to_owned(),
params: Vec::new(),
};
}
let mut params = Vec::new();
let arms: Vec<String> = items
.iter()
.map(|item| item_sql(item, next, &mut params))
.collect();
Predicate {
sql: format!("({})", arms.join(" OR ")),
params,
}
}
fn item_sql(item: &QueryItem, next: &mut usize, params: &mut Vec<Param>) -> String {
let mut conjuncts: Vec<String> = Vec::new();
if !item.types().is_empty() {
let placeholders: Vec<String> = item
.types()
.iter()
.map(|event_type| {
params.push(Param::EventType(event_type.as_str().to_owned()));
let placeholder = format!("${next}");
*next += 1;
placeholder
})
.collect();
conjuncts.push(format!("event_type IN ({})", placeholders.join(", ")));
}
if !item.tags().is_empty() {
params.push(Param::Tags(
item.tags()
.iter()
.map(|tag| tag.as_str().to_owned())
.collect(),
));
conjuncts.push(format!("tags @> ${next}::text[]"));
*next += 1;
}
if conjuncts.is_empty() {
return "(TRUE)".to_owned();
}
format!("({})", conjuncts.join(" AND "))
}
#[cfg(test)]
mod tests {
use happenstance_core::{Query, QueryItem, Tags};
use super::{Param, predicate};
fn build(query: &Query) -> (String, Vec<Param>) {
let mut next = 1;
let built = predicate(query, &mut next);
(built.sql().to_owned(), built.params().to_vec())
}
#[test]
fn query_all_is_true_and_binds_nothing() {
let (sql, params) = build(&Query::all());
assert_eq!(sql, "TRUE");
assert!(params.is_empty());
}
#[test]
fn a_query_with_no_items_cannot_be_built_at_all() {
assert!(
Query::from_items([]).is_err(),
"the core crate rejects an empty query; the FALSE branch is a guard, not a path"
);
}
#[test]
fn types_within_an_item_are_or() {
let item = QueryItem::of_types(["A", "B"]).expect("valid types");
let (sql, params) = build(&Query::from_item(item));
assert_eq!(sql, "((event_type IN ($1, $2)))");
assert_eq!(
params,
vec![
Param::EventType("A".to_owned()),
Param::EventType("B".to_owned())
]
);
}
#[test]
fn tags_within_an_item_are_one_containment_test() {
let tags = Tags::from_pairs([("course", "c1"), ("student", "s1")]).expect("valid tags");
let item = QueryItem::tagged(tags).expect("valid item");
let (sql, params) = build(&Query::from_item(item));
assert_eq!(sql, "((tags @> $1::text[]))");
assert_eq!(
params,
vec![Param::Tags(vec![
"course:c1".to_owned(),
"student:s1".to_owned()
])]
);
}
#[test]
fn types_and_tags_within_an_item_are_and() {
let tags = Tags::from_pairs([("course", "c1")]).expect("valid tags");
let item = QueryItem::new(["A"], tags).expect("valid item");
let (sql, _) = build(&Query::from_item(item));
assert_eq!(sql, "((event_type IN ($1) AND tags @> $2::text[]))");
}
#[test]
fn items_are_or_and_every_arm_is_parenthesised() {
let first = QueryItem::of_types(["A"]).expect("valid");
let second =
QueryItem::tagged(Tags::from_pairs([("k", "v")]).expect("valid")).expect("valid");
let (sql, _) = build(&Query::from_items([first, second]).expect("valid"));
assert_eq!(sql, "((event_type IN ($1)) OR (tags @> $2::text[]))");
}
#[test]
fn placeholder_numbering_continues_from_the_callers_index() {
let item = QueryItem::of_types(["A"]).expect("valid");
let query = Query::from_item(item);
let mut next = 7;
let built = predicate(&query, &mut next);
assert_eq!(built.sql(), "((event_type IN ($7)))");
assert_eq!(next, 8, "the caller must be told what it may use next");
}
#[test]
fn an_item_constraining_nothing_cannot_be_built_at_all() {
assert!(
QueryItem::tagged(Tags::default()).is_err(),
"the core crate rejects an unconstrained item; `Query::All` is how that is spelled"
);
}
}