Skip to content

Compiling Queries

Miguel Muscat edited this page May 21, 2022 · 2 revisions

Queries in Atlas are simple objects that contain generic data. They are compiled into strings using QueryTypeInterface instances. This is done by giving the query type to the query during creation:

use RebelCode\Atlas\Query;
use RebelCode\Atlas\QueryType\Select;

$type = new Select();
$query = new Query($type, [
    'from' => 'users',
    'columns' => ['id', 'name', 'email']
]);

The query can then be compiled by casting to string or calling toString(), which is equivalent to calling $type->compile($query).

Implementing Query Types

Query implementations receive the query object. Compiling the query into a string usually involves reading data from the Query object and using it to build the final string. The QueryCompiler class contains a lot of useful utility methods that you can use to render fragments of queries.

The below is an overly-simplified example of rendering SELECT queries:

use RebelCode\Atlas\Query;
use RebelCode\Atlas\QueryType\Select;
use RebelCode\Atlas\QueryTypeInterface;

class MySelect implements QueryTypeInterface
{
    public function compile(Query $query): string
    {
        $from = $query->get(Select::FROM);
        $columns = $query->get(Select::COLUMNS, ['*']);
        $where = $query->get(Select::WHERE);

        $result = [
            QueryCompiler::compileColumnList($columns, true),
            QueryCompiler::compileFrom($from, null, true),
            QueryCompiler::compileWhere($where),
        ];

        return 'SELECT ' . implode(' ', array_filter($result));
    }
}

As shown in the example above, data from the query is obtained via $query->get(). This retrieves the data from the query with the corresponding key. The query type classes provide constants for the standard data keys, such as SELECT::FROM.

$query = new Query($type, [
    'from' => 'my_table'
]);

$query->get('from'); // 'my_table'

Real code is often the best guide. Take a look at Atlas' query type implementations.

Clone this wiki locally