Generates a discriminator column SQL condition for the class with the given DQL alias.

@param string[] $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.

@return string
19131
private function generateDiscriminatorColumnConditionSQL(array $dqlAliases)
    {
        $sqlParts = [];

        foreach ($dqlAliases as $dqlAlias) {
            $class = $this->queryComponents[$dqlAlias]['metadata'];

            if ($class->inheritanceType !== InheritanceType::SINGLE_TABLE) {
                continue;
            }

            $conn   = $this->em->getConnection();
            $values = [];

            if ($class->discriminatorValue !== null) { // discriminators can be 0
                $values[] = $conn->quote($class->discriminatorValue);
            }

            foreach ($class->getSubClasses() as $subclassName) {
                $values[] = $conn->quote($this->em->getClassMetadata($subclassName)->discriminatorValue);
            }

            $discrColumn      = $class->discriminatorColumn;
            $discrColumnType  = $discrColumn->getType();
            $quotedColumnName = $this->platform->quoteIdentifier($discrColumn->getColumnName());
            $sqlTableAlias    = $this->useSqlTableAliases
                ? $this->getSQLTableAlias($discrColumn->getTableName(), $dqlAlias) . '.'
                : '';

            $sqlParts[] = sprintf(
                '%s IN (%s)',
                $discrColumnType->convertToDatabaseValueSQL($sqlTableAlias . $quotedColumnName, $this->platform),
                implode(', ', $values)
            );
        }

        $sql = implode(' AND ', $sqlParts);

        return isset($sqlParts[1]) ? '(' . $sql . ')' : $sql;
    }
586599
static function doSelectRS(Query $q = null) {
		$q = $q ? clone $q : static::getQuery();

		if (!$q->getTable()) {
			$q->setTable(static::getTableName());
		}

		return $q->doSelect(static::getConnection());
	}
330233
private function getEntity(array $data, $dqlAlias)
    {
        $className = $this->_rsm->aliasMap[$dqlAlias];

        if (isset($this->_rsm->discriminatorColumns[$dqlAlias])) {
            $fieldName = $this->_rsm->discriminatorColumns[$dqlAlias];

            if ( ! isset($this->_rsm->metaMappings[$fieldName])) {
                throw HydrationException::missingDiscriminatorMetaMappingColumn($className, $fieldName, $dqlAlias);
            }

            $discrColumn = $this->_rsm->metaMappings[$fieldName];

            if ( ! isset($data[$discrColumn])) {
                throw HydrationException::missingDiscriminatorColumn($className, $discrColumn, $dqlAlias);
            }

            if ($data[$discrColumn] === "") {
                throw HydrationException::emptyDiscriminatorValue($dqlAlias);
            }

            $discrMap = $this->_metadataCache[$className]->discriminatorMap;

            if ( ! isset($discrMap[$data[$discrColumn]])) {
                throw HydrationException::invalidDiscriminatorValue($data[$discrColumn], array_keys($discrMap));
            }

            $className = $discrMap[$data[$discrColumn]];

            unset($data[$discrColumn]);
        }

        if (isset($this->_hints[Query::HINT_REFRESH_ENTITY]) && isset($this->rootAliases[$dqlAlias])) {
            $this->registerManaged($this->_metadataCache[$className], $this->_hints[Query::HINT_REFRESH_ENTITY], $data);
        }

        $this->_hints['fetchAlias'] = $dqlAlias;

        return $this->_uow->createEntity($className, $data, $this->_hints);
    }
894801
private List<Class<?>> getClassesByDiscriminators(Collection<String> discriminators)
	{
		Map<String, Class<?>> entitiesByName = new HashMap<>();

		// Prepare a Map of discriminator name -> entity class
		for (QEntity child : entity.getSubEntities())
		{
			entitiesByName.put(child.getDiscriminatorValue(), child.getEntityClass());
		}

		// If the root class isn't abstract then add it to the list of possible discriminators too
		if (!entity.isEntityClassAbstract())
			entitiesByName.put(entity.getDiscriminatorValue(), entity.getEntityClass());

		// Translate the discriminator string values to classes
		List<Class<?>> classes = new ArrayList<>(discriminators.size());
		for (String discriminator : discriminators)
		{
			final Class<?> clazz = entitiesByName.get(discriminator);

			if (clazz != null)
				classes.add(clazz);
			else
				throw new IllegalArgumentException("Invalid class discriminator '" +
				                                   discriminator +
				                                   "', expected one of: " +
				                                   entitiesByName.keySet());
		}

		return classes;
	}
71221
protected function getValidAliases()
    {
        $aliases = new Collection();

        // Get all aliases
        foreach ($this->getAliases() as $name => $facade) {
            // Skip the Redis facade, if not available (otherwise Fatal PHP Error)
            if ($facade == 'Illuminate\Support\Facades\Redis' && $name == 'Redis' && !class_exists('Predis\Client')) {
                continue;
            }

            $magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : array();
            $alias = new Alias($this->config, $name, $facade, $magicMethods, $this->interfaces);
            if ($alias->isValid()) {
                //Add extra methods, from other classes (magic static calls)
                if (array_key_exists($name, $this->extra)) {
                    $alias->addClass($this->extra[$name]);
                }

                $aliases[] = $alias;
            }
        }

        return $aliases;
    }
593159
private function _generateClassTableInheritanceJoins($class, $dqlAlias)
    {
        $sql = '';

        $baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);

        // INNER JOIN parent class tables
        foreach ($class->parentClasses as $parentClassName) {
            $parentClass = $this->em->getClassMetadata($parentClassName);
            $tableAlias  = $this->getSQLTableAlias($parentClass->getTableName(), $dqlAlias);

            // If this is a joined association we must use left joins to preserve the correct result.
            $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER ';
            $sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON ';

            $sqlParts = array();

            foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) {
                $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
            }

            // Add filters on the root class
            if ($filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias)) {
                $sqlParts[] = $filterSql;
            }

            $sql .= implode(' AND ', $sqlParts);
        }

        // Ignore subclassing inclusion if partial objects is disallowed
        if ($this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) {
            return $sql;
        }

        // LEFT JOIN child class tables
        foreach ($class->subClasses as $subClassName) {
            $subClass   = $this->em->getClassMetadata($subClassName);
            $tableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias);

            $sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON ';

            $sqlParts = array();

            foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) {
                $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName;
            }

            $sql .= implode(' AND ', $sqlParts);
        }

        return $sql;
    }
17414
public function getDql()
    {
        if (null === $this->selectClause) {
            throw new MissingSelectClauseException('Select clause is missing');
        }

        $eol = PHP_EOL;
        $joinRelatives = $this->joinSingleRelatives ? $this->joinRelativesClause : '';
        if ($this->leftJoinPlugins) {
            $joinRelatives .= " LEFT JOIN node.resourceType rtp{$eol}
            LEFT JOIN rtp.plugin p{$eol}";
        }
        $joinRoles = $this->leftJoinRoles ?
            "LEFT JOIN node.workspace workspace{$eol}".
            "LEFT JOIN workspace.roles role{$eol}" :
            '';
        $joinRights = $this->leftJoinRights ?
            "LEFT JOIN node.rights rights{$eol}".
            "JOIN rights.role rightRole{$eol}" :
            '';
        $joinLogs = $this->leftJoinLogs ?
            "JOIN node.logs log{$eol}".
            "JOIN log.resourceNode log_node{$eol}" :
            '';
        $dql =
            $this->selectClause.
            $this->fromClause.
            $joinRelatives.
            $joinRoles.
            $joinRights.
            $joinLogs.
            $this->joinClause.
            $this->whereClause.
            $this->groupByClause.
            $this->orderClause;

        return $dql;
    }
1136672
public function getDescendantsAndSelf( $columns = ['*'] )
	{
		if ( is_array( $columns ) )
			return $this->descendantsAndSelf()->get( $columns );

		$arguments = func_get_args();

		$limit = intval( array_shift( $arguments ) );
		$columns = array_shift( $arguments ) ?: ['*'];

		return $this->descendantsAndSelf()->limitDepth( $limit )->get( $columns );
	}
233894
public function getDQL()
    {
        if ($this->_dql !== null && $this->_state === self::STATE_CLEAN) {
            return $this->_dql;
        }

        switch ($this->_type) {
            case self::DELETE:
                $dql = $this->_getDQLForDelete();
                break;

            case self::UPDATE:
                $dql = $this->_getDQLForUpdate();
                break;

            case self::SELECT:
            default:
                $dql = $this->_getDQLForSelect();
                break;
        }

        $this->_state = self::STATE_CLEAN;
        $this->_dql   = $dql;

        return $dql;
    }
