IndexShell.php 6.6 KB

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