db->schema->getTableSchemas(); $addForeignKeys = ''; $dropForeignKeys = ''; $result = "createTable(\'' . $table->name . '\', array(' . "\n"; foreach ($table->columns as $col) { $result .= ' \'' . $col->name . '\' => ' . $this->getColType($col) . ',' . "\n"; if ($col->isPrimaryKey && !$col->autoIncrement) { // Add column to composite primary key array $compositePrimaryKeyCols[] = $col->name; } } $result .= ' ), \'\');' . "\n\n"; // Add foreign key(s) and create indexes foreach ($table->foreignKeys as $col => $fk) { // Foreign key naming convention: fk_table_foreignTable_col (max 64 characters) $refColumn = end($fk); $column = key($fk); $fkName = substr('fk_' . $table->name . '_' . $fk[0] . '_' . $column, 0 , 64); $addForeignKeys .= ' $this->addForeignKey(' . "'$fkName', '$table->name', '$column', '$fk[0]', '$refColumn', 'NO ACTION', 'NO ACTION');\n\n"; $dropForeignKeys .= ' $this->dropForeignKey(' . "'$fkName', '$table->name');\n\n"; // Index naming convention: idx_col $result .= ' $this->createIndex(\'idx_' . $column . "', '$table->name', '$column', FALSE);\n\n"; } // Add composite primary key for join tables if ($compositePrimaryKeyCols) { $result .= ' $this->addPrimaryKey(\'pk_' . $table->name . "', '$table->name', '" . implode(',', $compositePrimaryKeyCols) . "');\n\n"; } } $result .= $addForeignKeys; // This needs to come after all of the tables have been created. $result .= "}\n\n\n"; $result .= "public function safeDown()\n{\n"; $result .= $dropForeignKeys; // This needs to come before the tables are dropped. foreach ($tables as $table) { $result .= ' $this->dropTable(\'' . $table->name . '\');' . "\n"; } $result .= "}\n"; echo $result; return self::EXIT_CODE_NORMAL; } public function getColType($col) { if ($col->isPrimaryKey && $col->autoIncrement) { return "Schema::TYPE_PK"; } $type = 'Schema::TYPE_'.strtoupper($col->type).' . \''; $typeSize = $col->size ? "({$col->size})" : ""; $result = $type.$typeSize; if (!$col->allowNull) { $result .= ' NOT NULL'; } if ($col->defaultValue != null) { $result .= " DEFAULT {$col->defaultValue}"; } elseif ($col->allowNull) { $result .= ' DEFAULT NULL'; } return $result.'\''; } }