Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 93 additions & 34 deletions EDatabaseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
/**
* Class file.
*
* @author Tobias Munk <schmunk@usrbin.de>
* @link http://www.phundament.com/
* @author Tobias Munk <schmunk@usrbin.de>
* @link http://www.phundament.com/
* @copyright Copyright &copy; 2005-2011 diemeisterei GmbH
* @license http://www.phundament.com/license/
* @license http://www.phundament.com/license/
*/

/**
Expand All @@ -27,30 +27,30 @@ class EDatabaseCommand extends CConsoleCommand
* Defaults to 'application.runtime' (meaning 'protected/runtime').
* Copy the created migration into eg. application.migrations to activate it for your project.
*/
public $migrationPath='application.runtime';
public $migrationPath = 'application.migrations';

/**
* @var string database connection component
*/
public $dbConnection = "db";

/**
* @var string wheter to dump a create table statement
* @var string whether to dump a create table statement
*/
public $createSchema = true;

/**
* @var string wheter to dump a insert data statements
* @var string whether to dump a insert data statements
*/
public $insertData = true;

/**
* @var string wheter to add truncate table data statements
* @var string whether to add truncate table data statements
*/
public $truncateTable = false;

/**
* @var string wheter to disable foreign key checks
* @var string whether to disable foreign key checks
*/
public $foreignKeyChecks = true;

Expand All @@ -60,26 +60,30 @@ class EDatabaseCommand extends CConsoleCommand
public $prefix = "";

/**
* @var string wheter to ignore the migration table
* @var string whether to ignore the migration table
*/
public $ignoreMigrationTable = true;

/**
* @var bool whether to ignore the SQLite if statements
*/
public $ignoreSQLiteChecks = true;

/**
* @var bool whether to display the Foreign Keys warning
*/
protected $_displayFkWarning = false;

public function beforeAction($action,$params)
public function beforeAction($action, $params)
{
$path=Yii::getPathOfAlias($this->migrationPath);
if($path===false || !is_dir($path))
{
echo 'Error: The migration directory does not exist: '.$this->migrationPath."\n";
$path = Yii::getPathOfAlias($this->migrationPath);
if ($path === false || !is_dir($path)) {
echo 'Error: The migration directory does not exist: ' . $this->migrationPath . "\n";
exit(1);
}
$this->migrationPath=$path;
$this->migrationPath = $path;

return parent::beforeAction($action,$params);
return parent::beforeAction($action, $params);
}

public function getHelp()
Expand All @@ -94,13 +98,16 @@ public function getHelp()
[--ignoreMigrationTable=<1|0>]
[--truncateTable=<0|1>] [--migrationPath=<application.runtime>]

//////To get only schema
php yiic database dump all_schema --insertData=0


EOS;
}

public function actionDump($args)
{
echo "Connecting to '".Yii::app()->{$this->dbConnection}->connectionString."'\n";
echo "Connecting to '" . Yii::app()->{$this->dbConnection}->connectionString . "'\n";

$schema = Yii::app()->{$this->dbConnection}->schema;
$tables = Yii::app()->{$this->dbConnection}->schema->tables;
Expand All @@ -124,7 +131,7 @@ public function actionDump($args)
$filename = $this->migrationPath . DIRECTORY_SEPARATOR . $migrationClassName . ".php";
$prefixes = explode(",", $this->prefix);

$codeTruncate = $codeSchema = $codeForeignKeys = $codeInserts = '';
$codeTruncate = $codeSchema = $codeForeignKeysAndIndexes = $codeInserts = '';

echo "Querying tables ";

Expand Down Expand Up @@ -154,24 +161,30 @@ public function actionDump($args)

if ($this->createSchema == true) {
$codeSchema .= $this->generateSchema($table, $schema);
$codeForeignKeys .= $this->generateForeignKeys($table, $schema);
$codeForeignKeysAndIndexes .=
$this->generateForeignKeys($table, $schema) . $this->generateIndexes($table, $schema);
}

if ($this->insertData == true) {
$codeInserts .= $this->generateInserts($table, $schema);
}
}

$code .= $codeTruncate."\n".$codeSchema."\n".$codeForeignKeys."\n".$codeForeignKeys."\n".$codeInserts;
$code .= $codeTruncate . "\n" . $codeSchema . "\n" . $codeForeignKeysAndIndexes . "\n" . $codeInserts;

if ($this->foreignKeyChecks == false) {
$code .= $this->indent(2) . "if (Yii::app()->db->schema instanceof CMysqlSchema)\n";
$code .= $this->indent(2) . " \$this->execute('SET FOREIGN_KEY_CHECKS = 1;');\n";
}

$migrationClassCode = $this->renderFile(
dirname(__FILE__) . '/views/migration.php', array('migrationClassName' => $migrationClassName,
'functionUp' => $code), true);
dirname(__FILE__) . '/views/migration.php',
array(
'migrationClassName' => $migrationClassName,
'functionUp' => $code
),
true
);

file_put_contents($filename, $migrationClassCode);

Expand All @@ -193,13 +206,13 @@ public function actionDump($args)

