Skip to content

Commit

Permalink
Code clean up and formatting + added some comments and output
Browse files Browse the repository at this point in the history
  • Loading branch information
dchancogne committed Jun 5, 2013
1 parent f38a2ed commit 9f5e5d3
Showing 1 changed file with 107 additions and 111 deletions.
218 changes: 107 additions & 111 deletions Console/Command/SqlMigrationShell.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/*
* Based on:
* http://bakery.cakephp.org/articles/erma/2010/01/05/cakephp-sql-shell-simple-and-powerful
/
*/

App::uses('Folder', 'Utility');
Expand All @@ -12,80 +11,77 @@
App::uses('SchemaVersion', 'SqlMigration.Model');

class SqlMigrationShell extends Shell {

/**
* Connection used
*
* @var string
*/
* Connection used
*
* @var string
*/
private $connection = 'default';

/**
* This plugin's name
*
* @var string
*/
* This plugin's name
*
* @var string
*/
private $myName = 'SqlMigration';

/**
* Table holding schema version
*
* @var string
*/
* Table holding schema version
*
* @var string
*/
private $tableName = 'schema_versions';


/**
* Sucess status
*
*/
* Sucess status
*
*/
private $successStatus = 'STATUS';

/**
* Skipped status
*
*/
* Skipped status
*
*/
private $skippedStatus = 'SKIPPED';

/**
* Data model
*
*/
* Data model
*
*/
private $schemaVersionModel;

/*
* Overridding this method will prevent welcome message
*/

/**
* Overridding this method will prevent default welcome message
*/
public function _welcome() {

$this->out('SQL Migration plugin');
}
$this->schemaVersionModel = new SchemaVersion();

} // End function _welcome()


/*
* Function called if no other command is psecified
*/
/**
* Function called if no other command is psecified
*/
public function main() {

$this->out('SqlMigration shell');

$this->schemaVersionModel = new SchemaVersion();

//$this->checkMigrationShema();
$this->out('Executing migration');
//$this->executeMigration();
//$v = $this->getVersion();
$this->update();

} // End function main()


