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\Api4\Service\Schema\Joinable\CustomGroupJoinable
;
15 use Civi\Api4\Utils\FormattingUtil
;
16 use Civi\Api4\Utils\CoreUtil
;
17 use Civi\Api4\Utils\SelectUtil
;
20 * A query `node` may be in one of three formats:
22 * * leaf: [$fieldName, $operator, $criteria]
23 * * negated: ['NOT', $node]
24 * * branch: ['OR|NOT', [$node, $node, ...]]
26 * Leaf operators are one of:
28 * * '=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=",
29 * * 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN',
30 * * 'IS NOT NULL', or 'IS NULL', 'CONTAINS'.
32 class Api4SelectQuery
{
35 MAIN_TABLE_ALIAS
= 'a',
36 UNLIMITED
= '18446744073709551615';
39 * @var \CRM_Utils_SQL_Select
46 protected $joins = [];
51 protected $apiFieldSpec;
56 protected $entityFieldNames = [];
61 protected $aclFields = [];
64 * @var \Civi\Api4\Generic\DAOGetAction
72 protected $selectAliases = [];
77 public $forceSelectId = TRUE;
80 * @param \Civi\Api4\Generic\DAOGetAction $apiGet
82 public function __construct($apiGet) {
85 // Always select ID of main table unless grouping by something else
86 $this->forceSelectId
= !$this->getGroupBy() ||
$this->getGroupBy() === ['id'];
89 foreach ($this->api
->entityFields() as $field) {
90 $this->entityFieldNames
[] = $field['name'];
91 $field['sql_name'] = '`' . self
::MAIN_TABLE_ALIAS
. '`.`' . $field['column_name'] . '`';
92 $this->addSpecField($field['name'], $field);
95 $tableName = CoreUtil
::getTableName($this->getEntity());
96 $this->query
= \CRM_Utils_SQL_Select
::from($tableName . ' ' . self
::MAIN_TABLE_ALIAS
);
98 // Add ACLs first to avoid redundant subclauses
99 $baoName = CoreUtil
::getBAOFromApiName($this->getEntity());
100 $this->query
->where($this->getAclClause(self
::MAIN_TABLE_ALIAS
, $baoName));
104 * Builds main final sql statement after initialization.
107 * @throws \API_Exception
108 * @throws \CRM_Core_Exception
110 public function getSql() {
111 // Add explicit joins. Other joins implied by dot notation may be added later
112 $this->addExplicitJoins();
113 $this->buildSelectClause();
114 $this->buildWhereClause();
115 $this->buildOrderBy();
117 $this->buildGroupBy();
118 $this->buildHavingClause();
119 return $this->query
->toSQL();
123 * Why walk when you can
127 public function run() {
129 $sql = $this->getSql();
130 $this->debug('sql', $sql);
131 $query = \CRM_Core_DAO
::executeQuery($sql);
132 while ($query->fetch()) {
134 foreach ($this->selectAliases
as $alias => $expr) {
135 $returnName = $alias;
136 $alias = str_replace('.', '_', $alias);
137 $result[$returnName] = property_exists($query, $alias) ?
$query->$alias : NULL;
139 $results[] = $result;
141 FormattingUtil
::formatOutputValues($results, $this->apiFieldSpec
, $this->getEntity());
147 * @throws \API_Exception
149 public function getCount() {
150 $this->addExplicitJoins();
151 $this->buildWhereClause();
152 // If no having or groupBy, we only need to select count
153 if (!$this->getHaving() && !$this->getGroupBy()) {
154 $this->query
->select('COUNT(*) AS `c`');
155 $sql = $this->query
->toSQL();
157 // Use a subquery to count groups from GROUP BY or results filtered by HAVING
159 // With no HAVING, just select the last field grouped by
160 if (!$this->getHaving()) {
161 $select = array_slice($this->getGroupBy(), -1);
163 $this->buildSelectClause($select ??
NULL);
164 $this->buildHavingClause();
165 $this->buildGroupBy();
166 $subquery = $this->query
->toSQL();
167 $sql = "SELECT count(*) AS `c` FROM ( $subquery ) AS rows";
169 $this->debug('sql', $sql);
170 return (int) \CRM_Core_DAO
::singleValueQuery($sql);
174 * @param array $select
175 * Array of select expressions; defaults to $this->getSelect
176 * @throws \API_Exception
178 protected function buildSelectClause($select = NULL) {
179 // Use default if select not provided, exclude row_count which is handled elsewhere
180 $select = array_diff($select ??
$this->getSelect(), ['row_count']);
181 // An empty select is the same as *
182 if (empty($select)) {
183 $select = $this->entityFieldNames
;
186 if ($this->forceSelectId
) {
187 $select = array_merge(['id'], $select);
190 // Expand the superstar 'custom.*' to select all fields in all custom groups
191 $customStar = array_search('custom.*', array_values($select), TRUE);
192 if ($customStar !== FALSE) {
193 $customGroups = civicrm_api4($this->getEntity(), 'getFields', [
194 'checkPermissions' => FALSE,
195 'where' => [['custom_group', 'IS NOT NULL']],
196 ], ['custom_group' => 'custom_group']);
198 foreach ($customGroups as $groupName) {
199 $customSelect[] = "$groupName.*";
201 array_splice($select, $customStar, 1, $customSelect);
204 // Expand wildcards in joins (the api wrapper already expanded non-joined wildcards)
205 $wildFields = array_filter($select, function($item) {
206 return strpos($item, '*') !== FALSE && strpos($item, '.') !== FALSE && strpos($item, '(') === FALSE && strpos($item, ' ') === FALSE;
209 foreach ($wildFields as $item) {
210 $pos = array_search($item, array_values($select));
211 $this->autoJoinFK($item);
212 $matches = SelectUtil
::getMatchingFields($item, array_keys($this->apiFieldSpec
));
213 array_splice($select, $pos, 1, $matches);
215 $select = array_unique($select);
217 foreach ($select as $item) {
218 $expr = SqlExpression
::convert($item, TRUE);
220 foreach ($expr->getFields() as $fieldName) {
221 $field = $this->getField($fieldName);
222 // Remove expressions with unknown fields without raising an error
224 $select = array_diff($select, [$item]);
225 $this->debug('undefined_fields', $fieldName);
230 $alias = $expr->getAlias();
231 if ($alias != $expr->getExpr() && isset($this->apiFieldSpec
[$alias])) {
232 throw new \
API_Exception('Cannot use existing field name as alias');
234 $this->selectAliases
[$alias] = $expr->getExpr();
235 $this->query
->select($expr->render($this->apiFieldSpec
) . " AS `$alias`");
241 * Add WHERE clause to query
243 protected function buildWhereClause() {
244 foreach ($this->getWhere() as $clause) {
245 $sql = $this->treeWalkClauses($clause, 'WHERE');
247 $this->query
->where($sql);
253 * Add HAVING clause to query
255 * Every expression referenced must also be in the SELECT clause.
257 protected function buildHavingClause() {
258 foreach ($this->getHaving() as $clause) {
259 $this->query
->having($this->treeWalkClauses($clause, 'HAVING'));
264 * Add ORDER BY to query
266 protected function buildOrderBy() {
267 foreach ($this->getOrderBy() as $item => $dir) {
268 if ($dir !== 'ASC' && $dir !== 'DESC') {
269 throw new \
API_Exception("Invalid sort direction. Cannot order by $item $dir");
271 $expr = $this->getExpression($item);
272 $column = $expr->render($this->apiFieldSpec
);
274 // Use FIELD() function to sort on pseudoconstant values
275 $suffix = strstr($item, ':');
276 if ($suffix && $expr->getType() === 'SqlField') {
277 $field = $this->getField($item);
278 $options = FormattingUtil
::getPseudoconstantList($field['entity'], $field['name'], substr($suffix, 1));
281 $column = "FIELD($column,'" . implode("','", array_keys($options)) . "')";
284 $this->query
->orderBy("$column $dir");
291 * @throws \CRM_Core_Exception
293 protected function buildLimit() {
294 if ($this->getLimit() ||
$this->getOffset()) {
295 // If limit is 0, mysql will actually return 0 results. Instead set to maximum possible.
296 $this->query
->limit($this->getLimit() ?
: self
::UNLIMITED
, $this->getOffset());
301 * Add GROUP BY clause to query
303 protected function buildGroupBy() {
304 foreach ($this->getGroupBy() as $item) {
305 $this->query
->groupBy($this->getExpression($item)->render($this->apiFieldSpec
));
310 * Recursively validate and transform a branch or leaf clause array to SQL.
312 * @param array $clause
313 * @param string $type
315 * @return string SQL where clause
317 * @throws \API_Exception
318 * @uses composeClause() to generate the SQL etc.
320 protected function treeWalkClauses($clause, $type) {
322 if (in_array($clause[0], ['AND', 'OR', 'NOT']) && empty($clause[1])) {
325 switch ($clause[0]) {
329 if (count($clause[1]) === 1) {
330 // a single set so AND|OR is immaterial
331 return $this->treeWalkClauses($clause[1][0], $type);
334 $sql_subclauses = [];
335 foreach ($clause[1] as $subclause) {
336 $sql_subclauses[] = $this->treeWalkClauses($subclause, $type);
338 return '(' . implode("\n" . $clause[0], $sql_subclauses) . ')';
342 // If we get a group of clauses with no operator, assume AND
343 if (!is_string($clause[1][0])) {
344 $clause[1] = ['AND', $clause[1]];
346 return 'NOT (' . $this->treeWalkClauses($clause[1], $type) . ')';
349 return $this->composeClause($clause, $type);
354 * Validate and transform a leaf clause array to SQL.
355 * @param array $clause [$fieldName, $operator, $criteria]
356 * @param string $type
359 * @throws \API_Exception
362 protected function composeClause(array $clause, string $type) {
363 // Pad array for unary operators
364 list($expr, $operator, $value) = array_pad($clause, 3, NULL);
365 if (!in_array($operator, CoreUtil
::getOperators(), TRUE)) {
366 throw new \
API_Exception('Illegal operator');
369 // For WHERE clause, expr must be the name of a field.
370 if ($type === 'WHERE') {
371 $field = $this->getField($expr, TRUE);
372 FormattingUtil
::formatInputValue($value, $expr, $field);
373 $fieldAlias = $field['sql_name'];
375 // For HAVING, expr must be an item in the SELECT clause
376 elseif ($type === 'HAVING') {
377 // Expr references a fieldName or alias
378 if (isset($this->selectAliases
[$expr])) {
380 // Attempt to format if this is a real field
381 if (isset($this->apiFieldSpec
[$expr])) {
382 $field = $this->getField($expr);
383 FormattingUtil
::formatInputValue($value, $expr, $field);
386 // Expr references a non-field expression like a function; convert to alias
387 elseif (in_array($expr, $this->selectAliases
)) {
388 $fieldAlias = array_search($expr, $this->selectAliases
);
390 // If either the having or select field contains a pseudoconstant suffix, match and perform substitution
392 list($fieldName) = explode(':', $expr);
393 foreach ($this->selectAliases
as $selectAlias => $selectExpr) {
394 list($selectField) = explode(':', $selectAlias);
395 if ($selectAlias === $selectExpr && $fieldName === $selectField && isset($this->apiFieldSpec
[$fieldName])) {
396 $field = $this->getField($fieldName);
397 FormattingUtil
::formatInputValue($value, $expr, $field);
398 $fieldAlias = $selectAlias;
403 if (!isset($fieldAlias)) {
404 throw new \
API_Exception("Invalid expression in HAVING clause: '$expr'. Must use a value from SELECT clause.");
406 $fieldAlias = '`' . $fieldAlias . '`';
408 elseif ($type === 'ON') {
409 $expr = $this->getExpression($expr);
410 $fieldName = count($expr->getFields()) === 1 ?
$expr->getFields()[0] : NULL;
411 $fieldAlias = $expr->render($this->apiFieldSpec
);
412 if (is_string($value)) {
413 $valExpr = $this->getExpression($value);
414 if ($fieldName && $valExpr->getType() === 'SqlString') {
415 FormattingUtil
::formatInputValue($valExpr->expr
, $fieldName, $this->apiFieldSpec
[$fieldName]);
417 return sprintf('%s %s %s', $fieldAlias, $operator, $valExpr->render($this->apiFieldSpec
));
419 elseif ($fieldName) {
420 $field = $this->getField($fieldName);
421 FormattingUtil
::formatInputValue($value, $fieldName, $field);
425 if ($operator === 'CONTAINS') {
426 switch ($field['serialize'] ??
NULL) {
427 case \CRM_Core_DAO
::SERIALIZE_JSON
:
429 $value = '%"' . $value . '"%';
430 // FIXME: Use this instead of the above hack once MIN_INSTALL_MYSQL_VER is bumped to 5.7.
431 // return sprintf('JSON_SEARCH(%s, "one", "%s") IS NOT NULL', $fieldAlias, \CRM_Core_DAO::escapeString($value));
434 case \CRM_Core_DAO
::SERIALIZE_SEPARATOR_BOOKEND
:
436 $value = '%' . \CRM_Core_DAO
::VALUE_SEPARATOR
. $value . \CRM_Core_DAO
::VALUE_SEPARATOR
. '%';
441 $value = '%' . $value . '%';
446 $sql_clause = \CRM_Core_DAO
::createSQLFilter($fieldAlias, [$operator => $value]);
447 if ($sql_clause === NULL) {
448 throw new \
API_Exception("Invalid value in $type clause for '$expr'");
454 * @param string $expr
455 * @return SqlExpression
456 * @throws \API_Exception
458 protected function getExpression(string $expr) {
459 $sqlExpr = SqlExpression
::convert($expr);
460 foreach ($sqlExpr->getFields() as $fieldName) {
461 $this->getField($fieldName, TRUE);
467 * Get acl clause for an entity
469 * @param string $tableAlias
470 * @param \CRM_Core_DAO|string $baoName
471 * @param array $stack
474 public function getAclClause($tableAlias, $baoName, $stack = []) {
475 if (!$this->getCheckPermissions()) {
478 // Prevent (most) redundant acl sub clauses if they have already been applied to the main entity.
479 // FIXME: Currently this only works 1 level deep, but tracking through multiple joins would increase complexity
480 // and just doing it for the first join takes care of most acl clause deduping.
481 if (count($stack) === 1 && in_array($stack[0], $this->aclFields
, TRUE)) {
484 $clauses = $baoName::getSelectWhereClause($tableAlias);
486 // Track field clauses added to the main entity
487 $this->aclFields
= array_keys($clauses);
489 return array_filter($clauses);
493 * Fetch a field from the getFields list
495 * @param string $expr
496 * @param bool $strict
497 * In strict mode, this will throw an exception if the field doesn't exist
500 * @throws \API_Exception
502 public function getField($expr, $strict = FALSE) {
503 // If the expression contains a pseudoconstant filter like activity_type_id:label,
504 // strip it to look up the base field name, then add the field:filter key to apiFieldSpec
505 $col = strpos($expr, ':');
506 $fieldName = $col ?
substr($expr, 0, $col) : $expr;
507 // Perform join if field not yet available - this will add it to apiFieldSpec
508 if (!isset($this->apiFieldSpec
[$fieldName]) && strpos($fieldName, '.')) {
509 $this->autoJoinFK($fieldName);
511 $field = $this->apiFieldSpec
[$fieldName] ??
NULL;
512 if ($strict && !$field) {
513 throw new \
API_Exception("Invalid field '$fieldName'");
515 $this->apiFieldSpec
[$expr] = $field;
520 * Join onto other entities as specified by the api call.
522 * @throws \API_Exception
523 * @throws \Civi\API\Exception\NotImplementedException
525 private function addExplicitJoins() {
526 foreach ($this->getJoin() as $join) {
527 // First item in the array is the entity name
528 $entity = array_shift($join);
529 // Which might contain an alias. Split on the keyword "AS"
530 list($entity, $alias) = array_pad(explode(' AS ', $entity), 2, NULL);
531 // Ensure alias is a safe string, and supply default if not given
532 $alias = $alias ? \CRM_Utils_String
::munge($alias) : strtolower($entity);
533 // First item in the array is a boolean indicating if the join is required (aka INNER or LEFT).
534 // The rest are join conditions.
535 $side = array_shift($join) ?
'INNER' : 'LEFT';
536 // Add all fields from joined entity to spec
537 $joinEntityGet = \Civi\API\Request
::create($entity, 'get', ['version' => 4, 'checkPermissions' => $this->getCheckPermissions()]);
538 foreach ($joinEntityGet->entityFields() as $field) {
539 $field['sql_name'] = '`' . $alias . '`.`' . $field['column_name'] . '`';
540 $this->addSpecField($alias . '.' . $field['name'], $field);
542 if (!empty($join[0]) && is_string($join[0]) && \CRM_Utils_Rule
::alphanumeric($join[0])) {
543 $conditions = $this->getBridgeJoin($join, $entity, $alias);
546 $conditions = $this->getJoinConditions($join, $entity, $alias);
548 foreach (array_filter($join) as $clause) {
549 $conditions[] = $this->treeWalkClauses($clause, 'ON');
551 $tableName = CoreUtil
::getTableName($entity);
552 $this->join($side, $tableName, $alias, $conditions);
557 * Supply conditions for an explicit join.
559 * @param array $joinTree
560 * @param string $joinEntity
561 * @param string $alias
564 private function getJoinConditions($joinTree, $joinEntity, $alias) {
566 // getAclClause() expects a stack of 1-to-1 join fields to help it dedupe, but this is more flexible,
567 // so unless this is a direct 1-to-1 join with the main entity, we'll just hack it
568 // with a padded empty stack to bypass its deduping.
569 $stack = [NULL, NULL];
570 // If we're not explicitly referencing the joinEntity ID in the ON clause, search for a default
571 $explicitId = array_filter($joinTree, function($clause) use ($alias) {
572 list($sideA, $op, $sideB) = array_pad((array) $clause, 3, NULL);
573 return $op === '=' && ($sideA === "$alias.id" ||
$sideB === "$alias.id");
576 foreach ($this->apiFieldSpec
as $name => $field) {
577 if ($field['entity'] !== $joinEntity && $field['fk_entity'] === $joinEntity) {
578 $conditions[] = $this->treeWalkClauses([$name, '=', "$alias.id"], 'ON');
580 elseif (strpos($name, "$alias.") === 0 && substr_count($name, '.') === 1 && $field['fk_entity'] === $this->getEntity()) {
581 $conditions[] = $this->treeWalkClauses([$name, '=', 'id'], 'ON');
585 // Hmm, if we came up with > 1 condition, then it's ambiguous how it should be joined so we won't return anything but the generic ACLs
586 if (count($conditions) > 1) {
587 $stack = [NULL, NULL];
591 $baoName = CoreUtil
::getBAOFromApiName($joinEntity);
592 $acls = array_values($this->getAclClause($alias, $baoName, $stack));
593 return array_merge($acls, $conditions);
597 * Join onto a BridgeEntity table
599 * @param array $joinTree
600 * @param string $joinEntity
601 * @param string $alias
603 * @throws \API_Exception
605 protected function getBridgeJoin(&$joinTree, $joinEntity, $alias) {
606 $bridgeEntity = array_shift($joinTree);
607 if (!is_a('\Civi\Api4\\' . $bridgeEntity, '\Civi\Api4\Generic\BridgeEntity', TRUE)) {
608 throw new \
API_Exception("Illegal bridge entity specified: " . $bridgeEntity);
610 $bridgeAlias = $alias . '_via_' . strtolower($bridgeEntity);
611 $bridgeTable = CoreUtil
::getTableName($bridgeEntity);
612 $joinTable = CoreUtil
::getTableName($joinEntity);
613 $bridgeEntityGet = \Civi\API\Request
::create($bridgeEntity, 'get', ['version' => 4, 'checkPermissions' => $this->getCheckPermissions()]);
614 $fkToJoinField = $fkToBaseField = NULL;
615 // Find the bridge field that links to the joinEntity (either an explicit FK or an entity_id/entity_table combo)
616 foreach ($bridgeEntityGet->entityFields() as $name => $field) {
617 if ($field['fk_entity'] === $joinEntity ||
(!$fkToJoinField && $name === 'entity_id')) {
618 $fkToJoinField = $name;
621 // Get list of entities allowed for entity_table
622 if (array_key_exists('entity_id', $bridgeEntityGet->entityFields())) {
623 $entityTables = (array) civicrm_api4($bridgeEntity, 'getFields', [
624 'checkPermissions' => FALSE,
625 'where' => [['name', '=', 'entity_table']],
626 'loadOptions' => TRUE,
627 ], ['options'])->first();
629 // If bridge field to joinEntity is entity_id, validate entity_table is allowed
630 if (!$fkToJoinField ||
($fkToJoinField === 'entity_id' && !array_key_exists($joinTable, $entityTables))) {
631 throw new \
API_Exception("Unable to join $bridgeEntity to $joinEntity");
633 // Create link between bridge entity and join entity
635 "`$bridgeAlias`.`$fkToJoinField` = `$alias`.`id`",
637 if ($fkToJoinField === 'entity_id') {
638 $joinConditions[] = "`$bridgeAlias`.`entity_table` = '$joinTable'";
640 // Register fields from the bridge entity as if they belong to the join entity
641 foreach ($bridgeEntityGet->entityFields() as $name => $field) {
642 if ($name == 'id' ||
$name == $fkToJoinField ||
($name == 'entity_table' && $fkToJoinField == 'entity_id')) {
645 if ($field['fk_entity'] ||
(!$fkToBaseField && $name == 'entity_id')) {
646 $fkToBaseField = $name;
648 // Note these fields get a sql alias pointing to the bridge entity, but an api alias pretending they belong to the join entity
649 $field['sql_name'] = '`' . $bridgeAlias . '`.`' . $field['column_name'] . '`';
650 $this->addSpecField($alias . '.' . $field['name'], $field);
652 // Move conditions for the bridge join out of the joinTree
653 $bridgeConditions = [];
654 $joinTree = array_filter($joinTree, function($clause) use ($fkToBaseField, $alias, $bridgeAlias, &$bridgeConditions) {
655 list($sideA, $op, $sideB) = array_pad((array) $clause, 3, NULL);
656 if ($op === '=' && $sideB && ($sideA === "$alias.$fkToBaseField" ||
$sideB === "$alias.$fkToBaseField")) {
657 $expr = $sideA === "$alias.$fkToBaseField" ?
$sideB : $sideA;
658 $bridgeConditions[] = "`$bridgeAlias`.`$fkToBaseField` = " . $this->getExpression($expr)->render($this->apiFieldSpec
);
661 elseif ($op === '=' && $fkToBaseField == 'entity_id' && ($sideA === "$alias.entity_table" ||
$sideB === "$alias.entity_table")) {
662 $expr = $sideA === "$alias.entity_table" ?
$sideB : $sideA;
663 $bridgeConditions[] = "`$bridgeAlias`.`entity_table` = " . $this->getExpression($expr)->render($this->apiFieldSpec
);
668 // If no bridge conditions were specified, link it to the base entity
669 if (!$bridgeConditions) {
670 $bridgeConditions[] = "`$bridgeAlias`.`$fkToBaseField` = a.id";
671 if ($fkToBaseField == 'entity_id') {
672 if (!array_key_exists($this->getFrom(), $entityTables)) {
673 throw new \
API_Exception("Unable to join $bridgeEntity to " . $this->getEntity());
675 $bridgeConditions[] = "`$bridgeAlias`.`entity_table` = '" . $this->getFrom() . "'";
679 $this->join('LEFT', $bridgeTable, $bridgeAlias, $bridgeConditions);
681 $baoName = CoreUtil
::getBAOFromApiName($joinEntity);
682 $acls = array_values($this->getAclClause($alias, $baoName, [NULL, NULL]));
683 return array_merge($acls, $joinConditions);
687 * Joins a path and adds all fields in the joined entity to apiFieldSpec
690 * @throws \API_Exception
693 protected function autoJoinFK($key) {
694 if (isset($this->apiFieldSpec
[$key])) {
698 $pathArray = explode('.', $key);
700 /** @var \Civi\Api4\Service\Schema\Joiner $joiner */
701 $joiner = \Civi
::container()->get('joiner');
702 // 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.
703 array_pop($pathArray);
704 $pathString = implode('.', $pathArray);
706 if (!$joiner->canAutoJoin($this->getFrom(), $pathString)) {
710 $joinPath = $joiner->join($this, $pathString);
712 $lastLink = array_pop($joinPath);
714 // Custom field names are already prefixed
715 $isCustom = $lastLink instanceof CustomGroupJoinable
;
717 array_pop($pathArray);
719 $prefix = $pathArray ?
implode('.', $pathArray) . '.' : '';
720 // Cache field info for retrieval by $this->getField()
721 foreach ($lastLink->getEntityFields() as $fieldObject) {
722 $fieldArray = $fieldObject->toArray();
723 $fieldArray['sql_name'] = '`' . $lastLink->getAlias() . '`.`' . $fieldArray['column_name'] . '`';
724 $this->addSpecField($prefix . $fieldArray['name'], $fieldArray);
729 * @param string $side
730 * @param string $tableName
731 * @param string $tableAlias
732 * @param array $conditions
734 public function join($side, $tableName, $tableAlias, $conditions) {
735 // INNER JOINs take precedence over LEFT JOINs
736 if ($side != 'LEFT' ||
!isset($this->joins
[$tableAlias])) {
737 $this->joins
[$tableAlias] = $side;
738 $this->query
->join($tableAlias, "$side JOIN `$tableName` `$tableAlias` ON " . implode(' AND ', $conditions));
743 * @return FALSE|string
745 public function getFrom() {
746 return CoreUtil
::getTableName($this->getEntity());
752 public function getEntity() {
753 return $this->api
->getEntityName();
759 public function getSelect() {
760 return $this->api
->getSelect();
766 public function getWhere() {
767 return $this->api
->getWhere();
773 public function getHaving() {
774 return $this->api
->getHaving();
780 public function getJoin() {
781 return $this->api
->getJoin();
787 public function getGroupBy() {
788 return $this->api
->getGroupBy();
794 public function getOrderBy() {
795 return $this->api
->getOrderBy();
801 public function getLimit() {
802 return $this->api
->getLimit();
808 public function getOffset() {
809 return $this->api
->getOffset();
813 * @return \CRM_Utils_SQL_Select
815 public function getQuery() {
820 * @return bool|string
822 public function getCheckPermissions() {
823 return $this->api
->getCheckPermissions();
827 * @param string $path
828 * @param array $field
830 private function addSpecField($path, $field) {
831 // Only add field to spec if we have permission
832 if ($this->getCheckPermissions() && !empty($field['permission']) && !\CRM_Core_Permission
::check($field['permission'])) {
833 $this->apiFieldSpec
[$path] = FALSE;
836 $this->apiFieldSpec
[$path] = $field;
840 * Add something to the api's debug output if debugging is enabled
845 public function debug($key, $item) {
846 if ($this->api
->getDebug()) {
847 $this->api
->_debugOutput
[$key][] = $item;