Lesson 7.5: Value expressions
Expressions and let assignments
Expressions are used to compute new values or capture the result of function calls as a new variable.
Declaration
To assign the result of an expression to a variable, use let $var = <expression>
. The following Fetch query shows how we might fetch the line totals for a particular order.
match $order isa order, has id "o0014";
$book isa book, has price $retail_price;
order-line ($order, $book), has quantity $quantity;
let $line_total = $quantity * $retail_price;
fetch { "line-total": $line_total };
Using computed values in writes
In addition to retrieving computed values in Fetch queries, we can also use them for data writes. In the following query, we modify the previous example to write the line total as an attribute to the order line instead of retrieving it.
match $order isa order, has id "o0014";
$book isa book, has price $retail_price;
$line isa order-line ($order, $book), has quantity $quantity;
let $line_total = $quantity * $retail_price;
insert $line has price == $line_total;
Computed variables have value types inferred from the expression. When inserting an attribute, you still specify the attribute type on the left-hand side of has
and the computed value on the right; inserting a bare variable without the attribute type is not valid.
Assignment
Computed variables are defined using let $var = <expression>
and can hold values of any value type. The assigned value is described by an expression, which can take any of the following forms:
-
A variable bound to an attribute’s value, copying out just the raw value:
let $value = $attribute;
-
A literal value:
let $value = "literal";
-
Any combination of the above, using certain value operations:
let $value = max($a + 100, $c) / $d;
-
A function call returning a single value
let $value = my_reducing_function($x);
There is also a separate let … in
syntax for assigning to an iterable one element at a time:
* A function call returning a stream of values, taken one at a time
+
let $value in match_subquery_function($x);
We will explore the different value operations, along with the value types they are valid for, in the remainder of this lesson.
Arithmetic operations
TypeQL ships with a number of built-in operators and functions. See the expressions reference for the current list.