Table.php 96 KB

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