* @license GPLv2 * @package tao */ namespace oat\generis\persistence\sql; use Doctrine\DBAL\Schema\AbstractSchemaManager; use oat\oatbox\log\LoggerAwareTrait; use Psr\Log\LoggerAwareInterface; use Doctrine\DBAL\Exception\ConnectionException; class SetupDb implements LoggerAwareInterface { use LoggerAwareTrait; /** * Setup the tables for the database * @param \common_persistence_SqlPersistence $p * @throws \common_exception_InconsistentData */ public function setupDatabase(\common_persistence_SqlPersistence $p) { $dbalDriver = $p->getDriver()->getDbalConnection(); $dbName = $dbalDriver->getDataBase(); $this->verifyDatabase($p, $dbName); $this->cleanDb($p); } /** * @author "Lionel Lecaque, " */ private function verifyDatabase(\common_persistence_SqlPersistence $p, $dbName) { $schemaManager = $p->getSchemaManager()->getDbalSchemaManager(); if (!$this->dbExists($schemaManager, $dbName)) { throw new \tao_install_utils_Exception('Unable to find the database, make sure that the db exists and that the db user has the rights to use it.'); } } /** * @author "Lionel Lecaque, " * @param string $dbName */ private function dbExists(AbstractSchemaManager $schemaManager, $dbName) { try { return in_array($dbName, $schemaManager->listDatabases()); } catch (ConnectionException $e) { $this->logWarning('Unable to connect to validate dbExists'); return false; } } /** * @author "Lionel Lecaque, " */ private function cleanDb(\common_persistence_SqlPersistence $p) { $schema = $p->getSchemaManager()->createSchema(); $queries = $p->getPlatForm()->toDropSql($schema); foreach ($queries as $query) { $p->exec($query); } } }