CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.3
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AclShell
  • ApiShell
  • BakeShell
  • CommandListShell
  • ConsoleShell
  • I18nShell
  • SchemaShell
  • ServerShell
  • TestShell
  • TestsuiteShell
  • UpgradeShell
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 11:  * @link          http://cakephp.org CakePHP(tm) Project
 12:  * @since         CakePHP(tm) v 1.2.0.5550
 13:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 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:  * Schema is a command-line database management utility for automating programmer chores.
 23:  *
 24:  * Schema is CakePHP's database management utility. This helps you maintain versions of
 25:  * of your database.
 26:  *
 27:  * @package       Cake.Console.Command
 28:  * @link          http://book.cakephp.org/2.0/en/console-and-shells/schema-management-and-migrations.html
 29:  */
 30: class SchemaShell extends AppShell {
 31: 
 32: /**
 33:  * Schema class being used.
 34:  *
 35:  * @var CakeSchema
 36:  */
 37:     public $Schema;
 38: 
 39: /**
 40:  * is this a dry run?
 41:  *
 42:  * @var boolean
 43:  */
 44:     protected $_dry = null;
 45: 
 46: /**
 47:  * Override startup
 48:  *
 49:  * @return void
 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:         if ($name) {
 71:             $this->params['file'] = Inflector::underscore($name);
 72:         }
 73: 
 74:         if (empty($this->params['file'])) {
 75:             $this->params['file'] = 'schema.php';
 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:  * Read and output contents of schema object
101:  * path to read as second arg
102:  *
103:  * @return void
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:  * Read database and Write schema object
118:  * accepts a connection as first arg or path to save as second arg
119:  *
120:  * @return void
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 ($snapshot === true) {
157:             $fileName = rtrim($this->params['file'], '.php');
158:             $Folder = new Folder($this->Schema->path);
159:             $result = $Folder->read();
160: 
161:             $numToUse = false;
162:             if (isset($this->params['snapshot'])) {
163:                 $numToUse = $this->params['snapshot'];
164:             }
165: 
166:             $count = 0;
167:             if (!empty($result[1])) {
168:                 foreach ($result[1] as $file) {
169:                     if (preg_match('/' . preg_quote($fileName) . '(?:[_\d]*)?\.php$/', $file)) {
170:                         $count++;
171:                     }
172:                 }
173:             }
174: 
175:             if ($numToUse !== false) {
176:                 if ($numToUse > $count) {
177:                     $count = $numToUse;
178:                 }
179:             }
180: 
181:             $content['file'] = $fileName . '_' . $count . '.php';
182:         }
183: 
184:         if ($this->Schema->write($content)) {
185:             $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
186:             return $this->_stop();
187:         }
188:         $this->err(__d('cake_console', 'Schema file: %s generated'));
189:         return $this->_stop();
190:     }
191: 
192: /**
193:  * Dump Schema object to sql file
194:  * Use the `write` param to enable and control SQL file output location.
195:  * Simply using -write will write the sql file to the same dir as the schema file.
196:  * If -write contains a full path name the file will be saved there. If -write only
197:  * contains no DS, that will be used as the file name, in the same dir as the schema file.
198:  *
199:  * @return string
200:  */
201:     public function dump() {
202:         $write = false;
203:         $Schema = $this->Schema->load();
204:         if (!$Schema) {
205:             $this->err(__d('cake_console', 'Schema could not be loaded'));
206:             return $this->_stop();
207:         }
208:         if (!empty($this->params['write'])) {
209:             if ($this->params['write'] == 1) {
210:                 $write = Inflector::underscore($this->Schema->name);
211:             } else {
212:                 $write = $this->params['write'];
213:             }
214:         }
215:         $db = ConnectionManager::getDataSource($this->Schema->connection);
216:         $contents = "\n\n" . $db->dropSchema($Schema) . "\n\n" . $db->createSchema($Schema);
217: 
218:         if ($write) {
219:             if (strpos($write, '.sql') === false) {
220:                 $write .= '.sql';
221:             }
222:             if (strpos($write, DS) !== false) {
223:                 $File = new File($write, true);
224:             } else {
225:                 $File = new File($this->Schema->path . DS . $write, true);
226:             }
227: 
228:             if ($File->write($contents)) {
229:                 $this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd()));
230:                 return $this->_stop();
231:             } else {
232:                 $this->err(__d('cake_console', 'SQL dump could not be created'));
233:                 return $this->_stop();
234:             }
235:         }
236:         $this->out($contents);
237:         return $contents;
238:     }
239: 
240: /**
241:  * Run database create commands. Alias for run create.
242:  *
243:  * @return void
244:  */
245:     public function create() {
246:         list($Schema, $table) = $this->_loadSchema();
247:         $this->_create($Schema, $table);
248:     }
249: 
250: /**
251:  * Run database create commands. Alias for run create.
252:  *
253:  * @return void
254:  */
255:     public function update() {
256:         list($Schema, $table) = $this->_loadSchema();
257:         $this->_update($Schema, $table);
258:     }
259: 
260: /**
261:  * Prepares the Schema objects for database operations.
262:  *
263:  * @return void
264:  */
265:     protected function _loadSchema() {
266:         $name = $plugin = null;
267:         if (!empty($this->params['name'])) {
268:             $name = $this->params['name'];
269:         }
270:         if (!empty($this->params['plugin'])) {
271:             $plugin = $this->params['plugin'];
272:         }
273: 
274:         if (!empty($this->params['dry'])) {
275:             $this->_dry = true;
276:             $this->out(__d('cake_console', 'Performing a dry run.'));
277:         }
278: 
279:         $options = array('name' => $name, 'plugin' => $plugin);
280:         if (!empty($this->params['snapshot'])) {
281:             $fileName = rtrim($this->Schema->file, '.php');
282:             $options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
283:         }
284: 
285:         $Schema = $this->Schema->load($options);
286: 
287:         if (!$Schema) {
288:             $this->err(__d('cake_console', 'The chosen schema could not be loaded. Attempted to load:'));
289:             $this->err(__d('cake_console', 'File: %s', $this->Schema->path . DS . $this->Schema->file));
290:             $this->err(__d('cake_console', 'Name: %s', $this->Schema->name));
291:             return $this->_stop();
292:         }
293:         $table = null;
294:         if (isset($this->args[1])) {
295:             $table = $this->args[1];
296:         }
297:         return array(&$Schema, $table);
298:     }
299: 
300: /**
301:  * Create database from Schema object
302:  * Should be called via the run method
303:  *
304:  * @param CakeSchema $Schema
305:  * @param string $table
306:  * @return void
307:  */
308:     protected function _create(CakeSchema $Schema, $table = null) {
309:         $db = ConnectionManager::getDataSource($this->Schema->connection);
310: 
311:         $drop = $create = array();
312: 
313:         if (!$table) {
314:             foreach ($Schema->tables as $table => $fields) {
315:                 $drop[$table] = $db->dropSchema($Schema, $table);
316:                 $create[$table] = $db->createSchema($Schema, $table);
317:             }
318:         } elseif (isset($Schema->tables[$table])) {
319:             $drop[$table] = $db->dropSchema($Schema, $table);
320:             $create[$table] = $db->createSchema($Schema, $table);
321:         }
322:         if (empty($drop) || empty($create)) {
323:             $this->out(__d('cake_console', 'Schema is up to date.'));
324:             return $this->_stop();
325:         }
326: 
327:         $this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
328:         $this->out(array_keys($drop));
329: 
330:         if ($this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n') === 'y') {
331:             $this->out(__d('cake_console', 'Dropping table(s).'));
332:             $this->_run($drop, 'drop', $Schema);
333:         }
334: 
335:         $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
336:         $this->out(array_keys($create));
337: 
338:         if ($this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y') === 'y') {
339:             $this->out(__d('cake_console', 'Creating table(s).'));
340:             $this->_run($create, 'create', $Schema);
341:         }
342:         $this->out(__d('cake_console', 'End create.'));
343:     }
344: 
345: /**
346:  * Update database with Schema object
347:  * Should be called via the run method
348:  *
349:  * @param CakeSchema $Schema
350:  * @param string $table
351:  * @return void
352:  */
353:     protected function _update(&$Schema, $table = null) {
354:         $db = ConnectionManager::getDataSource($this->Schema->connection);
355: 
356:         $this->out(__d('cake_console', 'Comparing Database to Schema...'));
357:         $options = array();
358:         if (isset($this->params['force'])) {
359:             $options['models'] = false;
360:         }
361:         $Old = $this->Schema->read($options);
362:         $compare = $this->Schema->compare($Old, $Schema);
363: 
364:         $contents = array();
365: 
366:         if (empty($table)) {
367:             foreach ($compare as $table => $changes) {
368:                 $contents[$table] = $db->alterSchema(array($table => $changes), $table);
369:             }
370:         } elseif (isset($compare[$table])) {
371:             $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
372:         }
373: 
374:         if (empty($contents)) {
375:             $this->out(__d('cake_console', 'Schema is up to date.'));
376:             return $this->_stop();
377:         }
378: 
379:         $this->out("\n" . __d('cake_console', 'The following statements will run.'));
380:         $this->out(array_map('trim', $contents));
381:         if ($this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n') === 'y') {
382:             $this->out();
383:             $this->out(__d('cake_console', 'Updating Database...'));
384:             $this->_run($contents, 'update', $Schema);
385:         }
386: 
387:         $this->out(__d('cake_console', 'End update.'));
388:     }
389: 
390: /**
391:  * Runs sql from _create() or _update()
392:  *
393:  * @param array $contents
394:  * @param string $event
395:  * @param CakeSchema $Schema
396:  * @return void
397:  */
398:     protected function _run($contents, $event, CakeSchema $Schema) {
399:         if (empty($contents)) {
400:             $this->err(__d('cake_console', 'Sql could not be run'));
401:             return;
402:         }
403:         Configure::write('debug', 2);
404:         $db = ConnectionManager::getDataSource($this->Schema->connection);
405: 
406:         foreach ($contents as $table => $sql) {
407:             if (empty($sql)) {
408:                 $this->out(__d('cake_console', '%s is up to date.', $table));
409:             } else {
410:                 if ($this->_dry === true) {
411:                     $this->out(__d('cake_console', 'Dry run for %s :', $table));
412:                     $this->out($sql);
413:                 } else {
414:                     if (!$Schema->before(array($event => $table))) {
415:                         return false;
416:                     }
417:                     $error = null;
418:                     try {
419:                         $db->execute($sql);
420:                     } catch (PDOException $e) {
421:                         $error = $table . ': ' . $e->getMessage();
422:                     }
423: 
424:                     $Schema->after(array($event => $table, 'errors' => $error));
425: 
426:                     if (!empty($error)) {
427:                         $this->err($error);
428:                     } else {
429:                         $this->out(__d('cake_console', '%s updated.', $table));
430:                     }
431:                 }
432:             }
433:         }
434:     }
435: 
436: /**
437:  * get the option parser
438:  *
439:  * @return void
440:  */
441:     public function getOptionParser() {
442:         $plugin = array(
443:             'short' => 'p',
444:             'help' => __d('cake_console', 'The plugin to use.'),
445:         );
446:         $connection = array(
447:             'short' => 'c',
448:             'help' => __d('cake_console', 'Set the db config to use.'),
449:             'default' => 'default'
450:         );
451:         $path = array(
452:             'help' => __d('cake_console', 'Path to read and write schema.php'),
453:             'default' => APP . 'Config' . DS . 'Schema'
454:         );
455:         $file = array(
456:             'help' => __d('cake_console', 'File name to read and write.'),
457:             'default' => 'schema.php'
458:         );
459:         $name = array(
460:             'help' => __d('cake_console', 'Classname to use. If its Plugin.class, both name and plugin options will be set.')
461:         );
462:         $snapshot = array(
463:             'short' => 's',
464:             'help' => __d('cake_console', 'Snapshot number to use/make.')
465:         );
466:         $models = array(
467:             'short' => 'm',
468:             'help' => __d('cake_console', 'Specify models as comma separated list.'),
469:         );
470:         $dry = array(
471:             'help' => __d('cake_console', 'Perform a dry run on create and update commands. Queries will be output instead of run.'),
472:             'boolean' => true
473:         );
474:         $force = array(
475:             'short' => 'f',
476:             'help' => __d('cake_console', 'Force "generate" to create a new schema'),
477:             'boolean' => true
478:         );
479:         $write = array(
480:             'help' => __d('cake_console', 'Write the dumped SQL to a file.')
481:         );
482: 
483:         $parser = parent::getOptionParser();
484:         $parser->description(
485:             __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
486:         )->addSubcommand('view', array(
487:             'help' => __d('cake_console', 'Read and output the contents of a schema file'),
488:             'parser' => array(
489:                 'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
490:                 'arguments' => compact('name')
491:             )
492:         ))->addSubcommand('generate', array(
493:             'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
494:             'parser' => array(
495:                 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force', 'models'),
496:                 'arguments' => array(
497:                     'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
498:                 )
499:             )
500:         ))->addSubcommand('dump', array(
501:             'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
502:             'parser' => array(
503:                 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'write'),
504:                 'arguments' => compact('name')
505:             )
506:         ))->addSubcommand('create', array(
507:             'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
508:             'parser' => array(
509:                 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
510:                 'args' => array(
511:                     'name' => array(
512:                         'help' => __d('cake_console', 'Name of schema to use.')
513:                     ),
514:                     'table' => array(
515:                         'help' => __d('cake_console', 'Only create the specified table.')
516:                     )
517:                 )
518:             )
519:         ))->addSubcommand('update', array(
520:             'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
521:             'parser' => array(
522:                 'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'force'),
523:                 'args' => array(
524:                     'name' => array(
525:                         'help' => __d('cake_console', 'Name of schema to use.')
526:                     ),
527:                     'table' => array(
528:                         'help' => __d('cake_console', 'Only create the specified table.')
529:                     )
530:                 )
531:             )
532:         ));
533:         return $parser;
534:     }
535: 
536: }
537: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs