/** * @test * @covers Plum\PlumDoctrine\ORM\QueryReader::count() */ public function countShouldReturnNumberOfResults() { $result = new stdClass(); $this->query->shouldReceive('getResult')->andReturn([$result, $result]); $reader = new QueryReader($this->query); $this->assertEquals(2, $reader->count()); }
function it_should_count_entities(ManagerRegistry $registry, EntityManager $em, AbstractQuery $query) { $query->getSingleScalarResult()->willReturn(42); $em->createQuery('SELECT COUNT(r) FROM foo r')->willReturn($query); $registry->getManager(null)->willReturn($em); $this->setRegistry($registry); $this->count()->shouldBe(42); }
function it_increments_read_count_for_each_record_reading($stepExecution, AbstractQuery $query) { $query->execute()->willReturn(array('foo', 'bar')); $stepExecution->incrementSummaryInfo('read')->shouldBeCalledTimes(2); $this->setQuery($query); $this->read(); $this->read(); $this->read(); }
/** * @param Doctrine\ORM\AbstractQuery $query */ public function __construct(AbstractQuery $query) { $this->result = $query->setMaxResults($query->getMaxResults() + 1)->getResult(); $this->prevPageOffset = $query->getFirstResult() ? max(0, $query->getFirstResult() - $query->getMaxResults() + 1) : null; $this->nextPageOffset = count($this->result) === $query->getMaxResults() ? $query->getMaxResults() + $query->getFirstResult() - 1 : null; $this->currentPageOffset = $query->getFirstResult(); if ($this->nextPageOffset) { array_pop($this->result); } }
public function modifyQuery(AbstractQuery $query) { if ($this->offset > 0) { $query->setFirstResult($this->offset); } if ($this->limit > 0) { $query->setMaxResults($this->limit); } // Propagate to child specification $this->child->modifyQuery($query); }
/** * Converts calendar events returned by the given query to form that can be used in API * * @param int $calendarId The target calendar id * @param AbstractQuery $query The query that should be used to get events * * @return array */ public function getCalendarEvents($calendarId, AbstractQuery $query) { $result = []; $rawData = $query->getArrayResult(); foreach ($rawData as $rawDataItem) { $result[] = $this->transformEntity($rawDataItem); } $this->applyAdditionalData($result, $calendarId); foreach ($result as &$resultItem) { $this->applyPermissions($resultItem, $calendarId); } $this->reminderManager->applyReminders($result, 'Oro\\Bundle\\CalendarBundle\\Entity\\CalendarEvent'); return $result; }
/** * @param int $calendarId * @param AbstractQuery $query * * @return array */ public function getTasks($calendarId, AbstractQuery $query) { $result = []; $items = $query->getArrayResult(); foreach ($items as $item) { /** @var \DateTime $start */ $start = $item['dueDate']; $end = clone $start; $end = $end->add(new \DateInterval('PT30M')); $result[] = ['calendar' => $calendarId, 'id' => $item['id'], 'title' => $item['subject'], 'description' => $item['description'], 'start' => $start->format('c'), 'end' => $end->format('c'), 'allDay' => false, 'createdAt' => $item['createdAt']->format('c'), 'updatedAt' => $item['updatedAt']->format('c'), 'editable' => false, 'removable' => false]; } $this->reminderManager->applyReminders($result, 'OroCRM\\Bundle\\TaskBundle\\Entity\\Task'); return $result; }
protected function doParse() { $result = null; $hash = $this->getCacheId(); $usedCacheDriver = !$this->query->getExpireQueryCache() ? $this->query->getQueryCacheDriver() : null; if ($usedCacheDriver) { $result = $usedCacheDriver->fetch($hash); } if (!$result instanceof \Doctrine\ORM\Query\ParserResult) { $result = $this->doParseWithoutCache(); if ($usedCacheDriver) { $usedCacheDriver->save($hash, $result, $this->query->getQueryCacheLifetime()); } } return $result; }
function it_does_not_try_to_join_attributes_when_finding_full_products_with_empty_attributes($em, QueryBuilder $queryBuilder, Expr $expr, AbstractQuery $query) { $expr->in('p.id', [42])->shouldBeCalled()->willReturn('product where clause'); $expr->in('a.id', Argument::any())->shouldNotBeCalled(); $queryBuilder->select(Argument::any())->shouldBeCalled()->willReturn($queryBuilder); $queryBuilder->addSelect(Argument::any())->shouldBeCalled()->willReturn($queryBuilder); $queryBuilder->from(Argument::any(), Argument::any())->shouldBeCalled()->willReturn($queryBuilder); $queryBuilder->leftJoin(Argument::any(), Argument::any())->shouldBeCalled()->willReturn($queryBuilder); $queryBuilder->where('product where clause')->shouldBeCalled()->willReturn($queryBuilder); $queryBuilder->andWhere(Argument::any())->shouldNotBeCalled(); $em->createQueryBuilder()->willReturn($queryBuilder); $query->execute()->shouldBeCalled(); $queryBuilder->expr()->willReturn($expr); $queryBuilder->getQuery()->willReturn($query); $this->getFullProducts([42]); }
/** * Get ids of products which are completes and in channel * * @return array */ protected function getIds() { if (!is_object($this->channel)) { $this->channel = $this->channelManager->getChannelByCode($this->channel); } if ($this->missingCompleteness) { $this->completenessManager->generateMissingForChannel($this->channel); } $this->query = $this->DnDBuildByChannelAndCompleteness($this->channel, $this->getIsComplete()); $rootAlias = current($this->query->getRootAliases()); $rootIdExpr = sprintf('%s.id', $rootAlias); $from = current($this->query->getDQLPart('from')); $this->query->select($rootIdExpr)->resetDQLPart('from')->from($from->getFrom(), $from->getAlias(), $rootIdExpr)->andWhere($this->query->expr()->orX($this->query->expr()->gte($from->getAlias() . '.updated', ':updated')))->setParameter('updated', $this->getDateFilter())->setParameter('enabled', $this->getIsEnabled())->groupBy($rootIdExpr); $results = $this->query->getQuery()->getArrayResult(); return array_keys($results); }
/** * Get ids of products which are completes and in channel * * @return array */ protected function getIds() { if (!is_object($this->channel)) { $this->channel = $this->channelManager->getChannelByCode($this->channel); } if ($this->missingCompleteness) { $this->completenessManager->generateMissingForChannel($this->channel); } $this->query = $this->repository->buildByChannelAndCompleteness($this->channel); $rootAlias = current($this->query->getRootAliases()); $rootIdExpr = sprintf('%s.id', $rootAlias); $from = current($this->query->getDQLPart('from')); $this->query->select($rootIdExpr)->resetDQLPart('from')->from($from->getFrom(), $from->getAlias(), $rootIdExpr)->groupBy($rootIdExpr); $results = $this->query->getQuery()->getArrayResult(); return array_keys($results); }
/** * @param AbstractQuery $query * * @throws \LogicException * @return int * */ public function cleanByQuery(AbstractQuery $query) { $numCleaned = 0; /** @var SourceInterface $source */ foreach ($query->iterate() as list($source)) { if (!$source instanceof SourceInterface) { throw new \LogicException(sprintf('Invalid iterator given, encountered %s instead of SourceInterface', is_object($source) ? get_class($source) : gettype($source))); } $this->eventDispatcher->dispatch(IoEvents::PRE_CLEAN_SOURCE, new SourceEvent($source)); $this->sourceManager->remove($source); $this->eventDispatcher->dispatch(IoEvents::POST_CLEAN_SOURCE, new SourceEvent($source)); ++$numCleaned; if ($numCleaned % 50 === 0) { $this->sourceManager->flush(); $this->sourceManager->clear(); } } if ($numCleaned > 0) { $this->sourceManager->flush(); $this->sourceManager->clear(); } return $numCleaned; }
public function testFromQuery() { $this->query->expects(self::any())->method('iterate')->willReturn(new ArrayIterator()); self::assertInstanceOf(SimpleBatchIteratorAggregate::class, SimpleBatchIteratorAggregate::fromQuery($this->query, 100)); }
/** * @param AbstractQuery $query */ public function modify(AbstractQuery $query) { $query->setHydrationMode(Query::HYDRATE_SINGLE_SCALAR); }
/** * Clone query * * @param Doctrine\ORM\AbstractQuery $query * @return Doctrine\ORM\AbstractQuery */ protected function cloneQuery(AbstractQuery $query) { $aclAppliedQuery = clone $query; $params = $query->getParameters(); $aclAppliedQuery->setParameters($params); return $aclAppliedQuery; }
/** * {@inheritdoc} */ protected function getHash() { return sha1(parent::getHash() . '-' . $this->_firstResult . '-' . $this->_maxResults); }
/** * {@inheritdoc} */ public function walkInstanceOfExpression($instanceOfExpr) { $sql = ''; $dqlAlias = $instanceOfExpr->identificationVariable; $discrClass = $class = $this->queryComponents[$dqlAlias]['metadata']; if ($class->discriminatorColumn) { $discrClass = $this->em->getClassMetadata($class->rootEntityName); } if ($this->useSqlTableAliases) { $sql .= $this->getSQLTableAlias($discrClass->getTableName(), $dqlAlias) . '.'; } $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN '); $sqlParameterList = array(); foreach ($instanceOfExpr->value as $parameter) { if ($parameter instanceof AST\InputParameter) { // We need to modify the parameter value to be its correspondent mapped value $dqlParamKey = $parameter->name; $dqlParam = $this->query->getParameter($dqlParamKey); $paramValue = $this->query->processParameterValue($dqlParam->getValue()); if (!$paramValue instanceof \Doctrine\ORM\Mapping\ClassMetadata) { throw QueryException::invalidParameterType('ClassMetadata', get_class($paramValue)); } $entityClassName = $paramValue->name; } else { // Get name from ClassMetadata to resolve aliases. $entityClassName = $this->em->getClassMetadata($parameter)->name; } if ($entityClassName == $class->name) { $sqlParameterList[] = $this->conn->quote($class->discriminatorValue); } else { $discrMap = array_flip($class->discriminatorMap); if (!isset($discrMap[$entityClassName])) { throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName); } $sqlParameterList[] = $this->conn->quote($discrMap[$entityClassName]); } } $sql .= '(' . implode(', ', $sqlParameterList) . ')'; return $sql; }
/** * Deep clone of all expression objects in the SQL parts. * * @return void */ public function __clone() { parent::__clone(); $this->qb = clone $this->qb; }
public function it_caches_query_for_given_time(AbstractQuery $query) { $query->setResultCacheLifetime($this->lifetime)->shouldBeCalled(); $this->modify($query); }
/** * @return ArrayIterator */ public function getIterator() { return $this->iterator ? $this->iterator : ($this->iterator = new ArrayIterator($this->query->getResult($this->options['hydrationMode']))); }
/** * @param AbstractQuery $query */ public function modify(AbstractQuery $query) { $query->setResultCacheLifetime($this->cacheLifetime); }
function it_sets_hydration_mode_to_array(AbstractQuery $query) { $query->setHydrationMode(Query::HYDRATE_ARRAY)->shouldBeCalled(); $this->modify($query); }
/** * {@inheritdoc} */ public function walkInputParameter($inputParam) { $this->parserResult->addParameterMapping($inputParam->name, $this->sqlParamIndex++); $parameter = $this->query->getParameter($inputParam->name); if ($parameter && Type::hasType($type = $parameter->getType())) { return Type::getType($type)->convertToDatabaseValueSQL('?', $this->platform); } return '?'; }
/** * {@inheritdoc} */ public function walkSelectExpression($selectExpression) { $sql = ''; $expr = $selectExpression->expression; $hidden = $selectExpression->hiddenAliasResultVariable; switch (true) { case $expr instanceof AST\PathExpression: if ($expr->type !== AST\PathExpression::TYPE_STATE_FIELD) { throw QueryException::invalidPathExpression($expr); } $fieldName = $expr->field; $dqlAlias = $expr->identificationVariable; $qComp = $this->queryComponents[$dqlAlias]; $class = $qComp['metadata']; $resultAlias = $selectExpression->fieldIdentificationVariable ?: $fieldName; $tableName = $class->isInheritanceTypeJoined() ? $this->em->getUnitOfWork()->getEntityPersister($class->name)->getOwningTable($fieldName) : $class->getTableName(); $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias); $columnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform); $columnAlias = $this->getSQLColumnAlias($class->fieldMappings[$fieldName]['columnName']); $col = $sqlTableAlias . '.' . $columnName; $fieldType = $class->getTypeOfField($fieldName); if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) { $type = Type::getType($fieldType); $col = $type->convertToPHPValueSQL($col, $this->conn->getDatabasePlatform()); } $sql .= $col . ' AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias] = $columnAlias; if (!$hidden) { $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType); $this->scalarFields[$dqlAlias][$fieldName] = $columnAlias; } break; case $expr instanceof AST\AggregateExpression: case $expr instanceof AST\Functions\FunctionNode: case $expr instanceof AST\SimpleArithmeticExpression: case $expr instanceof AST\ArithmeticTerm: case $expr instanceof AST\ArithmeticFactor: case $expr instanceof AST\ParenthesisExpression: case $expr instanceof AST\Literal: case $expr instanceof AST\NullIfExpression: case $expr instanceof AST\CoalesceExpression: case $expr instanceof AST\GeneralCaseExpression: case $expr instanceof AST\SimpleCaseExpression: $columnAlias = $this->getSQLColumnAlias('sclr'); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; $sql .= $expr->dispatch($this) . ' AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias] = $columnAlias; if (!$hidden) { // We cannot resolve field type here; assume 'string'. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string'); } break; case $expr instanceof AST\Subselect: $columnAlias = $this->getSQLColumnAlias('sclr'); $resultAlias = $selectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; $sql .= '(' . $this->walkSubselect($expr) . ') AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias] = $columnAlias; if (!$hidden) { // We cannot resolve field type here; assume 'string'. $this->rsm->addScalarResult($columnAlias, $resultAlias, 'string'); } break; case $expr instanceof AST\NewObjectExpression: $sql .= $this->walkNewObject($expr); break; default: // IdentificationVariable or PartialObjectExpression if ($expr instanceof AST\PartialObjectExpression) { $dqlAlias = $expr->identificationVariable; $partialFieldSet = $expr->partialFieldSet; } else { $dqlAlias = $expr; $partialFieldSet = array(); } $queryComp = $this->queryComponents[$dqlAlias]; $class = $queryComp['metadata']; $resultAlias = $selectExpression->fieldIdentificationVariable ?: null; if (!isset($this->selectedClasses[$dqlAlias])) { $this->selectedClasses[$dqlAlias] = array('class' => $class, 'dqlAlias' => $dqlAlias, 'resultAlias' => $resultAlias); } $sqlParts = array(); // Select all fields from the queried class foreach ($class->fieldMappings as $fieldName => $mapping) { if ($partialFieldSet && !in_array($fieldName, $partialFieldSet)) { continue; } $tableName = isset($mapping['inherited']) ? $this->em->getClassMetadata($mapping['inherited'])->getTableName() : $class->getTableName(); $sqlTableAlias = $this->getSQLTableAlias($tableName, $dqlAlias); $columnAlias = $this->getSQLColumnAlias($mapping['columnName']); $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $class, $this->platform); $col = $sqlTableAlias . '.' . $quotedColumnName; if (isset($class->fieldMappings[$fieldName]['requireSQLConversion'])) { $type = Type::getType($class->getTypeOfField($fieldName)); $col = $type->convertToPHPValueSQL($col, $this->platform); } $sqlParts[] = $col . ' AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias][] = $columnAlias; $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $class->name); } // Add any additional fields of subclasses (excluding inherited fields) // 1) on Single Table Inheritance: always, since its marginal overhead // 2) on Class Table Inheritance only if partial objects are disallowed, // since it requires outer joining subtables. if ($class->isInheritanceTypeSingleTable() || !$this->query->getHint(Query::HINT_FORCE_PARTIAL_LOAD)) { foreach ($class->subClasses as $subClassName) { $subClass = $this->em->getClassMetadata($subClassName); $sqlTableAlias = $this->getSQLTableAlias($subClass->getTableName(), $dqlAlias); foreach ($subClass->fieldMappings as $fieldName => $mapping) { if (isset($mapping['inherited']) || $partialFieldSet && !in_array($fieldName, $partialFieldSet)) { continue; } $columnAlias = $this->getSQLColumnAlias($mapping['columnName']); $quotedColumnName = $this->quoteStrategy->getColumnName($fieldName, $subClass, $this->platform); $col = $sqlTableAlias . '.' . $quotedColumnName; if (isset($subClass->fieldMappings[$fieldName]['requireSQLConversion'])) { $type = Type::getType($subClass->getTypeOfField($fieldName)); $col = $type->convertToPHPValueSQL($col, $this->platform); } $sqlParts[] = $col . ' AS ' . $columnAlias; $this->scalarResultAliasMap[$resultAlias][] = $columnAlias; $this->rsm->addFieldResult($dqlAlias, $columnAlias, $fieldName, $subClassName); } } } $sql .= implode(', ', $sqlParts); } return $sql; }
/** * {@inheritdoc} */ public function setHydrationMode($hydrationMode) { $this->_state = self::STATE_DIRTY; return parent::setHydrationMode($hydrationMode); }
function it_sets_hydration_mode_to_object(AbstractQuery $query) { $query->setHydrationMode(Query::HYDRATE_SINGLE_SCALAR)->shouldBeCalled(); $this->modify($query); }
/** * {@inheritdoc} */ public function walkSubselectFromClause($subselectFromClause) { $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations; $sqlParts = array(); foreach ($identificationVarDecls as $subselectIdVarDecl) { $sql = $this->platform->appendLockHint($this->walkRangeVariableDeclaration($subselectIdVarDecl->rangeVariableDeclaration), $this->query->getHint(Query::HINT_LOCK_MODE)); foreach ($subselectIdVarDecl->joins as $join) { $sql .= $this->walkJoin($join); } $sqlParts[] = $sql; } return ' FROM ' . implode(', ', $sqlParts); }
/** * @override */ public function free() { parent::free(); $this->_dql = null; $this->_state = self::STATE_CLEAN; }
/** * Cleanup Query resource when clone is called. * * @return void */ public function __clone() { parent::__clone(); $this->_state = self::STATE_DIRTY; }
/** * @param AbstractQuery $query */ public function modify(AbstractQuery $query) { $query->setHydrationMode(Query::HYDRATE_ARRAY); }