Merge pull request #17003 from colemanw/smartererGroups
[civicrm-core.git] / Civi / Api4 / Query / Api4SelectQuery.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\Api4\Query;
13
14 use Civi\API\SelectQuery;
15 use Civi\Api4\Event\Events;
16 use Civi\Api4\Event\PostSelectQueryEvent;
17 use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable;
18 use Civi\Api4\Service\Schema\Joinable\Joinable;
19 use Civi\Api4\Utils\FormattingUtil;
20 use Civi\Api4\Utils\CoreUtil;
21 use Civi\Api4\Utils\SelectUtil;
22 use CRM_Core_DAO_AllCoreTables as AllCoreTables;
23
24 /**
25 * A query `node` may be in one of three formats:
26 *
27 * * leaf: [$fieldName, $operator, $criteria]
28 * * negated: ['NOT', $node]
29 * * branch: ['OR|NOT', [$node, $node, ...]]
30 *
31 * Leaf operators are one of:
32 *
33 * * '=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=",
34 * * "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN',
35 * * 'IS NOT NULL', or 'IS NULL'.
36 */
37 class Api4SelectQuery extends SelectQuery {
38
39 /**
40 * @var int
41 */
42 protected $apiVersion = 4;
43
44 /**
45 * @var \Civi\Api4\Service\Schema\Joinable\Joinable[]
46 * The joinable tables that have been joined so far
47 */
48 protected $joinedTables = [];
49
50 /**
51 * @var array
52 */
53 protected $selectAliases = [];
54
55 /**
56 * If set to an array, this will start collecting debug info.
57 *
58 * @var null|array
59 */
60 public $debugOutput = NULL;
61
62 /**
63 * @var array
64 */
65 public $groupBy = [];
66
67 public $forceSelectId = TRUE;
68
69 /**
70 * @var array
71 */
72 public $having = [];
73
74 /**
75 * @param \Civi\Api4\Generic\DAOGetAction $apiGet
76 */
77 public function __construct($apiGet) {
78 $this->entity = $apiGet->getEntityName();
79 $this->checkPermissions = $apiGet->getCheckPermissions();
80 $this->select = $apiGet->getSelect();
81 $this->where = $apiGet->getWhere();
82 $this->groupBy = $apiGet->getGroupBy();
83 $this->orderBy = $apiGet->getOrderBy();
84 $this->limit = $apiGet->getLimit();
85 $this->offset = $apiGet->getOffset();
86 $this->having = $apiGet->getHaving();
87 // Always select ID of main table unless grouping is used
88 $this->forceSelectId = !$this->groupBy;
89 if ($apiGet->getDebug()) {
90 $this->debugOutput =& $apiGet->_debugOutput;
91 }
92 $baoName = CoreUtil::getBAOFromApiName($this->entity);
93 $this->entityFieldNames = array_column($baoName::fields(), 'name');
94 foreach ($apiGet->entityFields() as $path => $field) {
95 $field['sql_name'] = '`' . self::MAIN_TABLE_ALIAS . '`.`' . $field['column_name'] . '`';
96 $this->addSpecField($path, $field);
97 }
98
99 $this->constructQueryObject($baoName);
100
101 // Add ACLs first to avoid redundant subclauses
102 $this->query->where($this->getAclClause(self::MAIN_TABLE_ALIAS, $baoName));
103 }
104
105 /**
106 * Builds final sql statement after all params are set.
107 *
108 * @return string
109 * @throws \API_Exception
110 * @throws \CRM_Core_Exception
111 * @throws \Civi\API\Exception\UnauthorizedException
112 */
113 public function getSql() {
114 $this->buildSelectClause();
115 $this->buildWhereClause();
116 $this->buildOrderBy();
117 $this->buildLimit();
118 $this->buildGroupBy();
119 $this->buildHavingClause();
120 return $this->query->toSQL();
121 }
122
123 /**
124 * Why walk when you can
125 *
126 * @return array|int
127 */
128 public function run() {
129 $results = [];
130 $sql = $this->getSql();
131 if (is_array($this->debugOutput)) {
132 $this->debugOutput['sql'][] = $sql;
133 }
134 $query = \CRM_Core_DAO::executeQuery($sql);
135 $i = 0;
136 while ($query->fetch()) {
137 $id = $query->id ?? $i++;
138 if (in_array('row_count', $this->select)) {
139 $results[]['row_count'] = (int) $query->c;
140 break;
141 }
142 $results[$id] = [];
143 foreach ($this->selectAliases as $alias => $expr) {
144 $returnName = $alias;
145 $alias = str_replace('.', '_', $alias);
146 $results[$id][$returnName] = property_exists($query, $alias) ? $query->$alias : NULL;
147 }
148 }
149 $event = new PostSelectQueryEvent($results, $this);
150 \Civi::dispatcher()->dispatch(Events::POST_SELECT_QUERY, $event);
151
152 return $event->getResults();
153 }
154
155 protected function buildSelectClause() {
156 // An empty select is the same as *
157 if (empty($this->select)) {
158 $this->select = $this->entityFieldNames;
159 }
160 elseif (in_array('row_count', $this->select)) {
161 $this->query->select("COUNT(*) AS `c`");
162 return;
163 }
164 else {
165 if ($this->forceSelectId) {
166 $this->select = array_merge(['id'], $this->select);
167 }
168
169 // Expand wildcards in joins (the api wrapper already expanded non-joined wildcards)
170 $wildFields = array_filter($this->select, function($item) {
171 return strpos($item, '*') !== FALSE && strpos($item, '.') !== FALSE && strpos($item, '(') === FALSE && strpos($item, ' ') === FALSE;
172 });
173 foreach ($wildFields as $item) {
174 $pos = array_search($item, array_values($this->select));
175 $this->joinFK($item);
176 $matches = SelectUtil::getMatchingFields($item, array_keys($this->apiFieldSpec));
177 array_splice($this->select, $pos, 1, $matches);
178 }
179 $this->select = array_unique($this->select);
180 }
181 foreach ($this->select as $item) {
182 $expr = SqlExpression::convert($item, TRUE);
183 $valid = TRUE;
184 foreach ($expr->getFields() as $fieldName) {
185 $field = $this->getField($fieldName);
186 // Remove expressions with unknown fields without raising an error
187 if (!$field) {
188 $this->select = array_diff($this->select, [$item]);
189 if (is_array($this->debugOutput)) {
190 $this->debugOutput['undefined_fields'][] = $fieldName;
191 }
192 $valid = FALSE;
193 }
194 elseif ($field['is_many']) {
195 $valid = FALSE;
196 }
197 }
198 if ($valid) {
199 $alias = $expr->getAlias();
200 $this->selectAliases[$alias] = $expr->getExpr();
201 $this->query->select($expr->render($this->apiFieldSpec) . " AS `$alias`");
202 }
203 }
204 }
205
206 /**
207 * @inheritDoc
208 */
209 protected function buildWhereClause() {
210 foreach ($this->where as $clause) {
211 $this->query->where($this->treeWalkClauses($clause, 'WHERE'));
212 }
213 }
214
215 /**
216 * Build HAVING clause.
217 *
218 * Every expression referenced must also be in the SELECT clause.
219 */
220 protected function buildHavingClause() {
221 foreach ($this->having as $clause) {
222 $this->query->having($this->treeWalkClauses($clause, 'HAVING'));
223 }
224 }
225
226 /**
227 * @inheritDoc
228 */
229 protected function buildOrderBy() {
230 foreach ($this->orderBy as $item => $dir) {
231 if ($dir !== 'ASC' && $dir !== 'DESC') {
232 throw new \API_Exception("Invalid sort direction. Cannot order by $item $dir");
233 }
234 $expr = SqlExpression::convert($item);
235 foreach ($expr->getFields() as $fieldName) {
236 $this->getField($fieldName, TRUE);
237 }
238 $this->query->orderBy($expr->render($this->apiFieldSpec) . " $dir");
239 }
240 }
241
242 /**
243 * @throws \CRM_Core_Exception
244 */
245 protected function buildLimit() {
246 if (!empty($this->limit) || !empty($this->offset)) {
247 // If limit is 0, mysql will actually return 0 results. Instead set to maximum possible.
248 $this->query->limit($this->limit ?: '18446744073709551615', $this->offset);
249 }
250 }
251
252 /**
253 * Adds GROUP BY clause to query
254 */
255 protected function buildGroupBy() {
256 foreach ($this->groupBy as $item) {
257 $expr = SqlExpression::convert($item);
258 foreach ($expr->getFields() as $fieldName) {
259 $this->getField($fieldName, TRUE);
260 }
261 $this->query->groupBy($expr->render($this->apiFieldSpec));
262 }
263 }
264
265 /**
266 * Recursively validate and transform a branch or leaf clause array to SQL.
267 *
268 * @param array $clause
269 * @param string $type
270 * WHERE|HAVING
271 * @return string SQL where clause
272 *
273 * @throws \API_Exception
274 * @uses composeClause() to generate the SQL etc.
275 */
276 protected function treeWalkClauses($clause, $type) {
277 switch ($clause[0]) {
278 case 'OR':
279 case 'AND':
280 // handle branches
281 if (count($clause[1]) === 1) {
282 // a single set so AND|OR is immaterial
283 return $this->treeWalkClauses($clause[1][0], $type);
284 }
285 else {
286 $sql_subclauses = [];
287 foreach ($clause[1] as $subclause) {
288 $sql_subclauses[] = $this->treeWalkClauses($subclause, $type);
289 }
290 return '(' . implode("\n" . $clause[0], $sql_subclauses) . ')';
291 }
292
293 case 'NOT':
294 // If we get a group of clauses with no operator, assume AND
295 if (!is_string($clause[1][0])) {
296 $clause[1] = ['AND', $clause[1]];
297 }
298 return 'NOT (' . $this->treeWalkClauses($clause[1], $type) . ')';
299
300 default:
301 return $this->composeClause($clause, $type);
302 }
303 }
304
305 /**
306 * Validate and transform a leaf clause array to SQL.
307 * @param array $clause [$fieldName, $operator, $criteria]
308 * @param string $type
309 * WHERE|HAVING
310 * @return string SQL
311 * @throws \API_Exception
312 * @throws \Exception
313 */
314 protected function composeClause(array $clause, string $type) {
315 // Pad array for unary operators
316 list($expr, $operator, $value) = array_pad($clause, 3, NULL);
317
318 // For WHERE clause, expr must be the name of a field.
319 if ($type === 'WHERE') {
320 $field = $this->getField($expr, TRUE);
321 FormattingUtil::formatInputValue($value, $field, $this->getEntity());
322 $fieldAlias = $field['sql_name'];
323 }
324 // For HAVING, expr must be an item in the SELECT clause
325 else {
326 if (isset($this->selectAliases[$expr])) {
327 $fieldAlias = $expr;
328 }
329 elseif (in_array($expr, $this->selectAliases)) {
330 $fieldAlias = array_search($expr, $this->selectAliases);
331 }
332 else {
333 throw new \API_Exception("Invalid expression in $type clause: '$expr'. Must use a value from SELECT clause.");
334 }
335 }
336
337 $sql_clause = \CRM_Core_DAO::createSQLFilter($fieldAlias, [$operator => $value]);
338 if ($sql_clause === NULL) {
339 throw new \API_Exception("Invalid value in $type clause for '$expr'");
340 }
341 return $sql_clause;
342 }
343
344 /**
345 * @inheritDoc
346 */
347 protected function getFields() {
348 return $this->apiFieldSpec;
349 }
350
351 /**
352 * Fetch a field from the getFields list
353 *
354 * @param string $fieldName
355 * @param bool $strict
356 * In strict mode, this will throw an exception if the field doesn't exist
357 *
358 * @return string|null
359 * @throws \API_Exception
360 */
361 public function getField($fieldName, $strict = FALSE) {
362 // Perform join if field not yet available - this will add it to apiFieldSpec
363 if (!isset($this->apiFieldSpec[$fieldName]) && strpos($fieldName, '.')) {
364 $this->joinFK($fieldName);
365 }
366 $field = $this->apiFieldSpec[$fieldName] ?? NULL;
367 if ($strict && !$field) {
368 throw new \API_Exception("Invalid field '$fieldName'");
369 }
370 return $field;
371 }
372
373 /**
374 * Joins a path and adds all fields in the joined eneity to apiFieldSpec
375 *
376 * @param $key
377 * @throws \API_Exception
378 * @throws \Exception
379 */
380 protected function joinFK($key) {
381 if (isset($this->apiFieldSpec[$key])) {
382 return;
383 }
384
385 $pathArray = explode('.', $key);
386
387 /** @var \Civi\Api4\Service\Schema\Joiner $joiner */
388 $joiner = \Civi::container()->get('joiner');
389 // The last item in the path is the field name. We don't care about that; we'll add all fields from the joined entity.
390 array_pop($pathArray);
391 $pathString = implode('.', $pathArray);
392
393 if (!$joiner->canJoin($this, $pathString)) {
394 return;
395 }
396
397 $joinPath = $joiner->join($this, $pathString);
398
399 $isMany = FALSE;
400 foreach ($joinPath as $joinable) {
401 if ($joinable->getJoinType() === Joinable::JOIN_TYPE_ONE_TO_MANY) {
402 $isMany = TRUE;
403 }
404 }
405
406 /** @var \Civi\Api4\Service\Schema\Joinable\Joinable $lastLink */
407 $lastLink = array_pop($joinPath);
408
409 // Custom field names are already prefixed
410 $isCustom = $lastLink instanceof CustomGroupJoinable;
411 if ($isCustom) {
412 array_pop($pathArray);
413 }
414 $prefix = $pathArray ? implode('.', $pathArray) . '.' : '';
415 // Cache field info for retrieval by $this->getField()
416 $joinEntity = $lastLink->getEntity();
417 foreach ($lastLink->getEntityFields() as $fieldObject) {
418 $fieldArray = ['entity' => $joinEntity] + $fieldObject->toArray();
419 $fieldArray['sql_name'] = '`' . $lastLink->getAlias() . '`.`' . $fieldArray['column_name'] . '`';
420 $fieldArray['is_custom'] = $isCustom;
421 $fieldArray['is_join'] = TRUE;
422 $fieldArray['is_many'] = $isMany;
423 $this->addSpecField($prefix . $fieldArray['name'], $fieldArray);
424 }
425 }
426
427 /**
428 * @param \Civi\Api4\Service\Schema\Joinable\Joinable $joinable
429 *
430 * @return $this
431 */
432 public function addJoinedTable(Joinable $joinable) {
433 $this->joinedTables[] = $joinable;
434
435 return $this;
436 }
437
438 /**
439 * @return FALSE|string
440 */
441 public function getFrom() {
442 return AllCoreTables::getTableForClass(AllCoreTables::getFullName($this->entity));
443 }
444
445 /**
446 * @return string
447 */
448 public function getEntity() {
449 return $this->entity;
450 }
451
452 /**
453 * @return array
454 */
455 public function getSelect() {
456 return $this->select;
457 }
458
459 /**
460 * @return array
461 */
462 public function getWhere() {
463 return $this->where;
464 }
465
466 /**
467 * @return array
468 */
469 public function getOrderBy() {
470 return $this->orderBy;
471 }
472
473 /**
474 * @return mixed
475 */
476 public function getLimit() {
477 return $this->limit;
478 }
479
480 /**
481 * @return mixed
482 */
483 public function getOffset() {
484 return $this->offset;
485 }
486
487 /**
488 * @return array
489 */
490 public function getSelectFields() {
491 return $this->selectFields;
492 }
493
494 /**
495 * @return bool
496 */
497 public function isFillUniqueFields() {
498 return $this->isFillUniqueFields;
499 }
500
501 /**
502 * @return \CRM_Utils_SQL_Select
503 */
504 public function getQuery() {
505 return $this->query;
506 }
507
508 /**
509 * @return array
510 */
511 public function getJoins() {
512 return $this->joins;
513 }
514
515 /**
516 * @return array
517 */
518 public function getApiFieldSpec() {
519 return $this->apiFieldSpec;
520 }
521
522 /**
523 * @return array
524 */
525 public function getEntityFieldNames() {
526 return $this->entityFieldNames;
527 }
528
529 /**
530 * @return array
531 */
532 public function getAclFields() {
533 return $this->aclFields;
534 }
535
536 /**
537 * @return bool|string
538 */
539 public function getCheckPermissions() {
540 return $this->checkPermissions;
541 }
542
543 /**
544 * @return int
545 */
546 public function getApiVersion() {
547 return $this->apiVersion;
548 }
549
550 /**
551 * @return \Civi\Api4\Service\Schema\Joinable\Joinable[]
552 */
553 public function getJoinedTables() {
554 return $this->joinedTables;
555 }
556
557 /**
558 * @return \Civi\Api4\Service\Schema\Joinable\Joinable
559 */
560 public function getJoinedTable($alias) {
561 foreach ($this->joinedTables as $join) {
562 if ($join->getAlias() == $alias) {
563 return $join;
564 }
565 }
566 }
567
568 /**
569 * Get table name on basis of entity
570 *
571 * @param string $baoName
572 *
573 * @return void
574 */
575 public function constructQueryObject($baoName) {
576 if (strstr($this->entity, 'Custom_')) {
577 $this->query = \CRM_Utils_SQL_Select::from(CoreUtil::getCustomTableByName(str_replace('Custom_', '', $this->entity)) . ' ' . self::MAIN_TABLE_ALIAS);
578 $this->entityFieldNames = array_keys($this->apiFieldSpec);
579 }
580 else {
581 $bao = new $baoName();
582 $this->query = \CRM_Utils_SQL_Select::from($bao->tableName() . ' ' . self::MAIN_TABLE_ALIAS);
583 }
584 }
585
586 /**
587 * Checks if a field either belongs to the main entity or is joinable 1-to-1.
588 *
589 * Used to determine if a field can be added to the SELECT of the main query,
590 * or if it must be fetched post-query.
591 *
592 * @param string $fieldPath
593 * @return bool
594 */
595 public function isOneToOneField(string $fieldPath) {
596 return strpos($fieldPath, '.') === FALSE || !array_filter($this->getPathJoinTypes($fieldPath));
597 }
598
599 /**
600 * Separates a string like 'emails.location_type.label' into an array, where
601 * each value in the array tells whether it is 1-1 or 1-n join type
602 *
603 * @param string $pathString
604 * Dot separated path to the field
605 *
606 * @return array
607 * Index is table alias and value is boolean whether is 1-to-many join
608 */
609 public function getPathJoinTypes($pathString) {
610 $pathParts = explode('.', $pathString);
611 // remove field
612 array_pop($pathParts);
613 $path = [];
614 $query = $this;
615 $isMultipleChecker = function($alias) use ($query) {
616 foreach ($query->getJoinedTables() as $table) {
617 if ($table->getAlias() === $alias) {
618 return $table->getJoinType() === Joinable::JOIN_TYPE_ONE_TO_MANY;
619 }
620 }
621 return FALSE;
622 };
623
624 foreach ($pathParts as $part) {
625 $path[$part] = $isMultipleChecker($part);
626 }
627
628 return $path;
629 }
630
631 /**
632 * @param $path
633 * @param $field
634 */
635 private function addSpecField($path, $field) {
636 // Only add field to spec if we have permission
637 if ($this->checkPermissions && !empty($field['permission']) && !\CRM_Core_Permission::check($field['permission'])) {
638 $this->apiFieldSpec[$path] = FALSE;
639 return;
640 }
641 $defaults = [];
642 $defaults['is_custom'] = $defaults['is_join'] = $defaults['is_many'] = FALSE;
643 $field += $defaults;
644 $this->apiFieldSpec[$path] = $field;
645 }
646
647 }