Table.php 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Holds the Table class
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\DatabaseInterface;
  10. use PhpMyAdmin\Index;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Plugins;
  13. use PhpMyAdmin\Plugins\Export\ExportSql;
  14. use PhpMyAdmin\Relation;
  15. use PhpMyAdmin\SqlParser\Components\Expression;
  16. use PhpMyAdmin\SqlParser\Components\OptionsArray;
  17. use PhpMyAdmin\SqlParser\Context;
  18. use PhpMyAdmin\SqlParser\Parser;
  19. use PhpMyAdmin\SqlParser\Statements\DropStatement;
  20. use PhpMyAdmin\SqlParser\Utils\Table as TableUtils;
  21. use PhpMyAdmin\Util;
  22. /**
  23. * Handles everything related to tables
  24. *
  25. * @todo make use of Message and Error
  26. * @package PhpMyAdmin
  27. */
  28. class Table
  29. {
  30. /**
  31. * UI preferences properties
  32. */
  33. const PROP_SORTED_COLUMN = 'sorted_col';
  34. const PROP_COLUMN_ORDER = 'col_order';
  35. const PROP_COLUMN_VISIB = 'col_visib';
  36. /**
  37. * @var string engine (innodb, myisam, bdb, ...)
  38. */
  39. var $engine = '';
  40. /**
  41. * @var string type (view, base table, system view)
  42. */
  43. var $type = '';
  44. /**
  45. * @var array UI preferences
  46. */
  47. var $uiprefs;
  48. /**
  49. * @var array errors occurred
  50. */
  51. var $errors = array();
  52. /**
  53. * @var array messages
  54. */
  55. var $messages = array();
  56. /**
  57. * @var string table name
  58. */
  59. protected $_name = '';
  60. /**
  61. * @var string database name
  62. */
  63. protected $_db_name = '';
  64. /**
  65. * @var DatabaseInterface
  66. */
  67. protected $_dbi;
  68. /**
  69. * @var Relation $relation
  70. */
  71. private $relation;
  72. /**
  73. * Constructor
  74. *
  75. * @param string $table_name table name
  76. * @param string $db_name database name
  77. * @param DatabaseInterface $dbi database interface for the table
  78. */
  79. public function __construct($table_name, $db_name, DatabaseInterface $dbi = null)
  80. {
  81. if (empty($dbi)) {
  82. $dbi = $GLOBALS['dbi'];
  83. }
  84. $this->_dbi = $dbi;
  85. $this->_name = $table_name;
  86. $this->_db_name = $db_name;
  87. $this->relation = new Relation();
  88. }
  89. /**
  90. * returns table name
  91. *
  92. * @see Table::getName()
  93. * @return string table name
  94. */
  95. public function __toString()
  96. {
  97. return $this->getName();
  98. }
  99. /**
  100. * Table getter
  101. *
  102. * @param string $table_name table name
  103. * @param string $db_name database name
  104. * @param DatabaseInterface $dbi database interface for the table
  105. *
  106. * @return Table
  107. */
  108. public static function get($table_name, $db_name, DatabaseInterface $dbi = null)
  109. {
  110. return new Table($table_name, $db_name, $dbi);
  111. }
  112. /**
  113. * return the last error
  114. *
  115. * @return string the last error
  116. */
  117. public function getLastError()
  118. {
  119. return end($this->errors);
  120. }
  121. /**
  122. * return the last message
  123. *
  124. * @return string the last message
  125. */
  126. public function getLastMessage()
  127. {
  128. return end($this->messages);
  129. }
  130. /**
  131. * returns table name
  132. *
  133. * @param boolean $backquoted whether to quote name with backticks ``
  134. *
  135. * @return string table name
  136. */
  137. public function getName($backquoted = false)
  138. {
  139. if ($backquoted) {
  140. return Util::backquote($this->_name);
  141. }
  142. return $this->_name;
  143. }
  144. /**
  145. * returns database name for this table
  146. *
  147. * @param boolean $backquoted whether to quote name with backticks ``
  148. *
  149. * @return string database name for this table
  150. */
  151. public function getDbName($backquoted = false)
  152. {
  153. if ($backquoted) {
  154. return Util::backquote($this->_db_name);
  155. }
  156. return $this->_db_name;
  157. }
  158. /**
  159. * returns full name for table, including database name
  160. *
  161. * @param boolean $backquoted whether to quote name with backticks ``
  162. *
  163. * @return string
  164. */
  165. public function getFullName($backquoted = false)
  166. {
  167. return $this->getDbName($backquoted) . '.'
  168. . $this->getName($backquoted);
  169. }
  170. /**
  171. * Checks the storage engine used to create table
  172. *
  173. * @param array|string $engine Checks the table engine against an
  174. * array of engine strings or a single string, should be uppercase
  175. *
  176. * @return bool True, if $engine matches the storage engine for the table,
  177. * False otherwise.
  178. */
  179. public function isEngine($engine)
  180. {
  181. $tbl_storage_engine = $this->getStorageEngine();
  182. if (is_array($engine)){
  183. foreach($engine as $e){
  184. if($e == $tbl_storage_engine){
  185. return true;
  186. }
  187. }
  188. return false;
  189. }else{
  190. return $tbl_storage_engine == $engine;
  191. }
  192. }
  193. /**
  194. * returns whether the table is actually a view
  195. *
  196. * @return boolean whether the given is a view
  197. */
  198. public function isView()
  199. {
  200. $db = $this->_db_name;
  201. $table = $this->_name;
  202. if (empty($db) || empty($table)) {
  203. return false;
  204. }
  205. // use cached data or load information with SHOW command
  206. if ($this->_dbi->getCachedTableContent(array($db, $table)) != null
  207. || $GLOBALS['cfg']['Server']['DisableIS']
  208. ) {
  209. $type = $this->getStatusInfo('TABLE_TYPE');
  210. return $type == 'VIEW' || $type == 'SYSTEM VIEW';
  211. }
  212. // information_schema tables are 'SYSTEM VIEW's
  213. if ($db == 'information_schema') {
  214. return true;
  215. }
  216. // query information_schema
  217. $result = $this->_dbi->fetchResult(
  218. "SELECT TABLE_NAME
  219. FROM information_schema.VIEWS
  220. WHERE TABLE_SCHEMA = '" . $GLOBALS['dbi']->escapeString($db) . "'
  221. AND TABLE_NAME = '" . $GLOBALS['dbi']->escapeString($table) . "'"
  222. );
  223. return $result ? true : false;
  224. }
  225. /**
  226. * Returns whether the table is actually an updatable view
  227. *
  228. * @return boolean whether the given is an updatable view
  229. */
  230. public function isUpdatableView()
  231. {
  232. if (empty($this->_db_name) || empty($this->_name)) {
  233. return false;
  234. }
  235. $result = $this->_dbi->fetchResult(
  236. "SELECT TABLE_NAME
  237. FROM information_schema.VIEWS
  238. WHERE TABLE_SCHEMA = '" . $GLOBALS['dbi']->escapeString($this->_db_name) . "'
  239. AND TABLE_NAME = '" . $GLOBALS['dbi']->escapeString($this->_name) . "'
  240. AND IS_UPDATABLE = 'YES'"
  241. );
  242. return $result ? true : false;
  243. }
  244. /**
  245. * Checks if this is a merge table
  246. *
  247. * If the ENGINE of the table is MERGE or MRG_MYISAM (alias),
  248. * this is a merge table.
  249. *
  250. * @return boolean true if it is a merge table
  251. */
  252. public function isMerge()
  253. {
  254. return $this->isEngine(array('MERGE', 'MRG_MYISAM'));
  255. }
  256. /**
  257. * Returns full table status info, or specific if $info provided
  258. * this info is collected from information_schema
  259. *
  260. * @param string $info specific information to be fetched
  261. * @param boolean $force_read read new rather than serving from cache
  262. * @param boolean $disable_error if true, disables error message
  263. *
  264. * @todo DatabaseInterface::getTablesFull needs to be merged
  265. * somehow into this class or at least better documented
  266. *
  267. * @return mixed
  268. */
  269. public function getStatusInfo(
  270. $info = null,
  271. $force_read = false,
  272. $disable_error = false
  273. ) {
  274. $db = $this->_db_name;
  275. $table = $this->_name;
  276. if (! empty($_SESSION['is_multi_query'])) {
  277. $disable_error = true;
  278. }
  279. // sometimes there is only one entry (ExactRows) so
  280. // we have to get the table's details
  281. if ($this->_dbi->getCachedTableContent(array($db, $table)) == null
  282. || $force_read
  283. || count($this->_dbi->getCachedTableContent(array($db, $table))) == 1
  284. ) {
  285. $this->_dbi->getTablesFull($db, $table);
  286. }
  287. if ($this->_dbi->getCachedTableContent(array($db, $table)) == null) {
  288. // happens when we enter the table creation dialog
  289. // or when we really did not get any status info, for example
  290. // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
  291. return '';
  292. }
  293. if (null === $info) {
  294. return $this->_dbi->getCachedTableContent(array($db, $table));
  295. }
  296. // array_key_exists allows for null values
  297. if (!array_key_exists(
  298. $info, $this->_dbi->getCachedTableContent(array($db, $table))
  299. )
  300. ) {
  301. if (! $disable_error) {
  302. trigger_error(
  303. __('Unknown table status:') . ' ' . $info,
  304. E_USER_WARNING
  305. );
  306. }
  307. return false;
  308. }
  309. return $this->_dbi->getCachedTableContent(array($db, $table, $info));
  310. }
  311. /**
  312. * Returns the Table storage Engine for current table.
  313. *
  314. * @return string Return storage engine info if it is set for
  315. * the selected table else return blank.
  316. */
  317. public function getStorageEngine() {
  318. $table_storage_engine = $this->getStatusInfo('ENGINE', false, true);
  319. if ($table_storage_engine === false) {
  320. return '';
  321. }
  322. return strtoupper($table_storage_engine);
  323. }
  324. /**
  325. * Returns the comments for current table.
  326. *
  327. * @return string Return comment info if it is set for the selected table or return blank.
  328. */
  329. public function getComment() {
  330. $table_comment = $this->getStatusInfo('TABLE_COMMENT', false, true);
  331. if ($table_comment === false) {
  332. return '';
  333. }
  334. return $table_comment;
  335. }
  336. /**
  337. * Returns the collation for current table.
  338. *
  339. * @return string Return blank if collation is empty else return the collation info from table info.
  340. */
  341. public function getCollation() {
  342. $table_collation = $this->getStatusInfo('TABLE_COLLATION', false, true);
  343. if ($table_collation === false) {
  344. return '';
  345. }
  346. return $table_collation;
  347. }
  348. /**
  349. * Returns the info about no of rows for current table.
  350. *
  351. * @return integer Return no of rows info if it is not null for the selected table or return 0.
  352. */
  353. public function getNumRows() {
  354. $table_num_row_info = $this->getStatusInfo('TABLE_ROWS', false, true);
  355. if (false === $table_num_row_info) {
  356. $table_num_row_info = $this->_dbi->getTable($this->_db_name, $showtable['Name'])
  357. ->countRecords(true);
  358. }
  359. return $table_num_row_info ? $table_num_row_info : 0 ;
  360. }
  361. /**
  362. * Returns the Row format for current table.
  363. *
  364. * @return string Return table row format info if it is set for the selected table or return blank.
  365. */
  366. public function getRowFormat() {
  367. $table_row_format = $this->getStatusInfo('ROW_FORMAT', false, true);
  368. if ($table_row_format === false) {
  369. return '';
  370. }
  371. return $table_row_format;
  372. }
  373. /**
  374. * Returns the auto increment option for current table.
  375. *
  376. * @return integer Return auto increment info if it is set for the selected table or return blank.
  377. */
  378. public function getAutoIncrement() {
  379. $table_auto_increment = $this->getStatusInfo('AUTO_INCREMENT', false, true);
  380. return isset($table_auto_increment) ? $table_auto_increment : '';
  381. }
  382. /**
  383. * Returns the array for CREATE statement for current table.
  384. * @return array Return options array info if it is set for the selected table or return blank.
  385. */
  386. public function getCreateOptions() {
  387. $table_options = $this->getStatusInfo('CREATE_OPTIONS', false, true);
  388. $create_options_tmp = empty($table_options) ? array() : explode(' ', $table_options);
  389. $create_options = array();
  390. // export create options by its name as variables into global namespace
  391. // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
  392. // unset($pack_keys);
  393. foreach ($create_options_tmp as $each_create_option) {
  394. $each_create_option = explode('=', $each_create_option);
  395. if (isset($each_create_option[1])) {
  396. // ensure there is no ambiguity for PHP 5 and 7
  397. $create_options[$each_create_option[0]] = $each_create_option[1];
  398. }
  399. }
  400. // we need explicit DEFAULT value here (different from '0')
  401. $create_options['pack_keys'] = (! isset($create_options['pack_keys']) || strlen($create_options['pack_keys']) == 0)
  402. ? 'DEFAULT'
  403. : $create_options['pack_keys'];
  404. return $create_options;
  405. }
  406. /**
  407. * generates column specification for ALTER or CREATE TABLE syntax
  408. *
  409. * @param string $name name
  410. * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
  411. * @param string $length length ('2', '5,2', '', ...)
  412. * @param string $attribute attribute
  413. * @param string $collation collation
  414. * @param bool|string $null with 'NULL' or 'NOT NULL'
  415. * @param string $default_type whether default is CURRENT_TIMESTAMP,
  416. * NULL, NONE, USER_DEFINED
  417. * @param string $default_value default value for USER_DEFINED
  418. * default type
  419. * @param string $extra 'AUTO_INCREMENT'
  420. * @param string $comment field comment
  421. * @param string $virtuality virtuality of the column
  422. * @param string $expression expression for the virtual column
  423. * @param string $move_to new position for column
  424. *
  425. * @todo move into class PMA_Column
  426. * @todo on the interface, some js to clear the default value when the
  427. * default current_timestamp is checked
  428. *
  429. * @return string field specification
  430. */
  431. static function generateFieldSpec($name, $type, $length = '',
  432. $attribute = '', $collation = '', $null = false,
  433. $default_type = 'USER_DEFINED', $default_value = '', $extra = '',
  434. $comment = '', $virtuality = '', $expression = '', $move_to = ''
  435. ) {
  436. $is_timestamp = mb_strpos(
  437. mb_strtoupper($type),
  438. 'TIMESTAMP'
  439. ) !== false;
  440. $query = Util::backquote($name) . ' ' . $type;
  441. // allow the possibility of a length for TIME, DATETIME and TIMESTAMP
  442. // (will work on MySQL >= 5.6.4)
  443. //
  444. // MySQL permits a non-standard syntax for FLOAT and DOUBLE,
  445. // see https://dev.mysql.com/doc/refman/5.5/en/floating-point-types.html
  446. //
  447. $pattern = '@^(DATE|TINYBLOB|TINYTEXT|BLOB|TEXT|'
  448. . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN|UUID)$@i';
  449. if (strlen($length) !== 0 && ! preg_match($pattern, $type)) {
  450. // Note: The variable $length here can contain several other things
  451. // besides length - ENUM/SET value or length of DECIMAL (eg. 12,3)
  452. // so we can't just convert it to integer
  453. $query .= '(' . $length . ')';
  454. }
  455. if ($attribute != '') {
  456. $query .= ' ' . $attribute;
  457. if ($is_timestamp
  458. && preg_match('/TIMESTAMP/i', $attribute)
  459. && strlen($length) !== 0
  460. && $length !== 0
  461. ) {
  462. $query .= '(' . $length . ')';
  463. }
  464. }
  465. // if column is virtual, check if server type is Mysql as only Mysql server
  466. // supports extra column properties
  467. $isVirtualColMysql = $virtuality && in_array(Util::getServerType(), array('MySQL', 'Percona Server'));
  468. // if column is virtual, check if server type is MariaDB as MariaDB server
  469. // supports no extra virtual column properties except CHARACTER SET for text column types
  470. $isVirtualColMariaDB = $virtuality && Util::getServerType() === 'MariaDB';
  471. $matches = preg_match(
  472. '@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i',
  473. $type
  474. );
  475. if (! empty($collation) && $collation != 'NULL' && $matches) {
  476. $query .= Util::getCharsetQueryPart(
  477. $isVirtualColMariaDB ? preg_replace('~_.+~s', '', $collation) : $collation,
  478. true
  479. );
  480. }
  481. if ($virtuality) {
  482. $query .= ' AS (' . $expression . ') ' . $virtuality;
  483. }
  484. if (! $virtuality || $isVirtualColMysql) {
  485. if ($null !== false) {
  486. if ($null == 'YES') {
  487. $query .= ' NULL';
  488. } else {
  489. $query .= ' NOT NULL';
  490. }
  491. }
  492. if (! $virtuality) {
  493. switch ($default_type) {
  494. case 'USER_DEFINED' :
  495. if ($is_timestamp && $default_value === '0') {
  496. // a TIMESTAMP does not accept DEFAULT '0'
  497. // but DEFAULT 0 works
  498. $query .= ' DEFAULT 0';
  499. } elseif ($type == 'BIT') {
  500. $query .= ' DEFAULT b\''
  501. . preg_replace('/[^01]/', '0', $default_value)
  502. . '\'';
  503. } elseif ($type == 'BOOLEAN') {
  504. if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
  505. $query .= ' DEFAULT TRUE';
  506. } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
  507. $query .= ' DEFAULT FALSE';
  508. } else {
  509. // Invalid BOOLEAN value
  510. $query .= ' DEFAULT \''
  511. . $GLOBALS['dbi']->escapeString($default_value) . '\'';
  512. }
  513. } elseif ($type == 'BINARY' || $type == 'VARBINARY') {
  514. $query .= ' DEFAULT 0x' . $default_value;
  515. } else {
  516. $query .= ' DEFAULT \''
  517. . $GLOBALS['dbi']->escapeString($default_value) . '\'';
  518. }
  519. break;
  520. /** @noinspection PhpMissingBreakStatementInspection */
  521. case 'NULL' :
  522. // If user uncheck null checkbox and not change default value null,
  523. // default value will be ignored.
  524. if ($null !== false && $null !== 'YES') {
  525. break;
  526. }
  527. // else fall-through intended, no break here
  528. case 'CURRENT_TIMESTAMP' :
  529. case 'current_timestamp()':
  530. $query .= ' DEFAULT ' . $default_type;
  531. if (strlen($length) !== 0
  532. && $length !== 0
  533. && $is_timestamp
  534. && $default_type !== 'NULL' // Not to be added in case of NULL
  535. ) {
  536. $query .= '(' . $length . ')';
  537. }
  538. break;
  539. case 'NONE' :
  540. default :
  541. break;
  542. }
  543. }
  544. if (!empty($extra)) {
  545. if ($virtuality) {
  546. $extra = trim(preg_replace('~^\s*AUTO_INCREMENT\s*~is', ' ', $extra));
  547. }
  548. $query .= ' ' . $extra;
  549. }
  550. }
  551. if (!empty($comment)) {
  552. $query .= " COMMENT '" . $GLOBALS['dbi']->escapeString($comment) . "'";
  553. }
  554. // move column
  555. if ($move_to == '-first') { // dash can't appear as part of column name
  556. $query .= ' FIRST';
  557. } elseif ($move_to != '') {
  558. $query .= ' AFTER ' . Util::backquote($move_to);
  559. }
  560. return $query;
  561. } // end function
  562. /**
  563. * Checks if the number of records in a table is at least equal to
  564. * $min_records
  565. *
  566. * @param int $min_records Number of records to check for in a table
  567. *
  568. * @return bool True, if at least $min_records exist, False otherwise.
  569. */
  570. public function checkIfMinRecordsExist($min_records = 0)
  571. {
  572. $check_query = 'SELECT ';
  573. $fieldsToSelect = '';
  574. $uniqueFields = $this->getUniqueColumns(true, false);
  575. if (count($uniqueFields) > 0) {
  576. $fieldsToSelect = implode(', ', $uniqueFields);
  577. } else {
  578. $indexedCols = $this->getIndexedColumns(true, false);
  579. if (count($indexedCols) > 0) {
  580. $fieldsToSelect = implode(', ', $indexedCols);
  581. } else {
  582. $fieldsToSelect = '*';
  583. }
  584. }
  585. $check_query .= $fieldsToSelect
  586. . ' FROM ' . $this->getFullName(true)
  587. . ' LIMIT ' . $min_records;
  588. $res = $GLOBALS['dbi']->tryQuery(
  589. $check_query
  590. );
  591. if ($res !== false) {
  592. $num_records = $GLOBALS['dbi']->numRows($res);
  593. if ($num_records >= $min_records) {
  594. return true;
  595. }
  596. }
  597. return false;
  598. }
  599. /**
  600. * Counts and returns (or displays) the number of records in a table
  601. *
  602. * @param bool $force_exact whether to force an exact count
  603. *
  604. * @return mixed the number of records if "retain" param is true,
  605. * otherwise true
  606. */
  607. public function countRecords($force_exact = false)
  608. {
  609. $is_view = $this->isView();
  610. $db = $this->_db_name;
  611. $table = $this->_name;
  612. if ($this->_dbi->getCachedTableContent(array($db, $table, 'ExactRows')) != null) {
  613. $row_count = $this->_dbi->getCachedTableContent(
  614. array($db, $table, 'ExactRows')
  615. );
  616. return $row_count;
  617. }
  618. $row_count = false;
  619. if (! $force_exact) {
  620. if (($this->_dbi->getCachedTableContent(array($db, $table, 'Rows')) == null)
  621. && !$is_view
  622. ) {
  623. $tmp_tables = $this->_dbi->getTablesFull($db, $table);
  624. if (isset($tmp_tables[$table])) {
  625. $this->_dbi->cacheTableContent(
  626. array($db, $table),
  627. $tmp_tables[$table]
  628. );
  629. }
  630. }
  631. if ($this->_dbi->getCachedTableContent(array($db, $table, 'Rows')) != null) {
  632. $row_count = $this->_dbi->getCachedTableContent(
  633. array($db, $table, 'Rows')
  634. );
  635. } else {
  636. $row_count = false;
  637. }
  638. }
  639. // for a VIEW, $row_count is always false at this point
  640. if (false !== $row_count
  641. && $row_count >= $GLOBALS['cfg']['MaxExactCount']
  642. ) {
  643. return $row_count;
  644. }
  645. if (! $is_view) {
  646. $row_count = $this->_dbi->fetchValue(
  647. 'SELECT COUNT(*) FROM ' . Util::backquote($db) . '.'
  648. . Util::backquote($table)
  649. );
  650. } else {
  651. // For complex views, even trying to get a partial record
  652. // count could bring down a server, so we offer an
  653. // alternative: setting MaxExactCountViews to 0 will bypass
  654. // completely the record counting for views
  655. if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
  656. $row_count = false;
  657. } else {
  658. // Counting all rows of a VIEW could be too long,
  659. // so use a LIMIT clause.
  660. // Use try_query because it can fail (when a VIEW is
  661. // based on a table that no longer exists)
  662. $result = $this->_dbi->tryQuery(
  663. 'SELECT 1 FROM ' . Util::backquote($db) . '.'
  664. . Util::backquote($table) . ' LIMIT '
  665. . $GLOBALS['cfg']['MaxExactCountViews'],
  666. DatabaseInterface::CONNECT_USER,
  667. DatabaseInterface::QUERY_STORE
  668. );
  669. if (!$this->_dbi->getError()) {
  670. $row_count = $this->_dbi->numRows($result);
  671. $this->_dbi->freeResult($result);
  672. }
  673. }
  674. }
  675. if ($row_count) {
  676. $this->_dbi->cacheTableContent(array($db, $table, 'ExactRows'), $row_count);
  677. }
  678. return $row_count;
  679. } // end of the 'Table::countRecords()' function
  680. /**
  681. * Generates column specification for ALTER syntax
  682. *
  683. * @param string $oldcol old column name
  684. * @param string $newcol new column name
  685. * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
  686. * @param string $length length ('2', '5,2', '', ...)
  687. * @param string $attribute attribute
  688. * @param string $collation collation
  689. * @param bool|string $null with 'NULL' or 'NOT NULL'
  690. * @param string $default_type whether default is CURRENT_TIMESTAMP,
  691. * NULL, NONE, USER_DEFINED
  692. * @param string $default_value default value for USER_DEFINED default
  693. * type
  694. * @param string $extra 'AUTO_INCREMENT'
  695. * @param string $comment field comment
  696. * @param string $virtuality virtuality of the column
  697. * @param string $expression expression for the virtual column
  698. * @param string $move_to new position for column
  699. *
  700. * @see Table::generateFieldSpec()
  701. *
  702. * @return string field specification
  703. */
  704. public static function generateAlter($oldcol, $newcol, $type, $length,
  705. $attribute, $collation, $null, $default_type, $default_value,
  706. $extra, $comment, $virtuality, $expression, $move_to
  707. ) {
  708. return Util::backquote($oldcol) . ' '
  709. . self::generateFieldSpec(
  710. $newcol, $type, $length, $attribute,
  711. $collation, $null, $default_type, $default_value, $extra,
  712. $comment, $virtuality, $expression, $move_to
  713. );
  714. } // end function
  715. /**
  716. * Inserts existing entries in a PMA_* table by reading a value from an old
  717. * entry
  718. *
  719. * @param string $work The array index, which Relation feature to
  720. * check ('relwork', 'commwork', ...)
  721. * @param string $pma_table The array index, which PMA-table to update
  722. * ('bookmark', 'relation', ...)
  723. * @param array $get_fields Which fields will be SELECT'ed from the old entry
  724. * @param array $where_fields Which fields will be used for the WHERE query
  725. * (array('FIELDNAME' => 'FIELDVALUE'))
  726. * @param array $new_fields Which fields will be used as new VALUES.
  727. * These are the important keys which differ
  728. * from the old entry
  729. * (array('FIELDNAME' => 'NEW FIELDVALUE'))
  730. *
  731. * @global relation variable
  732. *
  733. * @return int|boolean
  734. */
  735. public static function duplicateInfo($work, $pma_table, array $get_fields,
  736. array $where_fields, array $new_fields
  737. ) {
  738. $relation = new Relation();
  739. $last_id = -1;
  740. if (!isset($GLOBALS['cfgRelation']) || !$GLOBALS['cfgRelation'][$work]) {
  741. return true;
  742. }
  743. $select_parts = array();
  744. $row_fields = array();
  745. foreach ($get_fields as $get_field) {
  746. $select_parts[] = Util::backquote($get_field);
  747. $row_fields[$get_field] = 'cc';
  748. }
  749. $where_parts = array();
  750. foreach ($where_fields as $_where => $_value) {
  751. $where_parts[] = Util::backquote($_where) . ' = \''
  752. . $GLOBALS['dbi']->escapeString($_value) . '\'';
  753. }
  754. $new_parts = array();
  755. $new_value_parts = array();
  756. foreach ($new_fields as $_where => $_value) {
  757. $new_parts[] = Util::backquote($_where);
  758. $new_value_parts[] = $GLOBALS['dbi']->escapeString($_value);
  759. }
  760. $table_copy_query = '
  761. SELECT ' . implode(', ', $select_parts) . '
  762. FROM ' . Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
  763. . Util::backquote($GLOBALS['cfgRelation'][$pma_table]) . '
  764. WHERE ' . implode(' AND ', $where_parts);
  765. // must use DatabaseInterface::QUERY_STORE here, since we execute
  766. // another query inside the loop
  767. $table_copy_rs = $relation->queryAsControlUser(
  768. $table_copy_query, true, DatabaseInterface::QUERY_STORE
  769. );
  770. while ($table_copy_row = @$GLOBALS['dbi']->fetchAssoc($table_copy_rs)) {
  771. $value_parts = array();
  772. foreach ($table_copy_row as $_key => $_val) {
  773. if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
  774. $value_parts[] = $GLOBALS['dbi']->escapeString($_val);
  775. }
  776. }
  777. $new_table_query = 'INSERT IGNORE INTO '
  778. . Util::backquote($GLOBALS['cfgRelation']['db'])
  779. . '.' . Util::backquote($GLOBALS['cfgRelation'][$pma_table])
  780. . ' (' . implode(', ', $select_parts) . ', '
  781. . implode(', ', $new_parts) . ') VALUES (\''
  782. . implode('\', \'', $value_parts) . '\', \''
  783. . implode('\', \'', $new_value_parts) . '\')';
  784. $relation->queryAsControlUser($new_table_query);
  785. $last_id = $GLOBALS['dbi']->insertId();
  786. } // end while
  787. $GLOBALS['dbi']->freeResult($table_copy_rs);
  788. return $last_id;
  789. } // end of 'Table::duplicateInfo()' function
  790. /**
  791. * Copies or renames table
  792. *
  793. * @param string $source_db source database
  794. * @param string $source_table source table
  795. * @param string $target_db target database
  796. * @param string $target_table target table
  797. * @param string $what what to be moved or copied (data, dataonly)
  798. * @param bool $move whether to move
  799. * @param string $mode mode
  800. *
  801. * @return bool true if success, false otherwise
  802. */
  803. public static function moveCopy($source_db, $source_table, $target_db,
  804. $target_table, $what, $move, $mode
  805. ) {
  806. global $err_url;
  807. $relation = new Relation();
  808. // Try moving the tables directly, using native `RENAME` statement.
  809. if ($move && $what == 'data') {
  810. $tbl = new Table($source_table, $source_db);
  811. if ($tbl->rename($target_table, $target_db)) {
  812. $GLOBALS['message'] = $tbl->getLastMessage();
  813. return true;
  814. }
  815. }
  816. // Setting required export settings.
  817. $GLOBALS['sql_backquotes'] = 1;
  818. $GLOBALS['asfile'] = 1;
  819. // Ensuring the target database is valid.
  820. if (! $GLOBALS['dblist']->databases->exists($source_db, $target_db)) {
  821. if (! $GLOBALS['dblist']->databases->exists($source_db)) {
  822. $GLOBALS['message'] = Message::rawError(
  823. sprintf(
  824. __('Source database `%s` was not found!'),
  825. htmlspecialchars($source_db)
  826. )
  827. );
  828. }
  829. if (! $GLOBALS['dblist']->databases->exists($target_db)) {
  830. $GLOBALS['message'] = Message::rawError(
  831. sprintf(
  832. __('Target database `%s` was not found!'),
  833. htmlspecialchars($target_db)
  834. )
  835. );
  836. }
  837. return false;
  838. }
  839. /**
  840. * The full name of source table, quoted.
  841. * @var string $source
  842. */
  843. $source = Util::backquote($source_db)
  844. . '.' . Util::backquote($source_table);
  845. // If the target database is not specified, the operation is taking
  846. // place in the same database.
  847. if (! isset($target_db) || strlen($target_db) === 0) {
  848. $target_db = $source_db;
  849. }
  850. // Selecting the database could avoid some problems with replicated
  851. // databases, when moving table from replicated one to not replicated one.
  852. $GLOBALS['dbi']->selectDb($target_db);
  853. /**
  854. * The full name of target table, quoted.
  855. * @var string $target
  856. */
  857. $target = Util::backquote($target_db)
  858. . '.' . Util::backquote($target_table);
  859. // No table is created when this is a data-only operation.
  860. if ($what != 'dataonly') {
  861. /**
  862. * Instance used for exporting the current structure of the table.
  863. *
  864. * @var PhpMyAdmin\Plugins\Export\ExportSql
  865. */
  866. $export_sql_plugin = Plugins::getPlugin(
  867. "export",
  868. "sql",
  869. 'libraries/classes/Plugins/Export/',
  870. array(
  871. 'export_type' => 'table',
  872. 'single_table' => false,
  873. )
  874. );
  875. $no_constraints_comments = true;
  876. $GLOBALS['sql_constraints_query'] = '';
  877. // set the value of global sql_auto_increment variable
  878. if (isset($_POST['sql_auto_increment'])) {
  879. $GLOBALS['sql_auto_increment'] = $_POST['sql_auto_increment'];
  880. }
  881. /**
  882. * The old structure of the table..
  883. * @var string $sql_structure
  884. */
  885. $sql_structure = $export_sql_plugin->getTableDef(
  886. $source_db, $source_table, "\n", $err_url, false, false
  887. );
  888. unset($no_constraints_comments);
  889. // -----------------------------------------------------------------
  890. // Phase 0: Preparing structures used.
  891. /**
  892. * The destination where the table is moved or copied to.
  893. * @var Expression
  894. */
  895. $destination = new Expression(
  896. $target_db, $target_table, ''
  897. );
  898. // Find server's SQL mode so the builder can generate correct
  899. // queries.
  900. // One of the options that alters the behaviour is `ANSI_QUOTES`.
  901. Context::setMode(
  902. $GLOBALS['dbi']->fetchValue("SELECT @@sql_mode")
  903. );
  904. // -----------------------------------------------------------------
  905. // Phase 1: Dropping existent element of the same name (if exists
  906. // and required).
  907. if (isset($_POST['drop_if_exists'])
  908. && $_POST['drop_if_exists'] == 'true'
  909. ) {
  910. /**
  911. * Drop statement used for building the query.
  912. * @var DropStatement $statement
  913. */
  914. $statement = new DropStatement();
  915. $tbl = new Table($target_db, $target_table);
  916. $statement->options = new OptionsArray(
  917. array(
  918. $tbl->isView() ? 'VIEW' : 'TABLE',
  919. 'IF EXISTS',
  920. )
  921. );
  922. $statement->fields = array($destination);
  923. // Building the query.
  924. $drop_query = $statement->build() . ';';
  925. // Executing it.
  926. $GLOBALS['dbi']->query($drop_query);
  927. $GLOBALS['sql_query'] .= "\n" . $drop_query;
  928. // If an existing table gets deleted, maintain any entries for
  929. // the PMA_* tables.
  930. $maintain_relations = true;
  931. }
  932. // -----------------------------------------------------------------
  933. // Phase 2: Generating the new query of this structure.
  934. /**
  935. * The parser responsible for parsing the old queries.
  936. * @var Parser $parser
  937. */
  938. $parser = new Parser($sql_structure);
  939. if (!empty($parser->statements[0])) {
  940. /**
  941. * The CREATE statement of this structure.
  942. * @var \PhpMyAdmin\SqlParser\Statements\CreateStatement $statement
  943. */
  944. $statement = $parser->statements[0];
  945. // Changing the destination.
  946. $statement->name = $destination;
  947. // Building back the query.
  948. $sql_structure = $statement->build() . ';';
  949. // Executing it.
  950. $GLOBALS['dbi']->query($sql_structure);
  951. $GLOBALS['sql_query'] .= "\n" . $sql_structure;
  952. }
  953. // -----------------------------------------------------------------
  954. // Phase 3: Adding constraints.
  955. // All constraint names are removed because they must be unique.
  956. if (($move || isset($GLOBALS['add_constraints']))
  957. && !empty($GLOBALS['sql_constraints_query'])
  958. ) {
  959. $parser = new Parser($GLOBALS['sql_constraints_query']);
  960. /**
  961. * The ALTER statement that generates the constraints.
  962. * @var \PhpMyAdmin\SqlParser\Statements\AlterStatement $statement
  963. */
  964. $statement = $parser->statements[0];
  965. // Changing the altered table to the destination.
  966. $statement->table = $destination;
  967. // Removing the name of the constraints.
  968. foreach ($statement->altered as $idx => $altered) {
  969. // All constraint names are removed because they must be unique.
  970. if ($altered->options->has('CONSTRAINT')) {
  971. $altered->field = null;
  972. }
  973. }
  974. // Building back the query.
  975. $GLOBALS['sql_constraints_query'] = $statement->build() . ';';
  976. // Executing it.
  977. if ($mode == 'one_table') {
  978. $GLOBALS['dbi']->query($GLOBALS['sql_constraints_query']);
  979. }
  980. $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
  981. if ($mode == 'one_table') {
  982. unset($GLOBALS['sql_constraints_query']);
  983. }
  984. }
  985. // -----------------------------------------------------------------
  986. // Phase 4: Adding indexes.
  987. // View phase 3.
  988. if (!empty($GLOBALS['sql_indexes'])) {
  989. $parser = new Parser($GLOBALS['sql_indexes']);
  990. $GLOBALS['sql_indexes'] = '';
  991. /**
  992. * The ALTER statement that generates the indexes.
  993. * @var \PhpMyAdmin\SqlParser\Statements\AlterStatement $statement
  994. */
  995. foreach ($parser->statements as $statement) {
  996. // Changing the altered table to the destination.
  997. $statement->table = $destination;
  998. // Removing the name of the constraints.
  999. foreach ($statement->altered as $idx => $altered) {
  1000. // All constraint names are removed because they must be unique.
  1001. if ($altered->options->has('CONSTRAINT')) {
  1002. $altered->field = null;
  1003. }
  1004. }
  1005. // Building back the query.
  1006. $sql_index = $statement->build() . ';';
  1007. // Executing it.
  1008. if ($mode == 'one_table' || $mode == 'db_copy') {
  1009. $GLOBALS['dbi']->query($sql_index);
  1010. }
  1011. $GLOBALS['sql_indexes'] .= $sql_index;
  1012. }
  1013. $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_indexes'];
  1014. if ($mode == 'one_table' || $mode == 'db_copy') {
  1015. unset($GLOBALS['sql_indexes']);
  1016. }
  1017. }
  1018. // -----------------------------------------------------------------
  1019. // Phase 5: Adding AUTO_INCREMENT.
  1020. if (! empty($GLOBALS['sql_auto_increments'])) {
  1021. if ($mode == 'one_table' || $mode == 'db_copy') {
  1022. $parser = new Parser($GLOBALS['sql_auto_increments']);
  1023. /**
  1024. * The ALTER statement that alters the AUTO_INCREMENT value.
  1025. * @var \PhpMyAdmin\SqlParser\Statements\AlterStatement $statement
  1026. */
  1027. $statement = $parser->statements[0];
  1028. // Changing the altered table to the destination.
  1029. $statement->table = $destination;
  1030. // Building back the query.
  1031. $GLOBALS['sql_auto_increments'] = $statement->build() . ';';
  1032. // Executing it.
  1033. $GLOBALS['dbi']->query($GLOBALS['sql_auto_increments']);
  1034. $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_auto_increments'];
  1035. unset($GLOBALS['sql_auto_increments']);
  1036. }
  1037. }
  1038. } else {
  1039. $GLOBALS['sql_query'] = '';
  1040. }
  1041. $_table = new Table($target_table, $target_db);
  1042. // Copy the data unless this is a VIEW
  1043. if (($what == 'data' || $what == 'dataonly')
  1044. && ! $_table->isView()
  1045. ) {
  1046. $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
  1047. $GLOBALS['dbi']->query($sql_set_mode);
  1048. $GLOBALS['sql_query'] .= "\n\n" . $sql_set_mode . ';';
  1049. $_old_table = new Table($source_table, $source_db);
  1050. $nonGeneratedCols = $_old_table->getNonGeneratedColumns(true);
  1051. if (count($nonGeneratedCols) > 0) {
  1052. $sql_insert_data = 'INSERT INTO ' . $target . '('
  1053. . implode(', ', $nonGeneratedCols)
  1054. . ') SELECT ' . implode(', ', $nonGeneratedCols)
  1055. . ' FROM ' . $source;
  1056. $GLOBALS['dbi']->query($sql_insert_data);
  1057. $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
  1058. }
  1059. }
  1060. $relation->getRelationsParam();
  1061. // Drops old table if the user has requested to move it
  1062. if ($move) {
  1063. // This could avoid some problems with replicated databases, when
  1064. // moving table from replicated one to not replicated one
  1065. $GLOBALS['dbi']->selectDb($source_db);
  1066. $_source_table = new Table($source_table, $source_db);
  1067. if ($_source_table->isView()) {
  1068. $sql_drop_query = 'DROP VIEW';
  1069. } else {
  1070. $sql_drop_query = 'DROP TABLE';
  1071. }
  1072. $sql_drop_query .= ' ' . $source;
  1073. $GLOBALS['dbi']->query($sql_drop_query);
  1074. // Renable table in configuration storage
  1075. $relation->renameTable(
  1076. $source_db, $target_db,
  1077. $source_table, $target_table
  1078. );
  1079. $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
  1080. // end if ($move)
  1081. return true;
  1082. }
  1083. // we are copying
  1084. // Create new entries as duplicates from old PMA DBs
  1085. if ($what == 'dataonly' || isset($maintain_relations)) {
  1086. return true;
  1087. }
  1088. if ($GLOBALS['cfgRelation']['commwork']) {
  1089. // Get all comments and MIME-Types for current table
  1090. $comments_copy_rs = $relation->queryAsControlUser(
  1091. 'SELECT column_name, comment'
  1092. . ($GLOBALS['cfgRelation']['mimework']
  1093. ? ', mimetype, transformation, transformation_options'
  1094. : '')
  1095. . ' FROM '
  1096. . Util::backquote($GLOBALS['cfgRelation']['db'])
  1097. . '.'
  1098. . Util::backquote($GLOBALS['cfgRelation']['column_info'])
  1099. . ' WHERE '
  1100. . ' db_name = \''
  1101. . $GLOBALS['dbi']->escapeString($source_db) . '\''
  1102. . ' AND '
  1103. . ' table_name = \''
  1104. . $GLOBALS['dbi']->escapeString($source_table) . '\''
  1105. );
  1106. // Write every comment as new copied entry. [MIME]
  1107. while ($comments_copy_row
  1108. = $GLOBALS['dbi']->fetchAssoc($comments_copy_rs)) {
  1109. $new_comment_query = 'REPLACE INTO '
  1110. . Util::backquote($GLOBALS['cfgRelation']['db'])
  1111. . '.' . Util::backquote(
  1112. $GLOBALS['cfgRelation']['column_info']
  1113. )
  1114. . ' (db_name, table_name, column_name, comment'
  1115. . ($GLOBALS['cfgRelation']['mimework']
  1116. ? ', mimetype, transformation, transformation_options'
  1117. : '')
  1118. . ') ' . ' VALUES(' . '\'' . $GLOBALS['dbi']->escapeString($target_db)
  1119. . '\',\'' . $GLOBALS['dbi']->escapeString($target_table) . '\',\''
  1120. . $GLOBALS['dbi']->escapeString($comments_copy_row['column_name'])
  1121. . '\',\''
  1122. . $GLOBALS['dbi']->escapeString($comments_copy_row['comment'])
  1123. . '\''
  1124. . ($GLOBALS['cfgRelation']['mimework']
  1125. ? ',\'' . $GLOBALS['dbi']->escapeString(
  1126. $comments_copy_row['mimetype']
  1127. )
  1128. . '\',' . '\'' . $GLOBALS['dbi']->escapeString(
  1129. $comments_copy_row['transformation']
  1130. )
  1131. . '\',' . '\'' . $GLOBALS['dbi']->escapeString(
  1132. $comments_copy_row['transformation_options']
  1133. )
  1134. . '\''
  1135. : '')
  1136. . ')';
  1137. $relation->queryAsControlUser($new_comment_query);
  1138. } // end while
  1139. $GLOBALS['dbi']->freeResult($comments_copy_rs);
  1140. unset($comments_copy_rs);
  1141. }
  1142. // duplicating the bookmarks must not be done here, but
  1143. // just once per db
  1144. $get_fields = array('display_field');
  1145. $where_fields = array(
  1146. 'db_name' => $source_db,
  1147. 'table_name' => $source_table
  1148. );
  1149. $new_fields = array(
  1150. 'db_name' => $target_db,
  1151. 'table_name' => $target_table
  1152. );
  1153. self::duplicateInfo(
  1154. 'displaywork',
  1155. 'table_info',
  1156. $get_fields,
  1157. $where_fields,
  1158. $new_fields
  1159. );
  1160. /**
  1161. * @todo revise this code when we support cross-db relations
  1162. */
  1163. $get_fields = array(
  1164. 'master_field',
  1165. 'foreign_table',
  1166. 'foreign_field'
  1167. );
  1168. $where_fields = array(
  1169. 'master_db' => $source_db,
  1170. 'master_table' => $source_table
  1171. );
  1172. $new_fields = array(
  1173. 'master_db' => $target_db,
  1174. 'foreign_db' => $target_db,
  1175. 'master_table' => $target_table
  1176. );
  1177. self::duplicateInfo(
  1178. 'relwork',
  1179. 'relation',
  1180. $get_fields,
  1181. $where_fields,
  1182. $new_fields
  1183. );
  1184. $get_fields = array(
  1185. 'foreign_field',
  1186. 'master_table',
  1187. 'master_field'
  1188. );
  1189. $where_fields = array(
  1190. 'foreign_db' => $source_db,
  1191. 'foreign_table' => $source_table
  1192. );
  1193. $new_fields = array(
  1194. 'master_db' => $target_db,
  1195. 'foreign_db' => $target_db,
  1196. 'foreign_table' => $target_table
  1197. );
  1198. self::duplicateInfo(
  1199. 'relwork',
  1200. 'relation',
  1201. $get_fields,
  1202. $where_fields,
  1203. $new_fields
  1204. );
  1205. /**
  1206. * @todo Can't get duplicating PDFs the right way. The
  1207. * page numbers always get screwed up independently from
  1208. * duplication because the numbers do not seem to be stored on a
  1209. * per-database basis. Would the author of pdf support please
  1210. * have a look at it?
  1211. *
  1212. $get_fields = array('page_descr');
  1213. $where_fields = array('db_name' => $source_db);
  1214. $new_fields = array('db_name' => $target_db);
  1215. $last_id = self::duplicateInfo(
  1216. 'pdfwork',
  1217. 'pdf_pages',
  1218. $get_fields,
  1219. $where_fields,
  1220. $new_fields
  1221. );
  1222. if (isset($last_id) && $last_id >= 0) {
  1223. $get_fields = array('x', 'y');
  1224. $where_fields = array(
  1225. 'db_name' => $source_db,
  1226. 'table_name' => $source_table
  1227. );
  1228. $new_fields = array(
  1229. 'db_name' => $target_db,
  1230. 'table_name' => $target_table,
  1231. 'pdf_page_number' => $last_id
  1232. );
  1233. self::duplicateInfo(
  1234. 'pdfwork',
  1235. 'table_coords',
  1236. $get_fields,
  1237. $where_fields,
  1238. $new_fields
  1239. );
  1240. }
  1241. */
  1242. return true;
  1243. }
  1244. /**
  1245. * checks if given name is a valid table name,
  1246. * currently if not empty, trailing spaces, '.', '/' and '\'
  1247. *
  1248. * @param string $table_name name to check
  1249. * @param boolean $is_backquoted whether this name is used inside backquotes or not
  1250. *
  1251. * @todo add check for valid chars in filename on current system/os
  1252. * @see https://dev.mysql.com/doc/refman/5.0/en/legal-names.html
  1253. *
  1254. * @return boolean whether the string is valid or not
  1255. */
  1256. static function isValidName($table_name, $is_backquoted = false)
  1257. {
  1258. if ($table_name !== rtrim($table_name)) {
  1259. // trailing spaces not allowed even in backquotes
  1260. return false;
  1261. }
  1262. if (strlen($table_name) === 0) {
  1263. // zero length
  1264. return false;
  1265. }
  1266. if (! $is_backquoted && $table_name !== trim($table_name)) {
  1267. // spaces at the start or in between only allowed inside backquotes
  1268. return false;
  1269. }
  1270. if (! $is_backquoted && preg_match('/^[a-zA-Z0-9_$]+$/', $table_name)) {
  1271. // only allow the above regex in unquoted identifiers
  1272. // see : https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
  1273. return true;
  1274. } elseif ($is_backquoted) {
  1275. // If backquoted, all characters should be allowed (except w/ trailing spaces)
  1276. return true;
  1277. }
  1278. // If not backquoted and doesn't follow the above regex
  1279. return false;
  1280. }
  1281. /**
  1282. * renames table
  1283. *
  1284. * @param string $new_name new table name
  1285. * @param string $new_db new database name
  1286. *
  1287. * @return bool success
  1288. */
  1289. public function rename($new_name, $new_db = null)
  1290. {
  1291. if ($GLOBALS['dbi']->getLowerCaseNames() === '1') {
  1292. $new_name = strtolower($new_name);
  1293. }
  1294. if (null !== $new_db && $new_db !== $this->getDbName()) {
  1295. // Ensure the target is valid
  1296. if (! $GLOBALS['dblist']->databases->exists($new_db)) {
  1297. $this->errors[] = __('Invalid database:') . ' ' . $new_db;
  1298. return false;
  1299. }
  1300. } else {
  1301. $new_db = $this->getDbName();
  1302. }
  1303. $new_table = new Table($new_name, $new_db);
  1304. if ($this->getFullName() === $new_table->getFullName()) {
  1305. return true;
  1306. }
  1307. // Allow whitespaces (not trailing) in $new_name,
  1308. // since we are using $backquoted in getting the fullName of table
  1309. // below to be used in the query
  1310. if (! self::isValidName($new_name, true)) {
  1311. $this->errors[] = __('Invalid table name:') . ' '
  1312. . $new_table->getFullName();
  1313. return false;
  1314. }
  1315. // If the table is moved to a different database drop its triggers first
  1316. $triggers = $this->_dbi->getTriggers(
  1317. $this->getDbName(), $this->getName(), ''
  1318. );
  1319. $handle_triggers = $this->getDbName() != $new_db && $triggers;
  1320. if ($handle_triggers) {
  1321. foreach ($triggers as $trigger) {
  1322. $sql = 'DROP TRIGGER IF EXISTS '
  1323. . Util::backquote($this->getDbName())
  1324. . '.' . Util::backquote($trigger['name']) . ';';
  1325. $this->_dbi->query($sql);
  1326. }
  1327. }
  1328. /*
  1329. * tested also for a view, in MySQL 5.0.92, 5.1.55 and 5.5.13
  1330. */
  1331. $GLOBALS['sql_query'] = '
  1332. RENAME TABLE ' . $this->getFullName(true) . '
  1333. TO ' . $new_table->getFullName(true) . ';';
  1334. // I don't think a specific error message for views is necessary
  1335. if (! $this->_dbi->query($GLOBALS['sql_query'])) {
  1336. // Restore triggers in the old database
  1337. if ($handle_triggers) {
  1338. $this->_dbi->selectDb($this->getDbName());
  1339. foreach ($triggers as $trigger) {
  1340. $this->_dbi->query($trigger['create']);
  1341. }
  1342. }
  1343. $this->errors[] = sprintf(
  1344. __('Failed to rename table %1$s to %2$s!'),
  1345. $this->getFullName(),
  1346. $new_table->getFullName()
  1347. );
  1348. return false;
  1349. }
  1350. $old_name = $this->getName();
  1351. $old_db = $this->getDbName();
  1352. $this->_name = $new_name;
  1353. $this->_db_name = $new_db;
  1354. // Renable table in configuration storage
  1355. $this->relation->renameTable(
  1356. $old_db, $new_db,
  1357. $old_name, $new_name
  1358. );
  1359. $this->messages[] = sprintf(
  1360. __('Table %1$s has been renamed to %2$s.'),
  1361. htmlspecialchars($old_name),
  1362. htmlspecialchars($new_name)
  1363. );
  1364. return true;
  1365. }
  1366. /**
  1367. * Get all unique columns
  1368. *
  1369. * returns an array with all columns with unique content, in fact these are
  1370. * all columns being single indexed in PRIMARY or UNIQUE
  1371. *
  1372. * e.g.
  1373. * - PRIMARY(id) // id
  1374. * - UNIQUE(name) // name
  1375. * - PRIMARY(fk_id1, fk_id2) // NONE
  1376. * - UNIQUE(x,y) // NONE
  1377. *
  1378. * @param bool $backquoted whether to quote name with backticks ``
  1379. * @param bool $fullName whether to include full name of the table as a prefix
  1380. *
  1381. * @return array
  1382. */
  1383. public function getUniqueColumns($backquoted = true, $fullName = true)
  1384. {
  1385. $sql = $this->_dbi->getTableIndexesSql(
  1386. $this->getDbName(),
  1387. $this->getName(),
  1388. 'Non_unique = 0'
  1389. );
  1390. $uniques = $this->_dbi->fetchResult(
  1391. $sql,
  1392. array('Key_name', null),
  1393. 'Column_name'
  1394. );
  1395. $return = array();
  1396. foreach ($uniques as $index) {
  1397. if (count($index) > 1) {
  1398. continue;
  1399. }
  1400. if ($fullName) {
  1401. $possible_column = $this->getFullName($backquoted) . '.';
  1402. } else {
  1403. $possible_column = '';
  1404. }
  1405. if ($backquoted) {
  1406. $possible_column .= Util::backquote($index[0]);
  1407. } else {
  1408. $possible_column .= $index[0];
  1409. }
  1410. // a column might have a primary and an unique index on it
  1411. if (! in_array($possible_column, $return)) {
  1412. $return[] = $possible_column;
  1413. }
  1414. }
  1415. return $return;
  1416. }
  1417. /**
  1418. * Formats lists of columns
  1419. *
  1420. * returns an array with all columns that make use of an index
  1421. *
  1422. * e.g. index(col1, col2) would return col1, col2
  1423. *
  1424. * @param array $indexed column data
  1425. * @param bool $backquoted whether to quote name with backticks ``
  1426. * @param bool $fullName whether to include full name of the table as a prefix
  1427. *
  1428. * @return array
  1429. */
  1430. private function _formatColumns(array $indexed, $backquoted, $fullName)
  1431. {
  1432. $return = array();
  1433. foreach ($indexed as $column) {
  1434. $return[] = ($fullName ? $this->getFullName($backquoted) . '.' : '')
  1435. . ($backquoted ? Util::backquote($column) : $column);
  1436. }
  1437. return $return;
  1438. }
  1439. /**
  1440. * Get all indexed columns
  1441. *
  1442. * returns an array with all columns that make use of an index
  1443. *
  1444. * e.g. index(col1, col2) would return col1, col2
  1445. *
  1446. * @param bool $backquoted whether to quote name with backticks ``
  1447. * @param bool $fullName whether to include full name of the table as a prefix
  1448. *
  1449. * @return array
  1450. */
  1451. public function getIndexedColumns($backquoted = true, $fullName = true)
  1452. {
  1453. $sql = $this->_dbi->getTableIndexesSql(
  1454. $this->getDbName(),
  1455. $this->getName(),
  1456. ''
  1457. );
  1458. $indexed = $this->_dbi->fetchResult($sql, 'Column_name', 'Column_name');
  1459. return $this->_formatColumns($indexed, $backquoted, $fullName);
  1460. }
  1461. /**
  1462. * Get all columns
  1463. *
  1464. * returns an array with all columns
  1465. *
  1466. * @param bool $backquoted whether to quote name with backticks ``
  1467. * @param bool $fullName whether to include full name of the table as a prefix
  1468. *
  1469. * @return array
  1470. */
  1471. public function getColumns($backquoted = true, $fullName = true)
  1472. {
  1473. $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
  1474. $indexed = $this->_dbi->fetchResult($sql, 'Field', 'Field');
  1475. return $this->_formatColumns($indexed, $backquoted, $fullName);
  1476. }
  1477. /**
  1478. * Get meta info for fields in table
  1479. *
  1480. * @return mixed
  1481. */
  1482. public function getColumnsMeta()
  1483. {
  1484. $move_columns_sql_query = sprintf(
  1485. 'SELECT * FROM %s.%s LIMIT 1',
  1486. Util::backquote($this->_db_name),
  1487. Util::backquote($this->_name)
  1488. );
  1489. $move_columns_sql_result = $this->_dbi->tryQuery($move_columns_sql_query);
  1490. if ($move_columns_sql_result !== false) {
  1491. return $this->_dbi->getFieldsMeta($move_columns_sql_result);
  1492. } else {
  1493. // unsure how to reproduce but it was seen on the reporting server
  1494. return array();
  1495. }
  1496. }
  1497. /**
  1498. * Get non-generated columns in table
  1499. *
  1500. * @param bool $backquoted whether to quote name with backticks ``
  1501. *
  1502. * @return array
  1503. */
  1504. public function getNonGeneratedColumns($backquoted = true)
  1505. {
  1506. $columns_meta_query = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
  1507. $ret = array();
  1508. $columns_meta_query_result = $this->_dbi->fetchResult(
  1509. $columns_meta_query
  1510. );
  1511. if ($columns_meta_query_result
  1512. && $columns_meta_query_result !== false
  1513. ) {
  1514. foreach ($columns_meta_query_result as $column) {
  1515. $value = $column['Field'];
  1516. if ($backquoted === true) {
  1517. $value = Util::backquote($value);
  1518. }
  1519. if ((
  1520. strpos($column['Extra'], 'GENERATED') === false
  1521. && strpos($column['Extra'], 'VIRTUAL') === false
  1522. ) || $column['Extra'] === 'DEFAULT_GENERATED') {
  1523. array_push($ret, $value);
  1524. }
  1525. }
  1526. }
  1527. return $ret;
  1528. }
  1529. /**
  1530. * Return UI preferences for this table from phpMyAdmin database.
  1531. *
  1532. * @return array
  1533. */
  1534. protected function getUiPrefsFromDb()
  1535. {
  1536. $cfgRelation = $this->relation->getRelationsParam();
  1537. $pma_table = Util::backquote($cfgRelation['db']) . "."
  1538. . Util::backquote($cfgRelation['table_uiprefs']);
  1539. // Read from phpMyAdmin database
  1540. $sql_query = " SELECT `prefs` FROM " . $pma_table
  1541. . " WHERE `username` = '" . $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']) . "'"
  1542. . " AND `db_name` = '" . $GLOBALS['dbi']->escapeString($this->_db_name) . "'"
  1543. . " AND `table_name` = '" . $GLOBALS['dbi']->escapeString($this->_name) . "'";
  1544. $row = $this->_dbi->fetchArray($this->relation->queryAsControlUser($sql_query));
  1545. if (isset($row[0])) {
  1546. return json_decode($row[0], true);
  1547. }
  1548. return array();
  1549. }
  1550. /**
  1551. * Save this table's UI preferences into phpMyAdmin database.
  1552. *
  1553. * @return true|Message
  1554. */
  1555. protected function saveUiPrefsToDb()
  1556. {
  1557. $cfgRelation = $this->relation->getRelationsParam();
  1558. $pma_table = Util::backquote($cfgRelation['db']) . "."
  1559. . Util::backquote($cfgRelation['table_uiprefs']);
  1560. $secureDbName = $GLOBALS['dbi']->escapeString($this->_db_name);
  1561. $username = $GLOBALS['cfg']['Server']['user'];
  1562. $sql_query = " REPLACE INTO " . $pma_table
  1563. . " (username, db_name, table_name, prefs) VALUES ('"
  1564. . $GLOBALS['dbi']->escapeString($username) . "', '" . $secureDbName
  1565. . "', '" . $GLOBALS['dbi']->escapeString($this->_name) . "', '"
  1566. . $GLOBALS['dbi']->escapeString(json_encode($this->uiprefs)) . "')";
  1567. $success = $this->_dbi->tryQuery($sql_query, DatabaseInterface::CONNECT_CONTROL);
  1568. if (!$success) {
  1569. $message = Message::error(
  1570. __('Could not save table UI preferences!')
  1571. );
  1572. $message->addMessage(
  1573. Message::rawError(
  1574. $this->_dbi->getError(DatabaseInterface::CONNECT_CONTROL)
  1575. ),
  1576. '<br /><br />'
  1577. );
  1578. return $message;
  1579. }
  1580. // Remove some old rows in table_uiprefs if it exceeds the configured
  1581. // maximum rows
  1582. $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
  1583. $rows_count = $this->_dbi->fetchValue($sql_query);
  1584. $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
  1585. if ($rows_count > $max_rows) {
  1586. $num_rows_to_delete = $rows_count - $max_rows;
  1587. $sql_query
  1588. = ' DELETE FROM ' . $pma_table .
  1589. ' ORDER BY last_update ASC' .
  1590. ' LIMIT ' . $num_rows_to_delete;
  1591. $success = $this->_dbi->tryQuery(
  1592. $sql_query, DatabaseInterface::CONNECT_CONTROL
  1593. );
  1594. if (!$success) {
  1595. $message = Message::error(
  1596. sprintf(
  1597. __(
  1598. 'Failed to cleanup table UI preferences (see ' .
  1599. '$cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'
  1600. ),
  1601. Util::showDocu('config', 'cfg_Servers_MaxTableUiprefs')
  1602. )
  1603. );
  1604. $message->addMessage(
  1605. Message::rawError(
  1606. $this->_dbi->getError(DatabaseInterface::CONNECT_CONTROL)
  1607. ),
  1608. '<br /><br />'
  1609. );
  1610. return $message;
  1611. }
  1612. }
  1613. return true;
  1614. }
  1615. /**
  1616. * Loads the UI preferences for this table.
  1617. * If pmadb and table_uiprefs is set, it will load the UI preferences from
  1618. * phpMyAdmin database.
  1619. *
  1620. * @return void
  1621. */
  1622. protected function loadUiPrefs()
  1623. {
  1624. $cfgRelation = $this->relation->getRelationsParam();
  1625. $server_id = $GLOBALS['server'];
  1626. // set session variable if it's still undefined
  1627. if (!isset($_SESSION['tmpval']['table_uiprefs'][$server_id][$this->_db_name][$this->_name])) {
  1628. // check whether we can get from pmadb
  1629. $_SESSION['tmpval']['table_uiprefs'][$server_id][$this->_db_name]
  1630. [$this->_name] = $cfgRelation['uiprefswork']
  1631. ? $this->getUiPrefsFromDb()
  1632. : array();
  1633. }
  1634. $this->uiprefs =& $_SESSION['tmpval']['table_uiprefs'][$server_id]
  1635. [$this->_db_name][$this->_name];
  1636. }
  1637. /**
  1638. * Get a property from UI preferences.
  1639. * Return false if the property is not found.
  1640. * Available property:
  1641. * - PROP_SORTED_COLUMN
  1642. * - PROP_COLUMN_ORDER
  1643. * - PROP_COLUMN_VISIB
  1644. *
  1645. * @param string $property property
  1646. *
  1647. * @return mixed
  1648. */
  1649. public function getUiProp($property)
  1650. {
  1651. if (! isset($this->uiprefs)) {
  1652. $this->loadUiPrefs();
  1653. }
  1654. // do checking based on property
  1655. if ($property == self::PROP_SORTED_COLUMN) {
  1656. if (!isset($this->uiprefs[$property])) {
  1657. return false;
  1658. }
  1659. if (!isset($_POST['discard_remembered_sort'])) {
  1660. // check if the column name exists in this table
  1661. $tmp = explode(' ', $this->uiprefs[$property]);
  1662. $colname = $tmp[0];
  1663. //remove backquoting from colname
  1664. $colname = str_replace('`', '', $colname);
  1665. //get the available column name without backquoting
  1666. $avail_columns = $this->getColumns(false);
  1667. foreach ($avail_columns as $each_col) {
  1668. // check if $each_col ends with $colname
  1669. if (substr_compare(
  1670. $each_col,
  1671. $colname,
  1672. mb_strlen($each_col) - mb_strlen($colname)
  1673. ) === 0
  1674. ) {
  1675. return $this->uiprefs[$property];
  1676. }
  1677. }
  1678. }
  1679. // remove the property, since it no longer exists in database
  1680. $this->removeUiProp($property);
  1681. return false;
  1682. }
  1683. if ($property == self::PROP_COLUMN_ORDER
  1684. || $property == self::PROP_COLUMN_VISIB
  1685. ) {
  1686. if ($this->isView() || !isset($this->uiprefs[$property])) {
  1687. return false;
  1688. }
  1689. // check if the table has not been modified
  1690. if ($this->getStatusInfo('Create_time') == $this->uiprefs['CREATE_TIME']
  1691. ) {
  1692. return array_map('intval', $this->uiprefs[$property]);
  1693. }
  1694. // remove the property, since the table has been modified
  1695. $this->removeUiProp($property);
  1696. return false;
  1697. }
  1698. // default behaviour for other property:
  1699. return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
  1700. }
  1701. /**
  1702. * Set a property from UI preferences.
  1703. * If pmadb and table_uiprefs is set, it will save the UI preferences to
  1704. * phpMyAdmin database.
  1705. * Available property:
  1706. * - PROP_SORTED_COLUMN
  1707. * - PROP_COLUMN_ORDER
  1708. * - PROP_COLUMN_VISIB
  1709. *
  1710. * @param string $property Property
  1711. * @param mixed $value Value for the property
  1712. * @param string $table_create_time Needed for PROP_COLUMN_ORDER
  1713. * and PROP_COLUMN_VISIB
  1714. *
  1715. * @return boolean|Message
  1716. */
  1717. public function setUiProp($property, $value, $table_create_time = null)
  1718. {
  1719. if (! isset($this->uiprefs)) {
  1720. $this->loadUiPrefs();
  1721. }
  1722. // we want to save the create time if the property is PROP_COLUMN_ORDER
  1723. if (! $this->isView()
  1724. && ($property == self::PROP_COLUMN_ORDER
  1725. || $property == self::PROP_COLUMN_VISIB)
  1726. ) {
  1727. $curr_create_time = $this->getStatusInfo('CREATE_TIME');
  1728. if (isset($table_create_time)
  1729. && $table_create_time == $curr_create_time
  1730. ) {
  1731. $this->uiprefs['CREATE_TIME'] = $curr_create_time;
  1732. } else {
  1733. // there is no $table_create_time, or
  1734. // supplied $table_create_time is older than current create time,
  1735. // so don't save
  1736. return Message::error(
  1737. sprintf(
  1738. __(
  1739. 'Cannot save UI property "%s". The changes made will ' .
  1740. 'not be persistent after you refresh this page. ' .
  1741. 'Please check if the table structure has been changed.'
  1742. ),
  1743. $property
  1744. )
  1745. );
  1746. }
  1747. }
  1748. // save the value
  1749. $this->uiprefs[$property] = $value;
  1750. // check if pmadb is set
  1751. $cfgRelation = $this->relation->getRelationsParam();
  1752. if ($cfgRelation['uiprefswork']) {
  1753. return $this->saveUiprefsToDb();
  1754. }
  1755. return true;
  1756. }
  1757. /**
  1758. * Remove a property from UI preferences.
  1759. *
  1760. * @param string $property the property
  1761. *
  1762. * @return true|Message
  1763. */
  1764. public function removeUiProp($property)
  1765. {
  1766. if (! isset($this->uiprefs)) {
  1767. $this->loadUiPrefs();
  1768. }
  1769. if (isset($this->uiprefs[$property])) {
  1770. unset($this->uiprefs[$property]);
  1771. // check if pmadb is set
  1772. $cfgRelation = $this->relation->getRelationsParam();
  1773. if ($cfgRelation['uiprefswork']) {
  1774. return $this->saveUiprefsToDb();
  1775. }
  1776. }
  1777. return true;
  1778. }
  1779. /**
  1780. * Get all column names which are MySQL reserved words
  1781. *
  1782. * @return array
  1783. * @access public
  1784. */
  1785. public function getReservedColumnNames()
  1786. {
  1787. $columns = $this->getColumns(false);
  1788. $return = array();
  1789. foreach ($columns as $column) {
  1790. $temp = explode('.', $column);
  1791. $column_name = $temp[2];
  1792. if (Context::isKeyword($column_name, true)) {
  1793. $return[] = $column_name;
  1794. }
  1795. }
  1796. return $return;
  1797. }
  1798. /**
  1799. * Function to get the name and type of the columns of a table
  1800. *
  1801. * @return array
  1802. */
  1803. public function getNameAndTypeOfTheColumns()
  1804. {
  1805. $columns = array();
  1806. foreach ($this->_dbi->getColumnsFull(
  1807. $this->_db_name, $this->_name
  1808. ) as $row) {
  1809. if (preg_match('@^(set|enum)\((.+)\)$@i', $row['Type'], $tmp)) {
  1810. $tmp[2] = mb_substr(
  1811. preg_replace('@([^,])\'\'@', '\\1\\\'', ',' . $tmp[2]), 1
  1812. );
  1813. $columns[$row['Field']] = $tmp[1] . '('
  1814. . str_replace(',', ', ', $tmp[2]) . ')';
  1815. } else {
  1816. $columns[$row['Field']] = $row['Type'];
  1817. }
  1818. }
  1819. return $columns;
  1820. }
  1821. /**
  1822. * Get index with index name
  1823. *
  1824. * @param string $index Index name
  1825. *
  1826. * @return Index
  1827. */
  1828. public function getIndex($index)
  1829. {
  1830. return Index::singleton($this->_db_name, $this->_name, $index);
  1831. }
  1832. /**
  1833. * Function to get the sql query for index creation or edit
  1834. *
  1835. * @param Index $index current index
  1836. * @param bool &$error whether error occurred or not
  1837. *
  1838. * @return string
  1839. */
  1840. public function getSqlQueryForIndexCreateOrEdit($index, &$error)
  1841. {
  1842. // $sql_query is the one displayed in the query box
  1843. $sql_query = sprintf(
  1844. 'ALTER TABLE %s.%s',
  1845. Util::backquote($this->_db_name),
  1846. Util::backquote($this->_name)
  1847. );
  1848. // Drops the old index
  1849. if (! empty($_POST['old_index'])) {
  1850. if ($_POST['old_index'] == 'PRIMARY') {
  1851. $sql_query .= ' DROP PRIMARY KEY,';
  1852. } else {
  1853. $sql_query .= sprintf(
  1854. ' DROP INDEX %s,',
  1855. Util::backquote($_POST['old_index'])
  1856. );
  1857. }
  1858. } // end if
  1859. // Builds the new one
  1860. switch ($index->getChoice()) {
  1861. case 'PRIMARY':
  1862. if ($index->getName() == '') {
  1863. $index->setName('PRIMARY');
  1864. } elseif ($index->getName() != 'PRIMARY') {
  1865. $error = Message::error(
  1866. __('The name of the primary key must be "PRIMARY"!')
  1867. );
  1868. }
  1869. $sql_query .= ' ADD PRIMARY KEY';
  1870. break;
  1871. case 'FULLTEXT':
  1872. case 'UNIQUE':
  1873. case 'INDEX':
  1874. case 'SPATIAL':
  1875. if ($index->getName() == 'PRIMARY') {
  1876. $error = Message::error(
  1877. __('Can\'t rename index to PRIMARY!')
  1878. );
  1879. }
  1880. $sql_query .= sprintf(
  1881. ' ADD %s ',
  1882. $index->getChoice()
  1883. );
  1884. if ($index->getName()) {
  1885. $sql_query .= Util::backquote($index->getName());
  1886. }
  1887. break;
  1888. } // end switch
  1889. $index_fields = array();
  1890. foreach ($index->getColumns() as $key => $column) {
  1891. $index_fields[$key] = Util::backquote($column->getName());
  1892. if ($column->getSubPart()) {
  1893. $index_fields[$key] .= '(' . $column->getSubPart() . ')';
  1894. }
  1895. } // end while
  1896. if (empty($index_fields)) {
  1897. $error = Message::error(__('No index parts defined!'));
  1898. } else {
  1899. $sql_query .= ' (' . implode(', ', $index_fields) . ')';
  1900. }
  1901. $keyBlockSizes = $index->getKeyBlockSize();
  1902. if (! empty($keyBlockSizes)) {
  1903. $sql_query .= sprintf(
  1904. ' KEY_BLOCK_SIZE = %s',
  1905. $GLOBALS['dbi']->escapeString($keyBlockSizes)
  1906. );
  1907. }
  1908. // specifying index type is allowed only for primary, unique and index only
  1909. // TokuDB is using Fractal Tree, Using Type is not useless
  1910. // Ref: https://mariadb.com/kb/en/mariadb/storage-engine-index-types/
  1911. $type = $index->getType();
  1912. if ($index->getChoice() != 'SPATIAL'
  1913. && $index->getChoice() != 'FULLTEXT'
  1914. && in_array($type, Index::getIndexTypes())
  1915. && ! $this->isEngine(array('TOKUDB'))
  1916. ) {
  1917. $sql_query .= ' USING ' . $type;
  1918. }
  1919. $parser = $index->getParser();
  1920. if ($index->getChoice() == 'FULLTEXT' && ! empty($parser)) {
  1921. $sql_query .= ' WITH PARSER ' . $GLOBALS['dbi']->escapeString($parser);
  1922. }
  1923. $comment = $index->getComment();
  1924. if (! empty($comment)) {
  1925. $sql_query .= sprintf(
  1926. " COMMENT '%s'",
  1927. $GLOBALS['dbi']->escapeString($comment)
  1928. );
  1929. }
  1930. $sql_query .= ';';
  1931. return $sql_query;
  1932. }
  1933. /**
  1934. * Function to handle update for display field
  1935. *
  1936. * @param string $display_field display field
  1937. * @param array $cfgRelation configuration relation
  1938. *
  1939. * @return boolean True on update succeed or False on failure
  1940. */
  1941. public function updateDisplayField($display_field, array $cfgRelation)
  1942. {
  1943. $upd_query = false;
  1944. if ($display_field == '') {
  1945. $upd_query = 'DELETE FROM '
  1946. . Util::backquote($GLOBALS['cfgRelation']['db'])
  1947. . '.' . Util::backquote($cfgRelation['table_info'])
  1948. . ' WHERE db_name = \''
  1949. . $GLOBALS['dbi']->escapeString($this->_db_name) . '\''
  1950. . ' AND table_name = \''
  1951. . $GLOBALS['dbi']->escapeString($this->_name) . '\'';
  1952. } else {
  1953. $upd_query = 'REPLACE INTO '
  1954. . Util::backquote($GLOBALS['cfgRelation']['db'])
  1955. . '.' . Util::backquote($cfgRelation['table_info'])
  1956. . '(db_name, table_name, display_field) VALUES('
  1957. . '\'' . $GLOBALS['dbi']->escapeString($this->_db_name) . '\','
  1958. . '\'' . $GLOBALS['dbi']->escapeString($this->_name) . '\','
  1959. . '\'' . $GLOBALS['dbi']->escapeString($display_field) . '\')';
  1960. }
  1961. if ($upd_query) {
  1962. $this->_dbi->query(
  1963. $upd_query,
  1964. DatabaseInterface::CONNECT_CONTROL,
  1965. 0,
  1966. false
  1967. );
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972. /**
  1973. * Function to get update query for updating internal relations
  1974. *
  1975. * @param array $multi_edit_columns_name multi edit column names
  1976. * @param array $destination_db destination tables
  1977. * @param array $destination_table destination tables
  1978. * @param array $destination_column destination columns
  1979. * @param array $cfgRelation configuration relation
  1980. * @param array|null $existrel db, table, column
  1981. *
  1982. * @return boolean
  1983. */
  1984. public function updateInternalRelations(array $multi_edit_columns_name,
  1985. array $destination_db, array $destination_table, array $destination_column,
  1986. array $cfgRelation, $existrel
  1987. ) {
  1988. $updated = false;
  1989. foreach ($destination_db as $master_field_md5 => $foreign_db) {
  1990. $upd_query = null;
  1991. // Map the fieldname's md5 back to its real name
  1992. $master_field = $multi_edit_columns_name[$master_field_md5];
  1993. $foreign_table = $destination_table[$master_field_md5];
  1994. $foreign_field = $destination_column[$master_field_md5];
  1995. if (! empty($foreign_db)
  1996. && ! empty($foreign_table)
  1997. && ! empty($foreign_field)
  1998. ) {
  1999. if (! isset($existrel[$master_field])) {
  2000. $upd_query = 'INSERT INTO '
  2001. . Util::backquote($GLOBALS['cfgRelation']['db'])
  2002. . '.' . Util::backquote($cfgRelation['relation'])
  2003. . '(master_db, master_table, master_field, foreign_db,'
  2004. . ' foreign_table, foreign_field)'
  2005. . ' values('
  2006. . '\'' . $GLOBALS['dbi']->escapeString($this->_db_name) . '\', '
  2007. . '\'' . $GLOBALS['dbi']->escapeString($this->_name) . '\', '
  2008. . '\'' . $GLOBALS['dbi']->escapeString($master_field) . '\', '
  2009. . '\'' . $GLOBALS['dbi']->escapeString($foreign_db) . '\', '
  2010. . '\'' . $GLOBALS['dbi']->escapeString($foreign_table) . '\','
  2011. . '\'' . $GLOBALS['dbi']->escapeString($foreign_field) . '\')';
  2012. } elseif ($existrel[$master_field]['foreign_db'] != $foreign_db
  2013. || $existrel[$master_field]['foreign_table'] != $foreign_table
  2014. || $existrel[$master_field]['foreign_field'] != $foreign_field
  2015. ) {
  2016. $upd_query = 'UPDATE '
  2017. . Util::backquote($GLOBALS['cfgRelation']['db'])
  2018. . '.' . Util::backquote($cfgRelation['relation'])
  2019. . ' SET foreign_db = \''
  2020. . $GLOBALS['dbi']->escapeString($foreign_db) . '\', '
  2021. . ' foreign_table = \''
  2022. . $GLOBALS['dbi']->escapeString($foreign_table) . '\', '
  2023. . ' foreign_field = \''
  2024. . $GLOBALS['dbi']->escapeString($foreign_field) . '\' '
  2025. . ' WHERE master_db = \''
  2026. . $GLOBALS['dbi']->escapeString($this->_db_name) . '\''
  2027. . ' AND master_table = \''
  2028. . $GLOBALS['dbi']->escapeString($this->_name) . '\''
  2029. . ' AND master_field = \''
  2030. . $GLOBALS['dbi']->escapeString($master_field) . '\'';
  2031. } // end if... else....
  2032. } elseif (isset($existrel[$master_field])) {
  2033. $upd_query = 'DELETE FROM '
  2034. . Util::backquote($GLOBALS['cfgRelation']['db'])
  2035. . '.' . Util::backquote($cfgRelation['relation'])
  2036. . ' WHERE master_db = \''
  2037. . $GLOBALS['dbi']->escapeString($this->_db_name) . '\''
  2038. . ' AND master_table = \''
  2039. . $GLOBALS['dbi']->escapeString($this->_name) . '\''
  2040. . ' AND master_field = \''
  2041. . $GLOBALS['dbi']->escapeString($master_field) . '\'';
  2042. } // end if... else....
  2043. if (isset($upd_query)) {
  2044. $this->_dbi->query(
  2045. $upd_query,
  2046. DatabaseInterface::CONNECT_CONTROL,
  2047. 0,
  2048. false
  2049. );
  2050. $updated = true;
  2051. }
  2052. }
  2053. return $updated;
  2054. }
  2055. /**
  2056. * Function to handle foreign key updates
  2057. *
  2058. * @param array $destination_foreign_db destination foreign database
  2059. * @param array $multi_edit_columns_name multi edit column names
  2060. * @param array $destination_foreign_table destination foreign table
  2061. * @param array $destination_foreign_column destination foreign column
  2062. * @param array $options_array options array
  2063. * @param string $table current table
  2064. * @param array $existrel_foreign db, table, column
  2065. *
  2066. * @return array
  2067. */
  2068. public function updateForeignKeys(array $destination_foreign_db,
  2069. array $multi_edit_columns_name, array $destination_foreign_table,
  2070. array $destination_foreign_column, array $options_array, $table, array $existrel_foreign
  2071. ) {
  2072. $html_output = '';
  2073. $preview_sql_data = '';
  2074. $display_query = '';
  2075. $seen_error = false;
  2076. foreach ($destination_foreign_db as $master_field_md5 => $foreign_db) {
  2077. $create = false;
  2078. $drop = false;
  2079. // Map the fieldname's md5 back to its real name
  2080. $master_field = $multi_edit_columns_name[$master_field_md5];
  2081. $foreign_table = $destination_foreign_table[$master_field_md5];
  2082. $foreign_field = $destination_foreign_column[$master_field_md5];
  2083. if (isset($existrel_foreign[$master_field_md5]['ref_db_name'])) {
  2084. $ref_db_name = $existrel_foreign[$master_field_md5]['ref_db_name'];
  2085. } else {
  2086. $ref_db_name = $GLOBALS['db'];
  2087. }
  2088. $empty_fields = false;
  2089. foreach ($master_field as $key => $one_field) {
  2090. if ((! empty($one_field) && empty($foreign_field[$key]))
  2091. || (empty($one_field) && ! empty($foreign_field[$key]))
  2092. ) {
  2093. $empty_fields = true;
  2094. }
  2095. if (empty($one_field) && empty($foreign_field[$key])) {
  2096. unset($master_field[$key]);
  2097. unset($foreign_field[$key]);
  2098. }
  2099. }
  2100. if (! empty($foreign_db)
  2101. && ! empty($foreign_table)
  2102. && ! $empty_fields
  2103. ) {
  2104. if (isset($existrel_foreign[$master_field_md5])) {
  2105. $constraint_name
  2106. = $existrel_foreign[$master_field_md5]['constraint'];
  2107. $on_delete = !empty(
  2108. $existrel_foreign[$master_field_md5]['on_delete']
  2109. )
  2110. ? $existrel_foreign[$master_field_md5]['on_delete']
  2111. : 'RESTRICT';
  2112. $on_update = ! empty(
  2113. $existrel_foreign[$master_field_md5]['on_update']
  2114. )
  2115. ? $existrel_foreign[$master_field_md5]['on_update']
  2116. : 'RESTRICT';
  2117. if ($ref_db_name != $foreign_db
  2118. || $existrel_foreign[$master_field_md5]['ref_table_name'] != $foreign_table
  2119. || $existrel_foreign[$master_field_md5]['ref_index_list'] != $foreign_field
  2120. || $existrel_foreign[$master_field_md5]['index_list'] != $master_field
  2121. || $_POST['constraint_name'][$master_field_md5] != $constraint_name
  2122. || ($_POST['on_delete'][$master_field_md5] != $on_delete)
  2123. || ($_POST['on_update'][$master_field_md5] != $on_update)
  2124. ) {
  2125. // another foreign key is already defined for this field
  2126. // or an option has been changed for ON DELETE or ON UPDATE
  2127. $drop = true;
  2128. $create = true;
  2129. } // end if... else....
  2130. } else {
  2131. // no key defined for this field(s)
  2132. $create = true;
  2133. }
  2134. } elseif (isset($existrel_foreign[$master_field_md5])) {
  2135. $drop = true;
  2136. } // end if... else....
  2137. $tmp_error_drop = false;
  2138. if ($drop) {
  2139. $drop_query = 'ALTER TABLE ' . Util::backquote($table)
  2140. . ' DROP FOREIGN KEY '
  2141. . Util::backquote(
  2142. $existrel_foreign[$master_field_md5]['constraint']
  2143. )
  2144. . ';';
  2145. if (! isset($_POST['preview_sql'])) {
  2146. $display_query .= $drop_query . "\n";
  2147. $this->_dbi->tryQuery($drop_query);
  2148. $tmp_error_drop = $this->_dbi->getError();
  2149. if (! empty($tmp_error_drop)) {
  2150. $seen_error = true;
  2151. $html_output .= Util::mysqlDie(
  2152. $tmp_error_drop, $drop_query, false, '', false
  2153. );
  2154. continue;
  2155. }
  2156. } else {
  2157. $preview_sql_data .= $drop_query . "\n";
  2158. }
  2159. }
  2160. $tmp_error_create = false;
  2161. if (!$create) {
  2162. continue;
  2163. }
  2164. $create_query = $this->_getSQLToCreateForeignKey(
  2165. $table, $master_field, $foreign_db, $foreign_table, $foreign_field,
  2166. $_POST['constraint_name'][$master_field_md5],
  2167. $options_array[$_POST['on_delete'][$master_field_md5]],
  2168. $options_array[$_POST['on_update'][$master_field_md5]]
  2169. );
  2170. if (! isset($_POST['preview_sql'])) {
  2171. $display_query .= $create_query . "\n";
  2172. $this->_dbi->tryQuery($create_query);
  2173. $tmp_error_create = $this->_dbi->getError();
  2174. if (! empty($tmp_error_create)) {
  2175. $seen_error = true;
  2176. if (substr($tmp_error_create, 1, 4) == '1005') {
  2177. $message = Message::error(
  2178. __(
  2179. 'Error creating foreign key on %1$s (check data ' .
  2180. 'types)'
  2181. )
  2182. );
  2183. $message->addParam(implode(', ', $master_field));
  2184. $html_output .= $message->getDisplay();
  2185. } else {
  2186. $html_output .= Util::mysqlDie(
  2187. $tmp_error_create, $create_query, false, '', false
  2188. );
  2189. }
  2190. $html_output .= Util::showMySQLDocu(
  2191. 'InnoDB_foreign_key_constraints'
  2192. ) . "\n";
  2193. }
  2194. } else {
  2195. $preview_sql_data .= $create_query . "\n";
  2196. }
  2197. // this is an alteration and the old constraint has been dropped
  2198. // without creation of a new one
  2199. if ($drop && $create && empty($tmp_error_drop)
  2200. && ! empty($tmp_error_create)
  2201. ) {
  2202. // a rollback may be better here
  2203. $sql_query_recreate = '# Restoring the dropped constraint...' . "\n";
  2204. $sql_query_recreate .= $this->_getSQLToCreateForeignKey(
  2205. $table,
  2206. $master_field,
  2207. $existrel_foreign[$master_field_md5]['ref_db_name'],
  2208. $existrel_foreign[$master_field_md5]['ref_table_name'],
  2209. $existrel_foreign[$master_field_md5]['ref_index_list'],
  2210. $existrel_foreign[$master_field_md5]['constraint'],
  2211. $options_array[$existrel_foreign[$master_field_md5]['on_delete']],
  2212. $options_array[$existrel_foreign[$master_field_md5]['on_update']]
  2213. );
  2214. if (! isset($_POST['preview_sql'])) {
  2215. $display_query .= $sql_query_recreate . "\n";
  2216. $this->_dbi->tryQuery($sql_query_recreate);
  2217. } else {
  2218. $preview_sql_data .= $sql_query_recreate;
  2219. }
  2220. }
  2221. } // end foreach
  2222. return array(
  2223. $html_output,
  2224. $preview_sql_data,
  2225. $display_query,
  2226. $seen_error
  2227. );
  2228. }
  2229. /**
  2230. * Returns the SQL query for foreign key constraint creation
  2231. *
  2232. * @param string $table table name
  2233. * @param array $field field names
  2234. * @param string $foreignDb foreign database name
  2235. * @param string $foreignTable foreign table name
  2236. * @param array $foreignField foreign field names
  2237. * @param string $name name of the constraint
  2238. * @param string $onDelete on delete action
  2239. * @param string $onUpdate on update action
  2240. *
  2241. * @return string SQL query for foreign key constraint creation
  2242. */
  2243. private function _getSQLToCreateForeignKey(
  2244. $table,
  2245. array $field,
  2246. $foreignDb,
  2247. $foreignTable,
  2248. array $foreignField,
  2249. $name = null,
  2250. $onDelete = null,
  2251. $onUpdate = null
  2252. ) {
  2253. $sql_query = 'ALTER TABLE ' . Util::backquote($table) . ' ADD ';
  2254. // if user entered a constraint name
  2255. if (! empty($name)) {
  2256. $sql_query .= ' CONSTRAINT ' . Util::backquote($name);
  2257. }
  2258. foreach ($field as $key => $one_field) {
  2259. $field[$key] = Util::backquote($one_field);
  2260. }
  2261. foreach ($foreignField as $key => $one_field) {
  2262. $foreignField[$key] = Util::backquote($one_field);
  2263. }
  2264. $sql_query .= ' FOREIGN KEY (' . implode(', ', $field) . ') REFERENCES '
  2265. . ($this->_db_name != $foreignDb
  2266. ? Util::backquote($foreignDb) . '.' : '')
  2267. . Util::backquote($foreignTable)
  2268. . '(' . implode(', ', $foreignField) . ')';
  2269. if (! empty($onDelete)) {
  2270. $sql_query .= ' ON DELETE ' . $onDelete;
  2271. }
  2272. if (! empty($onUpdate)) {
  2273. $sql_query .= ' ON UPDATE ' . $onUpdate;
  2274. }
  2275. $sql_query .= ';';
  2276. return $sql_query;
  2277. }
  2278. /**
  2279. * Returns the generation expression for virtual columns
  2280. *
  2281. * @param string $column name of the column
  2282. *
  2283. * @return array|boolean associative array of column name and their expressions
  2284. * or false on failure
  2285. */
  2286. public function getColumnGenerationExpression($column = null)
  2287. {
  2288. $serverType = Util::getServerType();
  2289. if ($serverType == 'MySQL'
  2290. && $GLOBALS['dbi']->getVersion() > 50705
  2291. && ! $GLOBALS['cfg']['Server']['DisableIS']
  2292. ) {
  2293. $sql
  2294. = "SELECT
  2295. `COLUMN_NAME` AS `Field`,
  2296. `GENERATION_EXPRESSION` AS `Expression`
  2297. FROM
  2298. `information_schema`.`COLUMNS`
  2299. WHERE
  2300. `TABLE_SCHEMA` = '" . $GLOBALS['dbi']->escapeString($this->_db_name) . "'
  2301. AND `TABLE_NAME` = '" . $GLOBALS['dbi']->escapeString($this->_name) . "'";
  2302. if ($column != null) {
  2303. $sql .= " AND `COLUMN_NAME` = '" . $GLOBALS['dbi']->escapeString($column)
  2304. . "'";
  2305. }
  2306. $columns = $this->_dbi->fetchResult($sql, 'Field', 'Expression');
  2307. return $columns;
  2308. }
  2309. $createTable = $this->showCreate();
  2310. if (!$createTable) {
  2311. return false;
  2312. }
  2313. $parser = new Parser($createTable);
  2314. /**
  2315. * @var \PhpMyAdmin\SqlParser\Statements\CreateStatement $stmt
  2316. */
  2317. $stmt = $parser->statements[0];
  2318. $fields = TableUtils::getFields($stmt);
  2319. if ($column != null) {
  2320. $expression = isset($fields[$column]['expr']) ?
  2321. substr($fields[$column]['expr'], 1, -1) : '';
  2322. return array($column => $expression);
  2323. }
  2324. $ret = array();
  2325. foreach ($fields as $field => $options) {
  2326. if (isset($options['expr'])) {
  2327. $ret[$field] = substr($options['expr'], 1, -1);
  2328. }
  2329. }
  2330. return $ret;
  2331. }
  2332. /**
  2333. * Returns the CREATE statement for this table
  2334. *
  2335. * @return mixed
  2336. */
  2337. public function showCreate()
  2338. {
  2339. return $this->_dbi->fetchValue(
  2340. 'SHOW CREATE TABLE ' . Util::backquote($this->_db_name) . '.'
  2341. . Util::backquote($this->_name),
  2342. 0, 1
  2343. );
  2344. }
  2345. /**
  2346. * Returns the real row count for a table
  2347. *
  2348. * @return number
  2349. */
  2350. public function getRealRowCountTable()
  2351. {
  2352. // SQL query to get row count for a table.
  2353. $result = $this->_dbi->fetchSingleRow(
  2354. sprintf(
  2355. 'SELECT COUNT(*) AS %s FROM %s.%s',
  2356. Util::backquote('row_count'),
  2357. Util::backquote($this->_db_name),
  2358. Util::backquote($this->_name)
  2359. )
  2360. );
  2361. return $result['row_count'];
  2362. }
  2363. /**
  2364. * Get columns with indexes
  2365. *
  2366. * @param int $types types bitmask
  2367. *
  2368. * @return array an array of columns
  2369. */
  2370. public function getColumnsWithIndex($types)
  2371. {
  2372. $columns_with_index = array();
  2373. foreach (
  2374. Index::getFromTableByChoice(
  2375. $this->_name,
  2376. $this->_db_name,
  2377. $types
  2378. ) as $index
  2379. ) {
  2380. $columns = $index->getColumns();
  2381. foreach ($columns as $column_name => $dummy) {
  2382. $columns_with_index[] = $column_name;
  2383. }
  2384. }
  2385. return $columns_with_index;
  2386. }
  2387. }