private function indent($level = 0)
{
return str_repeat(" ", $level);
return str_repeat(" ", $level);
}

private function generateSchema($table, $schema)
{
$options = "ENGINE=InnoDB DEFAULT CHARSET=utf8";
$code = "\n\n\n" . $this->indent(2) . "// Schema for table '" . $table->name . "'\n";
$code = "\n\n" . $this->indent(2) . "// Schema for table '" . $table->name . "'\n";
$code .= $this->indent(2) . '$this->createTable("' . $table->name . '", ';
$code .= "\n";
$code .= $this->indent(3) . 'array(' . "\n";
Expand All @@ -216,28 +229,72 @@ private function generateSchema($table, $schema)

private function generatePrimaryKeys($columns)
{
$keys = array();
foreach ($columns as $col) {
if ($col->isPrimaryKey && !$col->autoIncrement) {
return $this->indent(3) . '"PRIMARY KEY (' . $col->name . ')"' . "\n";
if ($col->isPrimaryKey) {
$keys[] = "`$col->name`";
}
}
return $this->indent(3) . '"PRIMARY KEY (' . implode(',', $keys) . ')"' . "\n";
}

private function generateForeignKeys($table, $schema)
{
if (count($table->foreignKeys) == 0) {
return "";
}
$code = "\n\n\n" . $this->indent(2) . "// Foreign Keys for table '" . $table->name . "'\n";
$code .= $this->indent(2) . "if ((Yii::app()->db->schema instanceof CSqliteSchema) == false):\n";

$code = "\n" . $this->indent(2) . "// FOREIGN KEYS for table '" . $table->name . "'\n";

if(!$this->ignoreSQLiteChecks){
$code .= $this->indent(2) . "if ((Yii::app()->db->schema instanceof CSqliteSchema) == false):\n";
}

foreach ($table->foreignKeys as $name => $foreignKey) {
$code .= $this->indent(3) . "\$this->addForeignKey('fk_{$table->name}_{$foreignKey[0]}_{$name}', '{$table->name}', '{$name}', '{$foreignKey[0]}', '{$foreignKey[1]}', null, null); // FIX RELATIONS \n";
$code .= $this->indent(3) . "\$this->addForeignKey('fk_{$table->name}_{$foreignKey[0]}_{$name}', '{$table->name}', '{$name}', '{$foreignKey[0]}', '{$foreignKey[1]}', 'CASCADE', 'CASCADE'); // FIX RELATIONS \n";
}

if(!$this->ignoreSQLiteChecks){
$code .= $this->indent(2) . "endif;\n";
}
$code .= $this->indent(2) . "endif;\n";
$this->_displayFkWarning = TRUE;
$this->_displayFkWarning = true;
return $code;
}

private function generateIndexes($table, $schema)
{
$indexes = Yii::app()->db->createCommand(
"SHOW INDEX FROM " . $table->name . "
WHERE Key_name != 'PRIMARY'"
)->queryAll();

if (count($indexes) == 0) {
return "";
}

$code = "\n" . $this->indent(2) . "// INDEXES for table '" . $table->name . "'\n";
if(!$this->ignoreSQLiteChecks){
$code .= $this->indent(2) . "if ((Yii::app()->db->schema instanceof CSqliteSchema) == false):\n";
}

$checker = false;

foreach ($indexes as $index) {
if (!isset($table->foreignKeys[$index['Column_name']])) {
$unique = !$index['Non_unique'] ? 'True' : 'False';
$code .= $this->indent(3) . "\$this->createIndex('index_{$index['Table']}_{$index['Column_name']}', '{$index['Table']}', '{$index['Column_name']}', {$unique}); \n";
$checker = true;
}

}
if(!$this->ignoreSQLiteChecks){
$code .= $this->indent(2) . "endif;\n";
}

//remove everything if there were no results
return $checker ? $code : '';
}

private function generateInserts($table, $schema)
{
$data = Yii::app()->{$this->dbConnection}->createCommand()
Expand All @@ -249,7 +306,7 @@ private function generateInserts($table, $schema)
$code .= $this->indent(2) . '$this->insert("' . $table->name . '", array(' . "\n";
foreach ($row AS $column => $value) {
$code .= $this->indent(3) . '"' . $column . '"=>' . (($value === null) ? 'null' :
'"' . addcslashes($value, '"\\$') . '"') . ',' . "\n";
'"' . addcslashes($value, '"\\$') . '"') . ',' . "\n";
}
$code .= $this->indent(2) . ') );' . "\n\n";
}
Expand All @@ -265,16 +322,18 @@ private function generateTruncate($table)

private function resolveColumnType($col)
{

$result = $col->dbType;

if (!$col->allowNull) {
$result .= ' NOT NULL';
}
if ($col->defaultValue != null) {
if ($col->defaultValue !== null) {

$result .= " DEFAULT '{$col->defaultValue}'";
}
if ($col->isPrimaryKey) {
$result .= " PRIMARY KEY";
// $result .= " PRIMARY KEY";
}
if ($col->autoIncrement) {
$result .= " AUTO_INCREMENT";
Expand Down