Repository navigation
Internals Database Query QueryBuilder
Framework Internals · Subsystem overview · Developer guide
Source: awt_src/classes/database/query/QueryBuilder.php · Snapshot 8411f4287706.
DatabaseManager delegates SQL generation to QueryBuilder, execution to IProvider, and result caching to ICache. Schema builders use MySQL DDL and the framework table registry.
class QueryBuilderSource description (behavioral corrections are recorded in Known discrepancies):
QueryBuilder
Solely responsible for assembling SQL strings and their PDO bindings. It never touches a database connection - execution is the provider's concern.
Usage (mirrors the old DatabaseManager API):
$payload = (new QueryBuilder()) ->table('users') ->select(['id', 'name']) ->where(['name' => 'Alice']) ->buildSelect();
// $payload->sql → "SELECT id, name FROM users WHERE name = :name" // $payload->bindings → [':name' => 'Alice'] // $payload->conditions → ['name' => 'Alice'] (used for cache invalidation)
Declarations below preserve visibility, type, default and modifiers exactly. A typed property without an initializer remains uninitialized until its constructor or another method assigns it. Mutable fields belong to this instance unless marked static; readonly fields can be initialized once. Constructor-promoted properties are also listed below.
| Member | Declaration | Purpose or source contract |
|---|---|---|
| $parameterIndex | private int $parameterIndex = 0; |
Used by placeholder(), reset(). |
| $table | private string $table = ''; |
Used by table(), getTable(), select(), buildSelect(), buildInsert(), buildUpdate(), buildDelete(), reset(). |
| $selectClause | private string $selectClause = ''; |
Used by select(), buildSelect(), reset(). |
| $joins | private array $joins = []; |
Used by join(), buildSelect(), reset(). |
| $whereClause | private string $whereClause = ''; |
Used by where(), appendWhere(), like(), buildSelect(), buildUpdate(), buildDelete(), reset(). |
| $bindings | private array $bindings = []; |
Used by where(), predicate(), like(), buildSelect(), buildUpdate(), buildDelete(), reset(). |
| $conditions | private array $conditions = []; |
Used by where(), predicate(), like(), buildSelect(), buildUpdate(), buildDelete(), reset(). |
| $orderByClauses | private array $orderByClauses = []; |
Used by orderBy(), buildSelect(), reset(). |
| $insertColumns | private array $insertColumns = []; |
Used by insert(), buildInsert(), reset(). |
| $insertBindings | private array $insertBindings = []; |
Used by insert(), buildInsert(), reset(). |
| Method | Signature |
|---|---|
| table | public function table(string $name): self |
| getTable | public function getTable(): string |
| insert | public function insert(array $data): self |
| select | public function select(array $columns = ['*']): self |
| join | public function join(string $table, string $on, string $type = 'INNER'): self |
| where | public function where(array $conditions, bool $useNot = false, string $conjunction = 'AND'): self |
| andWhere | public function andWhere(array $conditions, bool $useNot = false): self |
| orWhere | public function orWhere(array $conditions, bool $useNot = false): self |
| appendWhere | private function appendWhere(array $conditions, bool $useNot, string $conjunction): self |
| predicate | private function predicate(array $conditions, string $operator, string $conjunction): string |
| placeholder | private function placeholder(): string |
| assertIdentifier | private function assertIdentifier(string $identifier, bool $qualified = true, bool $numeric = false): void |
| joinOn | public function joinOn(string $table, string $leftColumn, string $rightColumn, string $type = 'INNER'): self |
| like | public function like(array $conditions, bool $useNot = false): self |
| orderBy | public function orderBy(string $column, string $direction = 'ASC'): self |
| buildSelect | public function buildSelect(?int $limit = null, ?int $offset = null): QueryPayload |
| buildInsert | public function buildInsert(): QueryPayload |
| buildUpdate | public function buildUpdate(array $data): QueryPayload |
| buildDelete | public function buildDelete(): QueryPayload |
| reset | public function reset(): void |
| sanitiseConjunction | private function sanitiseConjunction(string $conjunction): string |
public function table(string $name): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$name |
string $name |
Named key/label selected by this API; its exact scope is shown by the implementation trace. |
State writes: $this->table.
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
// -------------------------------------------------------------------------
// Fluent setters
// -------------------------------------------------------------------------
public function table(string $name): self
{
$this->assertIdentifier($name);
$this->table = $name;
return $this;
}public function getTable(): stringReturn expressions (including local callbacks): $this->table.
Implementation, validation guards and interaction order
public function getTable(): string
{
return $this->table;
}public function insert(array $data): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$data |
array $data |
Input data array or payload; see allowed fields and validation guards below. |
Prepare column / binding lists for a future INSERT.
State writes: $this->insertColumns[], $this->insertBindings[$this->placeholder()].
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
/** Prepare column / binding lists for a future INSERT. */
public function insert(array $data): self
{
foreach ($data as $column => $value) {
$this->assertIdentifier((string) $column, false);
$this->insertColumns[] = $column;
$this->insertBindings[$this->placeholder()] = $value;
}
return $this;
}public function select(array $columns = ['*']): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$columns |
array $columns = ['*'] |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Set the SELECT … FROM clause.
State writes: $this->selectClause.
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
/** Set the SELECT … FROM clause. */
public function select(array $columns = ['*']): self
{
$this->selectClause = 'SELECT ' . implode(', ', $columns) . " FROM {$this->table}";
return $this;
}public function join(string $table, string $on, string $type = 'INNER'): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$table |
string $table |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$on |
string $on |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$type |
string $type = 'INNER' |
Expected class/type or enum selection according to the signature. |
State writes: $this->joins[].
Return expressions (including local callbacks): $this.
Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
public function join(string $table, string $on, string $type = 'INNER'): self
{
$this->assertIdentifier($table);
$type = strtoupper($type);
if (!in_array($type, ['INNER', 'LEFT', 'RIGHT', 'LEFT OUTER', 'RIGHT OUTER', 'CROSS'], true)) {
throw new \InvalidArgumentException('Unsupported JOIN type.');
}
// Legacy ON expressions are trusted SQL. Use joinOn() with external identifiers.
$this->joins[] = " {$type} JOIN {$table} ON {$on}";
return $this;
}public function where(array $conditions, bool $useNot = false, string $conjunction = 'AND'): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$useNot |
bool $useNot = false |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$conjunction |
string $conjunction = 'AND' |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Add a WHERE … = … (or != …) clause.
Every column/value pair is also recorded in $this->conditions so that the cache layer can later invalidate by matching WHERE criteria.
State writes: $this->bindings, $this->conditions, $this->whereClause.
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
/**
* Add a WHERE … = … (or != …) clause.
*
* Every column/value pair is also recorded in $this->conditions so that
* the cache layer can later invalidate by matching WHERE criteria.
*/
public function where(array $conditions, bool $useNot = false, string $conjunction = 'AND'): self
{
// Preserve legacy replacement semantics, but discard replaced bindings.
$this->bindings = [];
$this->conditions = [];
$this->whereClause = $conditions === [] ? '' : ' WHERE ' . $this->predicate($conditions, $useNot ? '!=' : '=', $conjunction);
return $this;
}public function andWhere(array $conditions, bool $useNot = false): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$useNot |
bool $useNot = false |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Return expressions (including local callbacks): $this->appendWhere($conditions, $useNot, 'AND').
Implementation, validation guards and interaction order
public function andWhere(array $conditions, bool $useNot = false): self
{
return $this->appendWhere($conditions, $useNot, 'AND');
}public function orWhere(array $conditions, bool $useNot = false): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$useNot |
bool $useNot = false |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Return expressions (including local callbacks): $this->appendWhere($conditions, $useNot, 'OR').
Implementation, validation guards and interaction order
public function orWhere(array $conditions, bool $useNot = false): self
{
return $this->appendWhere($conditions, $useNot, 'OR');
}private function appendWhere(array $conditions, bool $useNot, string $conjunction): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$useNot |
bool $useNot |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$conjunction |
string $conjunction |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
State writes: $this->whereClause.
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
private function appendWhere(array $conditions, bool $useNot, string $conjunction): self
{
if ($conditions === []) return $this;
$predicate = $this->predicate($conditions, $useNot ? '!=' : '=', 'AND');
$this->whereClause = $this->whereClause === '' ? ' WHERE ' . $predicate
: ' WHERE (' . substr($this->whereClause, 7) . ') ' . $conjunction . ' (' . $predicate . ')';
return $this;
}private function predicate(array $conditions, string $operator, string $conjunction): string| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$operator |
string $operator |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$conjunction |
string $conjunction |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
State writes: $this->conditions[$column], $this->bindings[$placeholder].
Return expressions (including local callbacks): implode(' ' . $this->sanitiseConjunction($conjunction) . ' ', $clauses).
Implementation, validation guards and interaction order
private function predicate(array $conditions, string $operator, string $conjunction): string
{
$clauses = [];
foreach ($conditions as $column => $value) {
$this->assertIdentifier((string) $column, true, true);
$this->conditions[$column] = $value;
if ($value === null && in_array($operator, ['=', '!='], true)) {
$clauses[] = $column . ($operator === '=' ? ' IS NULL' : ' IS NOT NULL');
} else {
$placeholder = $this->placeholder();
$clauses[] = "{$column} {$operator} {$placeholder}";
$this->bindings[$placeholder] = $value;
}
}
return implode(' ' . $this->sanitiseConjunction($conjunction) . ' ', $clauses);
}private function placeholder(): stringReturn expressions (including local callbacks): ':p' . ++$this->parameterIndex.
Implementation, validation guards and interaction order
private function placeholder(): string { return ':p' . ++$this->parameterIndex; }private function assertIdentifier(string $identifier, bool $qualified = true, bool $numeric = false): void| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$identifier |
string $identifier |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$qualified |
bool $qualified = true |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$numeric |
bool $numeric = false |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
private function assertIdentifier(string $identifier, bool $qualified = true, bool $numeric = false): void
{
if ($numeric && preg_match('/^[0-9]+$/D', $identifier)) return;
$part = '(?:[A-Za-z_][A-Za-z0-9_]*|`[A-Za-z_][A-Za-z0-9_]*`)';
$pattern = $qualified ? '/^' . $part . '(?:\\.' . $part . ')*$/D' : '/^' . $part . '$/D';
if (!preg_match($pattern, $identifier)) throw new \InvalidArgumentException("Invalid SQL identifier: {$identifier}");
}public function joinOn(string $table, string $leftColumn, string $rightColumn, string $type = 'INNER'): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$table |
string $table |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$leftColumn |
string $leftColumn |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$rightColumn |
string $rightColumn |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$type |
string $type = 'INNER' |
Expected class/type or enum selection according to the signature. |
Return expressions (including local callbacks): $this->join($table, "{$leftColumn} = {$rightColumn}", $type).
Implementation, validation guards and interaction order
public function joinOn(string $table, string $leftColumn, string $rightColumn, string $type = 'INNER'): self
{
$this->assertIdentifier($leftColumn);
$this->assertIdentifier($rightColumn);
return $this->join($table, "{$leftColumn} = {$rightColumn}", $type);
}public function like(array $conditions, bool $useNot = false): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conditions |
array $conditions |
Column/value predicate map; values are bound and identifiers validated by QueryBuilder. |
$useNot |
bool $useNot = false |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Add a WHERE … LIKE … clause.
State writes: $this->bindings, $this->conditions, $this->whereClause.
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
/** Add a WHERE … LIKE … clause. */
public function like(array $conditions, bool $useNot = false): self
{
$this->bindings = [];
$this->conditions = [];
$this->whereClause = $conditions === [] ? '' : ' WHERE ' . $this->predicate($conditions, $useNot ? 'NOT LIKE' : 'LIKE', 'AND');
return $this;
}public function orderBy(string $column, string $direction = 'ASC'): self| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$column |
string $column |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
$direction |
string $direction = 'ASC' |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
State writes: $this->orderByClauses[].
Return expressions (including local callbacks): $this.
Implementation, validation guards and interaction order
public function orderBy(string $column, string $direction = 'ASC'): self
{
$this->assertIdentifier($column);
$direction = strtoupper($direction) === 'DESC' ? 'DESC' : 'ASC';
$this->orderByClauses[] = "{$column} {$direction}";
return $this;
}public function buildSelect(?int $limit = null, ?int $offset = null): QueryPayload| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$limit |
?int $limit = null |
Maximum result count; query pagination rejects negative values. |
$offset |
?int $offset = null |
Skipped row count; SQL offset is emitted only when a limit is set. |
Return expressions (including local callbacks): new QueryPayload($sql, $bindings, $this->table, $this->conditions).
Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
public function buildSelect(?int $limit = null, ?int $offset = null): QueryPayload
{
if (($limit !== null && $limit < 0) || ($offset !== null && $offset < 0)) {
throw new \InvalidArgumentException('Pagination values must be nonnegative.');
}
$sql = $this->selectClause . implode('', $this->joins) . $this->whereClause;
$bindings = $this->bindings;
if (!empty($this->orderByClauses)) {
$sql .= ' ORDER BY ' . implode(', ', $this->orderByClauses);
}
if ($limit !== null) {
$sql .= ' LIMIT :limit';
$bindings[':limit'] = $limit;
if ($offset !== null) {
$sql .= ' OFFSET :offset';
$bindings[':offset'] = $offset;
}
}
return new QueryPayload($sql, $bindings, $this->table, $this->conditions);
}public function buildInsert(): QueryPayloadReturn expressions (including local callbacks): new QueryPayload($sql, $this->insertBindings, $this->table, []).
Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
public function buildInsert(): QueryPayload
{
if ($this->insertColumns === []) throw new \InvalidArgumentException('Cannot insert an empty attribute list.');
if (count($this->insertColumns) !== count($this->insertBindings)) {
throw new \InvalidArgumentException('Column count does not match value count.');
}
$sql = sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$this->table,
implode(', ', $this->insertColumns),
implode(', ', array_keys($this->insertBindings))
);
return new QueryPayload($sql, $this->insertBindings, $this->table, []);
}public function buildUpdate(array $data): QueryPayload| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$data |
array $data |
Input data array or payload; see allowed fields and validation guards below. |
Build an UPDATE query.
SET bindings use the prefix "set_" to avoid placeholder collisions when the same column appears in both SET and WHERE (e.g. UPDATE t SET name=? WHERE name=?).
Return expressions (including local callbacks): new QueryPayload($sql, $bindings, $this->table, $this->conditions).
Explicit exceptions: \InvalidArgumentException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
/**
* Build an UPDATE query.
*
* SET bindings use the prefix "set_" to avoid placeholder collisions when
* the same column appears in both SET and WHERE (e.g. UPDATE t SET name=?
* WHERE name=?).
*/
public function buildUpdate(array $data): QueryPayload
{
if ($data === []) throw new \InvalidArgumentException('Cannot update an empty attribute list.');
$setClauses = [];
$setBindings = [];
foreach ($data as $column => $value) {
$this->assertIdentifier((string) $column, false);
if ($value instanceof SqlExpression || $value === 'DEFAULT') {
$expression = $value instanceof SqlExpression ? $value->sql : 'DEFAULT';
$setClauses[] = "{$column} = {$expression}";
} else {
$placeholder = $this->placeholder();
$setClauses[] = "{$column} = {$placeholder}";
$setBindings[$placeholder] = $value instanceof BoundValue ? $value->value : $value;
}
}
$sql = "UPDATE {$this->table} SET " . implode(', ', $setClauses) . $this->whereClause;
$bindings = array_merge($setBindings, $this->bindings);
return new QueryPayload($sql, $bindings, $this->table, $this->conditions);
}public function buildDelete(): QueryPayloadBuild a DELETE query — refuses to build without a WHERE clause.
Return expressions (including local callbacks): new QueryPayload($sql, $this->bindings, $this->table, $this->conditions).
Explicit exceptions: \LogicException. The guards in the implementation below show when each is raised; exceptions from collaborators also propagate unless caught.
Implementation, validation guards and interaction order
/** Build a DELETE query — refuses to build without a WHERE clause. */
public function buildDelete(): QueryPayload
{
if ($this->whereClause === '') {
throw new \LogicException(
'DELETE without a WHERE clause is not allowed. ' .
"Use ->where(['1' => '1']) if a full-table delete is truly intended."
);
}
$sql = "DELETE FROM {$this->table}" . $this->whereClause;
return new QueryPayload($sql, $this->bindings, $this->table, $this->conditions);
}public function reset(): voidState writes: $this->parameterIndex, $this->table, $this->selectClause, $this->joins, $this->whereClause, $this->bindings, $this->conditions, $this->orderByClauses, $this->insertColumns, $this->insertBindings.
Implementation, validation guards and interaction order
public function reset(): void
{
$this->parameterIndex = 0;
$this->table = '';
$this->selectClause = '';
$this->joins = [];
$this->whereClause = '';
$this->bindings = [];
$this->conditions = [];
$this->orderByClauses = [];
$this->insertColumns = [];
$this->insertBindings = [];
}private function sanitiseConjunction(string $conjunction): string| Parameter | Type, modifiers and default | Purpose |
|---|---|---|
$conjunction |
string $conjunction |
Operation input; the exact use, validation and propagation are shown in the implementation trace. |
Return expressions (including local callbacks): in_array($upper, ['AND', 'OR'], true) ? $upper : 'AND'.
Implementation, validation guards and interaction order
private function sanitiseConjunction(string $conjunction): string
{
$upper = strtoupper($conjunction);
return in_array($upper, ['AND', 'OR'], true) ? $upper : 'AND';
}AWT Framework Wiki · Home · Installation Guide · Developer Guide · Framework Internals
Philosophy · Architecture · Known discrepancies · Verification
Installation Guide
Developer Guide
- Learning sequence
- First package
- Package structure
- Lifecycle
- Runtimes
- Events and objects
- Routing and controllers
- Views and resources
- Database and models
- Storage and caching
- Configuration and CLI
- Responses and errors
- Extension points
Framework Internals
- Architecture
- Bootstrap
- Packages
- Runtime
- Events and context
- Objects
- HTTP routing and controllers
- Rendering
- Blade integration
- Database
- Models
- Storage and caching
- Settings
- CLI
- Identity and sessions
- Responses
- Errors
- Complete source inventory
Documentation notes