/**
* Get latest version
* @return int Latest version number
*/
* Get latest version
* @return int Latest version number
*/
private function getVersion() {
$latest = $this->schemaVersionModel->find('first', array(
'order' => array('created DESC'),
'limit' => 1
'order' => array('created DESC'),
'limit' => 1
));
if ( $latest && is_numeric($latest['SchemaVersion']['version']) ) {
return (int)$latest['SchemaVersion']['version'];
Expand All @@ -96,81 +92,81 @@ private function getVersion() {
}
} // End function getVersion()


/**
* Get all version history
* @return int Latest version number
*/
* Get all version history
* @return int Latest version number
*/
private function getAllVersions() {
$all = $this->schemaVersionModel->find('all', array(
'order' => array('created ASC')
'order' => array('created ASC')
));
return $all;
} // End function getAllVersions()


/**
* Set version
* Create new verision if doesn't exists, update if existing.
* @param int $version Version
* @param String $status Status of upgrade to version
*/
* Set version
* Create new verision if doesn't exists, update if existing.
* @param int $version Version
* @param String $status Status of upgrade to version
*/
private function setVersion($version, $status) {
$existingVersion = $this->schemaVersionModel->findByVersion($version);
if ( $existingVersion ) {
$this->schemaVersionModel->id = $existingVersion['SchemaVersion']['id'];
$this->schemaVersionModel->saveField('status', $status);
$this->schemaVersionModel->id = $existingVersion['SchemaVersion']['id'];
$this->schemaVersionModel->saveField('status', $status);
}
else {
$data = array('SchemaVersion' => array(
'version' => $version,
'status' => $status));
$this->schemaVersionModel->create();
$saved = $this->schemaVersionModel->save($data);
if ( !$saved ) {
$data = array('SchemaVersion' => array(
'version' => $version,
'status' => $status));
$this->schemaVersionModel->create();
$saved = $this->schemaVersionModel->save($data);
if ( !$saved ) {
$this->out('Unable to set version');
$this->_stop();
}
}
}
} // End function setVersion()


/**
* Get SQL to run (from file) for a given version
* @param int $verion Version number
* @return String SQL to run
*/
* Get SQL to run (from file) for a given version
* @param int $verion Version number
* @return String SQL to run
*/
private function getSql($version) {
if (($text = file_get_contents($filename = APP.'Config/Sql/upgrade-'.$version.'.sql')) !== false) {
return $text;
return $text;
} else {
$this->out("Couldn't load contents of file {$filename}, unable to uograde/downgrade");
$this->_stop();
}
} // End function getSql()


/**
* Run the update.
* This will try to run all upgrade SQL file in order of version.
* It wil also try to run./re-run any version that might have been
* skipped previously
*/
private function update() {
* Run the update.
* This will try to run all upgrade SQL file in order of version.
* It wil also try to run./re-run any version that might have been
* skipped previously
*/
public function update() {
$sqlFolder = new Folder(APP.'Config/Sql');
list($dirs, $files) = $sqlFolder->read();
$upgrades = array();
foreach ($files as $i => $file) {
if (preg_match( '/upgrade-(\d+)\.sql$/', $file, $matches)) {
//unset($files[$i]);
// $this->out($matches[1]);
if (preg_match( '/upgrade-(\d+)\.sql$/', $file, $matches)) {
$upgrades[(int)$matches[1]] = $file;
}
}
}
ksort($upgrades);
$version = max(array_keys($upgrades));
$this->out('Upgrading up to version : '.$version);

// Get all versions
$allVersions = $this->getAllVersions();
// $this->out(print_r($allVersions));

// Try to run missing/skipped versions
$this->out('Looking for missing versions');
Expand All @@ -194,15 +190,15 @@ private function update() {
if ( !$this->executeSql($currentVersion+1) ) {
break;
}
}
$this->out('Now at version '.$this->getVersion());
}
$this->out('Done with upgrades. Now at version '.$this->getVersion());
} // End function update

/**
* Execute SQL file for a given version
* @param int $version Version to execute
* @return boolean False if user choose to not run the SQL. 'Skip' will return true
*/
* Execute SQL file for a given version
* @param int $version Version to execute
* @return boolean False if user choose to not run the SQL. 'Skip' will return true
*/
private function executeSql($version) {
$this->out('Executing sql:');
$this->hr();
Expand All @@ -226,49 +222,49 @@ private function executeSql($version) {


/**
* Check if the appropriate database exists for the plugin
* @return [type] [description]
*/
* Check if the appropriate database exists for the plugin
* @return [type] [description]
*/
public function setup() {

$ds = ConnectionManager::getDataSource($this->connection);
$result = $ds->execute("SHOW TABLES LIKE '".$this->tableName."'")->fetch();
if ( empty($result) ) {
$this->out('Looks like this plugin was never used. Creating table needed');
$this->createMigrationSchema();
}
else {
$this->out('Updating database table needed by plugin');
$this->updateMigrationSchema();
}
$ds = ConnectionManager::getDataSource($this->connection);
$result = $ds->execute("SHOW TABLES LIKE '".$this->tableName."'")->fetch();
if ( empty($result) ) {
$this->out('Looks like this plugin was never used. Creating table needed');
$this->createMigrationSchema();
}
else {
$this->out('Updating database table needed by plugin');
$this->updateMigrationSchema();
}

} // End function checkMigrationSchema()


/**
* Update the database table for the plugin
*/
* Update the database table for the plugin
*/
private function updateMigrationSchema() {

// Command to run
$command = 'schema update --quiet --plugin '.$this->myName.' --connection ' . $this->connection;
// Dispatch to shell
$this->dispatchShell($command);
$this->out('Updated');
// Command to run
$command = 'schema update --quiet --plugin '.$this->myName.' --connection ' . $this->connection;
// Dispatch to shell
$this->dispatchShell($command);
$this->out('Updated');

} // End function updateMigrationchema()


/**
* Create database table needed by plugin
*/
* Create database table needed by plugin
*/
private function createMigrationSchema() {

// Command to run
$command = 'schema create --quiet --plugin '.$this->myName.' --connection ' . $this->connection;
// Dispatch to shell
$this->dispatchShell($command);
$this->out('Created');
// Command to run
$command = 'schema create --quiet --plugin '.$this->myName.' --connection ' . $this->connection;
// Dispatch to shell
$this->dispatchShell($command);
$this->out('Created');

} // End function createMigrationchema()

Expand Down

0 comments on commit 9f5e5d3

Please sign in to comment.