Elgg  Version 7.1
QueryBuilder.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Database;
4 
5 use Doctrine\DBAL\ArrayParameterType;
6 use Doctrine\DBAL\Connection;
7 use Doctrine\DBAL\ParameterType;
8 use Doctrine\DBAL\Query\Expression\CompositeExpression;
9 use Doctrine\DBAL\Query\QueryBuilder as DbalQueryBuilder;
10 use Doctrine\DBAL\Result;
16 use Elgg\Values;
17 
21 abstract class QueryBuilder extends DbalQueryBuilder {
22 
23  const CALCULATIONS = [
24  'avg',
25  'count',
26  'greatest',
27  'least',
28  'max',
29  'min',
30  'sum',
31  ];
32 
33  protected array $joins = [];
34 
35  protected int $join_index = 0;
36 
37  protected ?string $table_name = null;
38 
39  protected ?string $table_alias = null;
40 
46  public function __construct(protected readonly Connection $backup_connection) {
47  parent::__construct($backup_connection);
48  }
49 
57  public function getConnection(): Connection {
58  return $this->backup_connection;
59  }
60 
69  public function subquery(string $table, ?string $alias = null): Select {
70  $qb = new Select($this->getConnection());
71  $qb->from($table, $alias);
72 
73  return $qb;
74  }
75 
84  public function addClause(Clause $clause, ?string $alias = null): static {
85  if (!isset($alias)) {
86  $alias = $this->getTableAlias();
87  }
88 
89  $expr = $clause->prepare($this, $alias);
90  if ($clause instanceof WhereClause && ($expr instanceof CompositeExpression || is_string($expr))) {
91  $this->andWhere($expr);
92  }
93 
94  return $this;
95  }
96 
104  public function prefix(string $table): string {
105  $prefix = _elgg_services()->db->prefix;
106  if ($prefix === '') {
107  return $table;
108  }
109 
110  if (!str_starts_with($table, $prefix)) {
111  return "{$prefix}{$table}";
112  }
113 
114  return $table;
115  }
116 
122  public function getTableName(): string {
123  return (string) $this->table_name;
124  }
125 
131  public function getTableAlias(): ?string {
132  return $this->table_alias;
133  }
134 
145  public function param($value, string $type = ELGG_VALUE_STRING, ?string $key = null): string {
146  if (!$key) {
147  $parameters = $this->getParameters();
148  $key = ':qb' . (count($parameters) + 1);
149  }
150 
151  switch ($type) {
152  case ELGG_VALUE_GUID:
153  $type = ParameterType::INTEGER;
154 
155  $value = Values::normalizeGuids($value);
156 
157  break;
158  case ELGG_VALUE_ID:
159  $type = ParameterType::INTEGER;
160 
161  $value = Values::normalizeIds($value);
162 
163  break;
164  case ELGG_VALUE_INTEGER:
165  $type = ParameterType::INTEGER;
166 
167  break;
168  case ELGG_VALUE_BOOL:
169  $type = ParameterType::INTEGER;
170 
171  if (!is_array($value)) {
172  $value = [$value];
173  }
174 
175  $value = array_map(function($temp_value) {
176  return (int) (bool) $temp_value;
177  }, $value);
178 
179  break;
180  case ELGG_VALUE_STRING:
181  $type = ParameterType::STRING;
182 
183  break;
185  $type = ParameterType::INTEGER;
186 
187  if (!is_array($value)) {
188  $value = [$value];
189  }
190 
191  $value = array_map('\Elgg\Values::normalizeTimestamp', $value);
192  break;
193  }
194 
195  // convert array value or type based on array
196  if (is_array($value)) {
197  if (count($value) === 1) {
198  $value = array_shift($value);
199  } else {
200  if ($type === ParameterType::INTEGER) {
201  $type = ArrayParameterType::INTEGER;
202  } elseif ($type === ParameterType::STRING) {
203  $type = ArrayParameterType::STRING;
204  }
205  }
206  }
207 
208  return $this->createNamedParameter($value, $type, $key);
209  }
210 
218  public function execute(bool $track_query = true) {
219  if (!$track_query) {
220  if ($this instanceof Select) {
221  return $this->executeQuery();
222  } else {
223  return $this->executeStatement();
224  }
225  }
226 
227  return _elgg_services()->db->trackQuery($this, function() {
228  if ($this instanceof Select) {
229  return $this->executeQuery();
230  } else {
231  return $this->executeStatement();
232  }
233  });
234  }
235 
239  public function executeStatement(): int|string {
240  _elgg_services()->queryCache->clear();
241 
242  return parent::executeStatement();
243  }
244 
250  public function from(string $table, ?string $alias = null): self {
251  $this->table_name = $table;
252  $this->table_alias = $alias;
253 
254  return parent::from($this->prefix($table), $alias);
255  }
256 
262  public function insert(string $table): self {
263  $this->table_name = $table;
264 
265  return parent::insert($this->prefix($table));
266  }
267 
273  public function update(string $table): self {
274  $this->table_name = $table;
275 
276  return parent::update($this->prefix($table));
277  }
278 
284  public function delete(string $table): self {
285  $this->table_name = $table;
286 
287  return parent::delete($this->prefix($table));
288  }
289 
293  public function join(string $fromAlias, string $join, string $alias, ?string $condition = null): self {
294  return parent::join($fromAlias, $this->prefix($join), $alias, $condition);
295  }
296 
300  public function innerJoin(string $fromAlias, string $join, string $alias, ?string $condition = null): self {
301  return parent::innerJoin($fromAlias, $this->prefix($join), $alias, $condition);
302  }
303 
307  public function leftJoin(string $fromAlias, string $join, string $alias, ?string $condition = null): self {
308  return parent::leftJoin($fromAlias, $this->prefix($join), $alias, $condition);
309  }
310 
314  public function rightJoin(string $fromAlias, string $join, string $alias, ?string $condition = null): self {
315  return parent::rightJoin($fromAlias, $this->prefix($join), $alias, $condition);
316  }
317 
321  public function orderBy(string $sort, ?string $order = null): self {
322  if (isset($order) && !in_array(strtoupper($order), ['ASC', 'DESC'])) {
323  throw new DomainException("'{$order}' is not a valid order by direction");
324  }
325 
326  return parent::orderBy($sort, $order);
327  }
328 
332  public function addOrderBy(string $sort, ?string $order = null): self {
333  if (isset($order) && !in_array(strtoupper($order), ['ASC', 'DESC'])) {
334  throw new DomainException("'{$order}' is not a valid order by direction");
335  }
336 
337  return parent::addOrderBy($sort, $order);
338  }
339 
348  public function merge($parts = null, $boolean = 'AND') {
349  if (empty($parts)) {
350  return null;
351  }
352 
353  $parts = (array) $parts;
354 
355  $parts = array_filter($parts, function ($e) {
356  if (empty($e)) {
357  return false;
358  }
359 
360  if (!$e instanceof CompositeExpression && !is_string($e)) {
361  return false;
362  }
363 
364  return true;
365  });
366  if (empty($parts)) {
367  return null;
368  }
369 
370  if (count($parts) === 1) {
371  return array_shift($parts);
372  }
373 
374  // PHP 8 can use named arguments in call_user_func_array(), this causes issues
375  // @see: https://www.php.net/manual/en/function.call-user-func-array.php#125953
376  $parts = array_values($parts);
377  if (strtoupper($boolean) === 'OR') {
378  return call_user_func_array([$this->expr(), 'or'], $parts);
379  }
380 
381  return call_user_func_array([$this->expr(), 'and'], $parts);
382  }
383 
400  public function compare(string $x, string $comparison, $y = null, ?string $type = null, ?bool $case_sensitive = null) {
401  return (new ComparisonClause($x, $comparison, $y, $type, $case_sensitive))->prepare($this);
402  }
403 
414  public function between(string $x, $lower = null, $upper = null, ?string $type = null) {
415  $wheres = [];
416  if ($lower) {
417  $wheres[] = $this->compare($x, '>=', $lower, $type);
418  }
419 
420  if ($upper) {
421  $wheres[] = $this->compare($x, '<=', $upper, $type);
422  }
423 
424  return $this->merge($wheres);
425  }
426 
432  public function getNextJoinAlias(): string {
433  $this->join_index++;
434 
435  return "qbt{$this->join_index}";
436  }
437 
448  public function joinEntitiesTable(string $from_alias = '', string $from_column = 'guid', ?string $join_type = 'inner', ?string $joined_alias = null): string {
449  if (in_array($joined_alias, $this->joins)) {
450  return $joined_alias;
451  }
452 
453  if ($from_alias) {
454  $from_column = "{$from_alias}.{$from_column}";
455  }
456 
457  $hash = sha1(serialize([
458  $join_type,
459  EntityTable::TABLE_NAME,
460  $from_column,
461  ]));
462 
463  if (!isset($joined_alias) && !empty($this->joins[$hash])) {
464  return $this->joins[$hash];
465  }
466 
467  $condition = function (QueryBuilder $qb, $joined_alias) use ($from_column) {
468  return $qb->compare("{$joined_alias}.guid", '=', $from_column);
469  };
470 
471  $clause = new JoinClause(EntityTable::TABLE_NAME, $joined_alias, $condition, $join_type);
472  $joined_alias = $clause->prepare($this, $from_alias);
473 
474  $this->joins[$hash] = $joined_alias;
475 
476  return $joined_alias;
477  }
478 
490  public function joinMetadataTable(string $from_alias = '', string $from_column = 'guid', $name = null, ?string $join_type = 'inner', ?string $joined_alias = null): string {
491  if (in_array($joined_alias, $this->joins)) {
492  return $joined_alias;
493  }
494 
495  if ($from_alias) {
496  $from_column = "{$from_alias}.{$from_column}";
497  }
498 
499  $hash = sha1(serialize([
500  $join_type,
501  MetadataTable::TABLE_NAME,
502  $from_column,
503  (array) $name,
504  ]));
505 
506  if (!isset($joined_alias) && !empty($this->joins[$hash])) {
507  return $this->joins[$hash];
508  }
509 
510  $condition = function (QueryBuilder $qb, $joined_alias) use ($from_column, $name) {
511  return $qb->merge([
512  $qb->compare("{$joined_alias}.entity_guid", '=', $from_column),
513  $qb->compare("{$joined_alias}.name", '=', $name, ELGG_VALUE_STRING),
514  ]);
515  };
516 
517  $clause = new JoinClause(MetadataTable::TABLE_NAME, $joined_alias, $condition, $join_type);
518 
519  $joined_alias = $clause->prepare($this, $from_alias);
520 
521  $this->joins[$hash] = $joined_alias;
522 
523  return $joined_alias;
524  }
525 
537  public function joinAnnotationTable(string $from_alias = '', string $from_column = 'guid', $name = null, ?string $join_type = 'inner', ?string $joined_alias = null): string {
538  if (in_array($joined_alias, $this->joins)) {
539  return $joined_alias;
540  }
541 
542  if ($from_alias) {
543  $from_column = "{$from_alias}.{$from_column}";
544  }
545 
546  $hash = sha1(serialize([
547  $join_type,
548  AnnotationsTable::TABLE_NAME,
549  $from_column,
550  (array) $name,
551  ]));
552 
553  if (!isset($joined_alias) && !empty($this->joins[$hash])) {
554  return $this->joins[$hash];
555  }
556 
557  $condition = function (QueryBuilder $qb, $joined_alias) use ($from_column, $name) {
558  return $qb->merge([
559  $qb->compare("{$joined_alias}.entity_guid", '=', $from_column),
560  $qb->compare("{$joined_alias}.name", '=', $name, ELGG_VALUE_STRING),
561  ]);
562  };
563 
564  $clause = new JoinClause(AnnotationsTable::TABLE_NAME, $joined_alias, $condition, $join_type);
565 
566  $joined_alias = $clause->prepare($this, $from_alias);
567 
568  $this->joins[$hash] = $joined_alias;
569 
570  return $joined_alias;
571  }
572 
585  public function joinRelationshipTable(string $from_alias = '', string $from_column = 'guid', $name = null, bool $inverse = false, ?string $join_type = 'inner', ?string $joined_alias = null): string {
586  if (in_array($joined_alias, $this->joins)) {
587  return $joined_alias;
588  }
589 
590  if ($from_alias) {
591  $from_column = "{$from_alias}.{$from_column}";
592  }
593 
594  $hash = sha1(serialize([
595  $join_type,
596  RelationshipsTable::TABLE_NAME,
597  $from_column,
598  $inverse,
599  (array) $name,
600  ]));
601 
602  if (!isset($joined_alias) && !empty($this->joins[$hash])) {
603  return $this->joins[$hash];
604  }
605 
606  $condition = function (QueryBuilder $qb, $joined_alias) use ($from_column, $name, $inverse) {
607  $parts = [];
608  if ($inverse) {
609  $parts[] = $qb->compare("{$joined_alias}.guid_one", '=', $from_column);
610  } else {
611  $parts[] = $qb->compare("{$joined_alias}.guid_two", '=', $from_column);
612  }
613 
614  $parts[] = $qb->compare("{$joined_alias}.relationship", '=', $name, ELGG_VALUE_STRING);
615  return $qb->merge($parts);
616  };
617 
618  $clause = new JoinClause(RelationshipsTable::TABLE_NAME, $joined_alias, $condition, $join_type);
619 
620  $joined_alias = $clause->prepare($this, $from_alias);
621 
622  $this->joins[$hash] = $joined_alias;
623 
624  return $joined_alias;
625  }
626 }
if(! $user||! $user->canDelete()) $name
Definition: delete.php:22
$type
Definition: delete.php:21
return[ 'admin/delete_admin_notices'=>['access'=> 'admin'], 'admin/menu/save'=>['access'=> 'admin'], 'admin/plugins/activate'=>['access'=> 'admin'], 'admin/plugins/activate_all'=>['access'=> 'admin'], 'admin/plugins/deactivate'=>['access'=> 'admin'], 'admin/plugins/deactivate_all'=>['access'=> 'admin'], 'admin/plugins/set_priority'=>['access'=> 'admin'], 'admin/security/security_txt'=>['access'=> 'admin'], 'admin/security/settings'=>['access'=> 'admin'], 'admin/security/regenerate_site_secret'=>['access'=> 'admin'], 'admin/site/cache/clear'=>['access'=> 'admin'], 'admin/site/cache/invalidate'=>['access'=> 'admin'], 'admin/site/icons'=>['access'=> 'admin'], 'admin/site/set_maintenance_mode'=>['access'=> 'admin'], 'admin/site/set_robots'=>['access'=> 'admin'], 'admin/site/theme'=>['access'=> 'admin'], 'admin/site/unlock_upgrade'=>['access'=> 'admin'], 'admin/site/settings'=>['access'=> 'admin'], 'admin/upgrade'=>['access'=> 'admin'], 'admin/upgrade/reset'=>['access'=> 'admin'], 'admin/user/ban'=>['access'=> 'admin'], 'admin/user/bulk/ban'=>['access'=> 'admin'], 'admin/user/bulk/delete'=>['access'=> 'admin'], 'admin/user/bulk/unban'=>['access'=> 'admin'], 'admin/user/bulk/validate'=>['access'=> 'admin'], 'admin/user/change_email'=>['access'=> 'admin'], 'admin/user/delete'=>['access'=> 'admin'], 'admin/user/login_as'=>['access'=> 'admin'], 'admin/user/logout_as'=>[], 'admin/user/makeadmin'=>['access'=> 'admin'], 'admin/user/resetpassword'=>['access'=> 'admin'], 'admin/user/removeadmin'=>['access'=> 'admin'], 'admin/user/unban'=>['access'=> 'admin'], 'admin/user/validate'=>['access'=> 'admin'], 'annotation/delete'=>[], 'avatar/upload'=>[], 'comment/save'=>[], 'diagnostics/download'=>['access'=> 'admin', 'controller'=> \Elgg\Diagnostics\DownloadController::class,], 'entity/chooserestoredestination'=>[], 'entity/delete'=>[], 'entity/mute'=>[], 'entity/restore'=>[], 'entity/subscribe'=>[], 'entity/trash'=>[], 'entity/unmute'=>[], 'entity/unsubscribe'=>[], 'login'=>['access'=> 'logged_out'], 'logout'=>[], 'notifications/mute'=>['access'=> 'public'], 'plugins/settings/remove'=>['access'=> 'admin'], 'plugins/settings/save'=>['access'=> 'admin'], 'plugins/usersettings/save'=>[], 'register'=>['access'=> 'logged_out', 'middleware'=>[\Elgg\Router\Middleware\RegistrationAllowedGatekeeper::class,],], 'river/delete'=>[], 'settings/notifications'=>[], 'settings/notifications/subscriptions'=>[], 'user/changepassword'=>['access'=> 'public'], 'user/requestnewpassword'=>['access'=> 'public'], 'useradd'=>['access'=> 'admin'], 'usersettings/save'=>[], 'widgets/add'=>[], 'widgets/delete'=>[], 'widgets/move'=>[], 'widgets/save'=>[],]
Definition: actions.php:76
Interface that allows resolving statements and/or extending query builder.
Definition: Clause.php:14
Utility class for building composite comparison expression.
Extends QueryBuilder with JOIN clauses.
Definition: JoinClause.php:11
Builds a clause from closure or composite expression.
Definition: WhereClause.php:11
Database abstraction query builder.
join(string $fromAlias, string $join, string $alias, ?string $condition=null)
{}
merge($parts=null, $boolean='AND')
Merges multiple composite expressions with a boolean.
joinMetadataTable(string $from_alias='', string $from_column='guid', $name=null, ?string $join_type='inner', ?string $joined_alias=null)
Join metadata table from alias and return joined table alias.
between(string $x, $lower=null, $upper=null, ?string $type=null)
Build a between clause.
getNextJoinAlias()
Get an index of the next available join alias.
joinAnnotationTable(string $from_alias='', string $from_column='guid', $name=null, ?string $join_type='inner', ?string $joined_alias=null)
Join annotations table from alias and return joined table alias.
rightJoin(string $fromAlias, string $join, string $alias, ?string $condition=null)
{}
compare(string $x, string $comparison, $y=null, ?string $type=null, ?bool $case_sensitive=null)
Build value comparison clause.
prefix(string $table)
Prefixes the table name with installation DB prefix.
leftJoin(string $fromAlias, string $join, string $alias, ?string $condition=null)
{}
subquery(string $table, ?string $alias=null)
Creates a new SelectQueryBuilder for join/where sub queries using the DB connection of the primary Qu...
joinEntitiesTable(string $from_alias='', string $from_column='guid', ?string $join_type='inner', ?string $joined_alias=null)
Join entity table from alias and return joined table alias.
param($value, string $type=ELGG_VALUE_STRING, ?string $key=null)
Sets a new parameter assigning it a unique parameter key/name if none provided Returns the name of th...
addOrderBy(string $sort, ?string $order=null)
{}
getConnection()
Returns the connection.
getTableAlias()
Returns the alias of the primary table.
from(string $table, ?string $alias=null)
{}
orderBy(string $sort, ?string $order=null)
{}
innerJoin(string $fromAlias, string $join, string $alias, ?string $condition=null)
{}
execute(bool $track_query=true)
Execute the database query for this QueryBuilder.
addClause(Clause $clause, ?string $alias=null)
Apply clause to this instance.
getTableName()
Returns the name of the primary table.
__construct(protected readonly Connection $backup_connection)
Initializes a new QueryBuilder.
joinRelationshipTable(string $from_alias='', string $from_column='guid', $name=null, bool $inverse=false, ?string $join_type='inner', ?string $joined_alias=null)
Join relationship table from alias and return joined table alias.
Query builder for fetching data from the database.
Definition: Select.php:8
getConnection(string $type)
Gets (if required, also creates) a DB connection.
Definition: Database.php:113
Exception thrown if a value does not adhere to a defined valid data domain.
Functions for use as event handlers or other situations where you need a globally accessible callable...
Definition: Values.php:12
const ELGG_VALUE_BOOL
Definition: constants.php:116
const ELGG_VALUE_STRING
Definition: constants.php:112
const ELGG_VALUE_ID
Definition: constants.php:114
const ELGG_VALUE_GUID
Definition: constants.php:113
const ELGG_VALUE_TIMESTAMP
Definition: constants.php:115
const ELGG_VALUE_INTEGER
Value types.
Definition: constants.php:111
$table
Definition: database.php:52
if($item instanceof \ElggEntity) elseif($item instanceof \ElggRiverItem) elseif($item instanceof \ElggRelationship) elseif(is_callable([ $item, 'getType']))
Definition: item.php:48
_elgg_services()
Get the global service provider.
Definition: elgglib.php:347
$value
Definition: generic.php:51
$hash
Definition: logout_as.php:12
$qb
Definition: queue.php:14
if($container instanceof ElggGroup && $container->guid !=elgg_get_page_owner_guid()) $key
Definition: summary.php:44
if(parse_url(elgg_get_site_url(), PHP_URL_PATH) !=='/') if(file_exists(elgg_get_root_path() . 'robots.txt'))
Set robots.txt.
Definition: robots.php:10