222102
public function getFinalisedQuery($queriedColumns = null)
    {
        if (!$queriedColumns) {
            $queriedColumns = $this->queriedColumns;
        }
        if ($queriedColumns) {
            $queriedColumns = array_merge($queriedColumns, array('Created', 'LastEdited', 'ClassName'));
        }
        $query = clone $this->query;

        // Apply manipulators before finalising query
        foreach ($this->getDataQueryManipulators() as $manipulator) {
            $manipulator->beforeGetFinalisedQuery($this, $queriedColumns, $query);
        }

        $schema = DataObject::getSchema();
        $baseDataClass = $schema->baseDataClass($this->dataClass());
        $baseIDColumn = $schema->sqlColumnForField($baseDataClass, 'ID');
        $ancestorClasses = ClassInfo::ancestry($this->dataClass(), true);

        // Generate the list of tables to iterate over and the list of columns required
        // by any existing where clauses. This second step is skipped if we're fetching
        // the whole dataobject as any required columns will get selected regardless.
        if ($queriedColumns) {
            // Specifying certain columns allows joining of child tables
            $tableClasses = ClassInfo::dataClassesFor($this->dataClass);

            // Ensure that any filtered columns are included in the selected columns
            foreach ($query->getWhereParameterised($parameters) as $where) {
                // Check for any columns in the form '"Column" = ?' or '"Table"."Column"' = ?
                if (preg_match_all(
                    '/(?:"(?<table>[^"]+)"\.)?"(?<column>[^"]+)"(?:[^\.]|$)/',
                    $where,
                    $matches,
                    PREG_SET_ORDER
                )) {
                    foreach ($matches as $match) {
                        $column = $match['column'];
                        if (!in_array($column, $queriedColumns)) {
                            $queriedColumns[] = $column;
                        }
                    }
                }
            }
        } else {
            $tableClasses = $ancestorClasses;
        }

        // Iterate over the tables and check what we need to select from them. If any selects are made (or the table is
        // required for a select)
        foreach ($tableClasses as $tableClass) {
            // Determine explicit columns to select
            $selectColumns = null;
            if ($queriedColumns) {
                // Restrict queried columns to that on the selected table
                $tableFields = $schema->databaseFields($tableClass, false);
                unset($tableFields['ID']);
                $selectColumns = array_intersect($queriedColumns, array_keys($tableFields));
            }

            // If this is a subclass without any explicitly requested columns, omit this from the query
            if (!in_array($tableClass, $ancestorClasses) && empty($selectColumns)) {
                continue;
            }

            // Select necessary columns (unless an explicitly empty array)
            if ($selectColumns !== array()) {
                $this->selectColumnsFromTable($query, $tableClass, $selectColumns);
            }

            // Join if not the base table
            if ($tableClass !== $baseDataClass) {
                $tableName = $schema->tableName($tableClass);
                $query->addLeftJoin(
                    $tableName,
                    "\"{$tableName}\".\"ID\" = {$baseIDColumn}",
                    $tableName,
                    10
                );
            }
        }

        // Resolve colliding fields
        if ($this->collidingFields) {
            foreach ($this->collidingFields as $collisionField => $collisions) {
                $caseClauses = array();
                foreach ($collisions as $collision) {
                    if (preg_match('/^"(?<table>[^"]+)"\./', $collision, $matches)) {
                        $collisionTable = $matches['table'];
                        $collisionClass = $schema->tableClass($collisionTable);
                        if ($collisionClass) {
                            $collisionClassColumn = $schema->sqlColumnForField($collisionClass, 'ClassName');
                            $collisionClasses = ClassInfo::subclassesFor($collisionClass);
                            $collisionClassesSQL = implode(', ', Convert::raw2sql($collisionClasses, true));
                            $caseClauses[] = "WHEN {$collisionClassColumn} IN ({$collisionClassesSQL}) THEN $collision";
                        }
                    } else {
                        user_error("Bad collision item '$collision'", E_USER_WARNING);
                    }
                }
                $query->selectField("CASE " . implode(" ", $caseClauses) . " ELSE NULL END", $collisionField);
            }
        }


        if ($this->filterByClassName) {
            // If querying the base class, don't bother filtering on class name
            if ($this->dataClass != $baseDataClass) {
                // Get the ClassName values to filter to
                $classNames = ClassInfo::subclassesFor($this->dataClass);
                $classNamesPlaceholders = DB::placeholders($classNames);
                $baseClassColumn = $schema->sqlColumnForField($baseDataClass, 'ClassName');
                $query->addWhere(array(
                    "{$baseClassColumn} IN ($classNamesPlaceholders)" => $classNames
                ));
            }
        }

        // Select ID
        $query->selectField($baseIDColumn, "ID");

        // Select RecordClassName
        $baseClassColumn = $schema->sqlColumnForField($baseDataClass, 'ClassName');
        $query->selectField(
            "
			CASE WHEN {$baseClassColumn} IS NOT NULL THEN {$baseClassColumn}
			ELSE " . Convert::raw2sql($baseDataClass, true) . " END",
            "RecordClassName"
        );

        // TODO: Versioned, Translatable, SiteTreeSubsites, etc, could probably be better implemented as subclasses
        // of DataQuery

        $obj = Injector::inst()->get($this->dataClass);
        $obj->extend('augmentSQL', $query, $this);

        $this->ensureSelectContainsOrderbyColumns($query);

        // Apply post-finalisation manipulations
        foreach ($this->getDataQueryManipulators() as $manipulator) {
            $manipulator->afterGetFinalisedQuery($this, $queriedColumns, $query);
        }

        return $query;
    }
