Since: 2.0
Author: Guilherme Blanco (guilhermeblanco@hotmail.com)
Author: Jonathan Wage (jonwage@gmail.com)
Author: Roman Borschel (roman@code-factory.org)
Author: Benjamin Eberlei (kontakt@beberlei.de)
Author: Stefano Rodriguez (stefano.rodriguez@fubles.com)
 public function adminRefreshDatabaseAction(Request $request, Application $app)
 {
     $conn = $app['db'];
     $em = $app['doctrine.orm.entity_manager'];
     $params = $conn->getParams();
     $name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
     try {
         $conn->getSchemaManager()->dropDatabase($name);
         $conn->getSchemaManager()->createDatabase($name);
         $conn->close();
     } catch (\Exception $e) {
         return 1;
     }
     $classes = [];
     foreach ($app['authbucket_oauth2.model'] as $class) {
         $classes[] = $em->getClassMetadata($class);
     }
     PersistentObject::setObjectManager($em);
     $tool = new SchemaTool($em);
     $tool->dropSchema($classes);
     $tool->createSchema($classes);
     $purger = new ORMPurger();
     $executor = new ORMExecutor($em, $purger);
     $loader = new Loader();
     $loader->loadFromDirectory(__DIR__ . '/../DataFixtures/ORM');
     $executor->execute($loader->getFixtures());
     return $app->redirect($app['url_generator']->generate('index'));
 }
Example #2
0
    protected function setUp()
    {
        if (!class_exists('Doctrine\\Common\\Version')) {
            $this->markTestSkipped('Doctrine is not available.');
        }

        $this->em = DoctrineOrmTestCase::createTestEntityManager();

        parent::setUp();

        $schemaTool = new SchemaTool($this->em);
        $classes = array(
            $this->em->getClassMetadata(self::SINGLE_IDENT_CLASS),
            $this->em->getClassMetadata(self::SINGLE_STRING_IDENT_CLASS),
            $this->em->getClassMetadata(self::COMPOSITE_IDENT_CLASS),
            $this->em->getClassMetadata(self::COMPOSITE_STRING_IDENT_CLASS),
        );

        try {
            $schemaTool->dropSchema($classes);
        } catch(\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch(\Exception $e) {
        }
    }
 public function setUp()
 {
     $this->_oldEntityManager = \SoliantEntityAudit\Module::getModuleOptions()->getEntityManager();
     $this->_oldAuditedClassNames = \SoliantEntityAudit\Module::getModuleOptions()->getAuditedClassNames();
     $this->_oldJoinClasses = \SoliantEntityAudit\Module::getModuleOptions()->resetJoinClasses();
     $isDevMode = false;
     $config = Setup::createConfiguration($isDevMode, null, null);
     $chain = new DriverChain();
     // Use ZFC User for authentication tests
     $chain->addDriver(new XmlDriver(__DIR__ . '/../../../vendor/zf-commons/zfc-user-doctrine-orm/config/xml/zfcuser'), 'ZfcUser\\Entity');
     $chain->addDriver(new XmlDriver(__DIR__ . '/../../../vendor/zf-commons/zfc-user-doctrine-orm/config/xml/zfcuserdoctrineorm'), 'ZfcUserDoctrineORM\\Entity');
     $chain->addDriver(new StaticPHPDriver(__DIR__ . "/../Models"), 'SoliantEntityAuditTest\\Models\\LogRevision');
     $chain->addDriver(new AuditDriver('.'), 'SoliantEntityAudit\\Entity');
     $config->setMetadataDriverImpl($chain);
     // Replace entity manager
     $moduleOptions = \SoliantEntityAudit\Module::getModuleOptions();
     $conn = array('driver' => 'pdo_sqlite', 'memory' => true);
     $moduleOptions->setAuditedClassNames(array('SoliantEntityAuditTest\\Models\\LogRevision\\Album' => array(), 'SoliantEntityAuditTest\\Models\\LogRevision\\Performer' => array(), 'SoliantEntityAuditTest\\Models\\LogRevision\\Song' => array(), 'SoliantEntityAuditTest\\Models\\LogRevision\\SingleCoverArt' => array()));
     $entityManager = EntityManager::create($conn, $config);
     $moduleOptions->setEntityManager($entityManager);
     $schemaTool = new SchemaTool($entityManager);
     // Add auditing listener
     $entityManager->getEventManager()->addEventSubscriber(new LogRevision());
     $sql = $schemaTool->getUpdateSchemaSql($entityManager->getMetadataFactory()->getAllMetadata());
     #print_r($sql);die();
     $schemaTool->createSchema($entityManager->getMetadataFactory()->getAllMetadata());
     $this->_em = $entityManager;
 }
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
         $this->markTestSkipped('Doctrine DBAL is not available.');
     }
     if (!class_exists('Doctrine\\Common\\Version')) {
         $this->markTestSkipped('Doctrine Common is not available.');
     }
     if (!class_exists('Doctrine\\ORM\\EntityManager')) {
         $this->markTestSkipped('Doctrine ORM is not available.');
     }
     $this->em = DoctrineOrmTestCase::createTestEntityManager();
     $this->emRegistry = $this->createRegistryMock('default', $this->em);
     parent::setUp();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::ITEM_GROUP_CLASS), $this->em->getClassMetadata(self::SINGLE_IDENT_CLASS), $this->em->getClassMetadata(self::SINGLE_STRING_IDENT_CLASS), $this->em->getClassMetadata(self::COMPOSITE_IDENT_CLASS), $this->em->getClassMetadata(self::COMPOSITE_STRING_IDENT_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
 }
 public function setUp()
 {
     parent::setUp();
     $em = $this->client->getContainer()->get('doctrine.orm.entity_manager');
     $schemaTool = new SchemaTool($em);
     $schemaTool->createSchema($em->getMetadataFactory()->getAllMetadata());
 }
