change_collation_sql.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCoreScripts Scripts
  7. * @{
  8. */
  9. $aPathInfo = pathinfo(__FILE__);
  10. require_once ($aPathInfo['dirname'] . '/../inc/header.inc.php');
  11. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  12. /**
  13. * Command line interface for generating a list of service functions
  14. */
  15. class BxDolChangeCOllationSqlCmd
  16. {
  17. protected $_sTablesPrefix = '';
  18. protected $_aTextTypes = array('char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext');
  19. public function main()
  20. {
  21. $a = getopt('hp:');
  22. if (isset($a['h']) || !$a)
  23. $this->finish(0, $this->getHelp());
  24. if (isset($a['p']))
  25. $this->_sTablesPrefix = $a['p'];
  26. if (!$this->_sTablesPrefix)
  27. $this->finish(1, 'Tables prefix is mandatory');
  28. $this->process();
  29. }
  30. protected function process()
  31. {
  32. $oDb = BxDolDb::getInstance();
  33. $aTables = $oDb->getColumn("SHOW TABLES FROM `" . BX_DATABASE_NAME . "` LIKE ?", [$this->_sTablesPrefix . '%']);
  34. $s = '';
  35. foreach ($aTables as $sTable) {
  36. $s .= "-- TABLE: " . $sTable . "\n\n";
  37. $s .= "ALTER TABLE `$sTable` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n\n";
  38. $aFields = $oDb->getAll("SHOW COLUMNS FROM `" . $sTable . "`");
  39. foreach ($aFields as $r) {
  40. if (!$this->isTextField($r['Type']))
  41. continue;
  42. $s .= "ALTER TABLE `$sTable` CHANGE `{$r['Field']}` `{$r['Field']}` {$r['Type']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n";
  43. }
  44. $s .= "\n\n";
  45. }
  46. $this->finish(0, $s);
  47. }
  48. protected function isTextField($sType)
  49. {
  50. foreach ($this->_aTextTypes as $s) {
  51. if (0 === strpos($sType, $s))
  52. return true;
  53. }
  54. return false;
  55. }
  56. protected function getHelp()
  57. {
  58. $n = 21;
  59. $s = "\nUsage: php change_collation_sql.php [options]\n";
  60. $s .= str_pad("\t -h", $n) . "Print this help\n";
  61. $s .= str_pad("\t -p <prefix>", $n) . "Tables prefix to prins SQL queries for\n\n";
  62. $s .= "\n";
  63. return $s;
  64. }
  65. protected function finish ($iCode, $sMsg = null, $bAddLn = true)
  66. {
  67. if (null !== $sMsg)
  68. echo $sMsg . ($bAddLn ? "\n" : '');
  69. exit($iCode);
  70. }
  71. }
  72. $o = new BxDolChangeCOllationSqlCmd();
  73. $o->main();
  74. /** @} */