Table.php 91 KB

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