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