3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 namespace Civi\Api4\Query
;
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
;
25 * A query `node` may be in one of three formats:
27 * * leaf: [$fieldName, $operator, $criteria]
28 * * negated: ['NOT', $node]
29 * * branch: ['OR|NOT', [$node, $node, ...]]
31 * Leaf operators are one of:
33 * * '=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=",
34 * * "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN',
35 * * 'IS NOT NULL', or 'IS NULL'.
37 class Api4SelectQuery
extends SelectQuery
{
42 protected $apiVersion = 4;
45 * @var \Civi\Api4\Service\Schema\Joinable\Joinable[]
46 * The joinable tables that have been joined so far
48 protected $joinedTables = [];
53 protected $selectAliases = [];
56 * If set to an array, this will start collecting debug info.
60 public $debugOutput = NULL;
67 public $forceSelectId = TRUE;
75 * @param \Civi\Api4\Generic\DAOGetAction $apiGet
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
;
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);
99 $this->constructQueryObject($baoName);
101 // Add ACLs first to avoid redundant subclauses
102 $this->query
->where($this->getAclClause(self
::MAIN_TABLE_ALIAS
, $baoName));
106 * Builds final sql statement after all params are set.
109 * @throws \API_Exception
110 * @throws \CRM_Core_Exception
111 * @throws \Civi\API\Exception\UnauthorizedException
113 public function getSql() {
114 $this->buildSelectClause();
115 $this->buildWhereClause();
116 $this->buildOrderBy();
118 $this->buildGroupBy();
119 $this->buildHavingClause();
120 return $this->query
->toSQL();
124 * Why walk when you can
128 public function run() {
130 $sql = $this->getSql();
131 if (is_array($this->debugOutput
)) {
132 $this->debugOutput
['sql'][] = $sql;
134 $query = \CRM_Core_DAO
::executeQuery($sql);
136 while ($query->fetch()) {
137 $id = $query->id ??
$i++
;
138 if (in_array('row_count', $this->select
)) {
139 $results[]['row_count'] = (int) $query->c
;
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;
149 $event = new PostSelectQueryEvent($results, $this);
150 \Civi
::dispatcher()->dispatch(Events
::POST_SELECT_QUERY
, $event);
152 return $event->getResults();
155 protected function buildSelectClause() {
156 // An empty select is the same as *
157 if (empty($this->select
)) {
158 $this->select
= $this->entityFieldNames
;
160 elseif (in_array('row_count', $this->select
)) {
161 $this->query
->select("COUNT(*) AS `c`");
165 if ($this->forceSelectId
) {
166 $this->select
= array_merge(['id'], $this->select
);
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;
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);
179 $this->select
= array_unique($this->select
);
181 foreach ($this->select
as $item) {
182 $expr = SqlExpression
::convert($item, TRUE);
184 foreach ($expr->getFields() as $fieldName) {
185 $field = $this->getField($fieldName);
186 // Remove expressions with unknown fields without raising an error
188 $this->select
= array_diff($this->select
, [$item]);
189 if (is_array($this->debugOutput
)) {
190 $this->debugOutput
['undefined_fields'][] = $fieldName;
194 elseif ($field['is_many']) {
199 $alias = $expr->getAlias();
200 if ($alias != $expr->getExpr() && isset($this->apiFieldSpec
[$alias])) {
201 throw new \
API_Exception('Cannot use existing field name as alias');
203 $this->selectAliases
[$alias] = $expr->getExpr();
204 $this->query
->select($expr->render($this->apiFieldSpec
) . " AS `$alias`");
212 protected function buildWhereClause() {
213 foreach ($this->where
as $clause) {
214 $this->query
->where($this->treeWalkClauses($clause, 'WHERE'));
219 * Build HAVING clause.
221 * Every expression referenced must also be in the SELECT clause.
223 protected function buildHavingClause() {
224 foreach ($this->having
as $clause) {
225 $this->query
->having($this->treeWalkClauses($clause, 'HAVING'));
232 protected function buildOrderBy() {
233 foreach ($this->orderBy
as $item => $dir) {
234 if ($dir !== 'ASC' && $dir !== 'DESC') {
235 throw new \
API_Exception("Invalid sort direction. Cannot order by $item $dir");
237 $expr = SqlExpression
::convert($item);
238 foreach ($expr->getFields() as $fieldName) {
239 $this->getField($fieldName, TRUE);
241 $this->query
->orderBy($expr->render($this->apiFieldSpec
) . " $dir");
246 * @throws \CRM_Core_Exception
248 protected function buildLimit() {
249 if (!empty($this->limit
) ||
!empty($this->offset
)) {
250 // If limit is 0, mysql will actually return 0 results. Instead set to maximum possible.
251 $this->query
->limit($this->limit ?
: '18446744073709551615', $this->offset
);
256 * Adds GROUP BY clause to query
258 protected function buildGroupBy() {
259 foreach ($this->groupBy
as $item) {
260 $expr = SqlExpression
::convert($item);
261 foreach ($expr->getFields() as $fieldName) {
262 $this->getField($fieldName, TRUE);
264 $this->query
->groupBy($expr->render($this->apiFieldSpec
));
269 * Recursively validate and transform a branch or leaf clause array to SQL.
271 * @param array $clause
272 * @param string $type
274 * @return string SQL where clause
276 * @throws \API_Exception
277 * @uses composeClause() to generate the SQL etc.
279 protected function treeWalkClauses($clause, $type) {
280 switch ($clause[0]) {
284 if (count($clause[1]) === 1) {
285 // a single set so AND|OR is immaterial
286 return $this->treeWalkClauses($clause[1][0], $type);
289 $sql_subclauses = [];
290 foreach ($clause[1] as $subclause) {
291 $sql_subclauses[] = $this->treeWalkClauses($subclause, $type);
293 return '(' . implode("\n" . $clause[0], $sql_subclauses) . ')';
297 // If we get a group of clauses with no operator, assume AND
298 if (!is_string($clause[1][0])) {
299 $clause[1] = ['AND', $clause[1]];
301 return 'NOT (' . $this->treeWalkClauses($clause[1], $type) . ')';
304 return $this->composeClause($clause, $type);
309 * Validate and transform a leaf clause array to SQL.
310 * @param array $clause [$fieldName, $operator, $criteria]
311 * @param string $type
314 * @throws \API_Exception
317 protected function composeClause(array $clause, string $type) {
318 // Pad array for unary operators
319 list($expr, $operator, $value) = array_pad($clause, 3, NULL);
321 // For WHERE clause, expr must be the name of a field.
322 if ($type === 'WHERE') {
323 $field = $this->getField($expr, TRUE);
324 FormattingUtil
::formatInputValue($value, $field, $this->getEntity());
325 $fieldAlias = $field['sql_name'];
327 // For HAVING, expr must be an item in the SELECT clause
329 if (isset($this->selectAliases
[$expr])) {
332 elseif (in_array($expr, $this->selectAliases
)) {
333 $fieldAlias = array_search($expr, $this->selectAliases
);
336 throw new \
API_Exception("Invalid expression in $type clause: '$expr'. Must use a value from SELECT clause.");
340 $sql_clause = \CRM_Core_DAO
::createSQLFilter($fieldAlias, [$operator => $value]);
341 if ($sql_clause === NULL) {
342 throw new \
API_Exception("Invalid value in $type clause for '$expr'");
350 protected function getFields() {
351 return $this->apiFieldSpec
;
355 * Fetch a field from the getFields list
357 * @param string $fieldName
358 * @param bool $strict
359 * In strict mode, this will throw an exception if the field doesn't exist
361 * @return string|null
362 * @throws \API_Exception
364 public function getField($fieldName, $strict = FALSE) {
365 // Perform join if field not yet available - this will add it to apiFieldSpec
366 if (!isset($this->apiFieldSpec
[$fieldName]) && strpos($fieldName, '.')) {
367 $this->joinFK($fieldName);
369 $field = $this->apiFieldSpec
[$fieldName] ??
NULL;
370 if ($strict && !$field) {
371 throw new \
API_Exception("Invalid field '$fieldName'");
377 * Joins a path and adds all fields in the joined eneity to apiFieldSpec
380 * @throws \API_Exception
383 protected function joinFK($key) {
384 if (isset($this->apiFieldSpec
[$key])) {
388 $pathArray = explode('.', $key);
390 /** @var \Civi\Api4\Service\Schema\Joiner $joiner */
391 $joiner = \Civi
::container()->get('joiner');
392 // 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.
393 array_pop($pathArray);
394 $pathString = implode('.', $pathArray);
396 if (!$joiner->canJoin($this, $pathString)) {
400 $joinPath = $joiner->join($this, $pathString);
403 foreach ($joinPath as $joinable) {
404 if ($joinable->getJoinType() === Joinable
::JOIN_TYPE_ONE_TO_MANY
) {
409 /** @var \Civi\Api4\Service\Schema\Joinable\Joinable $lastLink */
410 $lastLink = array_pop($joinPath);
412 // Custom field names are already prefixed
413 $isCustom = $lastLink instanceof CustomGroupJoinable
;
415 array_pop($pathArray);
417 $prefix = $pathArray ?
implode('.', $pathArray) . '.' : '';
418 // Cache field info for retrieval by $this->getField()
419 $joinEntity = $lastLink->getEntity();
420 foreach ($lastLink->getEntityFields() as $fieldObject) {
421 $fieldArray = ['entity' => $joinEntity] +
$fieldObject->toArray();
422 $fieldArray['sql_name'] = '`' . $lastLink->getAlias() . '`.`' . $fieldArray['column_name'] . '`';
423 $fieldArray['is_custom'] = $isCustom;
424 $fieldArray['is_join'] = TRUE;
425 $fieldArray['is_many'] = $isMany;
426 $this->addSpecField($prefix . $fieldArray['name'], $fieldArray);
431 * @param \Civi\Api4\Service\Schema\Joinable\Joinable $joinable
435 public function addJoinedTable(Joinable
$joinable) {
436 $this->joinedTables
[] = $joinable;
442 * @return FALSE|string
444 public function getFrom() {
445 return AllCoreTables
::getTableForClass(AllCoreTables
::getFullName($this->entity
));
451 public function getEntity() {
452 return $this->entity
;
458 public function getSelect() {
459 return $this->select
;
465 public function getWhere() {
472 public function getOrderBy() {
473 return $this->orderBy
;
479 public function getLimit() {
486 public function getOffset() {
487 return $this->offset
;
493 public function getSelectFields() {
494 return $this->selectFields
;
500 public function isFillUniqueFields() {
501 return $this->isFillUniqueFields
;
505 * @return \CRM_Utils_SQL_Select
507 public function getQuery() {
514 public function getJoins() {
521 public function getApiFieldSpec() {
522 return $this->apiFieldSpec
;
528 public function getEntityFieldNames() {
529 return $this->entityFieldNames
;
535 public function getAclFields() {
536 return $this->aclFields
;
540 * @return bool|string
542 public function getCheckPermissions() {
543 return $this->checkPermissions
;
549 public function getApiVersion() {
550 return $this->apiVersion
;
554 * @return \Civi\Api4\Service\Schema\Joinable\Joinable[]
556 public function getJoinedTables() {
557 return $this->joinedTables
;
561 * @return \Civi\Api4\Service\Schema\Joinable\Joinable
563 public function getJoinedTable($alias) {
564 foreach ($this->joinedTables
as $join) {
565 if ($join->getAlias() == $alias) {
572 * Get table name on basis of entity
574 * @param string $baoName
578 public function constructQueryObject($baoName) {
579 if (strstr($this->entity
, 'Custom_')) {
580 $this->query
= \CRM_Utils_SQL_Select
::from(CoreUtil
::getCustomTableByName(str_replace('Custom_', '', $this->entity
)) . ' ' . self
::MAIN_TABLE_ALIAS
);
581 $this->entityFieldNames
= array_keys($this->apiFieldSpec
);
584 $bao = new $baoName();
585 $this->query
= \CRM_Utils_SQL_Select
::from($bao->tableName() . ' ' . self
::MAIN_TABLE_ALIAS
);
590 * Checks if a field either belongs to the main entity or is joinable 1-to-1.
592 * Used to determine if a field can be added to the SELECT of the main query,
593 * or if it must be fetched post-query.
595 * @param string $fieldPath
598 public function isOneToOneField(string $fieldPath) {
599 return strpos($fieldPath, '.') === FALSE ||
!array_filter($this->getPathJoinTypes($fieldPath));
603 * Separates a string like 'emails.location_type.label' into an array, where
604 * each value in the array tells whether it is 1-1 or 1-n join type
606 * @param string $pathString
607 * Dot separated path to the field
610 * Index is table alias and value is boolean whether is 1-to-many join
612 public function getPathJoinTypes($pathString) {
613 $pathParts = explode('.', $pathString);
615 array_pop($pathParts);
618 $isMultipleChecker = function($alias) use ($query) {
619 foreach ($query->getJoinedTables() as $table) {
620 if ($table->getAlias() === $alias) {
621 return $table->getJoinType() === Joinable
::JOIN_TYPE_ONE_TO_MANY
;
627 foreach ($pathParts as $part) {
628 $path[$part] = $isMultipleChecker($part);
638 private function addSpecField($path, $field) {
639 // Only add field to spec if we have permission
640 if ($this->checkPermissions
&& !empty($field['permission']) && !\CRM_Core_Permission
::check($field['permission'])) {
641 $this->apiFieldSpec
[$path] = FALSE;
645 $defaults['is_custom'] = $defaults['is_join'] = $defaults['is_many'] = FALSE;
647 $this->apiFieldSpec
[$path] = $field;