Example #6
0
 public function setUp()
 {
     parent::setUp();
     $schemaTool = new SchemaTool($this->entityManager);
     $schemaTool->createSchema(array($this->entityManager->getClassMetadata('Pagerfanta\\Tests\\Adapter\\DoctrineORM\\User'), $this->entityManager->getClassMetadata('Pagerfanta\\Tests\\Adapter\\DoctrineORM\\Group'), $this->entityManager->getClassMetadata('Pagerfanta\\Tests\\Adapter\\DoctrineORM\\Person')));
     $this->user1 = $user = new User();
     $this->user2 = $user2 = new User();
     $group1 = new Group();
     $group2 = new Group();
     $group3 = new Group();
     $user->groups[] = $group1;
     $user->groups[] = $group2;
     $user->groups[] = $group3;
     $user2->groups[] = $group1;
     $author1 = new Person();
     $author1->name = 'Foo';
     $author1->biography = 'Baz bar';
     $author2 = new Person();
     $author2->name = 'Bar';
     $author2->biography = 'Bar baz';
     $this->entityManager->persist($user);
     $this->entityManager->persist($user2);
     $this->entityManager->persist($group1);
     $this->entityManager->persist($group2);
     $this->entityManager->persist($group3);
     $this->entityManager->persist($author1);
     $this->entityManager->persist($author2);
     $this->entityManager->flush();
 }
 /**
  * do the thing here.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $driver = new DoctrineAdapter();
     $driver->init();
     $em = $driver->getManager();
     $schema = new SchemaTool($em);
     $models = [];
     $model_name = $input->getArgument('model_name');
     $full_name = Config::getInstance()->get('root-namespace') . '\\Models' . '\\' . $model_name . 'Model';
     $schemaManager = $em->getConnection()->getSchemaManager();
     try {
         $metadata = $em->getClassMetadata($full_name);
         $table_name = $metadata->getTableName();
         if ($schemaManager->tablesExist([$table_name]) == true) {
             $models[] = $metadata;
         }
         if (count($models) > 0) {
             $schema->dropSchema($models);
         } else {
             $output->writeln('O model ' . $full_name . ' nao esta registrado no banco de dados.');
         }
     } catch (\Doctrine\ORM\Mapping\MappingException $e) {
         $output->writeln('Erro encontrado:');
         $output->writeln($e->getMessage());
         return;
     }
     $output->writeln('Tabela ' . $table_name . ' removida com sucesso.');
 }
Example #8
0
 protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas)
 {
     // Defining if update is complete or not (--complete not defined means $saveMode = true)
     $saveMode = $input->getOption('complete') !== true;
     if ($input->getOption('dump-sql') === true) {
         $sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode);
         $output->write(implode(';' . PHP_EOL, $sqls) . PHP_EOL);
     } else {
         if ($input->getOption('force') === true) {
             $output->write('Updating database schema...' . PHP_EOL);
             $schemaTool->updateSchema($metadatas, $saveMode);
             $output->write('Database schema updated successfully!' . PHP_EOL);
         } else {
             $output->write('ATTENTION: This operation should not be executed in a production environment.' . PHP_EOL);
             $output->write('Use the incremental update to detect changes during development and use' . PHP_EOL);
             $output->write('this SQL DDL to manually update your database in production.' . PHP_EOL . PHP_EOL);
             $sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode);
             if (count($sqls)) {
                 $output->write('Schema-Tool would execute ' . count($sqls) . ' queries to update the database.' . PHP_EOL);
                 $output->write('Please run the operation with --force to execute these queries or use --dump-sql to see them.' . PHP_EOL);
             } else {
                 $output->write('Nothing to update. The database is in sync with the current entity metadata.' . PHP_EOL);
             }
         }
     }
 }
Example #9
0
 /**
  * @param EntityManager $em
  * @return SchemaTool
  */
 private function createSchemaTool(EntityManager $em)
 {
     $schemaTool = new SchemaTool($em);
     $schemaTool->dropDatabase();
     $schemaTool->createSchema($em->getMetadataFactory()->getAllMetadata());
     return $schemaTool;
 }
 /**
  * Updates DB Schema. Changes from Diamante only will be applied for current schema. Other bundles updating skips
  * @throws \Exception if there are no changes in entities
  */
 protected function updateDbSchema()
 {
     /**
      * @var $em \Doctrine\ORM\EntityManager
      */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     $event = $em->getEventManager();
     $sm = $em->getConnection()->getSchemaManager();
     $allMetadata = $em->getMetadataFactory()->getAllMetadata();
     $schemaTool = new SchemaTool($em);
     $entitiesMetadata = array($em->getClassMetadata(\Diamante\DeskBundle\Entity\Branch::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Ticket::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Comment::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Attachment::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\BranchEmailConfiguration::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\MessageReference::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\TicketHistory::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\WatcherList::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\TicketTimeline::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Audit::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\AuditField::getClassName()), $em->getClassMetadata(\Diamante\DeskBundle\Entity\Article::getClassName()));
     $event->disableListeners();
     $currentSchema = $sm->createSchema();
     $schemaFromMetadata = $schemaTool->getSchemaFromMetadata($allMetadata);
     $entitiesSchema = $schemaTool->getSchemaFromMetadata($entitiesMetadata);
     $entitiesTables = $entitiesSchema->getTables();
     $entitiesTableName = array_keys($entitiesTables);
     $currentDiamanteSchema = $this->getTargetSchema($currentSchema, $entitiesTableName);
     $diamanteSchemaFromMetadata = $this->getTargetSchema($schemaFromMetadata, $entitiesTableName);
     $comparator = new Comparator();
     $diff = $comparator->compare($currentDiamanteSchema, $diamanteSchemaFromMetadata);
     $toUpdate = $diff->toSql($em->getConnection()->getDatabasePlatform());
     if (empty($toUpdate)) {
         throw new \Exception('No new updates found. DiamanteDesk is up to date!');
     }
     $conn = $em->getConnection();
     foreach ($toUpdate as $sql) {
         $conn->executeQuery($sql);
     }
 }
 /**
  * Updates DB Schema.
  * @throws \Exception if there are no changes in entities
  */
 protected function updateDbSchema()
 {
     /**
      * @var $em \Doctrine\ORM\EntityManager
      */
     $em = $this->getContainer()->get('doctrine.orm.entity_manager');
     $event = $em->getEventManager();
     $sm = $em->getConnection()->getSchemaManager();
     $allMetadata = $em->getMetadataFactory()->getAllMetadata();
     $schemaTool = new SchemaTool($em);
     $entitiesMetadata = array($em->getClassMetadata(ApiUser::getClassName()), $em->getClassMetadata(DiamanteUser::getClassName()));
     $event->disableListeners();
     $currentSchema = $sm->createSchema();
     $schemaFromMetadata = $schemaTool->getSchemaFromMetadata($allMetadata);
     $entitiesSchema = $schemaTool->getSchemaFromMetadata($entitiesMetadata);
     $entitiesTables = $entitiesSchema->getTables();
     $entitiesTableName = array_keys($entitiesTables);
     $currentDiamanteSchema = $this->getTargetSchema($currentSchema, $entitiesTableName);
     $diamanteSchemaFromMetadata = $this->getTargetSchema($schemaFromMetadata, $entitiesTableName);
     $comparator = new Comparator();
     $diff = $comparator->compare($currentDiamanteSchema, $diamanteSchemaFromMetadata);
     $toUpdate = $diff->toSql($em->getConnection()->getDatabasePlatform());
     if (empty($toUpdate)) {
         throw new \Exception('No new updates found. Diamante Api Bundle is up to date!');
     }
     $conn = $em->getConnection();
     foreach ($toUpdate as $sql) {
         $conn->executeQuery($sql);
     }
 }
 private function prepareDatabase()
 {
     /** @var EntityManager $em */
     $em = $this->registry->getManager();
     $tool = new SchemaTool($em);
     $tool->createSchema($em->getMetadataFactory()->getAllMetadata());
 }
