Example #1
0
 /**
  * @todo
  */
 public function dbUpdate()
 {
     $success = true;
     try {
         $dummy = DB::em()->getConfiguration()->getMetadataDriverImpl();
         $dummy->addPaths(array(APPLICATION_PATH . '/models'));
         $metadatas = DB::em()->getMetadataFactory()->getAllMetadata();
         if (!empty($metadatas)) {
             $schemaTool = new \Doctrine\ORM\Tools\SchemaTool(DB::em());
             $sqls = $schemaTool->getUpdateSchemaSql($metadatas, true);
             if (!empty($sqls)) {
                 if (App::$inst->request->post('update')) {
                     $schemaTool->updateSchema($metadatas, true);
                     $message = 'Database schema updated successfully!';
                 } else {
                     $message = 'List of updates:<br/>';
                     $message .= implode(';' . PHP_EOL, $sqls) . ';';
                 }
             } else {
                 $message = 'SQLs are empty. Database schema is up to date';
             }
         } else {
             $message = 'Database schema is up to date';
         }
     } catch (Exception $e) {
         $success = false;
         $message = $e->getMessage() . $e->getTraceAsString();
     }
     $this->jsonResponse($success, $message);
 }
Example #2
0
 /**
  * Checks if the schema is up-to-date. If yes, it returns "complete", if not, it returns "incomplete".
  * 
  * @param none
  * @return string Either "complete" or "incomplete"
  */
 protected function getSchemaStatus()
 {
     $metadatas = PartKeepr::getEM()->getMetadataFactory()->getAllMetadata();
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool(PartKeepr::getEM());
     $queries = $schemaTool->getUpdateSchemaSql($metadatas, true);
     if (count($queries) > 0) {
         return "incomplete";
     } else {
         return "complete";
     }
 }
 public function update_dump_sql()
 {
     $driver = $this->em->getConfiguration()->getMetadataDriverImpl();
     $entities_names = $driver->getAllClassNames();
     $entities_metadata = array();
     foreach ($entities_names as $name) {
         array_push($entities_metadata, $this->em->getClassMetadata($name));
     }
     $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     return $tool->getUpdateSchemaSql($entities_metadata);
 }
 /**
  * @see Console\Command\Command
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $container = $this->getApplication()->getKernel()->getContainer();
     $em = $container->getService('em');
     $entityMetaClasses = array();
     foreach ($input->getArgument('entity') as $entity) {
         $entityMetaClasses[] = $em->getClassMetadata($entity);
     }
     $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
     if ($input->getOption('alter')) {
         $schema = $tool->getUpdateSchemaSql($entityMetaClasses, true);
     } else {
         $schema = $tool->getCreateSchemaSql($entityMetaClasses);
     }
     array_walk($schema, function (&$value) {
         $value = $value . ';';
     });
     $output->writeln($schema);
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output 
  */
 protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output)
 {
     $emHelper = $this->getHelper('em');
     /* @var $em \Doctrine\ORM\EntityManager */
     $em = $emHelper->getEntityManager();
     $metadatas = $em->getMetadataFactory()->getAllMetadata();
     if (!empty($metadatas)) {
         // Create SchemaTool
         $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
         $updateSql = $tool->getUpdateSchemaSql($metadatas, false);
         if (count($updateSql) == 0) {
             $output->write("[Database] OK - Metadata schema exactly matches the database schema.");
         } else {
             $output->write("[Database] FAIL - There are differences between metadata and database schema.");
         }
     } else {
         $output->write("No metadata mappings found");
     }
 }
Example #6
0
 /**
  * Secret function, to create/update database schema from doctrine entities
  * @param type $mode
  * @return type
  */
 function db_schema($mode = "update")
 {
     try {
         $this->em = $this->doctrine->em;
         $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
         $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
         $cmf->setEntityManager($this->em);
         $metadata = $cmf->getAllMetadata();
         if ($mode == "create") {
             $queries = $tool->getCreateSchemaSql($metadata);
         } else {
             $queries = $tool->getUpdateSchemaSql($metadata);
         }
         echo "Total queries: " . count($queries) . "<br /><br />";
         for ($i = 0; $i < count($queries); $i++) {
             $this->db->query($queries[$i]);
             echo $queries[$i] . "<br /><br />Execution Successfull: " . ($i + 1) . "<br /><br />";
         }
     } catch (Exception $err) {
         log_message("error", $err->getMessage());
         return show_error($err->getMessage());
     }
 }
 /**
  * Updates the DB schema using Doctrine's SchemaTool. The $safeMode flag is passed
  * to SchemaTool unchanged.
  *
  * @param boolean $safeMode
  * @param string $outputPathAndFilename A file to write SQL to, instead of executing it
  * @return string
  */
 public function updateSchema($safeMode = true, $outputPathAndFilename = null)
 {
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
     if ($outputPathAndFilename === null) {
         $schemaTool->updateSchema($this->entityManager->getMetadataFactory()->getAllMetadata(), $safeMode);
     } else {
         file_put_contents($outputPathAndFilename, implode(PHP_EOL, $schemaTool->getUpdateSchemaSql($this->entityManager->getMetadataFactory()->getAllMetadata(), $safeMode)));
     }
 }
Example #8
0
 /**
  * Execute this command
  * @param array $arguments Array of commandline arguments
  */
 public function execute(array $arguments)
 {
     $arguments = array_slice($arguments, 1);
     switch ($arguments[1]) {
         // empty /tmp/workbench
         case 'cleanup':
             $this->cleanup();
             break;
             // update database for component
         // update database for component
         case 'up':
         case 'update':
             // empty /tmp/workbench
             $this->cleanup();
             // prepare component filter
             $componentFilter = '';
             if (isset($arguments[2])) {
                 switch (strtolower($arguments[2])) {
                     case 'core':
                         $componentFilter .= 'Cx\\Core\\';
                         break;
                     case 'core_module':
                     case 'core_modules':
                         $componentFilter .= 'Cx\\Core_Modules\\';
                         break;
                     case 'module':
                     case 'modules':
                         $componentFilter .= 'Cx\\Modules\\';
                         break;
                 }
                 if (isset($arguments[3])) {
                     $componentFilter .= $arguments[3] . '\\';
                 }
             }
             if (!empty($componentFilter)) {
                 $componentFilter = '--filter=' . $componentFilter;
             }
             // doctrine orm:generate-entities --filter="{component filter}" entities
             $doctrineArgs = array('', 'doctrine', 'orm:generate-entities');
             if (!empty($componentFilter)) {
                 $doctrineArgs[] = $componentFilter;
             }
             $doctrineArgs[] = $this->cx->getWebsiteTempPath() . '/workbench';
             if ($this->executeDoctrine($doctrineArgs) != 0) {
                 return;
             }
             // move entities to component directory and add .class extension
             $modelMovedCompletely = $this->moveModel($this->cx->getWebsiteTempPath() . '/workbench/Cx', $this->cx->getWebsiteDocumentRootPath());
             // if all files could be moved, cleanup
             // if not: ask if moving should be forced (CAUTION!)
             if (!$modelMovedCompletely) {
                 echo "\r\n" . 'Not all entity files could be moved to their correct location. This is probably because there\'s an existing file there. ';
                 echo 'I can overwrite these files for you, but it is recommended, that you diff the changes manually. ';
                 if ($this->interface->yesNo('Would you like me to overwrite the files?')) {
                     $modelMovedCompletely = $this->moveModel($this->cx->getWebsiteTempPath() . '/workbench/Cx', $this->cx->getWebsiteDocumentRootPath(), true);
                 }
             }
             // doctrine orm:generate-repositories --filter="{component filter}" repositories
             $doctrineArgs = array('', 'doctrine', 'orm:generate-repositories');
             if (!empty($componentFilter)) {
                 $doctrineArgs[] = $componentFilter;
             }
             $doctrineArgs[] = $this->cx->getWebsiteTempPath() . '/workbench';
             if ($this->executeDoctrine($doctrineArgs) != 0) {
                 return;
             }
             // move repositories to component directory and add .class extension
             $modelMovedCompletely = $modelMovedCompletely && $this->moveModel($this->cx->getWebsiteTempPath() . '/workbench/Cx', $this->cx->getWebsiteDocumentRootPath());
             // if all files could be moved, cleanup
             // if not: ask if moving should be forced (CAUTION!)
             if (!$modelMovedCompletely) {
                 echo "\r\n" . 'Not all model files could be moved to their correct location. This is probably because there\'s an existing file there. ';
                 echo 'I can overwrite these files for you, but it is recommended, that you diff the changes manually. ';
                 if ($this->interface->yesNo('Would you like me to overwrite the files?')) {
                     $modelMovedCompletely = $this->moveModel($this->cx->getWebsiteTempPath() . '/workbench/Cx', $this->cx->getWebsiteDocumentRootPath(), true);
                 }
                 if (!$modelMovedCompletely) {
                     if ($this->interface->yesNo('There are remaining files in tmp/workbench. Should I remove them?')) {
                         $this->cleanup();
                     }
                 }
             } else {
                 $this->cleanup();
             }
             // doctrine orm:schema-tool:create --dump-sql
             // print queries and ask if those should be executed (CAUTION!)
             $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->cx->getDb()->getEntityManager());
             $metadatas = $this->cx->getDb()->getEntityManager()->getMetadataFactory()->getAllMetadata();
             $queries = $schemaTool->getUpdateSchemaSql($metadatas);
             foreach ($queries as $query) {
                 echo $query . "\r\n";
             }
             echo 'The above queries were generated for updating the database. Should I execute them on the database? ';
             if ($this->interface->yesNo('WARNING: Please check the SQL statements carefully and create a database backup before saying yes!')) {
                 $connection = $this->cx->getDb()->getEntityManager()->getConnection();
                 $i = 0;
                 foreach ($queries as $query) {
                     $query = trim($query);
                     if (empty($query)) {
                         continue;
                     }
                     $connection->executeQuery($query);
                     $i++;
                 }
                 echo 'Wrote ' . $i . ' queries to DB' . "\r\n";
             }
             // doctrine orm:validate-schema
             $this->validateSchema();
             if ($this->validateSchema() != 0) {
                 echo 'Your schema is not valid. Please correct this in before you proceed';
                 return;
             }
             break;
         case 'doctrine':
             $this->executeDoctrine($arguments);
             break;
         case 'help':
         default:
             echo 'Command `' . $this->getName() . "`\r\n" . $this->getDescription() . "\r\n\r\n" . $this->getSynopsis() . "\r\n\r\n" . $this->getHelp() . "\r\n";
             break;
     }
     echo "Done\r\n";
 }
