SchemaShell.php 15 KB

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