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