Example #9
0
 public function updateSchema()
 {
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     $classes = $this->em->getMetadataFactory()->getAllMetadata();
     $sql = $schemaTool->getUpdateSchemaSql($classes);
     $schemaTool->updateSchema($classes, true);
     return $sql;
 }
Example #10
0
<?php

/*
 * Copyright 2015 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md. 
 */
if (cli\choose("Are you sure", 'yn', 'n') == 'n') {
    exit;
}
require_once $cmds['cache-clear']->name();
$schema = new \Doctrine\ORM\Tools\SchemaTool($app->em->value());
cli\line('Calculating changes..');
$stmts = $schema->getUpdateSchemaSql($app->em->getMetadataFactory()->getAllMetadata(), false);
if (!count($stmts)) {
    cli\line("Nothing to update");
    exit;
}
cli\line("The following statements will be executed:\n  " . implode("\n  ", $stmts));
if (cli\choose("Execute these statements", 'yn', 'n') == 'n') {
    exit;
}
$app->em->beginTransaction();
try {
    $bar = new cli\progress\Bar("Executing statements..", count($stmts), 1);
    $conn = $app->em->getConnection();
    foreach ($stmts as $stmt) {
        $conn->exec($stmt);
        $bar->tick();
    }
    $bar->finish();
    $app->em->commit();
Example #11
0
 /**
  * Get DB schema
  *
  * @param string $mode Schema generation mode OPTIONAL
  *
  * @return array(string)
  */
 public function getDBSchema($mode = self::SCHEMA_CREATE)
 {
     $tool = new \Doctrine\ORM\Tools\SchemaTool(static::$em);
     $schemas = array();
     $rawSchemas = null;
     $postprocessMethod = null;
     if (static::SCHEMA_CREATE == $mode) {
         $rawSchemas = $tool->getCreateSchemaSql($this->getAllMetadata());
         $postprocessMethod = 'postprocessCreateSchema';
     } elseif (static::SCHEMA_UPDATE == $mode) {
         $rawSchemas = $tool->getUpdateSchemaSql($this->getAllMetadata());
         $postprocessMethod = 'postprocessUpdateSchema';
     } elseif (static::SCHEMA_DELETE == $mode) {
         $rawSchemas = $tool->getDropSchemaSql($this->getAllMetadata());
         $postprocessMethod = 'postprocessDropSchema';
     }
     if ($rawSchemas) {
         foreach ($rawSchemas as $schema) {
             // $postprocessMethod detected by $mode
             $schema = $this->{$postprocessMethod}($schema);
             if (is_array($schema)) {
                 $schemas = array_merge($schemas, $schema);
             } elseif (isset($schema) && $schema) {
                 $schemas[] = $schema;
             }
         }
         foreach (static::$em->getMetadataFactory()->getAllMetadata() as $cmd) {
             if (!$cmd->isMappedSuperclass) {
                 $schemas = static::getRepo($cmd->name)->processSchema($schemas, $mode);
             }
         }
         $schemas = array_map('trim', $schemas);
         $schemas = preg_grep('/^.+$/Ss', $schemas);
     }
     return $schemas;
 }
Example #12
0
 /**
  * Returns schema from doctrine
  *
  * @param string $mode Schema generation mode OPTIONAL
  *
  * @return array
  */
 protected function getDBSchemaFromDoctrine($mode = self::SCHEMA_CREATE)
 {
     $tool = new \Doctrine\ORM\Tools\SchemaTool(static::$em);
     switch ($mode) {
         case static::SCHEMA_CREATE:
             $result = $tool->getCreateSchemaSql($this->getAllMetadata());
             break;
         case static::SCHEMA_UPDATE:
             $result = $tool->getUpdateSchemaSql($this->getAllMetadata());
             break;
         case static::SCHEMA_DELETE:
             $result = $tool->getDropSchemaSql($this->getAllMetadata());
             break;
         default:
             $result = array();
     }
     return array_unique($result);
 }