public function __construct(EntityManager $enm, Writer $logger) { $this->evm = $enm->getEventManager(); //Unused, for now $this->enm = $enm; $this->logger = $logger; $this->connection = $enm->getConnection(); $enm->getConnection()->getConfiguration()->setSQLLogger($this); }
/** * @param LoadClassMetadataEventArgs $args */ public function loadClassMetadata(LoadClassMetadataEventArgs $args) { $this->em = $args->getEntityManager(); $this->meta = $args->getClassMetadata(); if (!$this->em->getConnection()->getWrappedConnection() instanceof AbstractConnection) { return; } if ($this->meta->customPersisterClassName === null) { $this->meta->setCustomPersisterClass(EntityPersister::class); } $this->markIndex(); foreach ($this->meta->fieldMappings as $property => &$mapping) { $this->remapIdentifier($property, $mapping); $this->remapVersion($property, $mapping); $this->markField($property, $mapping); } foreach ($this->meta->associationMappings as $property => &$mapping) { $this->remapAnyToOneAssociation($property, $mapping); $this->remapAnyToManyAssociation($property, $mapping); $this->remapManyToManyAssociation($property, $mapping); } if ($cache = $this->em->getMetadataFactory()->getCacheDriver()) { $cache->save($this->meta->name . '$CLASSMETADATA', $this->meta, null); } }
public function __construct(EntityManager $em, $defaultRenameMode = Doctrine\ORM\Query\ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT) { parent::__construct($em, $defaultRenameMode); $this->em = $em; $this->platform = $this->em->getConnection()->getDatabasePlatform(); $this->defaultRenameMode = $defaultRenameMode; }
public function getJobStatistics(Job $job) { $statisticData = array(); $dataPerCharacteristic = array(); $statistics = $this->em->getConnection()->query("SELECT * FROM jms_job_statistics WHERE job_id = " . $job->getId()); foreach ($statistics as $row) { $dataPerCharacteristic[$row['characteristic']][] = array($row['createdAt'], $row['charValue']); } if ($dataPerCharacteristic) { $statisticData = array(array_merge(array('Time'), $chars = array_keys($dataPerCharacteristic))); $startTime = strtotime($dataPerCharacteristic[$chars[0]][0][0]); $endTime = strtotime($dataPerCharacteristic[$chars[0]][count($dataPerCharacteristic[$chars[0]]) - 1][0]); $scaleFactor = $endTime - $startTime > 300 ? 1 / 60 : 1; // This assumes that we have the same number of rows for each characteristic. for ($i = 0, $c = count(reset($dataPerCharacteristic)); $i < $c; $i++) { $row = array((strtotime($dataPerCharacteristic[$chars[0]][$i][0]) - $startTime) * $scaleFactor); foreach ($chars as $name) { $value = (double) $dataPerCharacteristic[$name][$i][1]; switch ($name) { case 'memory': $value /= 1024 * 1024; break; } $row[] = $value; } $statisticData[] = $row; } } return $statisticData; }
/** * @param string $documentClass The type the provider is for * @param DocumentMetadataCollection $metadata The metadata collection for all ES types * @param EntityManager $em The Doctrine entity manager */ public function __construct($documentClass, DocumentMetadataCollection $metadata, EntityManager $em) { parent::__construct($documentClass, $metadata); $this->em = $em; // TODO: Doesn't seem to do anything, but just in case... $this->em->getConnection()->getConfiguration()->setSQLLogger(null); }
/** * {@inheritDoc}. */ protected function initialize() { $this->driver = $this->em->getConfiguration()->getMetadataDriverImpl(); $this->targetPlatform = $this->em->getConnection()->getDatabasePlatform(); $this->evm = $this->em->getEventManager(); $this->initialized = true; }
/** * Update configurable delta export. * * @param Channel $channel * @param JobInstance $jobInstance * @param string $identifier */ public function setLastExportDate(Channel $channel, JobInstance $jobInstance, $identifier) { $variantGroup = $this->groupRepository->findOneBy(['code' => $identifier]); if ($variantGroup) { $deltaConfigurableTable = $this->tableNameBuilder->getTableName('pim_magento_connector.entity.delta_configurable_export.class'); $exportableProducts = $this->productFilter->apply($channel, $variantGroup->getProducts()); foreach ($exportableProducts as $product) { $sql = <<<SQL INSERT INTO {$deltaConfigurableTable} (product_id, job_instance_id, last_export) VALUES (:product_id, :job_instance_id, :last_export) ON DUPLICATE KEY UPDATE last_export = :last_export SQL; $connection = $this->em->getConnection(); $query = $connection->prepare($sql); $now = new \DateTime('now', new \DateTimeZone('UTC')); $lastExport = $now->format('Y-m-d H:i:s'); $productId = $product->getId(); $jobInstanceId = $jobInstance->getId(); $query->bindParam(':last_export', $lastExport, PDO::PARAM_STR); $query->bindParam(':product_id', $productId, PDO::PARAM_INT); $query->bindParam(':job_instance_id', $jobInstanceId, PDO::PARAM_INT); $query->execute(); } } }
/** * @throws \Doctrine\ORM\ORMException */ public function boot() { $this->serializer = SerializerBuilder::create()->setDebug($this->devMode)->build(); $this->entityFolder->create(); AnnotationRegistry::registerAutoloadNamespace('JMS\\Serializer\\Annotation', __DIR__ . '/../../../../vendor/jms/serializer/src'); $proxyDoctrineFolder = new Folder(sys_get_temp_dir() . '/doctrine'); $config = Setup::createAnnotationMetadataConfiguration([$this->entityFolder->absolute()], $this->isDevMode(), $proxyDoctrineFolder->absolute()); if ($this->cache !== null) { $config->setQueryCacheImpl($this->getCache()); $config->setResultCacheImpl($this->getCache()); } $this->entityManager = $this->createEntityManager($config); $debugStack = new DebugStack(); $this->entityManager->getConnection()->getConfiguration()->setSQLLogger($debugStack); if ($this->getFileCreation()->getContent() == 1) { return; } if ($proxyDoctrineFolder->isFolder()) { $proxyDoctrineFolder->removeFiles(); } $tool = new SchemaTool($this->entityManager); $metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata(); $proxyDoctrineFolder->create(); $this->entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxyDoctrineFolder->absolute()); if ($this->cloudFoundryBoot->isInCloudFoundry()) { $tool->updateSchema($metadatas); } else { $tool->createSchema($metadatas); } $this->getFileCreation()->setContent(1); }
/** * {@inheritdoc} */ public function getProductCountByTree(ProductInterface $product) { $categories = $product->getCategories(); $categoryIds = array(); foreach ($categories as $category) { $categoryIds[] = $category->getId(); } $categoryRepository = $this->entityManager->getRepository($this->categoryClass); $categoryTable = $this->entityManager->getClassMetadata($this->categoryClass)->getTableName(); $categoryIds = implode(',', $categoryIds); if (!empty($categoryIds)) { $sql = "SELECT" . " tree.id AS tree_id," . " COUNT(category.id) AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " AND category.id IN ({$categoryIds})" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id"; } else { $sql = "SELECT" . " tree.id AS tree_id," . " '0' AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id"; } $stmt = $this->entityManager->getConnection()->prepare($sql); $stmt->execute(); $productCounts = $stmt->fetchAll(); $trees = array(); foreach ($productCounts as $productCount) { $tree = array(); $tree['productCount'] = $productCount['product_count']; $tree['tree'] = $categoryRepository->find($productCount['tree_id']); $trees[] = $tree; } return $trees; }
/** * Adds all fields of the given class to the result set mapping (columns and meta fields) */ protected function addAllClassFields($class, $alias, $renamedColumns = array()) { $classMetadata = $this->em->getClassMetadata($class); if ($classMetadata->isInheritanceTypeSingleTable() || $classMetadata->isInheritanceTypeJoined()) { throw new \InvalidArgumentException('ResultSetMapping builder does not currently support inheritance.'); } $platform = $this->em->getConnection()->getDatabasePlatform(); foreach ($classMetadata->getColumnNames() as $columnName) { $propertyName = $classMetadata->getFieldName($columnName); if (isset($renamedColumns[$columnName])) { $columnName = $renamedColumns[$columnName]; } $columnName = $platform->getSQLResultCasing($columnName); if (isset($this->fieldMappings[$columnName])) { throw new \InvalidArgumentException("The column '{$columnName}' conflicts with another column in the mapper."); } $this->addFieldResult($alias, $columnName, $propertyName); } foreach ($classMetadata->associationMappings as $associationMapping) { if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { foreach ($associationMapping['joinColumns'] as $joinColumn) { $columnName = $joinColumn['name']; $renamedColumnName = isset($renamedColumns[$columnName]) ? $renamedColumns[$columnName] : $columnName; $renamedColumnName = $platform->getSQLResultCasing($renamedColumnName); if (isset($this->metaMappings[$renamedColumnName])) { throw new \InvalidArgumentException("The column '{$renamedColumnName}' conflicts with another column in the mapper."); } $this->addMetaResult($alias, $renamedColumnName, $columnName); } } } }
public function __construct($setConfigFiles = true) { if ($setConfigFiles) { $this->configFile = __DIR__ . '/../../../config.php'; $this->localConfigFile = __DIR__ . '/../../../config.local.php'; } parent::__construct(); $isDevMode = false; $cache = new \Doctrine\Common\Cache\FilesystemCache(__DIR__ . '/../../tmp'); $config = Setup::createConfiguration($isDevMode, __DIR__ . '/../../tmp', $cache); $config->setProxyDir(__DIR__ . '/../../tmp'); $config->setProxyNamespace('MyProject\\Proxies'); $config->setAutoGenerateProxyClasses(true); $paths = [__DIR__ . '/../Entity']; $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(new AnnotationReader(), $paths); \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists'); $config->setMetadataDriverImpl($driver); //$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); $conn = ['driver' => 'mysqli', 'host' => '127.0.0.1', 'user' => $this->databaseFactory->getUserName(), 'password' => $this->databaseFactory->getPassword(), 'dbname' => $this->databaseFactory->getDatabaseName()]; $this->entityManager = EntityManager::create($conn, $config); $this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); \Doctrine\DBAL\Types\Type::addType('enum', StringType::class); $this->entityManager->getConfiguration()->addCustomStringFunction('DATE', DateFunction::class); $this->user = $this->entityManager->createQueryBuilder()->select('u')->from(Sources\Tests\Entity\User::class, 'u'); }
/** * Build an sql insert into query by the paramters provided * @param ORM\Entity $entities Result array with all entities to create an insert for * @param string $entityClassName Class of the specified entity (same as entities) * @param array $ignoreFields fields not to use in the insert query * @return string an insert sql query, of no result nul */ public function buildInsertSql($entities, $entityClassName, $ignoreFields = array()) { if (count($entities) <= 0) { return null; } $fieldNames = $this->entityManager->getClassMetadata($entityClassName)->getFieldNames(); $tableName = $this->entityManager->getClassMetadata($entityClassName)->getTableName(); $tableName = $this->entityManager->getConnection()->quoteIdentifier($tableName); $fieldNames = array_diff($fieldNames, $ignoreFields); $values = array(); foreach ($entities as $entity) { $insertValues = array(); foreach ($fieldNames as $fieldName) { $value = $entity->{'get' . $fieldName}(); if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } $insertValues[] = $this->entityManager->getConnection()->quote($value); } $values[] = '(' . implode(',', $insertValues) . ')'; } foreach ($fieldNames as $key => $fieldName) { $columnName = $this->entityManager->getClassMetadata($entityClassName)->getColumnName($fieldName); $fieldNames[$key] = $this->entityManager->getConnection()->quoteIdentifier($columnName); } $sql = sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, implode(",", $fieldNames), implode(', ', $values)); return $sql; }
private function getDatabaseName() { if (null === $this->database) { $this->database = $this->entityManager->getConnection()->getDatabase(); } return $this->database; }
/** * Finish processed batch */ protected function finishBatch() { $this->entityManager->flush(); if ($this->entityManager->getConnection()->getTransactionNestingLevel() == 1) { $this->entityManager->clear(); } }
protected function setUp() { $pathToEntities = [__DIR__ . '/Entity']; $isDevMode = true; $connectionParams = array('user' => 'user', 'password' => 'password', 'driver' => 'pdo_sqlite', 'memory' => true); $config = Setup::createConfiguration($isDevMode); $driver = new AnnotationDriver(new AnnotationReader(), $pathToEntities); AnnotationRegistry::registerLoader('class_exists'); $config->setMetadataDriverImpl($driver); $this->em = EntityManager::create($connectionParams, $config); /* * Устанавливаем фикстуры, знаю что можно это сделать более универсально, но ... в данном контексте мне больше и не надо */ $conn = $this->em->getConnection(); $conn->exec("CREATE TABLE clients (id INTEGER PRIMARY KEY, name TEXT, surname TEXT);"); $conn->exec("CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT, surname TEXT);"); $conn->exec("CREATE TABLE books (id INTEGER, owner_id INTEGER, name TEXT, surname TEXT, CONSTRAINT 'pk' PRIMARY KEY (id, owner_id));"); $conn->exec("INSERT INTO clients (name,surname) VALUES('Nikita','Sapogov')"); $conn->exec("INSERT INTO clients (name,surname) VALUES('Alex','Ivanov')"); $conn->exec("INSERT INTO clients (name,surname) VALUES('Sura','Soir')"); $conn->exec("INSERT INTO clients (name,surname) VALUES('Vasya','Poliakocv')"); $conn->exec("INSERT INTO books (id, owner_id, name) VALUES (1,1,'SuperBookNAme')"); $conn->exec("INSERT INTO books (id, owner_id, name) VALUES (2,15,'SuperBookNAme2')"); $conn->exec("INSERT INTO books (id, owner_id, name) VALUES (3,3,'SuperBookNAme3')"); }
/** * Rollback current transaction * @return none */ public static function rollbackTransaction() { if (self::$_entityManager != NULL) { $conn = self::$_entityManager->getConnection(); $conn->rollback(); } }
public function hydrateEntity($entity, array $values) { $classMetadata = $this->em->getClassMetadata(get_class($entity)); foreach ($values as $fieldName => $value) { if ($classMetadata->hasField($fieldName)) { $fieldMappping = $classMetadata->getFieldMapping($fieldName); if (null === $fieldMappping) { throw new HydrationException($fieldName); } $type = Type::getType($classMetadata->fieldMappings[$fieldName]['type']); $value = $type->convertToPHPValue($value, $this->em->getConnection()->getDatabasePlatform()); $classMetadata->setFieldValue($entity, $fieldName, $value); } elseif (isset($classMetadata->associationMappings[$fieldName])) { $fieldMapping = $classMetadata->associationMappings[$fieldName]; if (ClassMetadataInfo::MANY_TO_MANY === $fieldMapping['type']) { // expecting an array of ids in $value if (1 === count($fieldMapping['relationToTargetKeyColumns'])) { $columnName = array_pop($fieldMapping['relationToTargetKeyColumns']); $otherSideMapping = $this->em->getClassMetadata($fieldMapping['targetEntity']); $value = $this->em->getRepository($fieldMapping['targetEntity'])->findBy(array($otherSideMapping->fieldNames[$columnName] => $value)); } $classMetadata->setFieldValue($entity, $fieldName, $value); } elseif (ClassMetadataInfo::MANY_TO_ONE === $fieldMapping['type']) { // expecting an array of ids in $value $value = $this->em->getRepository($fieldMapping['targetEntity'])->find($value); $classMetadata->setFieldValue($entity, $fieldName, $value); } } else { throw new HydrationException($fieldName); } } }
public function getJobStatistics(Job $job) { $statisticData = array(); $dataPerCharacteristic = array(); $stmt = $this->em->getConnection()->prepare('SELECT * FROM jms_job_statistics WHERE job_id = :jobId'); $stmt->execute(array('jobId' => $job->getId())); $statistics = $stmt->fetchAll(); $propertyAccess = PropertyAccess::createPropertyAccessor(); foreach ($statistics as $row) { $dataPerCharacteristic[$propertyAccess->getValue($row, '[characteristic]')][] = array($propertyAccess->getValue($row, '[createdAt]'), $propertyAccess->getValue($row, '[charValue]')); } if ($dataPerCharacteristic) { $statisticData = array(array_merge(array('Time'), $chars = array_keys($dataPerCharacteristic))); $startTime = strtotime($dataPerCharacteristic[$chars[0]][0][0]); $endTime = strtotime($dataPerCharacteristic[$chars[0]][count($dataPerCharacteristic[$chars[0]]) - 1][0]); $scaleFactor = $endTime - $startTime > 300 ? 1 / 60 : 1; // This assumes that we have the same number of rows for each characteristic. for ($i = 0, $c = count(reset($dataPerCharacteristic)); $i < $c; $i++) { $row = array((strtotime($dataPerCharacteristic[$chars[0]][$i][0]) - $startTime) * $scaleFactor); foreach ($chars as $name) { $value = (double) $dataPerCharacteristic[$name][$i][1]; switch ($name) { case 'memory': $value /= 1024 * 1024; break; } $row[] = $value; } $statisticData[] = $row; } } return $statisticData; }
public function testCheckDatabase() { $schema = $this->getMockBuilder('Doctrine\\Tests\\Mocks\\SchemaManagerMock')->disableOriginalConstructor()->getMock(); $schema->expects($this->any())->method('listTableNames')->will($this->returnValue(array('oro_entity_config', 'oro_entity_config_field', 'oro_entity_config_value'))); $this->em->getConnection()->getDriver()->setSchemaManager($schema); $this->assertTrue($this->configModelManager->checkDatabase()); }
protected function tearDown() { if ($this->em) { $this->em->getConnection()->close(); } parent::tearDown(); }
private function ensureDatabaseConnection() { if ($this->em->getConnection()->ping() === false) { $this->em->getConnection()->close(); $this->em->getConnection()->connect(); } }
/** * Initializes the command just after the input has been validated. * * This is mainly useful when a lot of commands extends one main command * where some things need to be initialized based on the input arguments and options. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance */ protected function initialize(InputInterface $input, OutputInterface $output) { parent::initialize($input, $output); $this->entityManager = $this->getContainer()->get('doctrine.orm.default_entity_manager'); $this->router = $this->getContainer()->get('router.default'); $this->output = $output; $this->entityManager->getConnection()->getConfiguration()->setSQLLogger(null); }
/** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { parent::setUp(); $this->entityManager = $this->container->getBean("em"); $this->albumRepository = $this->container->getBean("albumRepository"); $this->connection = $this->entityManager->getConnection(); $this->connection->beginTransaction(); }
/** * Update the number of comment for a comment * * @param null|\Sonata\NewsBundle\Model\PostInterface $post * @return void */ public function updateCommentsCount(PostInterface $post = null) { $commentTableName = $this->em->getClassMetadata($this->getClass())->table['name']; $postTableName = $this->em->getClassMetadata($this->postManager->getClass())->table['name']; $this->em->getConnection()->query(sprintf('UPDATE %s p, (SELECT c.post_id, count(*) as total FROM %s as c WHERE c.status = 1 GROUP BY c.post_id) as count_comment SET p.comments_count = count_comment.total WHERE p.id = count_comment.post_id', $postTableName, $commentTableName)); }
/** * @param array $productIds */ protected function removeCascade(array $productIds) { $connection = $this->em->getConnection(); foreach ($this->deltaEntities as $deltaEntity) { $deltaTable = $this->tableNameBuilder->getTableName($deltaEntity); $connection->executeQuery($this->getDeleteSQLQuery($productIds, $deltaTable)); } }
/** * Configures the current connection * * @return void */ protected function configureConnection() { $connection = $this->entityManager->getConnection(); // Use the master if given a master/slave aggregate connection if ($connection instanceof MasterSlaveConnection) { $connection->connect('master'); } }
public function addSqliteFunctions() { /** @var Doctrine\DBAL\Driver\PDOConnection $pdo */ $pdo = $this->entityManager->getConnection()->getWrappedConnection(); $pdo->sqliteCreateFunction('if', function ($condition, $expr1, $expr2 = null) { return $condition ? $expr1 : $expr2; }); }
/** * (non-PHPdoc) * @see Lexik\Bundle\MaintenanceBundle\Drivers.PdoDriver::initDb() */ public function initDb() { if (null === $this->db) { $db = $this->em->getConnection(); $this->db = $db; $this->createTableQuery(); } return $this->db; }
protected function init() { $this->em = $this->app['em']; $this->connection = $this->em->getConnection(); $this->schemaManager = $this->em->getConnection()->getSchemaManager(); $this->schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em); $this->validator = new \Doctrine\ORM\Tools\SchemaValidator($this->em); $this->metadatas = $this->em->getMetadataFactory()->getAllMetadata(); }
/** * {@inheritdoc} */ public function purge() { $classes = array(); $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { if (!$metadata->isMappedSuperclass) { $classes[] = $metadata; } } $commitOrder = $this->getCommitOrder($this->em, $classes); // Drop association tables first $orderedTables = $this->getAssociationTables($commitOrder); // Get platform parameters $platform = $this->em->getConnection()->getDatabasePlatform(); // Drop tables in reverse commit order for ($i = count($commitOrder) - 1; $i >= 0; --$i) { $class = $commitOrder[$i]; if ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName || $class->isMappedSuperclass) { continue; } $orderedTables[] = $class->getQuotedTableName($platform); } $orderedTables = array_diff($orderedTables, $this->excludedTables); foreach ($orderedTables as $tbl) { if ($this->purgeMode === self::PURGE_MODE_DELETE) { $this->em->getConnection()->executeUpdate("DELETE FROM " . $tbl); } else { $this->em->getConnection()->executeUpdate($platform->getTruncateTableSQL($tbl, true)); } } }