fixed usage of empty params in ShellDispatcher, fixed missing variable in ProjectTask, updated SchemaShell and generation. Schema can now generate a snapshot, and can be forced to generate before models are created. Added 'run' command to handle create and update of the database. Test runs can be performed using -dry. Be sure to check out cake schema help.

git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@5908 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
gwoo 2007-10-27 20:00:29 +00:00
parent d5ca583326
commit ae9cdb78f4
5 changed files with 230 additions and 96 deletions

View file

@ -406,7 +406,12 @@ class ShellDispatcher {
$out = array();
for ($i = 0; $i < count($params); $i++) {
if (strpos($params[$i], '-') === 0) {
$this->params[substr($params[$i], 1)] = str_replace('"', '', $params[++$i]);
$key = substr($params[$i], 1);
$value = true;
if(isset($params[++$i])) {
$value = str_replace('"', '', $params[$i]);
}
$this->params[$key] = $value;
} else {
$this->args[] = $params[$i];
}

View file

@ -35,6 +35,13 @@ uses('file', 'model' . DS . 'schema');
* @subpackage cake.cake.console.libs
*/
class SchemaShell extends Shell {
/**
* is this a dry run?
*
* @var boolean
* @access private
*/
var $__dry = null;
/**
* Override initialize
*
@ -85,12 +92,49 @@ class SchemaShell extends Shell {
*/
function generate() {
$this->out('Generating Schema...');
$content = $this->Schema->read();
$options = array();
if (isset($this->params['f'])) {
$options = array('models' => false);
}
$content = $this->Schema->read($options);
$snapshot = false;
if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
$snapshot = true;
}
if(!$snapshot && file_exists($this->Schema->path . DS . 'schema.php')) {
$snapshot = true;
$result = $this->in("Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?", array('o', 's', 'q'), 's');
if($result === 'q') {
exit();
}
if($result === 'o') {
$snapshot = false;
}
}
$content['file'] = 'schema.php';
if($snapshot === true) {
$Folder =& new Folder($this->Schema->path);
$result = $Folder->read();
$count = 1;
if(!empty($result[1])) {
foreach ($result[1] as $file) {
if (preg_match('/schema/', $file)) {
$count++;
}
}
}
$content['file'] = 'schema_'.$count.'.php';
}
if ($this->Schema->write($content)) {
$this->out(__('Schema file created.', true));
$this->out(sprintf(__('Schema file: %s generated', true), $content['file']));
exit();
} else {
$this->err(__('Schema could not be created', true));
$this->err(__('Schema file: %s generated', true));
exit();
}
}
@ -131,88 +175,148 @@ class SchemaShell extends Shell {
return $contents;
}
/**
* Create database from Schema object
* Run database commands: create, update
*
* @access public
*/
function create() {
$Schema = $this->Schema->load();
function run() {
if (!isset($this->args[0])) {
$this->err('command not found');
exit();
}
$command = $this->args[0];
$this->Dispatch->shiftArgs();
if(isset($this->params['dry'])) {
$this->__dry = true;
$this->out(__('Performing a dry run.', true));
}
$options = array('file' => $this->Schema->file);
if(isset($this->params['s'])) {
$options = array('file' => 'schema_'.$this->params['s'].'.php');
}
$Schema = $this->Schema->load($options);
if(!$Schema) {
$this->err(sprintf(__('%s could not be loaded', true), $options['file']));
exit();
}
$table = null;
if(isset($this->args[1])) {
$table = $this->args[1];
}
switch($command) {
case 'create':
$this->__create($Schema, $table);
break;
case 'update':
$this->__update($Schema, $table);
break;
default:
$this->err('command not found');
exit();
}
}
/**
* Create database from Schema object
* Should be called via the run method
*
* @access private
*/
function __create($Schema, $table = null) {
$options = array();
$table = null;
$event = array_keys($Schema->tables);
if(isset($this->args[0])) {
$table = $this->args[0];
if($table) {
$event = array($table);
}
$errors = array();
Configure::write('debug', 2);
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db->fullDebug = true;
$drop = $db->dropSchema($Schema, $table);
$this->out($drop);
if('y' == $this->in('Are you sure you want to drop tables and create your database?', array('y', 'n'), 'n')) {
$create = $db->createSchema($Schema, $table);
$this->out('Updating Database...');
$contents = array_map('trim', explode(";", $drop. $create));
foreach($contents as $sql) {
if(!empty($sql)) {
if(!$this->Schema->before(array('created'=> $event))) {
return false;
if($this->__dry === true) {
$this->out($sql);
} else {
if(!empty($sql)) {
if(!$this->Schema->before(array('created'=> $event))) {
return false;
}
if (!$db->_execute($sql)) {
$errors[] = $db->lastError();
}
$this->Schema->after(array('created'=> $event, 'errors'=> $errors));
}
if (!$db->_execute($sql)) {
$errors[] = $db->lastError();
}
$this->Schema->after(array('created'=> $event, 'errors'=> $errors));
}
}
if(!empty($errors)) {
$this->err($errors);
} elseif ($this->__dry !== true) {
$this->out(__('Database updated', true));
exit();
}
}
if(!empty($errors)) {
$this->err($errors);
exit();
}
$this->out(__('Database updated', true));
$this->out(__('End', true));
exit();
}
/**
* Update database with Schema object
* Should be called via the run method
*
* @access public
* @access private
*/
function update() {
function __update($Schema, $table = null) {
$this->out('Comparing Database to Schema...');
$Old = $this->Schema->read();
$Schema = $this->Schema->load();
$compare = $this->Schema->compare($Old, $Schema);
$table = null;
if(isset($this->args[0])) {
$table = $this->args[0];
if(isset($compare[$table])) {
$compare = array($table => $compare[$table]);
}
Configure::write('debug', 2);
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db->fullDebug = true;
Configure::write('debug', 2);
$contents = $db->alterSchema($compare, $table);
if(empty($contents)) {
$this->out(__('Current database is up to date.', true));
$this->out(__('Schema is up to date.', true));
exit();
} else {
} elseif($this->__dry === true || 'y' == $this->in('Would you like to see the changes?', array('y', 'n'), 'y')) {
$this->out($contents);
}
if('y' == $this->in('Are you sure you want to update your database?', array('y', 'n'), 'n')) {
$this->out('Updating Database...');
if(!$this->Schema->before($compare)) {
return false;
}
if ($db->_execute($contents)) {
$this->Schema->after($compare);
$this->out(__('Database updated', true));
exit();
} else {
$this->err(__('Database could not be updated', true));
$this->err($db->lastError());
if($this->__dry !== true) {
if('y' == $this->in('Are you sure you want to update your database?', array('y', 'n'), 'n')) {
$this->out('Updating Database...');
if(!$this->Schema->before($compare)) {
return false;
}
if ($db->_execute($contents)) {
$this->Schema->after($compare);
$this->out(__('Database updated', true));
} else {
$this->err(__('Database could not be updated', true));
$this->err($db->lastError());
}
exit();
}
}
$this->out(__('End', true));
exit();
}
/**
* Displays help contents
@ -220,20 +324,24 @@ class SchemaShell extends Shell {
* @access public
*/
function help() {
$this->out('The Schema Shell generates a schema object from the database and updates the database from the schema.');
$this->out("The Schema Shell generates a schema object from \n\t\tthe database and updates the database from the schema.");
$this->hr();
$this->out("Usage: cake schema <command> <arg1> <arg2>...");
$this->hr();
$this->out('Params:');
$this->out("\n\t-connection\n\t\tset db config. uses 'default' if none is specified");
$this->out("\n\t-path\n\t\tpath to read and write schema.php. uses ". $this->Schema->path ." by default");
$this->out("\n\t-connection <config>\n\t\tset db config <config>. uses 'default' if none is specified");
$this->out("\n\t-path <dir>\n\t\tpath <dir> to read and write schema.php.\n\t\tdefault path: ". $this->Schema->path);
$this->out("\n\t-file <name>\n\t\tfile <name> to read and write.\n\t\tdefault file: ". $this->Schema->file);
$this->out("\n\t-s <number>\n\t\tsnapshot <number> to use for run.");
$this->out("\n\t-dry\n\t\tPerform a dry run on 'run' commands.\n\t\tQueries will be output to window instead of executed.");
$this->out("\n\t-f\n\t\tforce 'generate' to create a new schema.");
$this->out('Commands:');
$this->out("\n\tschema help\n\t\tshows this help message.");
$this->out("\n\tschema view\n\t\tread and output contents of schema file");
$this->out("\n\tschema generate\n\t\treads from 'connection' writes to 'path'");
$this->out("\n\tschema dump <filename>\n\t\tdump database sql based on schema file to filename in schema path. if filename is true, default will use the app directory name.");
$this->out("\n\tschema create <table>\n\t\tdrop tables and create database based on schema file\n\t\toptional <table> arg for creating only one table");
$this->out("\n\tschema update <table>\n\t\talter tables based on schema file\n\t\toptional <table> arg for altering only one table");
$this->out("\n\tschema generate\n\t\treads from 'connection' writes to 'path'\n\t\tTo force genaration of all tables into the schema, use the -f param.");
$this->out("\n\tschema dump <filename>\n\t\tdump database sql based on schema file to filename in schema path. \n\t\tif filename is true, default will use the app directory name.");
$this->out("\n\tschema run create <table>\n\t\tdrop tables and create database based on schema file\n\t\toptional <table> arg for creating only one table\n\t\tpass the -s param with a number to use a snapshot\n\t\tTo see the changes, perform a dry run with the -dry param");
$this->out("\n\tschema run update <table>\n\t\talter tables based on schema file\n\t\toptional <table> arg for altering only one table.\n\t\tTo use a snapshot, pass the -s param with the snapshot number\n\t\tTo see the changes, perform a dry run with the -dry param");
$this->out("");
exit();
}

View file

@ -140,6 +140,7 @@ class ProjectTask extends Shell {
}
$app = basename($path);
$this->out('Bake Project');
$this->out("Skel Directory: $skel");
$this->out("Will be copied to: {$path}");
@ -211,6 +212,7 @@ class ProjectTask extends Shell {
* @access public
*/
function createHome($dir) {
$app = basename($dir);
$path = $dir . 'views' . DS . 'pages' . DS;
include(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'console'.DS.'libs'.DS.'templates'.DS.'views'.DS.'home.ctp');
return $this->createFile($path.'home.ctp', $output);

View file

@ -77,6 +77,9 @@ class FileEngine extends CacheEngine {
$this->__File =& new File($this->settings['path'] . DS . 'cake');
}
$this->settings['path'] = $this->__File->Folder->cd($this->settings['path']);
if(empty($this->settings['path'])) {
return false;
}
if (!is_writable($this->settings['path'])) {
trigger_error(sprintf(__('%s is not writable', true), $this->settings['path']), E_USER_WARNING);
return false;

View file

@ -48,6 +48,13 @@ class CakeSchema extends Object {
* @access public
*/
var $path = TMP;
/**
* file to write
*
* @var string
* @access public
*/
var $file = 'schema.php';
/**
* connection used for read
*
@ -87,7 +94,7 @@ class CakeSchema extends Object {
*/
function _build($data) {
foreach ($data as $key => $val) {
if (!in_array($key, array('name', 'path', 'connection', 'tables', '_log'))) {
if (!in_array($key, array('name', 'path', 'file', 'connection', 'tables', '_log'))) {
$this->tables[$key] = $val;
unset($this->{$key});
} elseif ($key != 'tables' && !empty($val)) {
@ -131,8 +138,8 @@ class CakeSchema extends Object {
get_object_vars($this), $options
);
extract($options);
if (file_exists($path . DS . 'schema.php')) {
require_once($path . DS . 'schema.php');
if (file_exists($path . DS . $file)) {
require_once($path . DS . $file);
$class = $name .'Schema';
if(class_exists($class)) {
$Schema =& new $class();
@ -154,56 +161,56 @@ class CakeSchema extends Object {
array(
'connection' => $this->connection,
'name' => Inflector::camelize(Configure::read('App.dir')),
'models' => true,
),
$options
));
$db =& ConnectionManager::getDataSource($connection);
$currentTables = array_flip($db->sources());
$prefix = null;
loadModel(null);
$tables = array();
$currentTables = $db->sources();
if(isset($db->config['prefix'])) {
$prefix = $db->config['prefix'];
}
if (empty($models)) {
if (empty($models) && $models !== false) {
$models = Configure::listObjects('model');
}
loadModel(null);
$tables = array();
foreach ($models as $model) {
if($model == 'ArosAco') {
$model = 'Permission';
}
if (!class_exists(low($model))) {
if(!class_exists(low('AclNode')) && in_array($model, array('Aro','Aco', 'Permission'))) {
uses('model' . DS . 'db_acl');
} else {
if(is_array($models)) {
foreach ($models as $model) {
if (!class_exists($model)) {
loadModel($model);
}
}
if(class_exists(low($model))) {
$Object =& new $model();
$Object->setDataSource($connection);
$table = $db->fullTableName($Object, false);
if (is_object($Object)) {
if(class_exists($model)) {
$Object =& new $model();
$Object->setDataSource($connection);
$table = $db->fullTableName($Object, false);
if(isset($currentTables[$table])) {
if(empty($tables[$Object->table])) {
$tables[$Object->table] = $this->__columns($Object);
$tables[$Object->table]['indexes'] = $db->index($Object);
unset($currentTables[$table]);
}
if(!empty($Object->hasAndBelongsToMany)) {
foreach($Object->hasAndBelongsToMany as $Assoc => $assocData) {
if (isset($assocData['with'])) {
$class = $assocData['with'];
} elseif ($assocData['_with']) {
$class = $assocData['_with'];
}
if (is_object($Object->$class)) {
$table = $db->fullTableName($Object->$class, false);
if(isset($currentTables[$table])) {
$tables[$Object->$class->table] = $this->__columns($Object->$class);
$tables[$Object->$class->table]['indexes'] = $db->index($Object->$class);
unset($currentTables[$table]);
if (is_object($Object)) {
$table = $db->fullTableName($Object, false);
if(in_array($table, $currentTables)) {
$key = array_search($table, $currentTables);
if(empty($tables[$Object->table])) {
$tables[$Object->table] = $this->__columns($Object);
$tables[$Object->table]['indexes'] = $db->index($Object);
unset($currentTables[$key]);
}
if(!empty($Object->hasAndBelongsToMany)) {
foreach($Object->hasAndBelongsToMany as $Assoc => $assocData) {
if (isset($assocData['with'])) {
$class = $assocData['with'];
} elseif ($assocData['_with']) {
$class = $assocData['_with'];
}
if (is_object($Object->$class)) {
$table = $db->fullTableName($Object->$class, false);
if(in_array($table, $currentTables)) {
$key = array_search($table, $currentTables);
$tables[$Object->$class->table] = $this->__columns($Object->$class);
$tables[$Object->$class->table]['indexes'] = $db->index($Object->$class);
unset($currentTables[$key]);
}
}
}
}
@ -212,15 +219,19 @@ class CakeSchema extends Object {
}
}
}
if(!empty($currentTables)) {
foreach(array_flip($currentTables) as $table) {
foreach($currentTables as $table) {
if($prefix) {
$table = str_replace($prefix, '', $table);
}
$Object = new AppModel(array('name'=> Inflector::classify($table), 'table'=> $table, 'ds'=> $connection));
$tables['missing'][$table] = $this->__columns($Object);
$tables['missing'][$table]['indexes'] = $db->index($Object);
if(in_array($table, array('aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'))) {
$tables[$Object->table] = $this->__columns($Object);
$tables[$Object->table]['indexes'] = $db->index($Object);
} else {
$tables['missing'][$table] = $this->__columns($Object);
$tables['missing'][$table]['indexes'] = $db->index($Object);
}
}
}
@ -258,6 +269,10 @@ class CakeSchema extends Object {
$out .= "\tvar \$path = '{$path}';\n\n";
}
if ($file !== $this->file) {
$out .= "\tvar \$file = '{$file}';\n\n";
}
if ($connection !== 'default') {
$out .= "\tvar \$connection = '{$connection}';\n\n";
}
@ -301,8 +316,10 @@ class CakeSchema extends Object {
}
$out .="\n}\n\n";
$File =& new File($path . DS . 'schema.php', true);
$File =& new File($path . DS . $file, true);
$content = "<?php \n/*<!--". $name ." schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "-->*/\n{$out}?>";
$content = $File->prepare($content);
if ($File->write($content)) {
return $content;
}
@ -412,7 +429,6 @@ class CakeSchema extends Object {
function __columns(&$Obj) {
$db =& ConnectionManager::getDataSource($Obj->useDbConfig);
$fields = $Obj->schema(true);
//pr($fields);
$columns = $props = array();
foreach ($fields->value as $name => $value) {
@ -420,7 +436,7 @@ class CakeSchema extends Object {
$value['key'] = 'primary';
}
if (!isset($db->columns[$value['type']])) {
trigger_error('Schema generation error: invalid column type ' . $value['type'] . ' does not exist in DBO', E_USER_WARNING);
trigger_error('Schema generation error: invalid column type ' . $value['type'] . ' does not exist in DBO', E_USER_NOTICE);
continue;
} else {
$defaultCol = $db->columns[$value['type']];