Filter the query – The Expression Engine
Because Collection represents SQL SELECT query, they offer way to filter the query. Clear offer the Expression Engine, which is inspired by Sequel. It basically helps you to write complex filter conditions without sacrificing on code expressiveness.
The where clause
Filtering by value
In this example, let's assume we are looking for first_name or last_name equals to Richard. There's many ways to write the condition:
For very simple queries, using tuple is the way to go:
For more complex querying with elegance, see below.
Expression Engine: Operators
Example
In the example above, if some part of the expression are existing variable in the scope of the code execution, then the value of the variable will be taken in consideration.
Otherwise, the name will refers to a column, schema or anything related to the PostgreSQL universe.
List of permitted operators: <, >, <=, >=, !=, ==, =~, /, *, +, -
When comparing against nil with == or != operators, the expression engine
Expression Engine: Var, Raw
As explained above, one of the caveats of the expression engine is the variable scope reduction. Basically, whenever a part of the expression can be reduced to his value in Crystal, the Expression Engine will do it, which can lead to some surprises like in this example:
In this example, id will be reduced to the value of the variable id
and the comparaison will fail, leading to this:
Thankfully, the expression engine will reject any "static code" and throw an exception at compile time in this case. The good way to do it would be to use var or raw as below:
raw
can lead to SQL injection, as it pastes without safeguard the string passed as parameter. On other hand, var
will surround each part of the expression with double quote, to escape the column name aka PostgreSQL style.
Range and array and other methods
Expression engine manage natively range, array and other methods as see below.
Range:
Array / Tuples:
AND, OR methods
AND
and OR
operators are respectively mapped as &
and |
. As of now, we cannot override the operators &&
and ||
in Crystal. Since &
and |
behave differently in terms of priority order, parenthesis around the condition must be provided.
Last updated