public function parse(Database $database, Task $task = null)
 {
     $dataFetcher = $this->dbh->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'dtproperties'");
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     foreach ($dataFetcher as $row) {
         $name = $this->cleanDelimitedIdentifiers($row[0]);
         if ($name === $this->getMigrationTable()) {
             continue;
         }
         $table = new Table($name);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         $tables[] = $table;
     }
     // Now populate only columns.
     foreach ($tables as $table) {
         $this->addColumns($table);
     }
     // Now add indexes and constraints.
     foreach ($tables as $table) {
         $this->addForeignKeys($table);
         $this->addIndexes($table);
         $this->addPrimaryKey($table);
     }
     return count($tables);
 }
 protected function parseTables(Database $database, $filterTable = null)
 {
     $sql = 'SHOW FULL TABLES';
     if ($filterTable) {
         if ($schema = $filterTable->getSchema()) {
             $sql .= ' FROM ' . $database->getPlatform()->doQuoting($schema);
         }
         $sql .= sprintf(" LIKE '%s'", $filterTable->getCommonName());
     } else {
         if ($schema = $database->getSchema()) {
             $sql .= ' FROM ' . $database->getPlatform()->doQuoting($schema);
         }
     }
     $dataFetcher = $this->dbh->query($sql);
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     foreach ($dataFetcher as $row) {
         $name = $row[0];
         $type = $row[1];
         if ($name == $this->getMigrationTable() || $type !== 'BASE TABLE') {
             continue;
         }
         $table = new Table($name);
         $table->setIdMethod($database->getDefaultIdMethod());
         if ($filterTable && $filterTable->getSchema()) {
             $table->setSchema($filterTable->getSchema());
         }
         $database->addTable($table);
         $tables[] = $table;
     }
 }
 /**
  *
  */
 public function parse(Database $database)
 {
     $this->addVendorInfo = $this->getGeneratorConfig()->getBuildProperty('addVendorInfo');
     $sql = 'SHOW FULL TABLES';
     if ($schema = $database->getSchema()) {
         $sql .= ' FROM ' . $database->getPlatform()->quoteIdentifier($schema);
     }
     $dataFetcher = $this->dbh->query($sql);
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     foreach ($dataFetcher as $row) {
         $name = $row[0];
         $type = $row[1];
         if ($name == $this->getMigrationTable() || $type !== 'BASE TABLE') {
             continue;
         }
         $table = new Table($name);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         $tables[] = $table;
     }
     // Now populate only columns.
     foreach ($tables as $table) {
         $this->addColumns($table);
     }
     // Now add indices and constraints.
     foreach ($tables as $table) {
         $this->addForeignKeys($table);
         $this->addIndexes($table);
         $this->addPrimaryKey($table);
         $this->addTableVendorInfo($table);
     }
     return count($tables);
 }
Exemplo n.º 4
0
 /**
  *
  */
 public function parse(Database $database)
 {
     $dataFetcher = $this->dbh->query("SELECT name FROM sqlite_master WHERE type='table' UNION ALL SELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name;");
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     foreach ($dataFetcher as $row) {
         $name = $row[0];
         if ($name === $this->getMigrationTable()) {
             continue;
         }
         $table = new Table($name);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         $tables[] = $table;
     }
     // Now populate only columns.
     foreach ($tables as $table) {
         $this->addColumns($table);
     }
     // Now add indexes and constraints.
     foreach ($tables as $table) {
         $this->addIndexes($table);
     }
     return count($tables);
 }
 public function testTableNamespaceAndDbNamespace()
 {
     $d = new Database('fooDb');
     $d->setNamespace('Baz');
     $t = new Table('fooTable');
     $t->setNamespace('Foo\\Bar');
     $d->addTable($t);
     $builder = new TestableOMBuilder2($t);
     $this->assertEquals('Baz\\Foo\\Bar', $builder->getNamespace(), 'Builder namespace is composed from the database and table namespaces when both are set');
 }