Example #13
0
 private function createSchema(ContainerInterface $container)
 {
     $entityManager = $container->get('doctrine.orm.entity_manager');
     /** @var EntityManager $entityManager */
     $schemaTool = new SchemaTool($entityManager);
     $schemaTool->createSchema($entityManager->getMetadataFactory()->getAllMetadata());
 }
Example #14
0
 protected function tearDown()
 {
     // Clean anything still idle in the UOW
     $this->_em->clear();
     // Clear out anything set in the db (schema is recreated on setUp()
     $this->_schemaTool->dropDatabase();
 }
 private function dropAndCreateSchema()
 {
     $schemaTool = new SchemaTool($this->getEntityManager());
     $metadata = $this->getEntityManager()->getMetadataFactory()->getAllMetadata();
     $schemaTool->dropSchema($metadata);
     $schemaTool->createSchema($metadata);
 }
 /**
  * Creates schema for doctrine entities
  *
  * @throws \Doctrine\ORM\Tools\ToolsException
  */
 protected function createDoctrineSchema()
 {
     $metadata = $this->entityManager->getMetadataFactory()->getAllMetadata();
     $tool = new SchemaTool($this->entityManager);
     $tool->dropSchema($metadata);
     $tool->createSchema($metadata);
 }
 /**
  * @see https://github.com/zfcampus/zf-apigility/issues/18
  */
 public function testCreateReturnsRestServiceEntityWithControllerServiceNamePopulated()
 {
     $serviceManager = $this->getApplication()->getServiceManager();
     $em = $serviceManager->get('doctrine.entitymanager.orm_default');
     $tool = new SchemaTool($em);
     $res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata());
     // Create DB
     $resourceDefinition = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "Artist", "entityClass" => "Db\\Entity\\Artist", "routeIdentifierName" => "artist_id", "entityIdentifierName" => "id", "routeMatch" => "/db-test/artist");
     // Verify ORM is working
     $artist = new \Db\Entity\Artist();
     $artist->setName('TestInsert');
     $artist->setCreatedAt(new \Datetime());
     $em->persist($artist);
     $em->flush();
     $found = $em->getRepository('Db\\Entity\\Artist')->find($artist->getId());
     $this->assertInstanceOf('Db\\Entity\\Artist', $found);
     $this->resource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceResource');
     $this->resource->setModuleName('DbApi');
     $entity = $this->resource->create($resourceDefinition);
     $this->assertInstanceOf('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceEntity', $entity);
     $controllerServiceName = $entity->controllerServiceName;
     $this->assertNotEmpty($controllerServiceName);
     $this->assertContains('DbApi\\V1\\Rest\\Artist\\Controller', $controllerServiceName);
     //        $serviceManager = ServiceManagerFactory::getServiceManager();
     //        $config = $serviceManager->get('Config');
     //        $routerConfig = isset($config['router']) ? $config['router'] : array();
     //        $router = HttpRouter::factory($routerConfig);
     //        $routeMatch = new RouteMatch(array('controller' => $controllerServiceName));
     //        $event = new MvcEvent();
     //        $event->setRouter($router);
     //        $event->setRouteMatch($routeMatch);
     //        $this->getRequest()->setMethod('GET');
     $request = $this->getRequest();
     $request->setMethod('GET');
     $request->getHeaders()->addHeaders(array('Accept' => 'application/json'));
     $x = $this->dispatch('/db-api/artist');
     $this->resource->delete('DbApi\\V1\\Rest\\Artist\\Controller');
     print_r($x);
     return;
     //        $controller->setEvent($event);
     //        $controller->setServiceLocator($serviceManager);
     //        $routeMatch = new RouteMatch(array('controller' => $controllerServiceName));
     //        print_r($config);
     //        print_r(get_class_methods($router));
     $this->resource->delete('DbApi\\V1\\Rest\\Artist\\Controller');
     return;
     //        $controller = new $controllerServiceName;
     //        $request    = new Request();
     $query = array();
     $query[] = array('type' => 'eq', 'field' => 'id', 'value' => $found->getId());
     // Fetch test runs
     $routeMatch->setParam('action', 'index');
     $result = $controller->dispatch($this->request);
     $response = $controller->getResponse();
     //        $this->assertEquals(200, $response->getStatusCode());
     $hal = $response->getBody();
     $renderer = $this->getServiceLocator()->get('ZF\\Hal\\JsonRenderer');
     $data = json_decode($renderer->render($hal), true);
     print_r($data);
 }
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $configuration = $this->_getMigrationConfiguration($input, $output);

        $em = $this->getHelper('em')->getEntityManager();
        $conn = $em->getConnection();
        $platform = $conn->getDatabasePlatform();
        $metadata = $em->getMetadataFactory()->getAllMetadata();

        if (empty($metadata)) {
            $output->writeln('No mapping information to process.', 'ERROR');
            return;
        }

        $tool = new SchemaTool($em);

        $fromSchema = $conn->getSchemaManager()->createSchema();
        $toSchema = $tool->getSchemaFromMetadata($metadata);
        $up = $this->_buildCodeFromSql($configuration, $fromSchema->getMigrateToSql($toSchema, $platform));
        $down = $this->_buildCodeFromSql($configuration, $fromSchema->getMigrateFromSql($toSchema, $platform));

        if ( ! $up && ! $down) {
            $output->writeln('No changes detected in your mapping information.', 'ERROR');
            return;
        }

        $version = date('YmdHis');
        $path = $this->_generateMigration($configuration, $input, $version, $up, $down);

        $output->writeln(sprintf('Generated new migration class to "<info>%s</info>" from schema differences.', $path));
    }
 public function execute()
 {
     $d = $this->factory()->appDoctrine();
     $this->app->dataStorage->clearStorage('CyantreeDoctrineModule/Proxies');
     $this->app->cacheStorage->clearStorage('CyantreeDoctrineModule');
     $tool = new SchemaTool($d);
     $queries = $tool->getUpdateSchemaSql($d->getMetadataFactory()->getAllMetadata());
     if ($queries) {
         $hash = '';
         foreach ($queries as $query) {
             $hash = md5($hash . $query);
         }
         $code = substr($hash, 0, 8);
         if ($transferredCode = $this->request->args->get('code')) {
             if ($transferredCode == $code) {
                 $tool->updateSchema($d->getMetadataFactory()->getAllMetadata());
                 $this->result->showSuccess('Schema has been updated.');
                 return;
             } else {
                 $this->result->showError('Passed invalid code.');
             }
         }
         $this->result->showWarning('Schema is not up to date. The following queries would be executed:');
         foreach ($queries as $query) {
             $this->result->showInfo($query);
         }
         $this->result->showWarning("Execute with -code={$code} to update the database schema.");
     } else {
         $this->result->showSuccess('Schema is up to date.');
     }
 }
 protected function setUp()
 {
     parent::setUp();
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
         $this->markTestSkipped('Doctrine DBAL is not available.');
     }
     if (!class_exists('Doctrine\\Common\\Version')) {
         $this->markTestSkipped('Doctrine Common is not available.');
     }
     if (!class_exists('Doctrine\\ORM\\EntityManager')) {
         $this->markTestSkipped('Doctrine ORM is not available.');
     }
     $this->em = DoctrineTestHelper::createTestEntityManager();
     $this->emRegistry = $this->createRegistryMock('default', $this->em);
     $this->items = array();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
     $this->createEntities();
     $this->factory = Forms::createFormFactoryBuilder()->addExtensions($this->getExtensions())->addTypeExtension(new ChoiceSelect2TypeExtension($this->dispatcher, $this->requestStack, $this->router, $this->getExtensionTypeName(), 10))->addType(new EntityType($this->emRegistry))->addTypeExtension(new EntitySelect2TypeExtension())->getFormFactory();
     $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory);
 }
 /**
  * do the thing here.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $driver = new DoctrineAdapter();
     $driver->init();
     $em = $driver->getManager();
     $classes = loadAppModels();
     $schema = new SchemaTool($em);
     $models = [];
     try {
         $schemaManager = $em->getConnection()->getSchemaManager();
         foreach ($classes as $class) {
             $metadata = $em->getClassMetadata($class);
             $table_name = $metadata->getTableName();
             if ($schemaManager->tablesExist([$table_name]) == true) {
                 array_push($models, $metadata);
             }
         }
         if (count($models) > 0) {
             $schema->dropSchema($models);
         } else {
             $output->writeln('Nao ha models exportados para o banco de dados');
         }
     } catch (\Doctrine\ORM\Mapping\MappingException $e) {
         $output->writeln('Erro encontrado:');
         $output->writeln($e->getMessage());
         return;
     }
     $output->writeln('Tabelas removidas com sucesso.');
 }
Example #22
0
 /**
  * This is a functinoal test as there is a large integration necessary to get the validator working.
  */
 public function testValidateUniqueness()
 {
     $entityManagerName = "foo";
     $em = $this->createTestEntityManager();
     $schemaTool = new SchemaTool($em);
     $schemaTool->createSchema(array($em->getClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity')));
     $entity1 = new SingleIdentEntity(1, 'Foo');
     $registry = $this->createRegistryMock($entityManagerName, $em);
     $uniqueValidator = new UniqueEntityValidator($registry);
     $metadata = new ClassMetadata('Symfony\\Tests\\Bridge\\Doctrine\\Form\\Fixtures\\SingleIdentEntity');
     $metadata->addConstraint(new UniqueEntity(array('fields' => array('name'), 'em' => $entityManagerName)));
     $metadataFactory = $this->createMetadataFactoryMock($metadata);
     $validatorFactory = $this->createValidatorFactory($uniqueValidator);
     $validator = new Validator($metadataFactory, $validatorFactory);
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database.");
     $em->persist($entity1);
     $em->flush();
     $violationsList = $validator->validate($entity1);
     $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $entity2 = new SingleIdentEntity(2, 'Foo');
     $violationsList = $validator->validate($entity2);
     $this->assertEquals(1, $violationsList->count(), "No violations found on entity after it was saved to the database.");
     $violation = $violationsList[0];
     $this->assertEquals('This value is already used.', $violation->getMessage());
     $this->assertEquals('name', $violation->getPropertyPath());
     $this->assertEquals('Foo', $violation->getInvalidValue());
 }
Example #23
0
 protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas)
 {
     // Defining if update is complete or not (--complete not defined means $saveMode = true)
     $saveMode = $input->getOption('complete') !== true;
     $sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode);
     if (0 == count($sqls)) {
         $output->writeln('Nothing to update - your database is already in sync with the current entity metadata.');
         return;
     }
     $dumpSql = true === $input->getOption('dump-sql');
     $force = true === $input->getOption('force');
     if ($dumpSql && $force) {
         throw new \InvalidArgumentException('You can pass either the --dump-sql or the --force option (but not both simultaneously).');
     }
     if ($dumpSql) {
         $output->writeln(implode(';' . PHP_EOL, $sqls));
     } else {
         if ($force) {
             $output->writeln('Updating database schema...');
             $schemaTool->updateSchema($metadatas, $saveMode);
             $output->writeln(sprintf('Database schema updated successfully! "<info>%s</info>" queries were executed', count($sqls)));
         } else {
             $output->writeln('<comment>ATTENTION</comment>: This operation should not be executed in a production environment.');
             $output->writeln('           Use the incremental update to detect changes during development and use');
             $output->writeln('           the SQL DDL provided to manually update your database in production.');
             $output->writeln('');
             $output->writeln(sprintf('The Schema-Tool would execute <info>"%s"</info> queries to update the database.', count($sqls)));
             $output->writeln('Please run the operation by passing one of the following options:');
             $output->writeln(sprintf('    <info>%s --force</info> to execute the command', $this->getName()));
             $output->writeln(sprintf('    <info>%s --dump-sql</info> to dump the SQL statements to the screen', $this->getName()));
         }
     }
 }
