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;
73 * @param \Civi\Api4\Generic\DAOGetAction $apiGet
75 public function __construct($apiGet) {
76 $this->entity
= $apiGet->getEntityName();
77 $this->checkPermissions
= $apiGet->getCheckPermissions();
78 $this->select
= $apiGet->getSelect();
79 $this->where
= $apiGet->getWhere();
80 $this->groupBy
= $apiGet->getGroupBy();
81 $this->orderBy
= $apiGet->getOrderBy();
82 $this->limit
= $apiGet->getLimit();
83 $this->offset
= $apiGet->getOffset();
84 $this->having
= $apiGet->getHaving();
85 if ($apiGet->getDebug()) {
86 $this->debugOutput
=& $apiGet->_debugOutput
;
88 $baoName = CoreUtil
::getBAOFromApiName($this->entity
);
89 $this->entityFieldNames
= array_column($baoName::fields(), 'name');
90 foreach ($apiGet->entityFields() as $path => $field) {
91 $field['sql_name'] = '`' . self
::MAIN_TABLE_ALIAS
. '`.`' . $field['column_name'] . '`';
92 $this->addSpecField($path, $field);
95 $this->constructQueryObject($baoName);
97 // Add ACLs first to avoid redundant subclauses
98 $this->query
->where($this->getAclClause(self
::MAIN_TABLE_ALIAS
, $baoName));
102 * Builds final sql statement after all params are set.
105 * @throws \API_Exception
106 * @throws \CRM_Core_Exception
107 * @throws \Civi\API\Exception\UnauthorizedException
109 public function getSql() {
110 $this->buildSelectClause();
111 $this->buildWhereClause();
112 $this->buildOrderBy();
114 $this->buildGroupBy();
115 $this->buildHavingClause();
116 return $this->query
->toSQL();
120 * Why walk when you can
124 public function run() {
126 $sql = $this->getSql();
127 if (is_array($this->debugOutput
)) {
128 $this->debugOutput
['sql'][] = $sql;
130 $query = \CRM_Core_DAO
::executeQuery($sql);
132 while ($query->fetch()) {
133 $id = $query->id ??
$i++
;
134 if (in_array('row_count', $this->select
)) {
135 $results[]['row_count'] = (int) $query->c
;
139 foreach ($this->selectAliases
as $alias => $expr) {
140 $returnName = $alias;
141 $alias = str_replace('.', '_', $alias);
142 $results[$id][$returnName] = property_exists($query, $alias) ?
$query->$alias : NULL;
145 $event = new PostSelectQueryEvent($results, $this);
146 \Civi
::dispatcher()->dispatch(Events
::POST_SELECT_QUERY
, $event);
148 return $event->getResults();
151 protected function buildSelectClause() {
152 // An empty select is the same as *
153 if (empty($this->select
)) {
154 $this->select
= $this->entityFieldNames
;
156 elseif (in_array('row_count', $this->select
)) {
157 $this->query
->select("COUNT(*) AS `c`");
161 // Always select ID (unless we're doing groupBy).
162 if (!$this->groupBy
) {
163 $this->select
= array_merge(['id'], $this->select
);
166 // Expand wildcards in joins (the api wrapper already expanded non-joined wildcards)
167 $wildFields = array_filter($this->select
, function($item) {
168 return strpos($item, '*') !== FALSE && strpos($item, '.') !== FALSE && strpos($item, '(') === FALSE && strpos($item, ' ') === FALSE;
170 foreach ($wildFields as $item) {
171 $pos = array_search($item, array_values($this->select
));
172 $this->joinFK($item);
173 $matches = SelectUtil
::getMatchingFields($item, array_keys($this->apiFieldSpec
));
174 array_splice($this->select
, $pos, 1, $matches);
176 $this->select
= array_unique($this->select
);
178 foreach ($this->select
as $item) {
179 $expr = SqlExpression
::convert($item, TRUE);
181 foreach ($expr->getFields() as $fieldName) {
182 $field = $this->getField($fieldName);
183 // Remove expressions with unknown fields without raising an error
185 $this->select
= array_diff($this->select
, [$item]);
186 if (is_array($this->debugOutput
)) {
187 $this->debugOutput
['undefined_fields'][] = $fieldName;
191 elseif ($field['is_many']) {
196 $alias = $expr->getAlias();
197 $this->selectAliases
[$alias] = $expr->getExpr();
198 $this->query
->select($expr->render($this->apiFieldSpec
) . " AS `$alias`");
206 protected function buildWhereClause() {
207 foreach ($this->where
as $clause) {
208 $this->query
->where($this->treeWalkClauses($clause, 'WHERE'));
213 * Build HAVING clause.
215 * Every expression referenced must also be in the SELECT clause.
217 protected function buildHavingClause() {
218 foreach ($this->having
as $clause) {
219 $this->query
->having($this->treeWalkClauses($clause, 'HAVING'));
226 protected function buildOrderBy() {
227 foreach ($this->orderBy
as $item => $dir) {
228 if ($dir !== 'ASC' && $dir !== 'DESC') {
229 throw new \
API_Exception("Invalid sort direction. Cannot order by $item $dir");
231 $expr = SqlExpression
::convert($item);
232 foreach ($expr->getFields() as $fieldName) {
233 $this->getField($fieldName, TRUE);
235 $this->query
->orderBy($expr->render($this->apiFieldSpec
) . " $dir");
240 * @throws \CRM_Core_Exception
242 protected function buildLimit() {
243 if (!empty($this->limit
) ||
!empty($this->offset
)) {
244 // If limit is 0, mysql will actually return 0 results. Instead set to maximum possible.
245 $this->query
->limit($this->limit ?
: '18446744073709551615', $this->offset
);
250 * Adds GROUP BY clause to query
252 protected function buildGroupBy() {
253 foreach ($this->groupBy
as $item) {
254 $expr = SqlExpression
::convert($item);
255 foreach ($expr->getFields() as $fieldName) {
256 $this->getField($fieldName, TRUE);
258 $this->query
->groupBy($expr->render($this->apiFieldSpec
));
263 * Recursively validate and transform a branch or leaf clause array to SQL.
265 * @param array $clause
266 * @param string $type
268 * @return string SQL where clause
270 * @throws \API_Exception
271 * @uses composeClause() to generate the SQL etc.
273 protected function treeWalkClauses($clause, $type) {
274 switch ($clause[0]) {
278 if (count($clause[1]) === 1) {
279 // a single set so AND|OR is immaterial
280 return $this->treeWalkClauses($clause[1][0], $type);
283 $sql_subclauses = [];
284 foreach ($clause[1] as $subclause) {
285 $sql_subclauses[] = $this->treeWalkClauses($subclause, $type);
287 return '(' . implode("\n" . $clause[0], $sql_subclauses) . ')';
291 // If we get a group of clauses with no operator, assume AND
292 if (!is_string($clause[1][0])) {
293 $clause[1] = ['AND', $clause[1]];
295 return 'NOT (' . $this->treeWalkClauses($clause[1], $type) . ')';
298 return $this->composeClause($clause, $type);
303 * Validate and transform a leaf clause array to SQL.
304 * @param array $clause [$fieldName, $operator, $criteria]
305 * @param string $type
308 * @throws \API_Exception
311 protected function composeClause(array $clause, string $type) {
312 // Pad array for unary operators
313 list($expr, $operator, $value) = array_pad($clause, 3, NULL);
315 // For WHERE clause, expr must be the name of a field.
316 if ($type === 'WHERE') {
317 $field = $this->getField($expr, TRUE);
318 FormattingUtil
::formatInputValue($value, $field, $this->getEntity());
319 $fieldAlias = $field['sql_name'];
321 // For HAVING, expr must be an item in the SELECT clause
323 if (isset($this->selectAliases
[$expr])) {
326 elseif (in_array($expr, $this->selectAliases
)) {
327 $fieldAlias = array_search($expr, $this->selectAliases
);
330 throw new \
API_Exception("Invalid expression in $type clause: '$expr'. Must use a value from SELECT clause.");
334 $sql_clause = \CRM_Core_DAO
::createSQLFilter($fieldAlias, [$operator => $value]);
335 if ($sql_clause === NULL) {
336 throw new \
API_Exception("Invalid value in $type clause for '$expr'");
344 protected function getFields() {
345 return $this->apiFieldSpec
;
349 * Fetch a field from the getFields list
351 * @param string $fieldName
352 * @param bool $strict
353 * In strict mode, this will throw an exception if the field doesn't exist
355 * @return string|null
356 * @throws \API_Exception
358 public function getField($fieldName, $strict = FALSE) {
359 // Perform join if field not yet available - this will add it to apiFieldSpec
360 if (!isset($this->apiFieldSpec
[$fieldName]) && strpos($fieldName, '.')) {
361 $this->joinFK($fieldName);
363 $field = $this->apiFieldSpec
[$fieldName] ??
NULL;
364 if ($strict && !$field) {
365 throw new \
API_Exception("Invalid field '$fieldName'");
371 * Joins a path and adds all fields in the joined eneity to apiFieldSpec
374 * @throws \API_Exception
377 protected function joinFK($key) {
378 if (isset($this->apiFieldSpec
[$key])) {
382 $pathArray = explode('.', $key);
384 /** @var \Civi\Api4\Service\Schema\Joiner $joiner */
385 $joiner = \Civi
::container()->get('joiner');
386 // 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.
387 array_pop($pathArray);
388 $pathString = implode('.', $pathArray);
390 if (!$joiner->canJoin($this, $pathString)) {
394 $joinPath = $joiner->join($this, $pathString);
397 foreach ($joinPath as $joinable) {
398 if ($joinable->getJoinType() === Joinable
::JOIN_TYPE_ONE_TO_MANY
) {
403 /** @var \Civi\Api4\Service\Schema\Joinable\Joinable $lastLink */
404 $lastLink = array_pop($joinPath);
406 // Custom field names are already prefixed
407 $isCustom = $lastLink instanceof CustomGroupJoinable
;
409 array_pop($pathArray);
411 $prefix = $pathArray ?
implode('.', $pathArray) . '.' : '';
412 // Cache field info for retrieval by $this->getField()
413 $joinEntity = $lastLink->getEntity();
414 foreach ($lastLink->getEntityFields() as $fieldObject) {
415 $fieldArray = ['entity' => $joinEntity] +
$fieldObject->toArray();
416 $fieldArray['sql_name'] = '`' . $lastLink->getAlias() . '`.`' . $fieldArray['column_name'] . '`';
417 $fieldArray['is_custom'] = $isCustom;
418 $fieldArray['is_join'] = TRUE;
419 $fieldArray['is_many'] = $isMany;
420 $this->addSpecField($prefix . $fieldArray['name'], $fieldArray);
425 * @param \Civi\Api4\Service\Schema\Joinable\Joinable $joinable
429 public function addJoinedTable(Joinable
$joinable) {
430 $this->joinedTables
[] = $joinable;
436 * @return FALSE|string
438 public function getFrom() {
439 return AllCoreTables
::getTableForClass(AllCoreTables
::getFullName($this->entity
));
445 public function getEntity() {
446 return $this->entity
;
452 public function getSelect() {
453 return $this->select
;
459 public function getWhere() {
466 public function getOrderBy() {
467 return $this->orderBy
;
473 public function getLimit() {
480 public function getOffset() {
481 return $this->offset
;
487 public function getSelectFields() {
488 return $this->selectFields
;
494 public function isFillUniqueFields() {
495 return $this->isFillUniqueFields
;
499 * @return \CRM_Utils_SQL_Select
501 public function getQuery() {
508 public function getJoins() {
515 public function getApiFieldSpec() {
516 return $this->apiFieldSpec
;
522 public function getEntityFieldNames() {
523 return $this->entityFieldNames
;
529 public function getAclFields() {
530 return $this->aclFields
;
534 * @return bool|string
536 public function getCheckPermissions() {
537 return $this->checkPermissions
;
543 public function getApiVersion() {
544 return $this->apiVersion
;
548 * @return \Civi\Api4\Service\Schema\Joinable\Joinable[]
550 public function getJoinedTables() {
551 return $this->joinedTables
;
555 * @return \Civi\Api4\Service\Schema\Joinable\Joinable
557 public function getJoinedTable($alias) {
558 foreach ($this->joinedTables
as $join) {
559 if ($join->getAlias() == $alias) {
566 * Get table name on basis of entity
568 * @param string $baoName
572 public function constructQueryObject($baoName) {
573 if (strstr($this->entity
, 'Custom_')) {
574 $this->query
= \CRM_Utils_SQL_Select
::from(CoreUtil
::getCustomTableByName(str_replace('Custom_', '', $this->entity
)) . ' ' . self
::MAIN_TABLE_ALIAS
);
575 $this->entityFieldNames
= array_keys($this->apiFieldSpec
);
578 $bao = new $baoName();
579 $this->query
= \CRM_Utils_SQL_Select
::from($bao->tableName() . ' ' . self
::MAIN_TABLE_ALIAS
);
584 * Checks if a field either belongs to the main entity or is joinable 1-to-1.
586 * Used to determine if a field can be added to the SELECT of the main query,
587 * or if it must be fetched post-query.
589 * @param string $fieldPath
592 public function isOneToOneField(string $fieldPath) {
593 return strpos($fieldPath, '.') === FALSE ||
!array_filter($this->getPathJoinTypes($fieldPath));
597 * Separates a string like 'emails.location_type.label' into an array, where
598 * each value in the array tells whether it is 1-1 or 1-n join type
600 * @param string $pathString
601 * Dot separated path to the field
604 * Index is table alias and value is boolean whether is 1-to-many join
606 public function getPathJoinTypes($pathString) {
607 $pathParts = explode('.', $pathString);
609 array_pop($pathParts);
612 $isMultipleChecker = function($alias) use ($query) {
613 foreach ($query->getJoinedTables() as $table) {
614 if ($table->getAlias() === $alias) {
615 return $table->getJoinType() === Joinable
::JOIN_TYPE_ONE_TO_MANY
;
621 foreach ($pathParts as $part) {
622 $path[$part] = $isMultipleChecker($part);
632 private function addSpecField($path, $field) {
633 // Only add field to spec if we have permission
634 if ($this->checkPermissions
&& !empty($field['permission']) && !\CRM_Core_Permission
::check($field['permission'])) {
635 $this->apiFieldSpec
[$path] = FALSE;
639 $defaults['is_custom'] = $defaults['is_join'] = $defaults['is_many'] = FALSE;
641 $this->apiFieldSpec
[$path] = $field;