Exemplo n.º 6
0
 protected function validateDatabaseTables(Database $database)
 {
     $phpNames = array();
     foreach ($database->getTables() as $table) {
         if (in_array($table->getPhpName(), $phpNames)) {
             $this->errors[] = sprintf('Table "%s" declares a phpName already used in another table', $table->getName());
         }
         $phpNames[] = $table->getPhpName();
         $this->validateTableAttributes($table);
         $this->validateTableColumns($table);
     }
 }
 public function testParse()
 {
     $parser = new MysqlSchemaParser(Propel::getConnection('reverse-bookstore'));
     $parser->setGeneratorConfig(new QuickGeneratorConfig());
     $database = new Database();
     $database->setPlatform(new DefaultPlatform());
     $this->assertEquals(1, $parser->parse($database), 'One table and one view defined should return one as we exclude views');
     $tables = $database->getTables();
     $this->assertEquals(1, count($tables));
     $table = $tables[0];
     $this->assertEquals('Book', $table->getPhpName());
     $this->assertEquals(4, count($table->getColumns()));
 }
Exemplo n.º 8
0
 /**
  *
  */
 public function parse(Database $database, Task $task = null)
 {
     $this->addVendorInfo = $this->getGeneratorConfig()->getBuildProperty('addVendorInfo');
     $stmt = $this->dbh->query("SHOW FULL TABLES");
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     if ($task) {
         $task->log("Reverse Engineering Tables", Project::MSG_VERBOSE);
     }
     while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
         $name = $row[0];
         $type = $row[1];
         if ($name == $this->getMigrationTable() || $type != "BASE TABLE") {
             continue;
         }
         if ($task) {
             $task->log("  Adding table '" . $name . "'", Project::MSG_VERBOSE);
         }
         $table = new Table($name);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         $tables[] = $table;
     }
     // Now populate only columns.
     if ($task) {
         $task->log("Reverse Engineering Columns", Project::MSG_VERBOSE);
     }
     foreach ($tables as $table) {
         if ($task) {
             $task->log("  Adding columns for table '" . $table->getName() . "'", Project::MSG_VERBOSE);
         }
         $this->addColumns($table);
     }
     // Now add indices and constraints.
     if ($task) {
         $task->log("Reverse Engineering Indices And Constraints", Project::MSG_VERBOSE);
     }
     foreach ($tables as $table) {
         if ($task) {
             $task->log("  Adding indices and constraints for table '" . $table->getName() . "'", Project::MSG_VERBOSE);
         }
         $this->addForeignKeys($table);
         $this->addIndexes($table);
         $this->addPrimaryKey($table);
         if ($this->addVendorInfo) {
             $this->addTableVendorInfo($table);
         }
     }
     return count($tables);
 }
 /**
  * Detects the differences between current connected database and $pDatabase
  * and updates the schema. This does not DROP tables.
  *
  * @param Database $pDatabase
  */
 public function updateSchema($pDatabase)
 {
     $diff = DatabaseComparator::computeDiff($this->database, $pDatabase);
     $sql = $this->database->getPlatform()->getModifyDatabaseDDL($diff);
     $statements = SqlParser::parseString($sql);
     foreach ($statements as $statement) {
         if (strpos($statement, 'DROP') === 0) {
             // drop statements cause errors since the table doesn't exist
             continue;
         }
         $stmt = $this->con->prepare($statement);
         $stmt->execute();
     }
 }
Exemplo n.º 10
0
 public function testValidateReturnsFalseWhenTwoTablesHaveSamePhpName()
 {
     $table1 = new Table('foo');
     $table2 = new Table('bar');
     $table2->setPhpName('Foo');
     $database = new Database();
     $database->addTable($table1);
     $database->addTable($table2);
     $appData = new AppData();
     $appData->addDatabase($database);
     $validator = new SchemaValidator($appData);
     $this->assertFalse($validator->validate());
     $this->assertContains('Table "bar" declares a phpName already used in another table', $validator->getErrors());
 }
