1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20:
21:
22: App::uses('AppShell', 'Console/Command');
23: App::uses('File', 'Utility');
24: App::uses('Folder', 'Utility');
25: App::uses('CakeSchema', 'Model');
26:
27: 28: 29: 30: 31: 32: 33: 34: 35:
36: class SchemaShell extends AppShell {
37:
38: 39: 40: 41: 42:
43: public $Schema;
44:
45: 46: 47: 48: 49:
50: protected $_dry = null;
51:
52: 53: 54: 55: 56:
57: public function initialize() {
58: $this->_welcome();
59: $this->out('Cake Schema Shell');
60: $this->hr();
61: }
62:
63: 64: 65: 66: 67:
68: public function startup() {
69: $name = $path = $connection = $plugin = null;
70: if (!empty($this->params['name'])) {
71: $name = $this->params['name'];
72: } elseif (!empty($this->args[0]) && $this->args[0] !== 'snapshot') {
73: $name = $this->params['name'] = $this->args[0];
74: }
75:
76: if (strpos($name, '.')) {
77: list($this->params['plugin'], $splitName) = pluginSplit($name);
78: $name = $this->params['name'] = $splitName;
79: }
80:
81: if ($name) {
82: $this->params['file'] = Inflector::underscore($name);
83: }
84:
85: if (empty($this->params['file'])) {
86: $this->params['file'] = 'schema.php';
87: }
88: if (strpos($this->params['file'], '.php') === false) {
89: $this->params['file'] .= '.php';
90: }
91: $file = $this->params['file'];
92:
93: if (!empty($this->params['path'])) {
94: $path = $this->params['path'];
95: }
96:
97: if (!empty($this->params['connection'])) {
98: $connection = $this->params['connection'];
99: }
100: if (!empty($this->params['plugin'])) {
101: $plugin = $this->params['plugin'];
102: if (empty($name)) {
103: $name = $plugin;
104: }
105: }
106: $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
107: }
108:
109: 110: 111: 112: 113: 114:
115: public function view() {
116: $File = new File($this->Schema->path . DS . $this->params['file']);
117: if ($File->exists()) {
118: $this->out($File->read());
119: $this->_stop();
120: } else {
121: $file = $this->Schema->path . DS . $this->params['file'];
122: $this->err(__d('cake_console', 'Schema file (%s) could not be found.', $file));
123: $this->_stop();
124: }
125: }
126:
127: 128: 129: 130: 131: 132:
133: public function generate() {
134: $this->out(__d('cake_console', 'Generating Schema...'));
135: $options = array();
136: if ($this->params['force']) {
137: $options = array('models' => false);
138: }
139:
140: $snapshot = false;
141: if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
142: $snapshot = true;
143: }
144:
145: if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
146: $snapshot = true;
147: $prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
148: $result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
149: if ($result === 'q') {
150: return $this->_stop();
151: }
152: if ($result === 'o') {
153: $snapshot = false;
154: }
155: }
156:
157: $cacheDisable = Configure::read('Cache.disable');
158: Configure::write('Cache.disable', true);
159:
160: $content = $this->Schema->read($options);
161: $content['file'] = $this->params['file'];
162:
163: Configure::write('Cache.disable', $cacheDisable);
164:
165: if ($snapshot === true) {
166: $fileName = rtrim($this->params['file'], '.php');
167: $Folder = new Folder($this->Schema->path);
168: $result = $Folder->read();
169:
170: $numToUse = false;
171: if (isset($this->params['snapshot'])) {
172: $numToUse = $this->params['snapshot'];
173: }
174:
175: $count = 0;
176: if (!empty($result[1])) {
177: foreach ($result[1] as $file) {
178: if (preg_match('/'.preg_quote($fileName).'(?:[_\d]*)?\.php$/', $file)) {
179: $count++;
180: }
181: }
182: }
183:
184: if ($numToUse !== false) {
185: if ($numToUse > $count) {
186: $count = $numToUse;
187: }
188: }
189:
190: $content['file'] = $fileName . '_' . $count . '.php';
191: }
192:
193: if ($this->Schema->write($content)) {
194: $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
195: $this->_stop();
196: } else {
197: $this->err(__d('cake_console', 'Schema file: %s generated'));
198: $this->_stop();
199: }
200: }
201:
202: 203: 204: 205: 206: 207: 208: 209: 210:
211: public function dump() {
212: $write = false;
213: $Schema = $this->Schema->load();
214: if (!$Schema) {
215: $this->err(__d('cake_console', 'Schema could not be loaded'));
216: $this->_stop();
217: }
218: if (!empty($this->params['write'])) {
219: if ($this->params['write'] == 1) {
220: $write = Inflector::underscore($this->Schema->name);
221: } else {
222: $write = $this->params['write'];
223: }
224: }
225: $db = ConnectionManager::getDataSource($this->Schema->connection);
226: $contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
227: $contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
228:
229: if ($write) {
230: if (strpos($write, '.sql') === false) {
231: $write .= '.sql';
232: }
233: if (strpos($write, DS) !== false) {
234: $File = new File($write, true);
235: } else {
236: $File = new File($this->Schema->path . DS . $write, true);
237: }
238:
239: if ($File->write($contents)) {
240: $this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd()));
241: $this->_stop();
242: } else {
243: $this->err(__d('cake_console', 'SQL dump could not be created'));
244: $this->_stop();
245: }
246: }
247: $this->out($contents);
248: return $contents;
249: }
250:
251: 252: 253: 254: 255:
256: public function create() {
257: list($Schema, $table) = $this->_loadSchema();
258: $this->_create($Schema, $table);
259: }
260:
261: 262: 263: 264: 265:
266: public function update() {
267: list($Schema, $table) = $this->_loadSchema();
268: $this->_update($Schema, $table);
269: }
270:
271: 272: 273: 274: 275:
276: protected function _loadSchema() {
277: $name = $plugin = null;
278: if (!empty($this->params['name'])) {
279: $name = $this->params['name'];
280: }
281: if (!empty($this->params['plugin'])) {
282: $plugin = $this->params['plugin'];
283: }
284:
285: if (!empty($this->params['dry'])) {
286: $this->_dry = true;
287: $this->out(__d('cake_console', 'Performing a dry run.'));
288: }
289:
290: $options = array('name' => $name, 'plugin' => $plugin);
291: if (!empty($this->params['snapshot'])) {
292: $fileName = rtrim($this->Schema->file, '.php');
293: $options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
294: }
295:
296: $Schema = $this->Schema->load($options);
297:
298: if (!$Schema) {
299: $this->err(__d('cake_console', '%s could not be loaded', $this->Schema->path . DS . $this->Schema->file));
300: $this->_stop();
301: }
302: $table = null;
303: if (isset($this->args[1])) {
304: $table = $this->args[1];
305: }
306: return array(&$Schema, $table);
307: }
308:
309: 310: 311: 312: 313: 314: 315: 316:
317: protected function _create($Schema, $table = null) {
318: $db = ConnectionManager::getDataSource($this->Schema->connection);
319:
320: $drop = $create = array();
321:
322: if (!$table) {
323: foreach ($Schema->tables as $table => $fields) {
324: $drop[$table] = $db->dropSchema($Schema, $table);
325: $create[$table] = $db->createSchema($Schema, $table);
326: }
327: } elseif (isset($Schema->tables[$table])) {
328: $drop[$table] = $db->dropSchema($Schema, $table);
329: $create[$table] = $db->createSchema($Schema, $table);
330: }
331: if (empty($drop) || empty($create)) {
332: $this->out(__d('cake_console', 'Schema is up to date.'));
333: $this->_stop();
334: }
335:
336: $this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
337: $this->out(array_keys($drop));
338:
339: if ('y' == $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n')) {
340: $this->out(__d('cake_console', 'Dropping table(s).'));
341: $this->_run($drop, 'drop', $Schema);
342: }
343:
344: $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
345: $this->out(array_keys($create));
346:
347: if ('y' == $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y')) {
348: $this->out(__d('cake_console', 'Creating table(s).'));
349: $this->_run($create, 'create', $Schema);
350: }
351: $this->out(__d('cake_console', 'End create.'));
352: }
353:
354: 355: 356: 357: 358: 359: 360: 361:
362: protected function _update(&$Schema, $table = null) {
363: $db = ConnectionManager::getDataSource($this->Schema->connection);
364:
365: $this->out(__d('cake_console', 'Comparing Database to Schema...'));
366: $options = array();
367: if (isset($this->params['force'])) {
368: $options['models'] = false;
369: }
370: $Old = $this->Schema->read($options);
371: $compare = $this->Schema->compare($Old, $Schema);
372:
373: $contents = array();
374:
375: if (empty($table)) {
376: foreach ($compare as $table => $changes) {
377: $contents[$table] = $db->alterSchema(array($table => $changes), $table);
378: }
379: } elseif (isset($compare[$table])) {
380: $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
381: }
382:
383: if (empty($contents)) {
384: $this->out(__d('cake_console', 'Schema is up to date.'));
385: $this->_stop();
386: }
387:
388: $this->out("\n" . __d('cake_console', 'The following statements will run.'));
389: $this->out(array_map('trim', $contents));
390: if ('y' == $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) {
391: $this->out();
392: $this->out(__d('cake_console', 'Updating Database...'));
393: $this->_run($contents, 'update', $Schema);
394: }
395:
396: $this->out(__d('cake_console', 'End update.'));
397: }
398:
399: 400: 401: 402: 403: 404: 405: 406:
407: protected function _run($contents, $event, &$Schema) {
408: if (empty($contents)) {
409: $this->err(__d('cake_console', 'Sql could not be run'));
410: return;
411: }
412: Configure::write('debug', 2);
413: $db = ConnectionManager::getDataSource($this->Schema->connection);
414:
415: foreach ($contents as $table => $sql) {
416: if (empty($sql)) {
417: $this->out(__d('cake_console', '%s is up to date.', $table));
418: } else {
419: if ($this->_dry === true) {
420: $this->out(__d('cake_console', 'Dry run for %s :', $table));
421: $this->out($sql);
422: } else {
423: if (!$Schema->before(array($event => $table))) {
424: return false;
425: }
426: $error = null;
427: try {
428: $db->execute($sql);
429: } catch (PDOException $e) {
430: $error = $table . ': ' . $e->getMessage();
431: }
432:
433: $Schema->after(array($event => $table, 'errors' => $error));
434:
435: if (!empty($error)) {
436: $this->err($error);
437: } else {
438: $this->out(__d('cake_console', '%s updated.', $table));
439: }
440: }
441: }
442: }
443: }
444:
445: 446: 447: 448: 449:
450: public function getOptionParser() {
451: $plugin = array(
452: 'help' => __d('cake_console', 'The plugin to use.'),
453: );
454: $connection = array(
455: 'help' => __d('cake_console', 'Set the db config to use.'),
456: 'default' => 'default'
457: );
458: $path = array(
459: 'help' => __d('cake_console', 'Path to read and write schema.php'),
460: 'default' => APP . 'Config' . DS . 'Schema'
461: );
462: $file = array(
463: 'help' => __d('cake_console', 'File name to read and write.'),
464: 'default' => 'schema.php'
465: );
466: $name = array(
467: 'help' => __d('cake_console', 'Classname to use. If its Plugin.class, both name and plugin options will be set.')
468: );
469: $snapshot = array(
470: 'short' => 's',
471: 'help' => __d('cake_console', 'Snapshot number to use/make.')
472: );
473: $dry = array(
474: 'help' => __d('cake_console', 'Perform a dry run on create and update commands. Queries will be output instead of run.'),
475: 'boolean' => true
476: );
477: $force = array(
478: 'short' => 'f',
479: 'help' => __d('cake_console', 'Force "generate" to create a new schema'),
480: 'boolean' => true
481: );
482: $write = array(
483: 'help' => __d('cake_console', 'Write the dumped SQL to a file.')
484: );
485:
486: $parser = parent::getOptionParser();
487: $parser->description(
488: __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
489: )->addSubcommand('view', array(
490: 'help' => __d('cake_console', 'Read and output the contents of a schema file'),
491: 'parser' => array(
492: 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
493: 'arguments' => compact('name')
494: )
495: ))->addSubcommand('generate', array(
496: 'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
497: 'parser' => array(
498: 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force'),
499: 'arguments' => array(
500: 'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
501: )
502: )
503: ))->addSubcommand('dump', array(
504: 'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
505: 'parser' => array(
506: 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'write'),
507: 'arguments' => compact('name')
508: )
509: ))->addSubcommand('create', array(
510: 'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
511: 'parser' => array(
512: 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
513: 'args' => array(
514: 'name' => array(
515: 'help' => __d('cake_console', 'Name of schema to use.')
516: ),
517: 'table' => array(
518: 'help' => __d('cake_console', 'Only create the specified table.')
519: )
520: )
521: )
522: ))->addSubcommand('update', array(
523: 'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
524: 'parser' => array(
525: 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'force'),
526: 'args' => array(
527: 'name' => array(
528: 'help' => __d('cake_console', 'Name of schema to use.')
529: ),
530: 'table' => array(
531: 'help' => __d('cake_console', 'Only create the specified table.')
532: )
533: )
534: )
535: ));
536: return $parser;
537: }
538: }
539: