happenstance-postgres 0.2.0

PostgreSQL event store and projection store adapters for happenstance.
Documentation
//! Translating a [`Query`] into a Postgres `WHERE` clause.
//!
//! One translation, two callers: the read path's `DECLARE … CURSOR` and the
//! append condition's conflict probe. They are the same predicate over the same
//! table, and writing it twice is how the two acquire different bugs.
//!
//! # The semantics being reproduced
//!
//! Within a [`QueryItem`], **types are OR** (an empty list means any type) and
//! **tags are AND** (an empty set means any tags, and a superset matches).
//! **Across items it is OR.** `happenstance_core::Query::matches` is the
//! reference implementation and the conformance suite holds this to it.
//!
//! # Why `@>` and not a join table
//!
//! `Tags` is canonically sorted and deduplicated at construction, so the
//! containment operator expresses "the event's tags are a superset of the item's
//! tags" in one operator against one GIN index. The SQLite adapter uses a join
//! table with a correlated `EXISTS` per tag because SQLite has no array type and
//! no GIN; that difference is storage-shaped, not semantic.
//!
//! # Parameters, not interpolation
//!
//! Every value is bound. Not because a tag could contain a quote — `Tag` and
//! `EventType` both reject control characters at construction — but because the
//! moment a value reaches SQL as text, the next person to add a value type has
//! no interpolation-free example to copy.

use happenstance_core::{Query, QueryItem};

/// A `WHERE`-clause fragment and the parameters it binds, in order.
///
/// The fragment is always parenthesised as a unit, so a caller may `AND` it with
/// its own predicates without thinking about precedence.
#[derive(Debug, Clone)]
pub(crate) struct Predicate {
    /// SQL, using `$n` placeholders numbered from the caller's starting index.
    sql: String,
    /// The values to bind, in placeholder order.
    params: Vec<Param>,
}

/// A value bound into a generated predicate.
///
/// An enum rather than `sqlx`'s `Arguments` because the parameters are built by
/// one function and bound by another, and an owned, inspectable list is what
/// lets a test assert on the generated plan without executing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Param {
    /// One event type, bound as `text`.
    EventType(String),
    /// A whole tag set, bound as `text[]` for `@>`.
    Tags(Vec<String>),
}

impl Predicate {
    /// The SQL fragment.
    pub(crate) fn sql(&self) -> &str {
        &self.sql
    }

    /// The parameters, in placeholder order.
    pub(crate) fn params(&self) -> &[Param] {
        &self.params
    }
}

/// Builds the `WHERE`-clause fragment matching `query`, numbering placeholders
/// from `next` and leaving `next` pointing past the last one used.
///
/// [`Query::All`] yields `TRUE` rather than an empty string: a caller can always
/// write `WHERE {fragment} AND …` without a special case, and `TRUE` is what the
/// planner removes for free.
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() {
        // Unreachable through today's public API — `Query::from_items([])` is
        // rejected as `InvalidQuery::NoItems`, and the test below asserts that
        // rather than leaving this looking untested. Kept because `Query` is
        // `#[non_exhaustive]` and `items()` hands back a plain slice. `FALSE`
        // rather than `TRUE`: an empty disjunction is empty, and getting it
        // backwards turns a query matching nothing into one matching the whole
        // log — and an append condition into one that refuses every append.
        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 {
        // Each arm is parenthesised, and so is the disjunction. The core crate's
        // `AppendCondition` docs warn about exactly this: an adapter generating
        // SQL must parenthesise each guard explicitly, because the precedence
        // bug that already threatens the single-boundary form becomes n times
        // more likely here.
        sql: format!("({})", arms.join(" OR ")),
        params,
    }
}

/// One query item: types OR'd, tags AND'd, the two AND'd together.
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(),
        ));
        // `@>` is containment: the row's tags must be a superset of the item's.
        // `<@` would be the other direction and would silently turn a
        // superset match into an exact-subset one.
        conjuncts.push(format!("tags @> ${next}::text[]"));
        *next += 1;
    }

    if conjuncts.is_empty() {
        // Also unreachable, and for a stronger reason: `QueryItem` rejects an
        // item constraining neither types nor tags as
        // `InvalidQuery::UnconstrainedItem`, so "matches everything" is spelled
        // `Query::All` and has nowhere else to come from. Same
        // `#[non_exhaustive]` justification for keeping it; same test below.
        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());
    }

    /// The `FALSE` branch above is unreachable through the public API, and this
    /// is the test that says so rather than leaving it looking like a gap.
    ///
    /// `Query::from_items([])` is rejected as `InvalidQuery::NoItems`, so a
    /// query matching nothing cannot be built. The branch stays because `Query`
    /// is `#[non_exhaustive]` and `items()` hands back a plain slice — a future
    /// variant could yield an empty one — and because the failure it guards is
    /// silent and expensive in the wrong direction: emitting `TRUE` for an empty
    /// disjunction turns a query that should match nothing into one that matches
    /// the entire log, and as an append *condition* into one that refuses every
    /// append.
    #[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[]))");
        // Canonically sorted by `Tags` itself, which is what keeps `@>` usable.
        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[]))");
    }

    /// Across items it is OR, and every arm is parenthesised.
    ///
    /// The unparenthesised form is `a AND b OR c AND d`, which Postgres reads as
    /// `(a AND b) OR (c AND d)` — correct here by luck. Add a boundary predicate
    /// with `AND` at the caller and the luck runs out, which is why the whole
    /// disjunction is wrapped too.
    #[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");
    }

    /// The `(TRUE)` branch in `item_sql` is likewise unreachable, and for a
    /// stronger reason than the one above.
    ///
    /// `QueryItem` rejects an item with neither types nor tags outright, as
    /// `InvalidQuery::UnconstrainedItem` — so "matches everything" is spelled
    /// `Query::All` and has nowhere else to come from. Kept as a guard for the
    /// same `#[non_exhaustive]` reason, and asserted here so that a reader who
    /// notices the untested branch finds out why it is untestable instead of
    /// assuming it was missed.
    #[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"
        );
    }
}