Skip to content

Parse grouped calculations and the new calculate functions - #90

Open
jtnelson wants to merge 4 commits into
developfrom
feature/GH-89-grouped-calculations
Open

jtnelson wants to merge 4 commits into
developfrom
feature/GH-89-grouped-calculations

Conversation

@jtnelson

@jtnelson jtnelson commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Background

The Concourse epic cinchapi/concourse#1417 adds new calculations, which include
new functions, calculations grouped by the values of keys or by ranges of
numbers or time, and several calculations in one statement. Concourse builds the
command for a calculate statement from the CalculateSymbol that CCL parses the
statement into, so CCL has to parse each new form before Concourse can run it.

Before this change, a calculate statement applied one function to one key, and
that function had to be sum, avg, average, count, min or max. The
statement could not group its records. Its CalculateSymbol also had no
equals, hashCode or text, so a caller could neither compare two parses of a
statement nor turn a symbol back into CCL.

A calculation's key can be a function key, such as age | avg, so the hash code
of a CalculateSymbol depends on the hash code of a function. Before this
change, two equal functions had different hash codes, so a FunctionKeySymbol,
a FunctionValueSymbol, or a tree that held one could fail to match an equal
one in a hash set or as a hash map key.

Closes #89

Change

The calculate statement takes the new functions and an optional group by
clause, and a grouped statement can list several calculations separated by
commas. A CalculateSymbol exposes each calculation as a CalculationSymbol
through calculations(), and the group clause as a GroupSymbol through
group(). The GroupSymbol holds the group keys, the range, the having
clause as a HavingSymbol, the order of the groups as a ResultOrderSymbol,
and the page. For example, a caller reads a grouped statement like this.

Compiler compiler = Compiler.create(Convert::stringToJava,
        Convert::stringToOperator);
CommandTree tree = (CommandTree) compiler.parse("calculate count $id$, "
        + "avg rating where active = true group by brand, price per 10 "
        + "between 0 and 100 having count >= 2 order by avg desc limit 10");
CalculateSymbol calculate = (CalculateSymbol) tree.root();
calculate.calculations();      // [count $id$, avg rating]
tree.conditionTree();          // active = true

GroupSymbol group = calculate.group();
group.keys();                  // [brand, price]
group.width();                 // 10, the width of each range of price
group.lowerBound();            // 0
group.upperBound();            // 100
group.having().calculation();  // count $id$
group.order().calculation();   // avg rating
group.order().direction();     // DirectionSymbol.DESCENDING
group.page();                  // PageSymbol.fromLimit(10)

The order and page of a grouped statement belong to its GroupSymbol rather
than to the tree's OrderTree and PageTree, because they order and page
groups rather than records. For the same reason, a grouped statement orders its
groups by the result of a calculation, so its order by names a function
rather than a key.

The existing constructors and accessors of CalculateSymbol keep their meaning.
An ungrouped statement has one calculation, so a caller that reads function(),
key(), records() and timestamp() gets the same values as before. A
statement that holds the text group by in an unquoted value now fails to
parse, because the grammar reserves that text.

A caller can also build a symbol from its parts, and the text of a
CalculateSymbol is a statement that parses back to an equal symbol.

CalculationSymbol count = new CalculationSymbol("count",
        new KeySymbol("$id$"));
CalculateSymbol calculate = new CalculateSymbol(ImmutableList.of(count),
        null, null,
        GroupSymbol.builder(ImmutableList.of(new KeySymbol("category")))
                .order(new ResultOrderSymbol(count, DirectionSymbol.DESCENDING))
                .page(PageSymbol.fromLimit(10)).build());
calculate.toString();
// calculate count $id$ group by category order by count desc limit 10

JavaCC generates Grammar.java, GrammarConstants.java and
GrammarTokenManager.java from grammar/grammar.jjt, so the grammar change
itself is in grammar.jjt. The diff of Function moves its members into sorted
order, and its hash code is the one part whose behavior changes.

Semantics

Statements

  • The new function names are countDistinct, median, percentile, stddev,
    stddevPopulation, variance and variancePopulation, and every function
    name parses in any letter case.
  • percentile takes a fraction from 0 to 1 before its key, as in
    calculate percentile 0.99 latency, and no other function takes a fraction.
    A percentile without a fraction, or with one outside that range, is a syntax
    error.
  • Only a statement with a group by clause can list several calculations or
    use having, order by, limit or offset.
  • The group by clause comes after the scope (records or a where condition)
    and the timestamp. An at right after a comparison belongs to that
    comparison, as it does for find, so a statement with a condition sets the
    timestamp of its calculation with as of, or with at after a parenthesized
    condition.
  • The text group by is reserved in any letter case, even when a longer word
    starts with by, as in group bypass. So find name = rock group by sea is
    a syntax error, and a value that holds the text must be quoted, as in
    name = "rock group by sea". The words per and having are not reserved,
    so a key may have either name.

Groups

  • A group by clause names one or more group keys, which may be navigation
    keys. Its optional parts follow the keys in this order.
    • per <number> groups the values of the last key into number ranges of that
      width, and per "<duration>" groups them into time ranges of that period.
      A duration has the form of a within duration, such as "1 day".
    • between <a> and <b> follows per and asks for every range between the
      bounds, including an empty one. The bounds are numbers for number ranges
      and timestamps for time ranges.
    • having <function> <operator> <value> keeps the groups whose result
      satisfies the comparison, as in having count >= 2.
    • order by <function> [asc|desc] orders the groups by a result, ascending
      by default.
    • limit and offset page the groups.
  • The function in having and order by names one of the statement's
    calculations in any letter case, and avg and average name the same
    function. A function that names none of the calculations, or more than one,
    is a syntax error, and so is an order by that names a group key.
  • A width or a period must be positive, and the first bound of between must
    come before the second. A statement that breaks either rule is a syntax
    error.
  • A timestamp bound reads its text the way an at clause does, so a date
    without a time takes the current time of day. The start of a day needs an
    explicit time, such as "2026-01-01 00:00:00".

Symbols

  • calculations() returns the calculations in the order the statement lists
    them, and the function() and key() of a CalculateSymbol are those of the
    first.
  • function() returns a canonical name. It is camelCase for a new function,
    such as countDistinct, because that is the name of the Concourse calculation
    it asks for, and it stays lower case for sum, avg, average, count,
    min and max. fraction() is the fraction of a percentile and null for
    any other function.
  • group() is null for an ungrouped statement, and each part of a group that
    the statement leaves out is null. A whole number in a range is an Integer
    or a Long, a decimal is a Double, period() is a java.time.Duration,
    and start() and end() are TimestampSymbols.
  • The calculation() of a HavingSymbol or a ResultOrderSymbol is the
    element of calculations() that its function names.
  • CalculateSymbol, CalculationSymbol, GroupSymbol, HavingSymbol and
    ResultOrderSymbol implement equals and hashCode, and numbers in a group
    are equal when they have the same value, such as 10 and 10.0. The text of
    a CalculateSymbol is its statement without the condition, which stays a
    child of the CommandTree, and that text parses to an equal symbol.
  • A symbol built from its parts must follow the rules of the grammar. A
    constructor or a builder method throws IllegalArgumentException for an
    invalid part, and GroupSymbol.Builder#build() throws
    IllegalStateException for a range whose parts do not fit together, such as
    both a width and a period.
  • Compiler#analyze reports the key of every calculation and every group key.
  • Equal functions have equal hash codes, so a FunctionKeySymbol, a
    FunctionValueSymbol, or a tree that holds one matches an equal one in a hash
    set or as a hash map key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parse grouped calculations and the new calculate functions

1 participant