SchemaShell.php 15 KB

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