Exemplo n.º 11
0
 /**
  * Create FormTypes from a given database, bundle and models.
  *
  * @param BundleInterface $bundle   The bundle for which the FormTypes will be generated.
  * @param Database        $database The database to inspect.
  * @param array           $models   The models to build.
  * @param OutputInterface $output   An OutputInterface instance
  * @param boolean         $force    Override files if present.
  */
 protected function createFormTypeFromDatabase(BundleInterface $bundle, Database $database, $models, OutputInterface $output, $force = false)
 {
     $dir = $this->createDirectory($bundle, $output);
     foreach ($database->getTables() as $table) {
         if (0 < count($models) && !in_array($table->getPhpName(), $models)) {
             continue;
         }
         $file = new \SplFileInfo(sprintf('%s/%sType.php', $dir, $table->getPhpName()));
         if (!file_exists($file) || true === $force) {
             $this->writeFormType($bundle, $table, $file, $force, $output);
         } else {
             $output->writeln(sprintf('File <comment>%-60s</comment> exists, skipped. Try the <info>--force</info> option.', $this->getRelativeFileName($file)));
         }
     }
 }
Exemplo n.º 12
0
 /**
  * Appends the generated <database> XML node to its parent node.
  *
  * @param Database $database   The Database model instance
  * @param \DOMNode $parentNode The parent DOMNode object
  */
 private function appendDatabaseNode(Database $database, \DOMNode $parentNode)
 {
     $databaseNode = $parentNode->appendChild($this->document->createElement('database'));
     $databaseNode->setAttribute('name', $database->getName());
     $databaseNode->setAttribute('defaultIdMethod', $database->getDefaultIdMethod());
     if ($package = $database->getPackage()) {
         $databaseNode->setAttribute('package', $package);
     }
     if ($schema = $database->getSchema()) {
         $databaseNode->setAttribute('schema', $schema);
     }
     if ($namespace = $database->getNamespace()) {
         $databaseNode->setAttribute('namespace', $namespace);
     }
     if ($baseClass = $database->getBaseClass()) {
         $databaseNode->setAttribute('baseClass', $baseClass);
     }
     if ($baseQueryClass = $database->getBaseQueryClass()) {
         $databaseNode->setAttribute('baseQueryClass', $baseQueryClass);
     }
     if ($defaultNamingMethod = $database->getDefaultPhpNamingMethod()) {
         $databaseNode->setAttribute('defaultPhpNamingMethod', $defaultNamingMethod);
     }
     $defaultAccessorVisibility = $database->getDefaultAccessorVisibility();
     if ($defaultAccessorVisibility !== Database::VISIBILITY_PUBLIC) {
         $databaseNode->setAttribute('defaultAccessorVisibility', $defaultAccessorVisibility);
     }
     $defaultMutatorVisibility = $database->getDefaultMutatorVisibility();
     if ($defaultMutatorVisibility !== Database::VISIBILITY_PUBLIC) {
         $databaseNode->setAttribute('defaultMutatorVisibility', $defaultMutatorVisibility);
     }
     $defaultStringFormat = $database->getDefaultStringFormat();
     if (Database::DEFAULT_STRING_FORMAT !== $defaultStringFormat) {
         $databaseNode->setAttribute('defaultStringFormat', $defaultStringFormat);
     }
     if ($database->isHeavyIndexing()) {
         $databaseNode->setAttribute('heavyIndexing', 'true');
     }
     if ($tablePrefix = $database->getTablePrefix()) {
         $databaseNode->setAttribute('tablePrefix', $tablePrefix);
     }
     if ($database->isIdentifierQuotingEnabled()) {
         $databaseNode->setAttribute('identifierQuoting', 'true');
     }
     /*
        FIXME - Before we can add support for domains in the schema, we need
        to have a method of the Column that indicates whether the column was mapped
        to a SPECIFIC domain (since Column->getDomain() will always return a Domain object)
     
        foreach ($this->domainMap as $domain) {
            $this->appendDomainNode($databaseNode);
        }
     */
     foreach ($database->getVendorInformation() as $vendorInformation) {
         $this->appendVendorInformationNode($vendorInformation, $databaseNode);
     }
     foreach ($database->getTables() as $table) {
         $this->appendTableNode($table, $databaseNode);
     }
 }
