SchemaShell.php 15 KB

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