Example #24
0
 public function rebuildSchema()
 {
     $metadatas = $this->em->getMetadataFactory()->getAllMetadata();
     $tool = new SchemaTool($this->em);
     $tool->dropSchema($metadatas);
     $tool->updateSchema($metadatas, false);
 }
 public function testReferenceReconstruction()
 {
     $em = $this->getMockSqliteEntityManager();
     $referenceRepository = new ProxyReferenceRepository($em);
     $listener = new ORMReferenceListener($referenceRepository);
     $em->getEventManager()->addEventSubscriber($listener);
     $schemaTool = new SchemaTool($em);
     $schemaTool->dropSchema(array());
     $schemaTool->createSchema(array($em->getClassMetadata(self::TEST_ENTITY_ROLE)));
     $roleFixture = new TestFixtures\RoleFixture();
     $roleFixture->setReferenceRepository($referenceRepository);
     $roleFixture->load($em);
     // first test against managed state
     $ref = $referenceRepository->getReference('admin-role');
     $this->assertNotInstanceOf('Doctrine\\ORM\\Proxy\\Proxy', $ref);
     // test reference reconstruction from serialized data (was managed)
     $serializedData = $referenceRepository->serialize();
     $proxyReferenceRepository = new ProxyReferenceRepository($em);
     $proxyReferenceRepository->unserialize($serializedData);
     $ref = $proxyReferenceRepository->getReference('admin-role');
     $this->assertInstanceOf('Doctrine\\ORM\\Proxy\\Proxy', $ref);
     // now test reference reconstruction from identity
     $em->clear();
     $ref = $referenceRepository->getReference('admin-role');
     $this->assertInstanceOf('Doctrine\\ORM\\Proxy\\Proxy', $ref);
     // test reference reconstruction from serialized data (was identity)
     $serializedData = $referenceRepository->serialize();
     $proxyReferenceRepository = new ProxyReferenceRepository($em);
     $proxyReferenceRepository->unserialize($serializedData);
     $ref = $proxyReferenceRepository->getReference('admin-role');
     $this->assertInstanceOf('Doctrine\\ORM\\Proxy\\Proxy', $ref);
 }
 public function testDoctrineService()
 {
     $serviceManager = $this->getApplication()->getServiceManager();
     $em = $serviceManager->get('doctrine.entitymanager.orm_default');
     $tool = new SchemaTool($em);
     $res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata());
     // Create DB
     $resourceDefinition = array("objectManager" => "doctrine.entitymanager.orm_default", "serviceName" => "Artist", "entityClass" => "Db\\Entity\\Artist", "routeIdentifierName" => "artist_id", "entityIdentifierName" => "id", "routeMatch" => "/db-test/artist");
     $this->resource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceResource');
     $this->resource->setModuleName('DbApi');
     $entity = $this->resource->create($resourceDefinition);
     $this->assertInstanceOf('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRestServiceEntity', $entity);
     $controllerServiceName = $entity->controllerServiceName;
     $this->assertNotEmpty($controllerServiceName);
     $this->assertContains('DbApi\\V1\\Rest\\Artist\\Controller', $controllerServiceName);
     $filter = new FilterChain();
     $filter->attachByName('WordCamelCaseToUnderscore')->attachByName('StringToLower');
     $em = $serviceManager->get('doctrine.entitymanager.orm_default');
     $metadataFactory = $em->getMetadataFactory();
     $entityMetadata = $metadataFactory->getMetadataFor("Db\\Entity\\Artist");
     foreach ($entityMetadata->associationMappings as $mapping) {
         switch ($mapping['type']) {
             case 4:
                 $rpcServiceResource = $serviceManager->get('ZF\\Apigility\\Doctrine\\Admin\\Model\\DoctrineRpcServiceResource');
                 $rpcServiceResource->setModuleName('DbApi');
                 $rpcServiceResource->create(array('service_name' => 'Artist' . $mapping['fieldName'], 'route' => '/db-test/artist[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]', 'http_methods' => array('GET', 'PUT', 'POST'), 'options' => array('target_entity' => $mapping['targetEntity'], 'source_entity' => $mapping['sourceEntity'], 'field_name' => $mapping['fieldName']), 'selector' => 'custom selector'));
                 break;
             default:
                 break;
         }
     }
 }
 /**
  * @group DBAL-204
  */
 public function testGetCreateSchemaSql4()
 {
     $classes = array($this->_em->getClassMetadata(__NAMESPACE__ . '\\MysqlSchemaNamespacedEntity'));
     $tool = new SchemaTool($this->_em);
     $sql = $tool->getCreateSchemaSql($classes);
     $this->assertEquals(0, count($sql));
 }
 public function handleDatabaseUpdate(Args $args, IO $io, Command $command)
 {
     $tool = new SchemaTool($this->app['entyMgr']);
     $tool->updateSchema($this->app['entyMgr']->getMetadataFactory()->getAllMetadata());
     $io->writeLine("<info>Database schema updated.</info>");
     return 0;
 }
