SchemaShell.php 15 KB

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