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 $this->selectAliases
[$alias] = $expr->getExpr();
201 $this->query
->select($expr->render($this->apiFieldSpec
) . " AS `$alias`");
209 protected function buildWhereClause() {
210 foreach ($this->where
as $clause) {
211 $this->query
->where($this->treeWalkClauses($clause, 'WHERE'));
216 * Build HAVING clause.
218 * Every expression referenced must also be in the SELECT clause.
220 protected function buildHavingClause() {
221 foreach ($this->having
as $clause) {
222 $this->query
->having($this->treeWalkClauses($clause, 'HAVING'));
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");
234 $expr = SqlExpression
::convert($item);
235 foreach ($expr->getFields() as $fieldName) {
236 $this->getField($fieldName, TRUE);
238 $this->query
->orderBy($expr->render($this->apiFieldSpec
) . " $dir");
243 * @throws \CRM_Core_Exception
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
);
253 * Adds GROUP BY clause to query
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);
261 $this->query
->groupBy($expr->render($this->apiFieldSpec
));
266 * Recursively validate and transform a branch or leaf clause array to SQL.
268 * @param array $clause
269 * @param string $type
271 * @return string SQL where clause
273 * @throws \API_Exception
274 * @uses composeClause() to generate the SQL etc.
276 protected function treeWalkClauses($clause, $type) {
277 switch ($clause[0]) {
281 if (count($clause[1]) === 1) {
282 // a single set so AND|OR is immaterial
283 return $this->treeWalkClauses($clause[1][0], $type);
286 $sql_subclauses = [];
287 foreach ($clause[1] as $subclause) {
288 $sql_subclauses[] = $this->treeWalkClauses($subclause, $type);
290 return '(' . implode("\n" . $clause[0], $sql_subclauses) . ')';
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]];
298 return 'NOT (' . $this->treeWalkClauses($clause[1], $type) . ')';
301 return $this->composeClause($clause, $type);
306 * Validate and transform a leaf clause array to SQL.
307 * @param array $clause [$fieldName, $operator, $criteria]
308 * @param string $type
311 * @throws \API_Exception
314 protected function composeClause(array $clause, string $type) {
315 // Pad array for unary operators
316 list($expr, $operator, $value) = array_pad($clause, 3, NULL);
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'];
324 // For HAVING, expr must be an item in the SELECT clause
326 if (isset($this->selectAliases
[$expr])) {
329 elseif (in_array($expr, $this->selectAliases
)) {
330 $fieldAlias = array_search($expr, $this->selectAliases
);
333 throw new \
API_Exception("Invalid expression in $type clause: '$expr'. Must use a value from SELECT clause.");
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'");
347 protected function getFields() {
348 return $this->apiFieldSpec
;
352 * Fetch a field from the getFields list
354 * @param string $fieldName
355 * @param bool $strict
356 * In strict mode, this will throw an exception if the field doesn't exist
358 * @return string|null
359 * @throws \API_Exception
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);
366 $field = $this->apiFieldSpec
[$fieldName] ??
NULL;
367 if ($strict && !$field) {
368 throw new \
API_Exception("Invalid field '$fieldName'");
374 * Joins a path and adds all fields in the joined eneity to apiFieldSpec
377 * @throws \API_Exception
380 protected function joinFK($key) {
381 if (isset($this->apiFieldSpec
[$key])) {
385 $pathArray = explode('.', $key);
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);
393 if (!$joiner->canJoin($this, $pathString)) {
397 $joinPath = $joiner->join($this, $pathString);
400 foreach ($joinPath as $joinable) {
401 if ($joinable->getJoinType() === Joinable
::JOIN_TYPE_ONE_TO_MANY
) {
406 /** @var \Civi\Api4\Service\Schema\Joinable\Joinable $lastLink */
407 $lastLink = array_pop($joinPath);
409 // Custom field names are already prefixed
410 $isCustom = $lastLink instanceof CustomGroupJoinable
;
412 array_pop($pathArray);
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);
428 * @param \Civi\Api4\Service\Schema\Joinable\Joinable $joinable
432 public function addJoinedTable(Joinable
$joinable) {
433 $this->joinedTables
[] = $joinable;
439 * @return FALSE|string
441 public function getFrom() {
442 return AllCoreTables
::getTableForClass(AllCoreTables
::getFullName($this->entity
));
448 public function getEntity() {
449 return $this->entity
;
455 public function getSelect() {
456 return $this->select
;
462 public function getWhere() {
469 public function getOrderBy() {
470 return $this->orderBy
;
476 public function getLimit() {
483 public function getOffset() {
484 return $this->offset
;
490 public function getSelectFields() {
491 return $this->selectFields
;
497 public function isFillUniqueFields() {
498 return $this->isFillUniqueFields
;
502 * @return \CRM_Utils_SQL_Select
504 public function getQuery() {
511 public function getJoins() {
518 public function getApiFieldSpec() {
519 return $this->apiFieldSpec
;
525 public function getEntityFieldNames() {
526 return $this->entityFieldNames
;
532 public function getAclFields() {
533 return $this->aclFields
;
537 * @return bool|string
539 public function getCheckPermissions() {
540 return $this->checkPermissions
;
546 public function getApiVersion() {
547 return $this->apiVersion
;
551 * @return \Civi\Api4\Service\Schema\Joinable\Joinable[]
553 public function getJoinedTables() {
554 return $this->joinedTables
;
558 * @return \Civi\Api4\Service\Schema\Joinable\Joinable
560 public function getJoinedTable($alias) {
561 foreach ($this->joinedTables
as $join) {
562 if ($join->getAlias() == $alias) {
569 * Get table name on basis of entity
571 * @param string $baoName
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
);
581 $bao = new $baoName();
582 $this->query
= \CRM_Utils_SQL_Select
::from($bao->tableName() . ' ' . self
::MAIN_TABLE_ALIAS
);
587 * Checks if a field either belongs to the main entity or is joinable 1-to-1.
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.
592 * @param string $fieldPath
595 public function isOneToOneField(string $fieldPath) {
596 return strpos($fieldPath, '.') === FALSE ||
!array_filter($this->getPathJoinTypes($fieldPath));
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
603 * @param string $pathString
604 * Dot separated path to the field
607 * Index is table alias and value is boolean whether is 1-to-many join
609 public function getPathJoinTypes($pathString) {
610 $pathParts = explode('.', $pathString);
612 array_pop($pathParts);
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
;
624 foreach ($pathParts as $part) {
625 $path[$part] = $isMultipleChecker($part);
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;
642 $defaults['is_custom'] = $defaults['is_join'] = $defaults['is_many'] = FALSE;
644 $this->apiFieldSpec
[$path] = $field;