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