/** * @return Connection */ public function getConnection() { /** @var Connection $con */ $con = $this->em->getConnection(); $con = $this->pingIt($con); return $con; }
/** * Creates and persists a unique shortcode generated for provided url * * @param UriInterface $url * @param string[] $tags * @return string * @throws InvalidUrlException * @throws RuntimeException */ public function urlToShortCode(UriInterface $url, array $tags = []) { // If the url already exists in the database, just return its short code $shortUrl = $this->em->getRepository(ShortUrl::class)->findOneBy(['originalUrl' => $url]); if (isset($shortUrl)) { return $shortUrl->getShortCode(); } // Check that the URL exists $this->checkUrlExists($url); // Transactionally insert the short url, then generate the short code and finally update the short code try { $this->em->beginTransaction(); // First, create the short URL with an empty short code $shortUrl = new ShortUrl(); $shortUrl->setOriginalUrl($url); $this->em->persist($shortUrl); $this->em->flush(); // Generate the short code and persist it $shortCode = $this->convertAutoincrementIdToShortCode($shortUrl->getId()); $shortUrl->setShortCode($shortCode)->setTags($this->tagNamesToEntities($this->em, $tags)); $this->em->flush(); $this->em->commit(); return $shortCode; } catch (ORMException $e) { if ($this->em->getConnection()->isTransactionActive()) { $this->em->rollback(); $this->em->close(); } throw new RuntimeException('An error occurred while persisting the short URL', -1, $e); } }
public function execute() { $criteria = new Criteria(['owner' => $this->user], null, null, null); $items = $this->basketRepository->findByCriteria($criteria); $order = $this->orderRepository->findActive(); $connection = $this->entityManager->getConnection(); $connection->beginTransaction(); try { $orderItems = []; foreach ($items as $item) { /** @var Basket $item */ $previousOrderItem = $this->orderItemRepository->findOneByCriteria(new Criteria(['owner' => $item->getOwner(), 'product' => $item->getProduct()])); if ($previousOrderItem) { /** @var OrderItem $orderItem */ $orderItem = $previousOrderItem; $orderItem->increaseQuantityBy($item->getQuantity()); } else { $orderItem = OrderItem::createFromBasket($item, $order); } $this->entityManager->persist($orderItem); $this->entityManager->remove($item); $orderItems[] = $orderItem; } $this->entityManager->flush(); $connection->commit(); } catch (\Exception $e) { $connection->rollBack(); return $e->getMessage(); } }
/** * @BeforeScenario */ public function purgeDatabase() { $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); $purger = new ORMPurger($this->entityManager); $purger->purge(); $this->entityManager->clear(); }
/** * @param Url $url * @return Url|object * @throws \Doctrine\DBAL\ConnectionException * @throws \Exception */ public function encode(Url $url) { $this->em->beginTransaction(); try { $urlRepository = $this->em->getRepository('Rz\\Bundle\\UrlShortenerBundle\\Entity\\Url'); $entity = $urlRepository->findOneBy(['url' => $url->getUrl()]); if ($entity) { /** @var Url $url */ $url = $entity; } else { $url->setNew(true); $this->em->persist($url); $this->em->flush(); $url->setCode($this->encoder->encode($url->getId())); $params = ['code' => $url->getCode()]; if (!$url->isDefaultSequence()) { $params['index'] = $url->getSequence(); } $url->setShortUrl($this->router->generate(UrlShortenerBundle::URL_GO, $params, UrlGeneratorInterface::ABSOLUTE_URL)); $this->em->persist($url); $this->em->flush(); } $this->em->getConnection()->commit(); return $url; } catch (\Exception $e) { $this->em->getConnection()->rollBack(); throw $e; } }
private function purgeUsingCachedQueries() { $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); foreach ($this->cachedQueries as $cachedQuery) { $this->entityManager->getConnection()->executeUpdate($cachedQuery['sql'], $cachedQuery['params'], $cachedQuery['types']); } }
/** * Load country data * * @param string $countryIso Country iso * * @return $this Self object */ public function loadCountry($countryIso) { $content = $this->locationLoaderAdapter->getSqlForCountry($countryIso); $statement = $this->locationEntityManager->getConnection()->prepare($content); $statement->execute(); return $this; }
protected function tearDown() { //Close & unsets if (is_object($this->em)) { $this->em->getConnection()->close(); $this->em->close(); } unset($this->em); unset($this->container); unset($this->kern); unset($this->client); //Nettoyage des mocks //http://kriswallsmith.net/post/18029585104/faster-phpunit $refl = new \ReflectionObject($this); foreach ($refl->getProperties() as $prop) { if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) { $prop->setAccessible(true); $prop->setValue($this, null); } } //Nettoyage du garbage if (!gc_enabled()) { gc_enable(); } gc_collect_cycles(); //Parent parent::tearDown(); }
/** * Executes given sql file * * @param string $path * @throws \Doctrine\DBAL\DBALException * @throws \Exception */ private function executeSqlFile($path) { if (!file_exists($path)) { throw new \Exception(sprintf('SQL file does not exist: %s', $path)); } $databaseSchema = file_get_contents($path); $this->entityManager->getConnection()->exec($databaseSchema); }
/** * @BeforeScenario */ public function purgeDatabase() { if (null === $this->entityManager) { throw new \RuntimeException('Cannot purge database. Entity manager is not set'); } $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); $purger = new ORMPurger($this->entityManager); $purger->purge(); $this->entityManager->clear(); }
/** * Defer task. * * @param int $pid * @param callable $deferrer * * @return $this */ public function defer($pid, $deferrer) { $connection = $this->entityManager->getConnection(); $this->entity->setPid($pid); $this->entityManager->flush(); $connection->close(); $exitCode = $deferrer(); $connection->connect(); $this->entity->setExitCode($exitCode); $this->entityManager->flush(); return $this; }
/** * @param EntityManager $em * @param Cache $cache * @param CacheHitsContainer $hitsContainer */ public function __construct(EntityManagerInterface $em, Cache $cache, CacheHitsContainer $hitsContainer) { $this->em = $em; $this->connection = $em->getConnection(); $this->cache = $cache; $this->hitsContainer = $hitsContainer; }
/** * @param EntityManagerInterface $em */ public function __construct(EntityManagerInterface $em) { $params = $em->getConnection()->getParams(); $dsn = "mysql:host={$params['host']};dbname={$params['dbname']}"; $this->pdo = new PDO($dsn, $params['user'], $params['password']); $this->pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL); }
/** * @return Platforms\AbstractPlatform */ private function getTargetPlatform() { if (!$this->targetPlatform) { $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform(); } return $this->targetPlatform; }
/** * Gets the sequence of SQL statements that need to be performed in order * to bring the given class mappings in-synch with the relational schema. * If $saveMode is set to true the command is executed in the Database, * else SQL is returned. * * @param array $classes The classes to consider. * @param boolean $saveMode True for writing to DB, false for SQL string. * * @return array The sequence of SQL statements. */ public function getUpdateSchemaSql(array $classes, $saveMode = false) { $sm = $this->em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); $toSchema = $this->getSchemaFromMetadata($classes); foreach ($toSchema->getTables() as $table) { foreach ($table->getColumns() as $column) { if ($column->getAutoincrement()) { continue; } if (!preg_match('/^(?P<column>(?P<table>.*)_id)$/', $column->getName(), $matches)) { continue; } $referencedTable = 'oc_' . $matches['table']; if (!$toSchema->hasTable($referencedTable)) { continue; } if ($toSchema->getTable($referencedTable) === $table) { continue; } $table->addForeignKeyConstraint($toSchema->getTable($referencedTable), [$matches['column']], [$matches['column']]); } } $comparator = new Comparator(); $schemaDiff = $comparator->compare($fromSchema, $toSchema); foreach ($schemaDiff->changedTables as $changedTable) { $changedTable->changedColumns = []; } if ($saveMode) { return $schemaDiff->toSaveSql($this->platform); } return $schemaDiff->toSql($this->platform); }
/** * Adds all fields of the given class to the result set mapping (columns and meta fields). * * @param string $class * @param string $alias * @param array $columnAliasMap * * @return void * * @throws \InvalidArgumentException */ protected function addAllClassFields($class, $alias, $columnAliasMap = array()) { $classMetadata = $this->em->getClassMetadata($class); $platform = $this->em->getConnection()->getDatabasePlatform(); if (!$this->isInheritanceSupported($classMetadata)) { throw new \InvalidArgumentException('ResultSetMapping builder does not currently support your inheritance scheme.'); } foreach ($classMetadata->getColumnNames() as $columnName) { $propertyName = $classMetadata->getFieldName($columnName); $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); if (isset($this->fieldMappings[$columnAlias])) { throw new \InvalidArgumentException("The column '{$columnName}' conflicts with another column in the mapper."); } $this->addFieldResult($alias, $columnAlias, $propertyName); } foreach ($classMetadata->associationMappings as $associationMapping) { if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { $targetClass = $this->em->getClassMetadata($associationMapping['targetEntity']); $isIdentifier = isset($associationMapping['id']) && $associationMapping['id'] === true; foreach ($associationMapping['joinColumns'] as $joinColumn) { $columnName = $joinColumn['name']; $columnAlias = $platform->getSQLResultCasing($columnAliasMap[$columnName]); $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); if (isset($this->metaMappings[$columnAlias])) { throw new \InvalidArgumentException("The column '{$columnAlias}' conflicts with another column in the mapper."); } $this->addMetaResult($alias, $columnAlias, $columnName, $isIdentifier, $columnType); } } } }
/** * Constructor * * @param EntityManagerInterface $manager * @param string $productClass * @param string $productValueClass * @param string $attributeClass */ public function __construct(EntityManagerInterface $manager, $productClass, $productValueClass, $attributeClass) { $this->manager = $manager; $this->connection = $manager->getConnection(); $this->productClass = $productClass; $this->productValueClass = $productValueClass; $this->attributeClass = $attributeClass; }
public function __construct(EntityManagerInterface $entityManager, UserCategory $attributeCategory, Application $application, AvatarServiceInterface $avatarService) { $this->avatarService = $avatarService; $this->application = $application; $this->entityManager = $entityManager; $this->attributeCategory = $attributeCategory; $this->connection = $entityManager->getConnection(); }
/** * Determine if the migration repository exists. * @return bool */ public function repositoryExists() { $schema = $this->em->getConnection()->getSchemaManager(); $tables = array_filter($schema->listTables(), function ($value) { return $value->getName() === 'migrations'; }); return !empty($tables); }
/** * Initializes a new instance of a class derived from AbstractCollectionPersister. * * @param EntityManagerInterface $em */ public function __construct(EntityManagerInterface $em) { $this->em = $em; $this->uow = $em->getUnitOfWork(); $this->conn = $em->getConnection(); $this->platform = $this->conn->getDatabasePlatform(); $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy(); }
/** * Reconnect to mysql. */ private function reconnect() { $connection = $this->entityManager->getConnection(); try { $connection->executeQuery('SELECT 1;'); } catch (DBALException $exc) { $connection->close(); $connection->connect(); } }
public function setUp() { $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('DoctrineExtensions\\Tests\\Proxies'); $config->setAutoGenerateProxyClasses(true); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(__DIR__ . '/../Entities')); $config->setCustomDatetimeFunctions(array('YEAR' => 'DoctrineExtensions\\Query\\Sqlite\\Year', 'WEEKDAY' => 'DoctrineExtensions\\Query\\Sqlite\\WeekDay', 'WEEK' => 'DoctrineExtensions\\Query\\Sqlite\\Week', 'Month' => 'DoctrineExtensions\\Query\\Sqlite\\Month', 'MINUTE' => 'DoctrineExtensions\\Query\\Sqlite\\Minute', 'HOUR' => 'DoctrineExtensions\\Query\\Sqlite\\Hour', 'DAY' => 'DoctrineExtensions\\Query\\Sqlite\\Day', 'DATE' => 'DoctrineExtensions\\Query\\Sqlite\\Date', 'STRFTIME' => 'DoctrineExtensions\\Query\\Sqlite\\StrfTime', 'DATE_FORMAT' => 'DoctrineExtensions\\Query\\Sqlite\\DateFormat')); $this->entityManager = \Doctrine\ORM\EntityManager::create(array('driver' => 'pdo_sqlite', 'memory' => true), $config); $configuration = $this->entityManager->getConfiguration(); if (method_exists($configuration, 'getQuoteStrategy') === false) { // doctrine < 2.3 $this->columnAlias = 'sclr0'; } else { $this->columnAlias = $configuration->getQuoteStrategy()->getColumnAlias('sclr', 0, $this->entityManager->getConnection()->getDatabasePlatform(), $this->entityManager->getClassMetadata('DoctrineExtensions\\Tests\\Entities\\Date')); } }
/** * @param array $selectedIds * @param string $value * * @return int */ protected function finishBatch(array &$selectedIds, $value) { $qBuilder = $this->entityManager->createQueryBuilder(); $entitiesCount = $qBuilder->update($this->entityName, 'e')->set('e.' . $this->fieldName, ':value')->where($qBuilder->expr()->in('e.' . $this->identifierName, $selectedIds))->getQuery()->setParameter('value', $value)->execute(); $this->entityManager->flush(); if ($this->entityManager->getConnection()->getTransactionNestingLevel() == 1) { $this->entityManager->clear(); } $selectedIds = []; return $entitiesCount; }
/** * Gets the sequence of SQL statements that need to be performed in order * to bring the given class mappings in-synch with the relational schema. * If $saveMode is set to true the command is executed in the Database, * else SQL is returned. * * @param array $classes The classes to consider. * @param boolean $saveMode True for writing to DB, false for SQL string. * * @return array The sequence of SQL statements. */ public function getUpdateSchemaSql(array $classes, $saveMode = false) { $sm = $this->em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); $toSchema = $this->getSchemaFromMetadata($classes); $comparator = new Comparator(); $schemaDiff = $comparator->compare($fromSchema, $toSchema); if ($saveMode) { return $schemaDiff->toSaveSql($this->platform); } return $schemaDiff->toSql($this->platform); }
public function getEntityHistory($className, $id) { if (!$this->metadataFactory->isAudited($className)) { throw new NotAuditedException($className); } /** @var ClassMetadataInfo|ClassMetadata $class */ $class = $this->em->getClassMetadata($className); $tableName = $this->config->getTableName($class); if (!is_array($id)) { $id = array($class->identifier[0] => $id); } $whereId = array(); foreach ($class->identifier as $idField) { if (isset($class->fieldMappings[$idField])) { $columnName = $class->fieldMappings[$idField]['columnName']; } else { if (isset($class->associationMappings[$idField])) { $columnName = $class->associationMappings[$idField]['joinColumns'][0]; } else { continue; } } $whereId[] = "{$columnName} = ?"; } $whereSQL = implode(' AND ', $whereId); $columnList = array($this->config->getRevisionFieldName()); $columnMap = array(); foreach ($class->fieldNames as $columnName => $field) { $type = Type::getType($class->fieldMappings[$field]['type']); $columnList[] = $type->convertToPHPValueSQL($class->getQuotedColumnName($field, $this->platform), $this->platform) . ' AS ' . $this->platform->quoteSingleIdentifier($field); $columnMap[$field] = $this->platform->getSQLResultCasing($columnName); } foreach ($class->associationMappings as $assoc) { if (($assoc['type'] & ClassMetadata::TO_ONE) == 0 || !$assoc['isOwningSide']) { continue; } foreach ($assoc['targetToSourceKeyColumns'] as $sourceCol) { $columnList[] = $sourceCol; $columnMap[$sourceCol] = $this->platform->getSQLResultCasing($sourceCol); } } $values = array_values($id); $query = "SELECT " . implode(', ', $columnList) . " FROM " . $tableName . " e WHERE " . $whereSQL . " ORDER BY e.rev DESC"; $stmt = $this->em->getConnection()->executeQuery($query, $values); $result = array(); while ($row = $stmt->fetch(Query::HYDRATE_ARRAY)) { $rev = $row[$this->config->getRevisionFieldName()]; unset($row[$this->config->getRevisionFieldName()]); $result[] = $this->createEntity($class->name, $row, $rev); } return $result; }
function it_executes_cached_queries_after_the_first_purging(PurgerInterface $purger, EntityManagerInterface $entityManager, QueryLoggerInterface $queryLogger, Connection $connection, Configuration $configuration) { $entityManager->getConnection()->willReturn($connection); $connection->getConfiguration()->willReturn($configuration); $configuration->setSQLLogger($queryLogger)->shouldBeCalled(); $purger->purge()->shouldBeCalled(); $queryLogger->getLoggedQueries()->willReturn([['sql' => 'SQL QUERY', 'params' => [], 'types' => []]]); $queryLogger->clearLoggedQueries()->shouldBeCalled(); $this->purge(); $configuration->setSQLLogger(null)->shouldBeCalled(); $connection->executeUpdate('SQL QUERY', [], [])->shouldBeCalled(); $this->purge(); }
/** * Selects a celestial body that should be used for a new player. * * @todo could use a better algorithm. Maybe place new players in areas that * are not too densly populated. * Or place them among other players just having started playing. * Currently, we simply take any celestial body that doesn't yet have * an owner. * * @return \common\models\TerrestrialPlanet */ public function getTerrestrialPlanetForNewPlayer() { $celestialBodyEntity = $this->celestialBodyRepository->findForNewPlayer(); if ($celestialBodyEntity instanceof TerrestrialPlanetEntity) { $terrestrialPlanetEntity = $celestialBodyEntity; } else { $this->em->detach($celestialBodyEntity); // This is the bad part. // Maybe there's a better alternative? $discrTerrestrialPlanet = CelestialBodyEntity::DISCR_TERRESTRIAL_PLANET; $query = "UPDATE celestialbody SET discr = {$discrTerrestrialPlanet} WHERE id = {$celestialBodyEntity->getId()}"; $this->em->getConnection()->exec($query); // this is now a terrestrial planet $terrestrialPlanetEntity = $this->celestialBodyRepository->find($celestialBodyEntity->getId()); } $terrestrialPlanetModel = CelestialBodyFactory::create($terrestrialPlanetEntity, $this->celestialBodySpecialtyRepository); $terrestrialPlanetModel->reset(); return $terrestrialPlanetModel; }
/** * @param string $mySqlQuery * @param string $postgreSqlQuery * @param EntityManagerInterface|ObjectManager $manager */ protected function runQuery($mySqlQuery, $postgreSqlQuery, EntityManagerInterface $manager) { /** @var Connection $conn */ $conn = $manager->getConnection(); $platformName = $conn->getDatabasePlatform()->getName(); $query = null; if ($platformName === DatabasePlatformInterface::DATABASE_MYSQL) { $query = $mySqlQuery; } elseif ($platformName === DatabasePlatformInterface::DATABASE_POSTGRESQL) { $query = $postgreSqlQuery; } else { return; } try { $conn->beginTransaction(); $conn->exec($query); $conn->commit(); } catch (\Exception $e) { $conn->rollBack(); } }
/** * Returns the database connection used by the entity manager * * @return \Doctrine\DBAL\Connection */ protected final function getConnection() { return $this->em->getConnection(); }
/** * Acquire a lock on the given entity. * * @param object $entity * @param int $lockMode * @param int $lockVersion * * @return void * * @throws ORMInvalidArgumentException * @throws TransactionRequiredException * @throws OptimisticLockException */ public function lock($entity, $lockMode, $lockVersion = null) { if ($entity === null) { throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock()."); } if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) { throw ORMInvalidArgumentException::entityNotManaged($entity); } $class = $this->em->getClassMetadata(get_class($entity)); switch (true) { case LockMode::OPTIMISTIC === $lockMode: if (!$class->isVersioned) { throw OptimisticLockException::notVersioned($class->name); } if ($lockVersion === null) { return; } if ($entity instanceof Proxy && !$entity->__isInitialized__) { $entity->__load(); } $entityVersion = $class->reflFields[$class->versionField]->getValue($entity); if ($entityVersion != $lockVersion) { throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion); } break; case LockMode::NONE === $lockMode: case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: if (!$this->em->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } $oid = spl_object_hash($entity); $this->getEntityPersister($class->name)->lock(array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]), $lockMode); break; default: // Do nothing } }