Exemplo n.º 13
0
 /**
  *
  */
 public function parse(Database $database)
 {
     $stmt = $this->dbh->query('SELECT version() as ver');
     $nativeVersion = $stmt->fetchColumn();
     if (!$nativeVersion) {
         throw new EngineException('Failed to get database version');
     }
     $arrVersion = sscanf($nativeVersion, '%*s %d.%d');
     $version = sprintf('%d.%d', $arrVersion[0], $arrVersion[1]);
     // Clean up
     $stmt = null;
     $stmt = $this->dbh->query("SELECT c.oid,\n            c.relname, n.nspname\n            FROM pg_class c join pg_namespace n on (c.relnamespace=n.oid)\n            WHERE c.relkind = 'r'\n            AND n.nspname NOT IN ('information_schema','pg_catalog')\n            AND n.nspname NOT LIKE 'pg_temp%'\n            AND n.nspname NOT LIKE 'pg_toast%'\n            ORDER BY relname");
     $tableWraps = array();
     // First load the tables (important that this happen before filling out details of tables)
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         $name = $row['relname'];
         $namespacename = $row['nspname'];
         if ($name == $this->getMigrationTable()) {
             continue;
         }
         $oid = $row['oid'];
         $table = new Table($name);
         if ($namespacename != 'public') {
             $table->setSchema($namespacename);
         }
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         // Create a wrapper to hold these tables and their associated OID
         $wrap = new \stdClass();
         $wrap->table = $table;
         $wrap->oid = $oid;
         $tableWraps[] = $wrap;
     }
     // Now populate only columns.
     foreach ($tableWraps as $wrap) {
         $this->addColumns($wrap->table, $wrap->oid, $version);
     }
     // Now add indexes and constraints.
     foreach ($tableWraps as $wrap) {
         $this->addForeignKeys($wrap->table, $wrap->oid, $version);
         $this->addIndexes($wrap->table, $wrap->oid, $version);
         $this->addPrimaryKey($wrap->table, $wrap->oid, $version);
     }
     // @TODO - Handle Sequences ...
     return count($tableWraps);
 }
Exemplo n.º 14
0
 /**
  * Returns the DDL SQL to add the tables of a database
  * together with index and foreign keys. 
  * Since MSSQL always checks it the tables in foreign key definitions exist, 
  * the foreign key DDLs are moved after all tables are created
  *
  * @return string
  */
 public function getAddTablesDDL(Database $database)
 {
     $ret = $this->getBeginDDL();
     foreach ($database->getTablesForSql() as $table) {
         $this->normalizeTable($table);
     }
     foreach ($database->getTablesForSql() as $table) {
         $ret .= $this->getCommentBlockDDL($table->getName());
         $ret .= $this->getDropTableDDL($table);
         $ret .= $this->getAddTableDDL($table);
         $ret .= $this->getAddIndicesDDL($table);
     }
     foreach ($database->getTablesForSql() as $table) {
         $ret .= $this->getAddForeignKeysDDL($table);
     }
     $ret .= $this->getEndDDL();
     return $ret;
 }
