Updates the database schema of the given classes by comparing the ClassMetadata
ins$tableNametances to the current database schema that is inspected.
public updateSchema ( array $classes, $saveMode = false ) : void | ||
$classes | array | |
리턴 | void |
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); if (!GeometryEngineRegistry::has()) { $this->markTestSkipped('This test requires a connection to a database.'); } $engine = GeometryEngineRegistry::get(); if (!$engine instanceof PDOEngine) { $this->markTestSkipped('This test currently only works with a PDO connection.'); } $this->platform = $this->_conn->getDatabasePlatform(); $this->platform->registerDoctrineTypeMapping('geometry', 'binary'); $this->platform->registerDoctrineTypeMapping('linestring', 'binary'); $this->platform->registerDoctrineTypeMapping('multilinestring', 'binary'); $this->platform->registerDoctrineTypeMapping('multipoint', 'binary'); $this->platform->registerDoctrineTypeMapping('multipolygon', 'binary'); $this->platform->registerDoctrineTypeMapping('point', 'binary'); $this->platform->registerDoctrineTypeMapping('polygon', 'binary'); switch ($this->platform->getName()) { case 'postgresql': $this->_conn->executeQuery('CREATE EXTENSION IF NOT EXISTS postgis;'); break; } $this->fixtureLoader = new Loader(); $config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/Fixtures'], false); $config->addCustomNumericFunction('EarthDistance', EarthDistanceFunction::class); $this->em = EntityManager::create($this->_conn, $config, $this->platform->getEventManager()); $this->schemaTool = new SchemaTool($this->em); $this->schemaTool->updateSchema([$this->em->getClassMetadata(Fixtures\GeometryEntity::class), $this->em->getClassMetadata(Fixtures\LineStringEntity::class), $this->em->getClassMetadata(Fixtures\MultiLineStringEntity::class), $this->em->getClassMetadata(Fixtures\MultiPointEntity::class), $this->em->getClassMetadata(Fixtures\MultiPolygonEntity::class), $this->em->getClassMetadata(Fixtures\PointEntity::class), $this->em->getClassMetadata(Fixtures\PolygonEntity::class)]); $purger = new ORMPurger(); $this->ormExecutor = new ORMExecutor($this->em, $purger); }
/** * Builds the DB Schema * * @return void */ protected function rebuildDatabase() { # 2. Drop the existing database schema $this->schemaTool->dropDatabase(); # 3. Create the new database schema based on (1) $entityMeta = $this->em->getMetadataFactory()->getAllMetadata(); $this->schemaTool->updateSchema($entityMeta); }
/** * Set up test env * * @return void */ public function setUp() { $this->eventDispatcher = new EventDispatcher(); $this->params = new CollectorParamBag(); $setup = Setup::createAnnotationMetadataConfiguration([ENTITIES], true); $this->em = EntityManager::create(['driver' => 'pdo_mysql', 'user' => 'user', 'password' => '', 'dbname' => 'warden'], $setup); // Setup Param Bag $this->params->add('query_limit', ['type' => 'integer', 'default' => 5, 'limit' => 5, 'value' => null, 'expression' => 'value >= limit']); // Sync the schema $this->schema = new SchemaTool($this->em); $this->schema->updateSchema($this->em->getMetadataFactory()->getAllMetadata(), true); // Events $this->start = new StartEvent(); $this->stop = new StopEvent($this->params); }
public function update_entity_settings() { if (!$this->token->validate("update_entity_settings")) { $this->error->add($this->token->getErrorMessage()); } if (!$this->error->has()) { if ($this->isPost()) { $ddm = $this->post('DOCTRINE_DEV_MODE') == 1 ? 1 : 0; if ($this->request->request->get('refresh')) { $em = ORM::entityManager(); $config = $em->getConfiguration(); // First, we flush the metadata cache. if (is_object($cache = $config->getMetadataCacheImpl())) { $cache->flushAll(); } // Next, we regnerate proxies $metadatas = $em->getMetadataFactory()->getAllMetadata(); $em->getProxyFactory()->generateProxyClasses($metadatas, $this->app->make('config')->get('database.proxy_classes')); // Finally, we update the schema $tool = new SchemaTool($em); $tool->updateSchema($metadatas, true); $this->flash('success', t('Doctrine cache cleared, proxy classes regenerated, entity database table schema updated.')); $this->redirect('/dashboard/system/environment/entities', 'view'); } else { Config::save('concrete.cache.doctrine_dev_mode', (bool) $ddm); $this->flash('success', t('Doctrine development settings updated.')); } $this->redirect('/dashboard/system/environment/entities', 'view'); } } else { $this->set('error', array($this->token->getErrorMessage())); } }
/** * Runs command * * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ public function execute(InputInterface $input, OutputInterface $output) { $output->writeln($this->getDescription()); /** @var EntityManager $em */ $em = $this->getContainer()->get('doctrine.orm.entity_manager'); /** @var ConfigManager $configManager */ $configManager = $this->getContainer()->get('oro_entity_config.config_manager'); $metadata = array_filter($em->getMetadataFactory()->getAllMetadata(), function ($doctrineMetadata) use($configManager) { /** @var ClassMetadataInfo $doctrineMetadata */ return $this->isExtendEntity($doctrineMetadata->getReflectionClass()->getName(), $configManager); }); $schemaTool = new SchemaTool($em); $sqls = $schemaTool->getUpdateSchemaSql($metadata, true); if (0 === count($sqls)) { $output->writeln('Nothing to update - a database is already in sync with the current entity metadata.'); } else { if ($input->getOption('dry-run')) { $output->writeln(implode(';' . PHP_EOL, $sqls) . ';'); } else { $output->writeln('Updating database schema...'); $schemaTool->updateSchema($metadata, true); $output->writeln(sprintf('Database schema updated successfully! "<info>%s</info>" queries were executed', count($sqls))); } } if (!$input->getOption('dry-run')) { /** @var EnumSynchronizer $enumSynchronizer */ $enumSynchronizer = $this->getContainer()->get('oro_entity_extend.enum_synchronizer'); $enumSynchronizer->sync(); } }
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())); } } }
/** * main method * * @return void */ public function main() { static $em; if ($em === null) { $wd = getcwd(); $zf = $this->project->getProperty('zf'); $application = (require $zf); if (!$application instanceof Application) { throw new BuildException(sprintf('zf bootstrap file "%s" should return an instance of Zend\\Mvc\\Application', $zf)); } chdir($wd); $em = $application->getServiceManager()->get($this->em); } $metadatas = $em->getMetadataFactory()->getAllMetadata(); if (!empty($metadatas)) { $tool = new SchemaTool($em); $sqls = $tool->getUpdateSchemaSql($metadatas, false); if (0 === count($sqls)) { $this->log('Nothing to update - your database is already in sync with the current entity metadata.'); } else { $this->log('Updating database schema...'); $tool->updateSchema($metadatas, false); $this->log(sprintf('Database schema updated successfully! %s queries were executed', count($sqls))); } } else { $this->log('No metadata classes to process'); } }
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; }
public function rebuildSchema() { $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); $tool = new SchemaTool($this->em); $tool->dropSchema($metadatas); $tool->updateSchema($metadatas, false); }
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 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); } } } }
public static function updateSchema($appName, $modelNames = null) { $em = self::getEntityManager($appName, $modelNames); $tool = new SchemaTool($em); $classes = self::getMetadata($appName, $modelNames); $tool->updateSchema($classes, true); }
public function schemaUpdateAction() { /* @var $em EntityManager */ $em = $this->serviceLocator->get("doctrine.entitymanager.orm_dest"); $metadata = $em->getMetadataFactory()->getAllMetadata(); $shemaTool = new SchemaTool($em); $shemaTool->updateSchema($metadata, true); }
/** * Execute the console command. * * @return void */ public function fire() { $this->info('Checking if database needs updating....'); $clean = $this->option('clean'); $sql = $this->tool->getUpdateSchemaSql($this->metadata->getAllMetadata(), !$clean); if (empty($sql)) { $this->info('No updates found.'); return; } if ($this->option('sql')) { $this->info('Outputting update query:'); $this->info(implode(';' . PHP_EOL, $sql)); } else { $this->info('Updating database schema....'); $this->tool->updateSchema($this->metadata->getAllMetadata(), !$clean); $this->info('Schema has been updated!'); } }
protected function performDatabaseUpgrade() { /** * @var EntityManager */ $entityManager = $this->container->get('doctrine')->getManager(); $tool = new SchemaTool($entityManager); $meta = $this->container->get('doctrine')->getManager()->getMetadataFactory()->getAllMetadata(); $tool->updateSchema($meta, true); }
/** * Creates a database if not done already. */ public function createDb() { if (self::$hasDb) { return; } $em = $this->getEntityManager(); $tool = new SchemaTool($em); $tool->updateSchema($em->getMetadataFactory()->getAllMetadata()); self::$hasDb = true; }
public function __construct($aParams = array()) { $oConfig = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . DIRECTORY_SEPARATOR . "Entities"), true); $em = EntityManager::create($aParams['db'], $oConfig); if (isset($aParams["createDb"]) && $aParams["createDb"]) { $oSchemaTool = new \Doctrine\ORM\Tools\SchemaTool($em); $classes = array($em->getClassMetadata('\\F2Dev\\InvoiceEngine\\Database\\Connectors\\Entities\\Invoice'), $em->getClassMetadata('\\F2Dev\\InvoiceEngine\\Database\\Connectors\\Entities\\Item'), $em->getClassMetadata('\\F2Dev\\InvoiceEngine\\Database\\Connectors\\Entities\\InvoiceInfo')); $oSchemaTool->updateSchema($classes); } $this->em = $em; }
public function fire() { $this->info('Checking if database needs updating....'); $sql = $this->tool->getUpdateSchemaSql($this->metadata->getAllMetadata(), $this->option('clean')); if (empty($sql)) { $this->info('No updates found.'); return; } if ($this->option('sql')) { $this->info('Outputting update query:'); $this->info(implode(';' . PHP_EOL, $sql) . ';'); } else { if ($this->option('commit')) { $this->info('Updating database schema....'); $this->tool->updateSchema($this->metadata->getAllMetadata()); $this->info('Schema has been updated!'); } else { $this->comment("Warning: this command can cause data loss. Run with --sql or --commit."); } } }
public function install(InstallContext $context) { $context->scheduleClearCache(InstallContext::CACHE_LIST_DEFAULT); $service = $this->container->get('shopware_attribute.crud_service'); $service->update('s_articles_attributes', 'my_column', 'combobox', ['label' => 'Field label', 'supportText' => 'Value under the field', 'helpText' => 'Value which displayed inside a help icon tooltip', 'translatable' => true, 'displayInBackend' => true, 'entity' => 'Shopware\\Models\\Article\\Article', 'position' => 100, 'custom' => true, 'arrayStore' => [['key' => '1', 'value' => 'first value'], ['key' => '2', 'value' => 'second value']]]); $service->update('s_articles_attributes', 'my_own_validation', 'string', ['label' => 'My own validation', 'displayInBackend' => true, 'translatable' => true], null, true); $service->update('s_articles_attributes', 'my_own_type', 'text', ['label' => 'My own extjs type', 'displayInBackend' => true, 'translatable' => true], null, true); $em = $this->container->get('models'); $schemaTool = new SchemaTool($em); $schemaTool->updateSchema([$em->getClassMetadata(\SwagAttribute\Models\SwagAttribute::class)], true); $service->update('s_articles_attributes', 'my_multi_selection', 'multi_selection', ['entity' => \SwagAttribute\Models\SwagAttribute::class, 'displayInBackend' => true, 'label' => 'My multi selection'], null, true); }
protected function execute(InputInterface $input, OutputInterface $output) { $app = $this->getSilexApplication(); $names = $app['orm.rm']->getRepositoryList(); $output->writeln(sprintf('Updating schema for entities: %s', implode(', ', $names))); $classes = []; foreach ($names as $name) { $classes[] = $app['orm.rm']->getRepository($name)->getClassMetadata(); } $tool = new SchemaTool($app['orm.em']); $tool->updateSchema($classes); }
function index() { try { $schemaTool = new SchemaTool($this->em); $classes = $this->em->getMetadataFactory()->getAllMetadata(); $schemaTool->updateSchema($classes); echo "<div style='margin:10% 40% 10% 40%;height:10%;padding:5% 5% 5% 5%;background-color:gainsboro'>"; echo "<h4 align='center'>Schema Updated</h4>"; echo "<div>"; } catch (Exception $e) { echo $e->getMessage(); } }
/** * @param $entityManager * @return array */ private function preparePurger(EntityManager $entityManager) { $this->setForeignKeyChecks($entityManager, false); if (!self::$hasSchema) { $tool = new SchemaTool($entityManager); $metadata = $this->getMetadata($entityManager); $tool->updateSchema($metadata, true); self::$hasSchema = true; } $this->purger->setEntityManager($entityManager); $this->purger->setPurgeMode(ORMPurger::PURGE_MODE_TRUNCATE); return $this->purger; }
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 { $output->write('Updating database schema...' . PHP_EOL); $schemaTool->updateSchema($metadatas, $saveMode); $output->write('Database schema updated successfully!' . PHP_EOL); } }
public static function updateSchema(EntityManager $em, array $classes, $saveMode = true) { $tool = new SchemaTool($em); $metaClasses = array(); foreach ($classes as $class) { $metaClasses[] = $em->getClassMetadata($class); } try { $tool->updateSchema($metaClasses, $saveMode); } catch (\PDOException $e) { throw $e; } }
/** * Check and create table if not exists * * @param ContainerInterface $container ContainerInterface Container * @param $className String Name of the ORM class * @param bool $force bool Force update table */ public static function checkAndCreateTableByEntityName(ContainerInterface $container, $className, $force = false) { /** @var Registry $doctrine */ /** @var Connection $connection */ /** @var ClassMetadata $classMetadata */ $doctrine = $container->get('doctrine'); $manager = $doctrine->getManager(); $schemaTool = new SchemaTool($doctrine->getManager()); $connection = $doctrine->getConnection(); $schemaManager = $connection->getSchemaManager(); $classMetadata = $manager->getClassMetadata($className); if ($force || !$schemaManager->tablesExist($classMetadata->getTableName())) { if ($schemaManager instanceof SqliteSchemaManager) { $columns = array(); $identifiers = $classMetadata->getIdentifierColumnNames(); foreach ($classMetadata->getFieldNames() as $fieldName) { $fieldMapping = $classMetadata->getFieldMapping($fieldName); $columnSql = $fieldMapping["fieldName"]; switch ($fieldMapping["type"]) { case 'integer': $columnSql .= " INTEGER "; break; case 'real': case 'double': case 'float': $columnSql .= " REAL "; break; case 'datetime': case 'date': case 'boolean': $columnSql .= " INTEGER "; break; case 'blob': case 'file': $columnSql .= " BLOB "; break; default: $columnSql .= " TEXT "; } // PRIMARY KEY in_array($fieldName, $identifiers) && ($columnSql .= "PRIMARY KEY "); $columnSql .= $fieldMapping["nullable"] ? "NULL " : "NOT NULL "; $columns[] = $columnSql; } $sql = 'CREATE TABLE IF NOT EXISTS ' . $classMetadata->getTableName() . '( ' . implode(",\n", $columns) . ')'; $statement = $connection->query($sql); } else { $schemaTool->updateSchema(array($classMetadata), true); } } }
private function checkThatNewConstraintsCanBeApplied(EntityManager $em) { $tool = new SchemaTool($em); $metas = $em->getMetadataFactory()->getAllMetadata(); // Bad ordering of Indexes changes in Doctrine DBAL-2.5 $sqls = $tool->getUpdateSchemaSql($metas, true); foreach ($sqls as $sql) { if ('DROP INDEX usr_id ON Sessions' === $sql) { $em->getConnection()->executeQuery($sql); } } // End patching DBAL-2.5 $tool->updateSchema($metas, true); }
protected function execute(InputInterface $input, OutputInterface $output) { try { $schemaTool = new Doctrine\ORM\Tools\SchemaTool($this->em); $schemaTool->updateSchema($this->em->getMetadataFactory()->getAllMetadata()); $output->writeLn('<info>[OK] - BLOG:UPDATE</info>'); return 0; // zero return code means everything is ok } catch (\Exception $exc) { $output->writeLn('<error>BLOG:UPDATE - ' . $exc->getMessage() . '</error>'); return 1; // non-zero return code means error } }
/** * @Route("/setup/_int_setup_schema") */ public function intSetupSchemaAction() { $response = array("success" => true, "errors" => [], "message" => "Database successfully installed/updated"); $entityManager = $this->get("doctrine.orm.default_entity_manager"); $schemaTool = new SchemaTool($entityManager); $metadatas = $entityManager->getMetadataFactory()->getAllMetadata(); try { $schemaTool->updateSchema($metadatas, true); } catch (\Exception $e) { $response["success"] = false; $response["message"] = "Database setup error"; $response["errors"] = [$e->getMessage()]; } return new JsonResponse($response); }
protected function setUp() { $connectionParams = array('driver' => 'pdo_sqlite', 'memory' => true); $evm = new EventManager(); $config = $this->getMockAnnotatedConfig(); $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config, $evm); $em = EntityManager::create($conn, $config, $evm); $schema = array_map(function ($class) use($em) { return $em->getClassMetadata($class); }, array(self::FIXTURES . 'News', self::FIXTURES . 'Post')); $schemaTool = new SchemaTool($em); $schemaTool->dropSchema($schema); $schemaTool->updateSchema($schema, true); $this->em = $em; }
/** * Creates the structure into the database * NEVER! Call this on a server database! */ public function createStructure() { $tool = new SchemaTool($this->entityManager); $classes = array(); $dir = ROOT_DIR . 'mappings' . DS . 'internal' . DS; if ($handle = opendir($dir)) { while (false !== ($entry = readdir($handle))) { if (is_file($dir . $entry) && StringUtils::endsWith($entry, '.dcm.xml')) { $entry = substr($entry, 0, strlen($entry) - strlen('.dcm.xml')); $entry = str_replace('.', '\\', $entry); $classes[] = $this->entityManager->getClassMetadata($entry); } } } $tool->updateSchema($classes); }