Querying
The query macro and where clause combine to give you full control over your query.
Where
Where is using a QueryBuilder that allows you to chain where clauses together to build up a complete query.
It supports different operators:
Supported operators are :eq, :gteq, :lteq, :neq, :gt, :lt, :nlt, :ngt, :ltgt, :in, :nin, :like, :nlike
Alternatively, #where
, #and
, and #or
accept a raw SQL clause, with an optional placeholder (?
for MySQL/SQLite, $
for Postgres) to avoid SQL Injection.
This is useful for building more sophisticated queries, including queries dependent on database specific features not supported by the operators above. However, clauses built with this method are not validated.
Order
Order is using the QueryBuilder and supports providing an ORDER BY clause:
Direction
Multiple fields
With direction
Group By
Group is using the QueryBuilder and supports providing an GROUP BY clause:
Multiple fields
Limit
Limit is using the QueryBuilder and provides the ability to limit the number of tuples returned:
Offset
Offset is using the QueryBuilder and provides the ability to offset the results. This is used for pagination:
All
All is not using the QueryBuilder. It allows you to directly query the database using SQL.
When using the all
method, the selected fields will match the fields specified in the model unless the select
macro was used to customize the SELECT.
Always pass in parameters to avoid SQL Injection. Use a ?
in your query as placeholder. Checkout the Crystal DB Driver for documentation of the drivers.
Here are some examples:
Customizing SELECT
The select_statement
macro allows you to customize the entire query, including the SELECT portion. This shouldn't be necessary in most cases, but allows you to craft more complex (i.e. cross-table) queries if needed:
You can combine this with an argument to all
or first
for maximum flexibility:
Note - the column order does matter, and you should match your SELECT query to have the columns in the same order they are in the database.
Exists?
The exists?
class method returns true
if a record exists in the table that matches the provided id or criteria, otherwise false
.
If passed a Number
or String
, it will attempt to find a record with that primary key. If passed a Hash
or NamedTuple
, it will find the record that matches that criteria, similar to find_by
.
The exists?
method can also be used with the query builder.
Last updated