Exemplo n.º 15
0
 protected function parseTables(Database $database, Table $filterTable = null)
 {
     $sql = "\n        SELECT name\n        FROM sqlite_master\n        WHERE type='table'\n        %filter%\n        UNION ALL\n        SELECT name\n        FROM sqlite_temp_master\n        WHERE type='table'\n        %filter%\n        ORDER BY name;";
     $filter = '';
     if ($filterTable) {
         if ($schema = $filterTable->getSchema()) {
             $filter = sprintf(" AND name LIKE '%s§%%'", $schema);
         }
         $filter .= sprintf(" AND (name = '%s' OR name LIKE '%%§%1\$s')", $filterTable->getCommonName());
     } else {
         if ($schema = $database->getSchema()) {
             $filter = sprintf(" AND name LIKE '%s§%%'", $schema);
         }
     }
     $sql = str_replace('%filter%', $filter, $sql);
     $dataFetcher = $this->dbh->query($sql);
     // First load the tables (important that this happen before filling out details of tables)
     foreach ($dataFetcher as $row) {
         $tableName = $row[0];
         $tableSchema = '';
         if ('sqlite_' == substr($tableName, 0, 7)) {
             continue;
         }
         if (false !== ($pos = strpos($tableName, '§'))) {
             $tableSchema = substr($tableName, 0, $pos);
             $tableName = substr($tableName, $pos + 2);
         }
         $table = new Table($tableName);
         if ($filterTable && $filterTable->getSchema()) {
             $table->setSchema($filterTable->getSchema());
         } else {
             if (!$database->getSchema() && $tableSchema) {
                 //we have no schema to filter, but this belongs to one, so next
                 continue;
             }
         }
         if ($tableName === $this->getMigrationTable()) {
             continue;
         }
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
     }
 }
Exemplo n.º 16
0
 /**
  * Compares the current database with $database.
  *
  * @param Database $database
  */
 public function compareCurrentDatabase(Database $database)
 {
     $this->readDatabase();
     $diff = DatabaseComparator::computeDiff($this->database, $database);
     if (false !== $diff) {
         $sql = $this->database->getPlatform()->getModifyDatabaseDDL($diff);
         $this->fail(sprintf("There are unexpected diffs: \n%s\n`%s`\nCurrent Database: \n%s\nTo XML Database: \n%s\n", $diff, $sql, $this->database, $database));
     }
     $this->assertFalse($diff, 'no changes.');
 }
Exemplo n.º 17
0
 /**
  * Compares the current database with $database.
  *
  * @param Database $database
  * @throws BuildException if a difference has been found between $database and the real database
  */
 public function compareCurrentDatabase(Database $database)
 {
     $this->readDatabase();
     $diff = DatabaseComparator::computeDiff($this->database, $database);
     if (false !== $diff) {
         $sql = $this->database->getPlatform()->getModifyDatabaseDDL($diff);
         throw new BuildException(sprintf("There are unexpected diffs (real to model): \n%s\n-----%s-----\nCurrent Database: \n%s\nTo XML Database: \n%s\n", $diff, $sql, $this->database, $database));
     }
     $this->assertFalse($diff, 'no changes.');
 }
Exemplo n.º 18
0
 /**
  * @return Database
  */
 public function readConnectedDatabase()
 {
     $this->getDatabase();
     $database = new Database();
     $database->setSchema($this->database->getSchema());
     $database->setName($this->database->getName());
     $database->setPlatform($this->getPlatform());
     $this->getParser()->parse($database);
     return $database;
 }
 /**
  * @dataProvider parseDataProvider
  */
 public function testParse($columnDDL, $expectedColumnPhpName, $expectedColumnDefaultType, $expectedColumnDefaultValue, $expectedSize, $expectedScale)
 {
     $this->con->query("create table foo ( {$columnDDL} );");
     $parser = new PgsqlSchemaParser($this->con);
     $parser->setGeneratorConfig(new QuickGeneratorConfig());
     $database = new Database();
     $database->setPlatform(new DefaultPlatform());
     // make sure our DDL insert produced exactly the SQL we inserted
     $this->assertGreaterThanOrEqual(1, $parser->parse($database), 'We parsed at least one table.');
     $table = $database->getTable('foo');
     $columns = $table->getColumns();
     $this->assertEquals(1, count($columns));
     // check out our rev-eng column info
     $defaultValue = $columns[0]->getDefaultValue();
     $this->assertEquals($expectedColumnPhpName, $columns[0]->getPhpName());
     $this->assertEquals($expectedColumnDefaultType, $defaultValue->getType());
     $this->assertEquals($expectedColumnDefaultValue, $defaultValue->getValue());
     $this->assertEquals($expectedSize, $columns[0]->getSize());
     $this->assertEquals($expectedScale, $columns[0]->getScale());
 }
Exemplo n.º 20
0
 protected function validateDatabaseTables(Database $database)
 {
     $phpNames = [];
     $namespaces = [];
     foreach ($database->getTables() as $table) {
         $list =& $phpNames;
         if ($table->getNamespace()) {
             if (!isset($namespaces[$table->getNamespace()])) {
                 $namespaces[$table->getNamespace()] = [];
             }
             $list =& $namespaces[$table->getNamespace()];
         }
         if (in_array($table->getPhpName(), $list)) {
             $this->errors[] = sprintf('Table "%s" declares a phpName already used in another table', $table->getName());
         }
         $list[] = $table->getPhpName();
         $this->validateTableAttributes($table);
         $this->validateTableColumns($table);
     }
 }
Exemplo n.º 21
0
 /**
  * Searches for tables in the database. Maybe we want to search also the views.
  * @param Database $database The Database model class to add tables to.
  * @param Table[]  $additionalTables
  */
 public function parse(Database $database, array $additionalTables = array())
 {
     $tables = array();
     $stmt = $this->dbh->query("SELECT OBJECT_NAME FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE'");
     $seqPattern = $this->getGeneratorConfig()->get()['database']['adapters']['oracleAutoincrementSequencePattern'];
     // First load the tables (important that this happen before filling out details of tables)
     while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
         if (false !== strpos($row['OBJECT_NAME'], '$')) {
             // this is an Oracle internal table or materialized view - prune
             continue;
         }
         if (strtoupper($row['OBJECT_NAME']) === strtoupper($this->getMigrationTable())) {
             continue;
         }
         $table = new Table($row['OBJECT_NAME']);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         // Add columns, primary keys and indexes.
         $this->addColumns($table);
         $this->addPrimaryKey($table);
         $this->addIndexes($table);
         $pkColumns = $table->getPrimaryKey();
         if (1 === count($pkColumns) && $seqPattern) {
             $seqName = str_replace('${table}', $table->getName(), $seqPattern);
             $seqName = strtoupper($seqName);
             $stmt2 = $this->dbh->query("SELECT * FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '" . $seqName . "'");
             $hasSeq = $stmt2->fetch(\PDO::FETCH_ASSOC);
             if ($hasSeq) {
                 $pkColumns[0]->setAutoIncrement(true);
                 $idMethodParameter = new IdMethodParameter();
                 $idMethodParameter->setValue($seqName);
                 $table->addIdMethodParameter($idMethodParameter);
             }
         }
         $tables[] = $table;
     }
     foreach ($tables as $table) {
         $this->addForeignKeys($table);
     }
     return count($tables);
 }
 /**
  * Returns the number of differences.
  *
  * Compares the tables of the fromDatabase and the toDatabase, and modifies
  * the inner databaseDiff if necessary.
  *
  * @param  boolean $caseInsensitive
  * @return integer
  */
 public function compareTables($caseInsensitive = false)
 {
     $fromDatabaseTables = $this->fromDatabase->getTables();
     $toDatabaseTables = $this->toDatabase->getTables();
     $databaseDifferences = 0;
     $platform = $this->toDatabase->getPlatform() ?: $this->fromDatabase->getPlatform();
     // check for new tables in $toDatabase
     foreach ($toDatabaseTables as $table) {
         if ($platform) {
             $platform->normalizeTable($table);
         }
         if (!$this->fromDatabase->hasTable($table->getName(), $caseInsensitive) && !$table->isSkipSql()) {
             $this->databaseDiff->addAddedTable($table->getName(), $table);
             $databaseDifferences++;
         }
     }
     // check for removed tables in $toDatabase
     foreach ($fromDatabaseTables as $table) {
         if (!$this->toDatabase->hasTable($table->getName(), $caseInsensitive) && !$table->isSkipSql()) {
             $this->databaseDiff->addRemovedTable($table->getName(), $table);
             $databaseDifferences++;
         }
     }
     // check for table differences
     foreach ($fromDatabaseTables as $fromTable) {
         if ($this->toDatabase->hasTable($fromTable->getName(), $caseInsensitive)) {
             $toTable = $this->toDatabase->getTable($fromTable->getName(), $caseInsensitive);
             $databaseDiff = TableComparator::computeDiff($fromTable, $toTable, $caseInsensitive);
             if ($databaseDiff) {
                 $this->databaseDiff->addModifiedTable($fromTable->getName(), $databaseDiff);
                 $databaseDifferences++;
             }
         }
     }
     $renamed = [];
     // check for table renamings
     foreach ($this->databaseDiff->getAddedTables() as $addedTableName => $addedTable) {
         foreach ($this->databaseDiff->getRemovedTables() as $removedTableName => $removedTable) {
             if (!in_array($addedTableName, $renamed) && !TableComparator::computeDiff($addedTable, $removedTable, $caseInsensitive)) {
                 // no difference except the name, that's probably a renaming
                 $renamed[] = $addedTableName;
                 $this->databaseDiff->addRenamedTable($removedTableName, $addedTableName);
                 $this->databaseDiff->removeAddedTable($addedTableName);
                 $this->databaseDiff->removeRemovedTable($removedTableName);
                 $databaseDifferences--;
             }
         }
     }
     return $databaseDifferences;
 }
 /**
  *
  */
 public function parse(Database $database)
 {
     $dataFetcher = $this->dbh->query("\n        SELECT name\n        FROM sqlite_master\n        WHERE type='table'\n        UNION ALL\n        SELECT name\n        FROM sqlite_temp_master\n        WHERE type='table'\n        ORDER BY name;");
     // First load the tables (important that this happen before filling out details of tables)
     $tables = array();
     foreach ($dataFetcher as $row) {
         $name = $row[0];
         $commonName = '';
         if ('sqlite_' == substr($name, 0, 7)) {
             continue;
         }
         if ($database->getSchema()) {
             if (false !== ($pos = strpos($name, '§'))) {
                 if ($database->getSchema()) {
                     if ($database->getSchema() !== substr($name, 0, $pos)) {
                         continue;
                     } else {
                         $commonName = substr($name, $pos + 2);
                         //2 because the delimiter § uses in UTF8 one byte more.
                     }
                 }
             } else {
                 continue;
             }
         }
         if ($name === $this->getMigrationTable()) {
             continue;
         }
         $table = new Table($commonName ?: $name);
         $table->setIdMethod($database->getDefaultIdMethod());
         $database->addTable($table);
         $tables[] = $table;
     }
     // Now populate only columns.
     foreach ($tables as $table) {
         $this->addColumns($table);
     }
     // Now add indexes and constraints.
     foreach ($tables as $table) {
         $this->addIndexes($table);
         $this->addForeignKeys($table);
     }
     return count($tables);
 }
