IndexShell.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. if (!defined('CONFIGS')) {
  3. define('CONFIGS', APP . 'Config' . DS);
  4. }
  5. App::uses('ConnectionManager', 'Model');
  6. App::uses('AppShell', 'Console/Command');
  7. /**
  8. * Add missing indexes to your schema in a snip
  9. * based on ad7six' UuidifyShell
  10. *
  11. * Currently supports automatically:
  12. * - BTREE Indexes for UUIDs
  13. *
  14. * TODO:
  15. * - BTREE Indexes for AIIDs if desired
  16. * - PRIMARY_KEY Indexes for primary keys ("id")
  17. *
  18. * @author Mark Scherer
  19. * @link
  20. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  21. */
  22. class IndexShell extends AppShell {
  23. /**
  24. * Runtime settings
  25. *
  26. * @var array
  27. */
  28. public $settings = array(
  29. 'ds' => 'default',
  30. );
  31. /**
  32. * The Stack of sql queries to run as an array
  33. *
  34. * @var array
  35. */
  36. protected $_script = array();
  37. /**
  38. * Startup method
  39. *
  40. * @return void
  41. */
  42. public function startup() {
  43. parent::startup();
  44. $this->_welcome();
  45. }
  46. /**
  47. * Initialize method
  48. *
  49. * If the flags -h, -help or --help are present bail here and show help
  50. *
  51. * @return void
  52. */
  53. public function initialize() {
  54. parent::initialize();
  55. $this->_loadModels();
  56. }
  57. /**
  58. * Main method
  59. *
  60. * Generate the required sql, and then run it
  61. * To run for more than one datasource - comma seperate them:
  62. * cake Tools.Index default,permissions,other
  63. *
  64. * @return void
  65. */
  66. public function run() {
  67. $this->_buildScript(explode(',', $this->settings['ds']));
  68. $this->_runScript();
  69. }
  70. /**
  71. * Process each named datasource in turn
  72. *
  73. * E.g. ->_buildScript(array('default', 'users'));
  74. *
  75. * @param array $sources array()
  76. * @return void
  77. */
  78. protected function _buildScript($sources = array()) {
  79. foreach ($sources as $ds) {
  80. $this->_buildScriptForDataSource($ds);
  81. }
  82. }
  83. /**
  84. * Generate the conversion sql for the requested datasource.
  85. *
  86. * For each table in the db - find all primary or foreign keys (that follow conventions)
  87. * currently skips primary keys (should already be PRIMARY)
  88. *
  89. * @param mixed $ds
  90. * @return void
  91. */
  92. protected function _buildScriptForDataSource($ds = 'default') {
  93. $tables = $this->_tables($ds);
  94. $db = ConnectionManager::getDataSource($ds);
  95. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  96. $doneSomething = false;
  97. foreach ($tables as $table) {
  98. if (in_array($table, array('i18n'))) {
  99. continue;
  100. }
  101. $model = Inflector::classify($table);
  102. $Inst = ClassRegistry::init(array(
  103. 'class' => $model,
  104. 'table' => $table,
  105. 'ds' => $ds
  106. ));
  107. if (!is_callable(array($Inst, 'schema'))) {
  108. continue;
  109. }
  110. $fields = $Inst->schema();
  111. $indexInfo = $Inst->query('SHOW INDEX FROM `' . $usePrefix . $table . '`');
  112. foreach ($fields as $field => $details) {
  113. if (!preg_match('@(^|_)(id|key)$@', $field)) {
  114. continue;
  115. }
  116. if ($details['type'] !== 'integer' && ($details['type'] !== 'string' || $details['length'] !== 36)) {
  117. continue;
  118. }
  119. // right now ONLY for uuids
  120. if ($details['type'] !== 'string') {
  121. continue;
  122. }
  123. foreach ($indexInfo as $info) {
  124. $column = $info['STATISTICS']['Column_name'];
  125. $key = $info['STATISTICS']['Key_name'];
  126. // dont override primary keys
  127. if ($column == $field && $key === 'PRIMARY') {
  128. continue 2;
  129. }
  130. // already exists
  131. if ($column == $field && $key == $field) {
  132. continue 2;
  133. }
  134. }
  135. $this->out('Create index for ' . $table . '.' . $field);
  136. $this->_script[$ds]['index'][] = "ALTER TABLE `$usePrefix$table` ADD INDEX (`$field`)";
  137. }
  138. }
  139. }
  140. protected function _tables($useDbConfig = 'default') {
  141. if (!$useDbConfig) {
  142. return array();
  143. }
  144. require_once CONFIGS . 'database.php';
  145. $connections = get_class_vars('DATABASE_CONFIG');
  146. if (!isset($connections[$useDbConfig])) {
  147. return array();
  148. }
  149. $db = ConnectionManager::getDataSource($useDbConfig);
  150. if (!$db) {
  151. return array();
  152. }
  153. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  154. $tables = array();
  155. if ($usePrefix) {
  156. foreach ($db->listSources() as $table) {
  157. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  158. $tables[$useDbConfig . '::' . $table] = substr($table, strlen($usePrefix));
  159. }
  160. }
  161. } else {
  162. $_tables = $db->listSources();
  163. foreach ($_tables as $table) {
  164. $tables[$useDbConfig . '::' . $table] = $table;
  165. }
  166. }
  167. return $tables;
  168. }
  169. /**
  170. * Query method
  171. *
  172. * If the force (or the shortcut f) parameter is set, don't ask for confirmation
  173. * If the user chooses to quit - stop processing at that moment
  174. * If the parameter `dry-run` is specified - don't do anything except dump the script to stdout
  175. *
  176. * @param mixed $statement
  177. * @return void
  178. */
  179. protected function _query($statement) {
  180. if (!$statement) {
  181. $this->out();
  182. return;
  183. }
  184. $statement .= ';';
  185. $this->out($statement);
  186. if (!empty($this->params['dry-run'])) {
  187. return;
  188. }
  189. if (empty($this->params['interactive'])) {
  190. $continue = 'Y';
  191. } else {
  192. $continue = strtoupper($this->in(__('Run this statement?'), array('Y', 'N', 'A', 'Q')));
  193. switch ($continue) {
  194. case 'Q':
  195. return $this->_stop();
  196. return;
  197. case 'N':
  198. return;
  199. case 'A':
  200. $continue = 'Y';
  201. $this->params['interactive'] = false;
  202. case 'Y':
  203. break;
  204. }
  205. }
  206. if ($continue === 'Y') {
  207. $this->Db->query($statement);
  208. }
  209. }
  210. /**
  211. * Loop over the script running each statement in turn
  212. *
  213. * @return void
  214. */
  215. protected function _runScript() {
  216. foreach ($this->_script as $ds => $steps) {
  217. ksort($steps);
  218. $this->Db = ConnectionManager::getDataSource($ds);
  219. foreach ($steps as $step => $statements) {
  220. foreach ($statements as $statement) {
  221. $this->_query($statement);
  222. }
  223. }
  224. }
  225. }
  226. public function getOptionParser() {
  227. $subcommandParser = array(
  228. 'options' => array(
  229. 'dry-run' => array(
  230. 'short' => 'd',
  231. 'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'),
  232. 'boolean' => true
  233. ),
  234. 'log' => array(
  235. 'short' => 'l',
  236. 'help' => __d('cake_console', 'Log all ouput to file log.txt in TMP dir'),
  237. 'boolean' => true
  238. ),
  239. 'interactive' => array(
  240. 'short' => 'i',
  241. 'help' => __d('cake_console', 'Interactive'),
  242. 'boolean' => true
  243. ),
  244. 'ds' => array(
  245. 'short' => 'c',
  246. 'help' => __d('cake_console', 'custom ds'),
  247. 'boolean' => true
  248. )
  249. )
  250. );
  251. return parent::getOptionParser()
  252. ->description(__d('cake_console', "..."))
  253. ->addSubcommand('run', array(
  254. 'help' => __d('cake_console', 'Run'),
  255. 'parser' => $subcommandParser
  256. ));
  257. }
  258. }