IndexShell.php 6.3 KB

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