Exemplo n.º 24
0
 /**
  * Adds a database to the list and sets the Schema property to this
  * Schema. The database can be specified as a Database object or a
  * DOMNode object.
  *
  * @param  Database|array $database
  * @return Database
  */
 public function addDatabase($database)
 {
     if ($database instanceof Database) {
         $platform = null;
         $database->setParentSchema($this);
         if (null === $database->getPlatform()) {
             if ($config = $this->getGeneratorConfig()) {
                 $platform = $config->getConfiguredPlatform(null, $database->getName());
             }
             $database->setPlatform($platform ? $platform : $this->platform);
         }
         $this->databases[] = $database;
         return $database;
     }
     // XML attributes array / hash
     $db = new Database();
     $db->setParentSchema($this);
     $db->loadMapping($database);
     return $this->addDatabase($db);
 }
Exemplo n.º 25
0
 public function getAddTablesDDL(Database $database)
 {
     $ret = '';
     foreach ($database->getTablesForSql() as $table) {
         $ret .= $this->getCommentBlockDDL($table->getName());
         $ret .= $this->getDropTableDDL($table);
         $ret .= $this->getAddTableDDL($table);
     }
     if ($ret) {
         $ret = $this->getBeginDDL() . $ret . $this->getEndDDL();
     }
     return $ret;
 }