Example #29
0
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
         $this->markTestSkipped('Doctrine DBAL is not available.');
     }
     if (!class_exists('Doctrine\\Common\\Version')) {
         $this->markTestSkipped('Doctrine Common is not available.');
     }
     if (!class_exists('Doctrine\\ORM\\EntityManager')) {
         $this->markTestSkipped('Doctrine ORM is not available.');
     }
     $this->em = DoctrineOrmTestCase::createTestEntityManager();
     parent::setUp();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::ENTITY_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
     $ids = range(1, 300);
     foreach ($ids as $id) {
         $name = 65 + chr($id % 57);
         $this->em->persist(new SingleIdentEntity($id, $name));
     }
     $this->em->flush();
 }
Example #30
0
 /**
  * Initializes the database (once).
  *
  * @throws \Doctrine\DBAL\DBALException
  * @throws \Doctrine\ORM\ORMException
  * @throws \Doctrine\ORM\Tools\ToolsException
  */
 protected function setUp()
 {
     if (null === static::$_conn) {
         $dbPath = __DIR__ . '/../../../db.sqlite';
         if (file_exists($dbPath)) {
             unlink($dbPath);
         }
         $params = ['driver' => 'pdo_sqlite', 'path' => $dbPath];
         static::$_conn = DriverManager::getConnection($params);
         static::$_conn->getConfiguration()->setSQLLogger(null);
     }
     if (null === static::$_em) {
         $paths = [__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/ORM/Resources/mapping'];
         $isDevMode = true;
         $config = Setup::createXMLMetadataConfiguration($paths, $isDevMode);
         $em = EntityManager::create(static::$_conn, $config);
         $classes = [];
         foreach (static::$_classes as $class) {
             array_push($classes, $em->getClassMetadata($class));
         }
         $schemaTool = new SchemaTool($em);
         $schemaTool->dropSchema($classes);
         $schemaTool->createSchema($classes);
         // Load fixtures
         $loader = new Loader();
         $loader->loadFromDirectory(__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/Fixtures');
         $purger = new ORMPurger();
         $executor = new ORMExecutor($em, $purger);
         $executor->execute($loader->getFixtures());
         static::$_em = $em;
     }
 }