/** * Returns a MySqlComparisonSchema reflecting the schema of a database table. * * @param $tableName * @return MySqlComparisonSchema */ public static function fromTable($tableName) { $repos = Repository::getDefaultRepositoryClassName(); // Get the create table syntax for the table - we'll analyse this and build our schema accordingly. $row = $repos::returnFirstRow("SHOW CREATE TABLE {$tableName}"); $sql = $row["Create Table"]; $lines = explode("\n", $sql); // First and last lines aren't needed $lines = array_slice($lines, 1, -1); $comparisonSchema = new MySqlComparisonSchema(); foreach ($lines as $line) { $line = trim($line); // If the line starts with a back tick we have a column if ($line[0] == "`") { $default = null; preg_match("/`([^`]+)`/", rtrim($line, ','), $matches); $name = $matches[1]; $comparisonSchema->columns[$name] = rtrim(trim($line), ","); } else { $words = explode(" ", $line); $indexKeywords = ["PRIMARY", "KEY", "UNIQUE"]; if (in_array($words[0], $indexKeywords)) { $comparisonSchema->indexes[] = preg_replace('/\\s+/', ' ', rtrim(trim($line), ",")); } } } return $comparisonSchema; }
/** * Creates the table in the back end data store. */ private function createTable() { $sql = "CREATE TABLE " . $this->schemaName . " ("; $definitions = []; foreach ($this->columns as $columnName => $column) { // The column might be using a more generic type for it's storage. $storageColumns = $column->createStorageColumns(); foreach ($storageColumns as $storageColumn) { // And if so that column will be a generic column type - we need to upgrade it. $storageColumn = $storageColumn->getRepositorySpecificColumn("MySql"); $definitions[] = $storageColumn->getDefinition(); } } foreach ($this->indexes as $indexName => $index) { $definitions[] = $index->getDefinition(); } $sql .= implode(",", $definitions); $sql .= "\n\t\t\t)"; $repos = Repository::getDefaultRepositoryClassName(); $repos::executeStatement($sql); }