Exemplo n.º 26
0
 /**
  * Builds the model classes from the database schema.
  *
  * @return Database The built-out Database (with all tables, etc.)
  */
 protected function buildModel()
 {
     $config = $this->getGeneratorConfig();
     $connection = $this->getConnection();
     $databaseName = $config->getConfigProperty('reverse.connection');
     $database = new Database($this->getDatabaseName());
     $database->setPlatform($config->getConfiguredPlatform($connection), $databaseName);
     $database->setDefaultIdMethod(IdMethod::NATIVE);
     $buildConnection = $config->getBuildConnection($databaseName);
     $this->log(sprintf('Reading database structure of database `%s` using dsn `%s`', $this->getDatabaseName(), $buildConnection['dsn']));
     $parser = $config->getConfiguredSchemaParser($connection, $databaseName);
     $this->log(sprintf('SchemaParser `%s` chosen', get_class($parser)));
     $nbTables = $parser->parse($database);
     $excludeTables = $config->getConfigProperty('exclude_tables');
     $tables = [];
     foreach ($database->getTables() as $table) {
         /* Was copypasted from DatabaseComparator::isTableExcluded() */
         $skip = false;
         $tablename = $table->getName();
         if (in_array($tablename, $excludeTables)) {
             $skip = true;
         } else {
             foreach ($excludeTables as $exclude_tablename) {
                 if (preg_match('/^' . str_replace('*', '.*', $exclude_tablename) . '$/', $tablename)) {
                     $skip = true;
                 }
             }
         }
         $skip && $database->removeTable($table);
     }
     $this->log(sprintf('Successfully reverse engineered %d tables', $nbTables));
     return $database;
 }
Exemplo n.º 27
0
 public function testGetColumnDDLAutoIncrement()
 {
     $database = new Database();
     $database->setPlatform($this->getPlatform());
     $table = new Table('foo_table');
     $table->setIdMethod(IdMethod::NATIVE);
     $database->addTable($table);
     $column = new Column('foo');
     $column->getDomain()->copy($this->getPlatform()->getDomainForType(PropelTypes::BIGINT));
     $column->setAutoIncrement(true);
     $table->addColumn($column);
     $expected = 'foo bigserial';
     $this->assertEquals($expected, $this->getPlatform()->getColumnDDL($column));
 }
Exemplo n.º 28
0
 public function testTablePrefix()
 {
     $database = new Database();
     $database->loadMapping(array('name' => 'bookstore', 'defaultIdMethod' => 'native', 'defaultPhpNamingMethod' => 'underscore', 'tablePrefix' => 'acme_', 'defaultStringFormat' => 'XML'));
     $table = new Table();
     $database->addTable($table);
     $table->loadMapping(array('name' => 'books'));
     $this->assertEquals('Books', $table->getPhpName());
     $this->assertEquals('acme_books', $table->getCommonName());
 }
Exemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function getAddTablesDDL(Database $database)
 {
     $ret = '';
     foreach ($database->getTablesForSql() as $table) {
         $this->checkTable($table);
     }
     foreach ($database->getTablesForSql() as $table) {
         $ret .= $this->getCommentBlockDDL($table->getName());
         $ret .= $this->getDropTableDDL($table);
         $ret .= $this->getAddTableDDL($table);
         $ret .= $this->getAddIndicesDDL($table);
     }
     return $ret;
 }
Exemplo n.º 30
0
 public function getAddSchemasDDL(Database $database)
 {
     $ret = '';
     $schemas = array();
     foreach ($database->getTables() as $table) {
         $vi = $table->getVendorInfoForType('pgsql');
         if ($vi->hasParameter('schema') && !isset($schemas[$vi->getParameter('schema')])) {
             $schemas[$vi->getParameter('schema')] = true;
             $ret .= $this->getAddSchemaDDL($table);
         }
     }
     return $ret;
 }