6724
public function generateSelectClause($tableAliases = array())
    {
        $sql = "";

        foreach ($this->columnOwnerMap as $columnName => $dqlAlias) {
            $tableAlias = isset($tableAliases[$dqlAlias])
                ? $tableAliases[$dqlAlias] : $dqlAlias;

            if ($sql) {
                $sql .= ", ";
            }

            $sql .= $tableAlias . ".";

            if (isset($this->fieldMappings[$columnName])) {
                $class = $this->em->getClassMetadata($this->declaringClasses[$columnName]);
                $sql  .= $class->fieldMappings[$this->fieldMappings[$columnName]]['columnName'];
            } else if (isset($this->metaMappings[$columnName])) {
                $sql .= $this->metaMappings[$columnName];
            } else if (isset($this->discriminatorColumn[$columnName])) {
                $sql .= $this->discriminatorColumn[$columnName];
            }

            $sql .= " AS " . $columnName;
        }

        return $sql;
    }
439008
final private function getSqlKeyConditions() {
	
		$class		= get_called_class();
		$tableKey	= (array)$class::TABLE_KEY;
		$conds		= array();
		
			foreach ($tableKey as $field) {
				$conds[] = $this->db->escape($field) . ' = ?';
			}
		
		return $conds;

	}
1370970
public function getLdapQuery($conditions = null, $objectClass = null) {
		if (!empty($objectClass)) {
			$objectClass = mb_strtolower($objectClass);
		} else {
			$objectClass = 'user';
		}

		$baseQuery = '(!(useraccountcontrol:1.2.840.113556.1.4.803:=2))(objectClass=' . $objectClass . ')';
		if ($objectClass === 'user') {
			$baseQuery .= '(userAccountControl:1.2.840.113556.1.4.803:=512)';
		}

		if (empty($conditions) || !is_array($conditions)) {
			return $baseQuery;
		}

		$result = '(&' . $baseQuery;
		foreach ($conditions as $attribute => $value) {
			list(, $attributeName) = pluginSplit($attribute);
			if (empty($value)) {
				continue;
			}

			switch ($attributeName) {
				case CAKE_LDAP_LDAP_DISTINGUISHED_NAME:
					$attributeName = CAKE_LDAP_LDAP_ATTRIBUTE_DISTINGUISHED_NAME;
					break;
				case CAKE_LDAP_LDAP_ATTRIBUTE_OBJECT_GUID:
					$value = GuidStringToLdap($value);
					break;
			}
			$result .= '(' . $attributeName . '=' . (string)$value . ')';
		}
		$result .= ')';

		return $result;
	}
1307047
public function transform(QueryBuilder $qb, $dqlAlias)
    {
        if ($this->expression instanceof Filter) {
            $expression = $this->expression->getFilter($qb, $dqlAlias);
        } else {
            $expression = ArgumentToOperandConverter::toField($this->expression);
            $expression = $expression->transform($qb, $dqlAlias);
        }

        return sprintf($this->getAliasFormat(), $expression, $this->alias);
    }
1097055
public function getFilter(QueryBuilder $qb, $dqlAlias)
    {
        if (null !== $this->dqlAlias) {
            $dqlAlias = $this->dqlAlias;
        }

        $field = ArgumentToOperandConverter::toField($this->field);

        return (string) $qb->expr()->isNotNull($field->transform($qb, $dqlAlias));
    }
719106
protected function getLr($ids)
    {
        $class = $this->className;
        return $class::find()
            ->select(['id', $this->leftAttribute, $this->rightAttribute])
            ->where(['id' => $ids])
            ->indexBy('id')
            ->asArray(true)
            ->all();
    }
675334
protected function getDatabaseClass($databaseClasses)
    {
        $envDatabase = Environment::getEnv('SS_DATABASE_CLASS');
        if ($envDatabase) {
            return $envDatabase;
        }

        // Check supported versions
        foreach ($this->preferredDatabases as $candidate) {
            if (!empty($databaseClasses[$candidate]['supported'])) {
                return $candidate;
            }
        }
        return null;
    }