SchemaShell.php 15 KB

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