PageRenderTime 77ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/classes/Plugins/Export/ExportSql.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 2859 lines | 1995 code | 362 blank | 502 comment | 308 complexity | a75ad2d2fbb396e6354cbeb6aab6cde7 MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0
  1. <?php
  2. /**
  3. * Set of functions used to build SQL dumps of tables
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Plugins\Export;
  7. use PhpMyAdmin\Charsets;
  8. use PhpMyAdmin\DatabaseInterface;
  9. use PhpMyAdmin\FieldMetadata;
  10. use PhpMyAdmin\Plugins\ExportPlugin;
  11. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
  12. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
  13. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertySubgroup;
  14. use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
  15. use PhpMyAdmin\Properties\Options\Items\MessageOnlyPropertyItem;
  16. use PhpMyAdmin\Properties\Options\Items\NumberPropertyItem;
  17. use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
  18. use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
  19. use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
  20. use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
  21. use PhpMyAdmin\SqlParser\Components\CreateDefinition;
  22. use PhpMyAdmin\SqlParser\Context;
  23. use PhpMyAdmin\SqlParser\Parser;
  24. use PhpMyAdmin\SqlParser\Statements\CreateStatement;
  25. use PhpMyAdmin\SqlParser\Token;
  26. use PhpMyAdmin\Util;
  27. use PhpMyAdmin\Version;
  28. use function __;
  29. use function bin2hex;
  30. use function count;
  31. use function defined;
  32. use function explode;
  33. use function implode;
  34. use function in_array;
  35. use function intval;
  36. use function is_array;
  37. use function mb_strlen;
  38. use function mb_strpos;
  39. use function mb_substr;
  40. use function preg_quote;
  41. use function preg_replace;
  42. use function preg_split;
  43. use function sprintf;
  44. use function str_repeat;
  45. use function str_replace;
  46. use function strtotime;
  47. use function strtoupper;
  48. use function trigger_error;
  49. use const E_USER_ERROR;
  50. use const PHP_VERSION;
  51. /**
  52. * Handles the export for the SQL class
  53. */
  54. class ExportSql extends ExportPlugin
  55. {
  56. /**
  57. * Whether charset header was sent.
  58. *
  59. * @var bool
  60. */
  61. private $sentCharset = false;
  62. protected function init(): void
  63. {
  64. // Avoids undefined variables, use NULL so isset() returns false
  65. if (isset($GLOBALS['sql_backquotes'])) {
  66. return;
  67. }
  68. $GLOBALS['sql_backquotes'] = null;
  69. }
  70. /**
  71. * @psalm-return non-empty-lowercase-string
  72. */
  73. public function getName(): string
  74. {
  75. return 'sql';
  76. }
  77. protected function setProperties(): ExportPluginProperties
  78. {
  79. global $plugin_param, $dbi;
  80. $hideSql = false;
  81. $hideStructure = false;
  82. if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) {
  83. $hideStructure = true;
  84. $hideSql = true;
  85. }
  86. // In case we have `raw_query` parameter set,
  87. // we initialize SQL option
  88. if (isset($_REQUEST['raw_query'])) {
  89. $hideStructure = false;
  90. $hideSql = false;
  91. }
  92. $exportPluginProperties = new ExportPluginProperties();
  93. $exportPluginProperties->setText('SQL');
  94. $exportPluginProperties->setExtension('sql');
  95. $exportPluginProperties->setMimeType('text/x-sql');
  96. if ($hideSql) {
  97. return $exportPluginProperties;
  98. }
  99. $exportPluginProperties->setOptionsText(__('Options'));
  100. // create the root group that will be the options field for
  101. // $exportPluginProperties
  102. // this will be shown as "Format specific options"
  103. $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
  104. // general options main group
  105. $generalOptions = new OptionsPropertyMainGroup('general_opts');
  106. // comments
  107. $subgroup = new OptionsPropertySubgroup('include_comments');
  108. $leaf = new BoolPropertyItem(
  109. 'include_comments',
  110. __(
  111. 'Display comments <i>(includes info such as export timestamp, PHP version, and server version)</i>'
  112. )
  113. );
  114. $subgroup->setSubgroupHeader($leaf);
  115. $leaf = new TextPropertyItem(
  116. 'header_comment',
  117. __('Additional custom header comment (\n splits lines):')
  118. );
  119. $subgroup->addProperty($leaf);
  120. $leaf = new BoolPropertyItem(
  121. 'dates',
  122. __(
  123. 'Include a timestamp of when databases were created, last updated, and last checked'
  124. )
  125. );
  126. $subgroup->addProperty($leaf);
  127. if (! empty($GLOBALS['cfgRelation']['relation'])) {
  128. $leaf = new BoolPropertyItem(
  129. 'relation',
  130. __('Display foreign key relationships')
  131. );
  132. $subgroup->addProperty($leaf);
  133. }
  134. if (! empty($GLOBALS['cfgRelation']['mimework'])) {
  135. $leaf = new BoolPropertyItem(
  136. 'mime',
  137. __('Display media types')
  138. );
  139. $subgroup->addProperty($leaf);
  140. }
  141. $generalOptions->addProperty($subgroup);
  142. // enclose in a transaction
  143. $leaf = new BoolPropertyItem(
  144. 'use_transaction',
  145. __('Enclose export in a transaction')
  146. );
  147. $leaf->setDoc(
  148. [
  149. 'programs',
  150. 'mysqldump',
  151. 'option_mysqldump_single-transaction',
  152. ]
  153. );
  154. $generalOptions->addProperty($leaf);
  155. // disable foreign key checks
  156. $leaf = new BoolPropertyItem(
  157. 'disable_fk',
  158. __('Disable foreign key checks')
  159. );
  160. $leaf->setDoc(
  161. [
  162. 'manual_MySQL_Database_Administration',
  163. 'server-system-variables',
  164. 'sysvar_foreign_key_checks',
  165. ]
  166. );
  167. $generalOptions->addProperty($leaf);
  168. // export views as tables
  169. $leaf = new BoolPropertyItem(
  170. 'views_as_tables',
  171. __('Export views as tables')
  172. );
  173. $generalOptions->addProperty($leaf);
  174. // export metadata
  175. $leaf = new BoolPropertyItem(
  176. 'metadata',
  177. __('Export metadata')
  178. );
  179. $generalOptions->addProperty($leaf);
  180. // compatibility maximization
  181. $compats = $dbi->getCompatibilities();
  182. if (count($compats) > 0) {
  183. $values = [];
  184. foreach ($compats as $val) {
  185. $values[$val] = $val;
  186. }
  187. $leaf = new SelectPropertyItem(
  188. 'compatibility',
  189. __(
  190. 'Database system or older MySQL server to maximize output compatibility with:'
  191. )
  192. );
  193. $leaf->setValues($values);
  194. $leaf->setDoc(
  195. [
  196. 'manual_MySQL_Database_Administration',
  197. 'Server_SQL_mode',
  198. ]
  199. );
  200. $generalOptions->addProperty($leaf);
  201. unset($values);
  202. }
  203. // what to dump (structure/data/both)
  204. $subgroup = new OptionsPropertySubgroup(
  205. 'dump_table',
  206. __('Dump table')
  207. );
  208. $leaf = new RadioPropertyItem('structure_or_data');
  209. $leaf->setValues(
  210. [
  211. 'structure' => __('structure'),
  212. 'data' => __('data'),
  213. 'structure_and_data' => __('structure and data'),
  214. ]
  215. );
  216. $subgroup->setSubgroupHeader($leaf);
  217. $generalOptions->addProperty($subgroup);
  218. // add the main group to the root group
  219. $exportSpecificOptions->addProperty($generalOptions);
  220. // structure options main group
  221. if (! $hideStructure) {
  222. $structureOptions = new OptionsPropertyMainGroup(
  223. 'structure',
  224. __('Object creation options')
  225. );
  226. $structureOptions->setForce('data');
  227. // begin SQL Statements
  228. $subgroup = new OptionsPropertySubgroup();
  229. $leaf = new MessageOnlyPropertyItem(
  230. 'add_statements',
  231. __('Add statements:')
  232. );
  233. $subgroup->setSubgroupHeader($leaf);
  234. // server export options
  235. if ($plugin_param['export_type'] === 'server') {
  236. $leaf = new BoolPropertyItem(
  237. 'drop_database',
  238. sprintf(__('Add %s statement'), '<code>DROP DATABASE IF EXISTS</code>')
  239. );
  240. $subgroup->addProperty($leaf);
  241. }
  242. if ($plugin_param['export_type'] === 'database') {
  243. $createClause = '<code>CREATE DATABASE / USE</code>';
  244. $leaf = new BoolPropertyItem(
  245. 'create_database',
  246. sprintf(__('Add %s statement'), $createClause)
  247. );
  248. $subgroup->addProperty($leaf);
  249. }
  250. if ($plugin_param['export_type'] === 'table') {
  251. $dropClause = $dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->isView()
  252. ? '<code>DROP VIEW</code>'
  253. : '<code>DROP TABLE</code>';
  254. } else {
  255. $dropClause = '<code>DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT</code>';
  256. }
  257. $dropClause .= '<code> / TRIGGER</code>';
  258. $leaf = new BoolPropertyItem(
  259. 'drop_table',
  260. sprintf(__('Add %s statement'), $dropClause)
  261. );
  262. $subgroup->addProperty($leaf);
  263. $subgroupCreateTable = new OptionsPropertySubgroup();
  264. // Add table structure option
  265. $leaf = new BoolPropertyItem(
  266. 'create_table',
  267. sprintf(__('Add %s statement'), '<code>CREATE TABLE</code>')
  268. );
  269. $subgroupCreateTable->setSubgroupHeader($leaf);
  270. $leaf = new BoolPropertyItem(
  271. 'if_not_exists',
  272. '<code>IF NOT EXISTS</code> ' . __(
  273. '(less efficient as indexes will be generated during table creation)'
  274. )
  275. );
  276. $subgroupCreateTable->addProperty($leaf);
  277. $leaf = new BoolPropertyItem(
  278. 'auto_increment',
  279. sprintf(__('%s value'), '<code>AUTO_INCREMENT</code>')
  280. );
  281. $subgroupCreateTable->addProperty($leaf);
  282. $subgroup->addProperty($subgroupCreateTable);
  283. // Add view option
  284. $subgroupCreateView = new OptionsPropertySubgroup();
  285. $leaf = new BoolPropertyItem(
  286. 'create_view',
  287. sprintf(__('Add %s statement'), '<code>CREATE VIEW</code>')
  288. );
  289. $subgroupCreateView->setSubgroupHeader($leaf);
  290. $leaf = new BoolPropertyItem(
  291. 'simple_view_export',
  292. /* l10n: Allow simplifying exported view syntax to only "CREATE VIEW" */
  293. __('Use simple view export')
  294. );
  295. $subgroupCreateView->addProperty($leaf);
  296. $leaf = new BoolPropertyItem(
  297. 'view_current_user',
  298. __('Exclude definition of current user')
  299. );
  300. $subgroupCreateView->addProperty($leaf);
  301. $leaf = new BoolPropertyItem(
  302. 'or_replace_view',
  303. sprintf(__('%s view'), '<code>OR REPLACE</code>')
  304. );
  305. $subgroupCreateView->addProperty($leaf);
  306. $subgroup->addProperty($subgroupCreateView);
  307. $leaf = new BoolPropertyItem(
  308. 'procedure_function',
  309. sprintf(
  310. __('Add %s statement'),
  311. '<code>CREATE PROCEDURE / FUNCTION / EVENT</code>'
  312. )
  313. );
  314. $subgroup->addProperty($leaf);
  315. // Add triggers option
  316. $leaf = new BoolPropertyItem(
  317. 'create_trigger',
  318. sprintf(__('Add %s statement'), '<code>CREATE TRIGGER</code>')
  319. );
  320. $subgroup->addProperty($leaf);
  321. $structureOptions->addProperty($subgroup);
  322. $leaf = new BoolPropertyItem(
  323. 'backquotes',
  324. __(
  325. 'Enclose table and column names with backquotes '
  326. . '<i>(Protects column and table names formed with'
  327. . ' special characters or keywords)</i>'
  328. )
  329. );
  330. $structureOptions->addProperty($leaf);
  331. // add the main group to the root group
  332. $exportSpecificOptions->addProperty($structureOptions);
  333. }
  334. // begin Data options
  335. $dataOptions = new OptionsPropertyMainGroup(
  336. 'data',
  337. __('Data creation options')
  338. );
  339. $dataOptions->setForce('structure');
  340. $leaf = new BoolPropertyItem(
  341. 'truncate',
  342. __('Truncate table before insert')
  343. );
  344. $dataOptions->addProperty($leaf);
  345. // begin SQL Statements
  346. $subgroup = new OptionsPropertySubgroup();
  347. $leaf = new MessageOnlyPropertyItem(
  348. __('Instead of <code>INSERT</code> statements, use:')
  349. );
  350. $subgroup->setSubgroupHeader($leaf);
  351. $leaf = new BoolPropertyItem(
  352. 'delayed',
  353. __('<code>INSERT DELAYED</code> statements')
  354. );
  355. $leaf->setDoc(
  356. [
  357. 'manual_MySQL_Database_Administration',
  358. 'insert_delayed',
  359. ]
  360. );
  361. $subgroup->addProperty($leaf);
  362. $leaf = new BoolPropertyItem(
  363. 'ignore',
  364. __('<code>INSERT IGNORE</code> statements')
  365. );
  366. $leaf->setDoc(
  367. [
  368. 'manual_MySQL_Database_Administration',
  369. 'insert',
  370. ]
  371. );
  372. $subgroup->addProperty($leaf);
  373. $dataOptions->addProperty($subgroup);
  374. // Function to use when dumping dat
  375. $leaf = new SelectPropertyItem(
  376. 'type',
  377. __('Function to use when dumping data:')
  378. );
  379. $leaf->setValues(
  380. [
  381. 'INSERT' => 'INSERT',
  382. 'UPDATE' => 'UPDATE',
  383. 'REPLACE' => 'REPLACE',
  384. ]
  385. );
  386. $dataOptions->addProperty($leaf);
  387. /* Syntax to use when inserting data */
  388. $subgroup = new OptionsPropertySubgroup();
  389. $leaf = new MessageOnlyPropertyItem(
  390. null,
  391. __('Syntax to use when inserting data:')
  392. );
  393. $subgroup->setSubgroupHeader($leaf);
  394. $leaf = new RadioPropertyItem(
  395. 'insert_syntax',
  396. __('<code>INSERT IGNORE</code> statements')
  397. );
  398. $leaf->setValues(
  399. [
  400. 'complete' => __(
  401. 'include column names in every <code>INSERT</code> statement'
  402. . ' <br> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO'
  403. . ' tbl_name (col_A,col_B,col_C) VALUES (1,2,3)</code>'
  404. ),
  405. 'extended' => __(
  406. 'insert multiple rows in every <code>INSERT</code> statement'
  407. . '<br> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO'
  408. . ' tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)</code>'
  409. ),
  410. 'both' => __(
  411. 'both of the above<br> &nbsp; &nbsp; &nbsp; Example:'
  412. . ' <code>INSERT INTO tbl_name (col_A,col_B,col_C) VALUES'
  413. . ' (1,2,3), (4,5,6), (7,8,9)</code>'
  414. ),
  415. 'none' => __(
  416. 'neither of the above<br> &nbsp; &nbsp; &nbsp; Example:'
  417. . ' <code>INSERT INTO tbl_name VALUES (1,2,3)</code>'
  418. ),
  419. ]
  420. );
  421. $subgroup->addProperty($leaf);
  422. $dataOptions->addProperty($subgroup);
  423. // Max length of query
  424. $leaf = new NumberPropertyItem(
  425. 'max_query_size',
  426. __('Maximal length of created query')
  427. );
  428. $dataOptions->addProperty($leaf);
  429. // Dump binary columns in hexadecimal
  430. $leaf = new BoolPropertyItem(
  431. 'hex_for_binary',
  432. __(
  433. 'Dump binary columns in hexadecimal notation <i>(for example, "abc" becomes 0x616263)</i>'
  434. )
  435. );
  436. $dataOptions->addProperty($leaf);
  437. // Dump time in UTC
  438. $leaf = new BoolPropertyItem(
  439. 'utc_time',
  440. __(
  441. 'Dump TIMESTAMP columns in UTC <i>(enables TIMESTAMP columns'
  442. . ' to be dumped and reloaded between servers in different'
  443. . ' time zones)</i>'
  444. )
  445. );
  446. $dataOptions->addProperty($leaf);
  447. // add the main group to the root group
  448. $exportSpecificOptions->addProperty($dataOptions);
  449. // set the options for the export plugin property item
  450. $exportPluginProperties->setOptions($exportSpecificOptions);
  451. return $exportPluginProperties;
  452. }
  453. /**
  454. * Generates SQL for routines export
  455. *
  456. * @param string $db Database
  457. * @param array $aliases Aliases of db/table/columns
  458. * @param string $type Type of exported routine
  459. * @param string $name Verbose name of exported routine
  460. * @param array $routines List of routines to export
  461. * @param string $delimiter Delimiter to use in SQL
  462. *
  463. * @return string SQL query
  464. */
  465. protected function exportRoutineSQL(
  466. $db,
  467. array $aliases,
  468. $type,
  469. $name,
  470. array $routines,
  471. $delimiter
  472. ) {
  473. global $crlf, $dbi;
  474. $text = $this->exportComment()
  475. . $this->exportComment($name)
  476. . $this->exportComment();
  477. $usedAlias = false;
  478. $procQuery = '';
  479. foreach ($routines as $routine) {
  480. if (! empty($GLOBALS['sql_drop_table'])) {
  481. $procQuery .= 'DROP ' . $type . ' IF EXISTS '
  482. . Util::backquote($routine)
  483. . $delimiter . $crlf;
  484. }
  485. $createQuery = $this->replaceWithAliases(
  486. $dbi->getDefinition($db, $type, $routine),
  487. $aliases,
  488. $db,
  489. '',
  490. $flag
  491. );
  492. // One warning per database
  493. if ($flag) {
  494. $usedAlias = true;
  495. }
  496. $procQuery .= $createQuery . $delimiter . $crlf . $crlf;
  497. }
  498. if ($usedAlias) {
  499. $text .= $this->exportComment(
  500. __('It appears your database uses routines;')
  501. )
  502. . $this->exportComment(
  503. __('alias export may not work reliably in all cases.')
  504. )
  505. . $this->exportComment();
  506. }
  507. $text .= $procQuery;
  508. return $text;
  509. }
  510. /**
  511. * Exports routines (procedures and functions)
  512. *
  513. * @param string $db Database
  514. * @param array $aliases Aliases of db/table/columns
  515. */
  516. public function exportRoutines($db, array $aliases = []): bool
  517. {
  518. global $crlf, $dbi;
  519. $dbAlias = $db;
  520. $this->initAlias($aliases, $dbAlias);
  521. $text = '';
  522. $delimiter = '$$';
  523. $procedureNames = $dbi->getProceduresOrFunctions($db, 'PROCEDURE');
  524. $functionNames = $dbi->getProceduresOrFunctions($db, 'FUNCTION');
  525. if ($procedureNames || $functionNames) {
  526. $text .= $crlf
  527. . 'DELIMITER ' . $delimiter . $crlf;
  528. if ($procedureNames) {
  529. $text .= $this->exportRoutineSQL(
  530. $db,
  531. $aliases,
  532. 'PROCEDURE',
  533. __('Procedures'),
  534. $procedureNames,
  535. $delimiter
  536. );
  537. }
  538. if ($functionNames) {
  539. $text .= $this->exportRoutineSQL(
  540. $db,
  541. $aliases,
  542. 'FUNCTION',
  543. __('Functions'),
  544. $functionNames,
  545. $delimiter
  546. );
  547. }
  548. $text .= 'DELIMITER ;' . $crlf;
  549. }
  550. if (! empty($text)) {
  551. return $this->export->outputHandler($text);
  552. }
  553. return false;
  554. }
  555. /**
  556. * Possibly outputs comment
  557. *
  558. * @param string $text Text of comment
  559. *
  560. * @return string The formatted comment
  561. */
  562. private function exportComment($text = '')
  563. {
  564. if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
  565. // see https://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
  566. if (empty($text)) {
  567. return '--' . $GLOBALS['crlf'];
  568. }
  569. $lines = preg_split("/\\r\\n|\\r|\\n/", $text);
  570. if ($lines === false) {
  571. return '--' . $GLOBALS['crlf'];
  572. }
  573. $result = [];
  574. foreach ($lines as $line) {
  575. $result[] = '-- ' . $line . $GLOBALS['crlf'];
  576. }
  577. return implode('', $result);
  578. }
  579. return '';
  580. }
  581. /**
  582. * Possibly outputs CRLF
  583. *
  584. * @return string crlf or nothing
  585. */
  586. private function possibleCRLF()
  587. {
  588. if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
  589. return $GLOBALS['crlf'];
  590. }
  591. return '';
  592. }
  593. /**
  594. * Outputs export footer
  595. */
  596. public function exportFooter(): bool
  597. {
  598. global $crlf, $dbi;
  599. $foot = '';
  600. if (isset($GLOBALS['sql_disable_fk'])) {
  601. $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
  602. }
  603. if (isset($GLOBALS['sql_use_transaction'])) {
  604. $foot .= 'COMMIT;' . $crlf;
  605. }
  606. // restore connection settings
  607. if ($this->sentCharset) {
  608. $foot .= $crlf
  609. . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;'
  610. . $crlf
  611. . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;'
  612. . $crlf
  613. . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;'
  614. . $crlf;
  615. $this->sentCharset = false;
  616. }
  617. /* Restore timezone */
  618. if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
  619. $dbi->query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
  620. }
  621. return $this->export->outputHandler($foot);
  622. }
  623. /**
  624. * Outputs export header. It is the first method to be called, so all
  625. * the required variables are initialized here.
  626. */
  627. public function exportHeader(): bool
  628. {
  629. global $crlf, $cfg, $dbi;
  630. if (isset($GLOBALS['sql_compatibility'])) {
  631. $tmpCompat = $GLOBALS['sql_compatibility'];
  632. if ($tmpCompat === 'NONE') {
  633. $tmpCompat = '';
  634. }
  635. $dbi->tryQuery('SET SQL_MODE="' . $tmpCompat . '"');
  636. unset($tmpCompat);
  637. }
  638. $head = $this->exportComment('phpMyAdmin SQL Dump')
  639. . $this->exportComment('version ' . Version::VERSION)
  640. . $this->exportComment('https://www.phpmyadmin.net/')
  641. . $this->exportComment();
  642. $hostString = __('Host:') . ' ' . $cfg['Server']['host'];
  643. if (! empty($cfg['Server']['port'])) {
  644. $hostString .= ':' . $cfg['Server']['port'];
  645. }
  646. $head .= $this->exportComment($hostString);
  647. $head .= $this->exportComment(
  648. __('Generation Time:') . ' '
  649. . Util::localisedDate()
  650. )
  651. . $this->exportComment(
  652. __('Server version:') . ' ' . $dbi->getVersionString()
  653. )
  654. . $this->exportComment(__('PHP Version:') . ' ' . PHP_VERSION)
  655. . $this->possibleCRLF();
  656. if (isset($GLOBALS['sql_header_comment']) && ! empty($GLOBALS['sql_header_comment'])) {
  657. // '\n' is not a newline (like "\n" would be), it's the characters
  658. // backslash and n, as explained on the export interface
  659. $lines = explode('\n', $GLOBALS['sql_header_comment']);
  660. $head .= $this->exportComment();
  661. foreach ($lines as $oneLine) {
  662. $head .= $this->exportComment($oneLine);
  663. }
  664. $head .= $this->exportComment();
  665. }
  666. if (isset($GLOBALS['sql_disable_fk'])) {
  667. $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
  668. }
  669. // We want exported AUTO_INCREMENT columns to have still same value,
  670. // do this only for recent MySQL exports
  671. if (! isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] === 'NONE') {
  672. $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf;
  673. }
  674. if (isset($GLOBALS['sql_use_transaction'])) {
  675. $head .= 'START TRANSACTION;' . $crlf;
  676. }
  677. /* Change timezone if we should export timestamps in UTC */
  678. if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
  679. $head .= 'SET time_zone = "+00:00";' . $crlf;
  680. $GLOBALS['old_tz'] = $dbi
  681. ->fetchValue('SELECT @@session.time_zone');
  682. $dbi->query('SET time_zone = "+00:00"');
  683. }
  684. $head .= $this->possibleCRLF();
  685. if (! empty($GLOBALS['asfile'])) {
  686. // we are saving as file, therefore we provide charset information
  687. // so that a utility like the mysql client can interpret
  688. // the file correctly
  689. if (isset($GLOBALS['charset'], Charsets::$mysqlCharsetMap[$GLOBALS['charset']])) {
  690. // we got a charset from the export dialog
  691. $setNames = Charsets::$mysqlCharsetMap[$GLOBALS['charset']];
  692. } else {
  693. // by default we use the connection charset
  694. $setNames = Charsets::$mysqlCharsetMap['utf-8'];
  695. }
  696. if ($setNames === 'utf8' && $dbi->getVersion() > 50503) {
  697. $setNames = 'utf8mb4';
  698. }
  699. $head .= $crlf
  700. . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT='
  701. . '@@CHARACTER_SET_CLIENT */;' . $crlf
  702. . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS='
  703. . '@@CHARACTER_SET_RESULTS */;' . $crlf
  704. . '/*!40101 SET @OLD_COLLATION_CONNECTION='
  705. . '@@COLLATION_CONNECTION */;' . $crlf
  706. . '/*!40101 SET NAMES ' . $setNames . ' */;' . $crlf . $crlf;
  707. $this->sentCharset = true;
  708. }
  709. return $this->export->outputHandler($head);
  710. }
  711. /**
  712. * Outputs CREATE DATABASE statement
  713. *
  714. * @param string $db Database name
  715. * @param string $exportType 'server', 'database', 'table'
  716. * @param string $dbAlias Aliases of db
  717. */
  718. public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
  719. {
  720. global $crlf, $dbi;
  721. if (empty($dbAlias)) {
  722. $dbAlias = $db;
  723. }
  724. if (isset($GLOBALS['sql_compatibility'])) {
  725. $compat = $GLOBALS['sql_compatibility'];
  726. } else {
  727. $compat = 'NONE';
  728. }
  729. if (isset($GLOBALS['sql_drop_database'])) {
  730. if (
  731. ! $this->export->outputHandler(
  732. 'DROP DATABASE IF EXISTS '
  733. . Util::backquoteCompat(
  734. $dbAlias,
  735. $compat,
  736. isset($GLOBALS['sql_backquotes'])
  737. )
  738. . ';' . $crlf
  739. )
  740. ) {
  741. return false;
  742. }
  743. }
  744. if ($exportType === 'database' && ! isset($GLOBALS['sql_create_database'])) {
  745. return true;
  746. }
  747. $createQuery = 'CREATE DATABASE IF NOT EXISTS '
  748. . Util::backquoteCompat($dbAlias, $compat, isset($GLOBALS['sql_backquotes']));
  749. $collation = $dbi->getDbCollation($db);
  750. if (mb_strpos($collation, '_')) {
  751. $createQuery .= ' DEFAULT CHARACTER SET '
  752. . mb_substr(
  753. $collation,
  754. 0,
  755. (int) mb_strpos($collation, '_')
  756. )
  757. . ' COLLATE ' . $collation;
  758. } else {
  759. $createQuery .= ' DEFAULT CHARACTER SET ' . $collation;
  760. }
  761. $createQuery .= ';' . $crlf;
  762. if (! $this->export->outputHandler($createQuery)) {
  763. return false;
  764. }
  765. return $this->exportUseStatement($dbAlias, $compat);
  766. }
  767. /**
  768. * Outputs USE statement
  769. *
  770. * @param string $db db to use
  771. * @param string $compat sql compatibility
  772. */
  773. private function exportUseStatement($db, $compat): bool
  774. {
  775. global $crlf;
  776. if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'NONE') {
  777. $result = $this->export->outputHandler(
  778. 'USE '
  779. . Util::backquoteCompat(
  780. $db,
  781. $compat,
  782. isset($GLOBALS['sql_backquotes'])
  783. )
  784. . ';' . $crlf
  785. );
  786. } else {
  787. $result = $this->export->outputHandler('USE ' . $db . ';' . $crlf);
  788. }
  789. return $result;
  790. }
  791. /**
  792. * Outputs database header
  793. *
  794. * @param string $db Database name
  795. * @param string $dbAlias Alias of db
  796. */
  797. public function exportDBHeader($db, $dbAlias = ''): bool
  798. {
  799. if (empty($dbAlias)) {
  800. $dbAlias = $db;
  801. }
  802. if (isset($GLOBALS['sql_compatibility'])) {
  803. $compat = $GLOBALS['sql_compatibility'];
  804. } else {
  805. $compat = 'NONE';
  806. }
  807. $head = $this->exportComment()
  808. . $this->exportComment(
  809. __('Database:') . ' '
  810. . Util::backquoteCompat(
  811. $dbAlias,
  812. $compat,
  813. isset($GLOBALS['sql_backquotes'])
  814. )
  815. )
  816. . $this->exportComment();
  817. return $this->export->outputHandler($head);
  818. }
  819. /**
  820. * Outputs database footer
  821. *
  822. * @param string $db Database name
  823. */
  824. public function exportDBFooter($db): bool
  825. {
  826. global $crlf;
  827. $result = true;
  828. //add indexes to the sql dump file
  829. if (isset($GLOBALS['sql_indexes'])) {
  830. $result = $this->export->outputHandler($GLOBALS['sql_indexes']);
  831. unset($GLOBALS['sql_indexes']);
  832. }
  833. //add auto increments to the sql dump file
  834. if (isset($GLOBALS['sql_auto_increments'])) {
  835. $result = $this->export->outputHandler($GLOBALS['sql_auto_increments']);
  836. unset($GLOBALS['sql_auto_increments']);
  837. }
  838. //add constraints to the sql dump file
  839. if (isset($GLOBALS['sql_constraints'])) {
  840. $result = $this->export->outputHandler($GLOBALS['sql_constraints']);
  841. unset($GLOBALS['sql_constraints']);
  842. }
  843. return $result;
  844. }
  845. /**
  846. * Exports events
  847. *
  848. * @param string $db Database
  849. */
  850. public function exportEvents($db): bool
  851. {
  852. global $crlf, $dbi;
  853. $text = '';
  854. $delimiter = '$$';
  855. $eventNames = $dbi->fetchResult(
  856. 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE'
  857. . " EVENT_SCHEMA= '" . $dbi->escapeString($db)
  858. . "';"
  859. );
  860. if ($eventNames) {
  861. $text .= $crlf
  862. . 'DELIMITER ' . $delimiter . $crlf;
  863. $text .= $this->exportComment()
  864. . $this->exportComment(__('Events'))
  865. . $this->exportComment();
  866. foreach ($eventNames as $eventName) {
  867. if (! empty($GLOBALS['sql_drop_table'])) {
  868. $text .= 'DROP EVENT IF EXISTS '
  869. . Util::backquote($eventName)
  870. . $delimiter . $crlf;
  871. }
  872. $text .= $dbi->getDefinition($db, 'EVENT', $eventName)
  873. . $delimiter . $crlf . $crlf;
  874. }
  875. $text .= 'DELIMITER ;' . $crlf;
  876. }
  877. if (! empty($text)) {
  878. return $this->export->outputHandler($text);
  879. }
  880. return false;
  881. }
  882. /**
  883. * Exports metadata from Configuration Storage
  884. *
  885. * @param string $db database being exported
  886. * @param string|array $tables table(s) being exported
  887. * @param array $metadataTypes types of metadata to export
  888. */
  889. public function exportMetadata(
  890. $db,
  891. $tables,
  892. array $metadataTypes
  893. ): bool {
  894. $cfgRelation = $this->relation->getRelationsParam();
  895. if (! isset($cfgRelation['db'])) {
  896. return true;
  897. }
  898. $comment = $this->possibleCRLF()
  899. . $this->possibleCRLF()
  900. . $this->exportComment()
  901. . $this->exportComment(__('Metadata'))
  902. . $this->exportComment();
  903. if (! $this->export->outputHandler($comment)) {
  904. return false;
  905. }
  906. if (! $this->exportUseStatement($cfgRelation['db'], $GLOBALS['sql_compatibility'])) {
  907. return false;
  908. }
  909. $r = 1;
  910. if (is_array($tables)) {
  911. // export metadata for each table
  912. foreach ($tables as $table) {
  913. $r &= (int) $this->exportConfigurationMetadata($db, $table, $metadataTypes);
  914. }
  915. // export metadata for the database
  916. $r &= (int) $this->exportConfigurationMetadata($db, null, $metadataTypes);
  917. } else {
  918. // export metadata for single table
  919. $r &= (int) $this->exportConfigurationMetadata($db, $tables, $metadataTypes);
  920. }
  921. return (bool) $r;
  922. }
  923. /**
  924. * Exports metadata from Configuration Storage
  925. *
  926. * @param string $db database being exported
  927. * @param string|null $table table being exported
  928. * @param array $metadataTypes types of metadata to export
  929. */
  930. private function exportConfigurationMetadata(
  931. $db,
  932. $table,
  933. array $metadataTypes
  934. ): bool {
  935. global $dbi;
  936. $cfgRelation = $this->relation->getRelationsParam();
  937. if (isset($table)) {
  938. $types = [
  939. 'column_info' => 'db_name',
  940. 'table_uiprefs' => 'db_name',
  941. 'tracking' => 'db_name',
  942. ];
  943. } else {
  944. $types = [
  945. 'bookmark' => 'dbase',
  946. 'relation' => 'master_db',
  947. 'pdf_pages' => 'db_name',
  948. 'savedsearches' => 'db_name',
  949. 'central_columns' => 'db_name',
  950. ];
  951. }
  952. $aliases = [];
  953. $comment = $this->possibleCRLF()
  954. . $this->exportComment();
  955. if (isset($table)) {
  956. $comment .= $this->exportComment(
  957. sprintf(
  958. __('Metadata for table %s'),
  959. $table
  960. )
  961. );
  962. } else {
  963. $comment .= $this->exportComment(
  964. sprintf(
  965. __('Metadata for database %s'),
  966. $db
  967. )
  968. );
  969. }
  970. $comment .= $this->exportComment();
  971. if (! $this->export->outputHandler($comment)) {
  972. return false;
  973. }
  974. foreach ($types as $type => $dbNameColumn) {
  975. if (! in_array($type, $metadataTypes) || ! isset($cfgRelation[$type])) {
  976. continue;
  977. }
  978. // special case, designer pages and their coordinates
  979. if ($type === 'pdf_pages') {
  980. $sqlQuery = 'SELECT `page_nr`, `page_descr` FROM '
  981. . Util::backquote($cfgRelation['db'])
  982. . '.' . Util::backquote($cfgRelation[$type])
  983. . ' WHERE ' . Util::backquote($dbNameColumn)
  984. . " = '" . $dbi->escapeString($db) . "'";
  985. $result = $dbi->fetchResult($sqlQuery, 'page_nr', 'page_descr');
  986. foreach ($result as $page => $name) {
  987. // insert row for pdf_page
  988. $sqlQueryRow = 'SELECT `db_name`, `page_descr` FROM '
  989. . Util::backquote($cfgRelation['db'])
  990. . '.' . Util::backquote($cfgRelation[$type])
  991. . ' WHERE ' . Util::backquote($dbNameColumn)
  992. . " = '" . $dbi->escapeString($db) . "'"
  993. . " AND `page_nr` = '" . intval($page) . "'";
  994. if (
  995. ! $this->exportData(
  996. $cfgRelation['db'],
  997. $cfgRelation[$type],
  998. $GLOBALS['crlf'],
  999. '',
  1000. $sqlQueryRow,
  1001. $aliases
  1002. )
  1003. ) {
  1004. return false;
  1005. }
  1006. $lastPage = $GLOBALS['crlf']
  1007. . 'SET @LAST_PAGE = LAST_INSERT_ID();'
  1008. . $GLOBALS['crlf'];
  1009. if (! $this->export->outputHandler($lastPage)) {
  1010. return false;
  1011. }
  1012. $sqlQueryCoords = 'SELECT `db_name`, `table_name`, '
  1013. . "'@LAST_PAGE' AS `pdf_page_number`, `x`, `y` FROM "
  1014. . Util::backquote($cfgRelation['db'])
  1015. . '.' . Util::backquote($cfgRelation['table_coords'])
  1016. . " WHERE `pdf_page_number` = '" . $page . "'";
  1017. $GLOBALS['exporting_metadata'] = true;
  1018. if (
  1019. ! $this->exportData(
  1020. $cfgRelation['db'],
  1021. $cfgRelation['table_coords'],
  1022. $GLOBALS['crlf'],
  1023. '',
  1024. $sqlQueryCoords,
  1025. $aliases
  1026. )
  1027. ) {
  1028. $GLOBALS['exporting_metadata'] = false;
  1029. return false;
  1030. }
  1031. $GLOBALS['exporting_metadata'] = false;
  1032. }
  1033. continue;
  1034. }
  1035. // remove auto_incrementing id field for some tables
  1036. if ($type === 'bookmark') {
  1037. $sqlQuery = 'SELECT `dbase`, `user`, `label`, `query` FROM ';
  1038. } elseif ($type === 'column_info') {
  1039. $sqlQuery = 'SELECT `db_name`, `table_name`, `column_name`,'
  1040. . ' `comment`, `mimetype`, `transformation`,'
  1041. . ' `transformation_options`, `input_transformation`,'
  1042. . ' `input_transformation_options` FROM';
  1043. } elseif ($type === 'savedsearches') {
  1044. $sqlQuery = 'SELECT `username`, `db_name`, `search_name`, `search_data` FROM';
  1045. } else {
  1046. $sqlQuery = 'SELECT * FROM ';
  1047. }
  1048. $sqlQuery .= Util::backquote($cfgRelation['db'])
  1049. . '.' . Util::backquote($cfgRelation[$type])
  1050. . ' WHERE ' . Util::backquote($dbNameColumn)
  1051. . " = '" . $dbi->escapeString($db) . "'";
  1052. if (isset($table)) {
  1053. $sqlQuery .= " AND `table_name` = '"
  1054. . $dbi->escapeString($table) . "'";
  1055. }
  1056. if (
  1057. ! $this->exportData(
  1058. $cfgRelation['db'],
  1059. $cfgRelation[$type],
  1060. $GLOBALS['crlf'],
  1061. '',
  1062. $sqlQuery,
  1063. $aliases
  1064. )
  1065. ) {
  1066. return false;
  1067. }
  1068. }
  1069. return true;
  1070. }
  1071. /**
  1072. * Returns a stand-in CREATE definition to resolve view dependencies
  1073. *
  1074. * @param string $db the database name
  1075. * @param string $view the view name
  1076. * @param string $crlf the end of line sequence
  1077. * @param array $aliases Aliases of db/table/columns
  1078. *
  1079. * @return string resulting definition
  1080. */
  1081. public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
  1082. {
  1083. global $dbi;
  1084. $dbAlias = $db;
  1085. $viewAlias = $view;
  1086. $this->initAlias($aliases, $dbAlias, $viewAlias);
  1087. $createQuery = '';
  1088. if (! empty($GLOBALS['sql_drop_table'])) {
  1089. $createQuery .= 'DROP VIEW IF EXISTS '
  1090. . Util::backquote($viewAlias)
  1091. . ';' . $crlf;
  1092. }
  1093. $createQuery .= 'CREATE TABLE ';
  1094. if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
  1095. $createQuery .= 'IF NOT EXISTS ';
  1096. }
  1097. $createQuery .= Util::backquote($viewAlias) . ' (' . $crlf;
  1098. $tmp = [];
  1099. $columns = $dbi->getColumnsFull($db, $view);
  1100. foreach ($columns as $columnName => $definition) {
  1101. $colAlias = $columnName;
  1102. if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
  1103. $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
  1104. }
  1105. $tmp[] = Util::backquote($colAlias) . ' ' .
  1106. $definition['Type'] . $crlf;
  1107. }
  1108. return $createQuery . implode(',', $tmp) . ');' . $crlf;
  1109. }
  1110. /**
  1111. * Returns CREATE definition that matches $view's structure
  1112. *
  1113. * @param string $db the database name
  1114. * @param string $view the view name
  1115. * @param string $crlf the end of line sequence
  1116. * @param bool $addSemicolon whether to add semicolon and end-of-line at
  1117. * the end
  1118. * @param array $aliases Aliases of db/table/columns
  1119. *
  1120. * @return string resulting schema
  1121. */
  1122. private function getTableDefForView(
  1123. $db,
  1124. $view,
  1125. $crlf,
  1126. $addSemicolon = true,
  1127. array $aliases = []
  1128. ) {
  1129. global $dbi;
  1130. $dbAlias = $db;
  1131. $viewAlias = $view;
  1132. $this->initAlias($aliases, $dbAlias, $viewAlias);
  1133. $createQuery = 'CREATE TABLE';
  1134. if (isset($GLOBALS['sql_if_not_exists'])) {
  1135. $createQuery .= ' IF NOT EXISTS ';
  1136. }
  1137. $createQuery .= Util::backquote($viewAlias) . '(' . $crlf;
  1138. $columns = $dbi->getColumns($db, $view, null, true);
  1139. $firstCol = true;
  1140. foreach ($columns as $column) {
  1141. $colAlias = $column['Field'];
  1142. if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
  1143. $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
  1144. }
  1145. $extractedColumnspec = Util::extractColumnSpec($column['Type']);
  1146. if (! $firstCol) {
  1147. $createQuery .= ',' . $crlf;
  1148. }
  1149. $createQuery .= ' ' . Util::backquote($colAlias);
  1150. $createQuery .= ' ' . $column['Type'];
  1151. if ($extractedColumnspec['can_contain_collation'] && ! empty($column['Collation'])) {
  1152. $createQuery .= ' COLLATE ' . $column['Collation'];
  1153. }
  1154. if ($column['Null'] === 'NO') {
  1155. $createQuery .= ' NOT NULL';
  1156. }
  1157. if (isset($column['Default'])) {
  1158. $createQuery .= " DEFAULT '"
  1159. . $dbi->escapeString($column['Default']) . "'";
  1160. } else {
  1161. if ($column['Null'] === 'YES') {
  1162. $createQuery .= ' DEFAULT NULL';
  1163. }
  1164. }
  1165. if (! empty($column['Comment'])) {
  1166. $createQuery .= " COMMENT '"
  1167. . $dbi->escapeString($column['Comment']) . "'";
  1168. }
  1169. $firstCol = false;
  1170. }
  1171. $createQuery .= $crlf . ')' . ($addSemicolon ? ';' : '') . $crlf;
  1172. if (isset($GLOBALS['sql_compatibility'])) {
  1173. $compat = $GLOBALS['sql_compatibility'];
  1174. } else {
  1175. $compat = 'NONE';
  1176. }
  1177. if ($compat === 'MSSQL') {
  1178. $createQuery = $this->makeCreateTableMSSQLCompatible($createQuery);
  1179. }
  1180. return $createQuery;
  1181. }
  1182. /**
  1183. * Returns $table's CREATE definition
  1184. *
  1185. * @param string $db the database name
  1186. * @param string $table the table name
  1187. * @param string $crlf the end of line sequence
  1188. * @param string $errorUrl the url to go back in case
  1189. * of error
  1190. * @param bool $showDates whether to include creation/
  1191. * update/check dates
  1192. * @param bool $addSemicolon whether to add semicolon and
  1193. * end-of-line at the end
  1194. * @param bool $view whether we're handling a view
  1195. * @param bool $updateIndexesIncrements whether we need to update
  1196. * two global variables
  1197. * @param array $aliases Aliases of db/table/columns
  1198. *
  1199. * @return string resulting schema
  1200. */
  1201. public function getTableDef(
  1202. $db,
  1203. $table,
  1204. $crlf,
  1205. $errorUrl,
  1206. $showDates = false,
  1207. $addSemicolon = true,
  1208. $view = false,
  1209. $updateIndexesIncrements = true,
  1210. array $aliases = []
  1211. ) {
  1212. global $sql_drop_table, $sql_backquotes, $sql_constraints,
  1213. $sql_constraints_query, $sql_indexes, $sql_indexes_query,
  1214. $sql_auto_increments, $sql_drop_foreign_keys, $dbi;
  1215. $dbAlias = $db;
  1216. $tableAlias = $table;
  1217. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1218. $schemaCreate = '';
  1219. $autoIncrement = '';
  1220. $newCrlf = $crlf;
  1221. if (isset($GLOBALS['sql_compatibility'])) {
  1222. $compat = $GLOBALS['sql_compatibility'];
  1223. } else {
  1224. $compat = 'NONE';
  1225. }
  1226. // need to use PhpMyAdmin\DatabaseInterface::QUERY_STORE
  1227. // with $dbi->numRows() in mysqli
  1228. $result = $dbi->tryQuery(
  1229. 'SHOW TABLE STATUS FROM ' . Util::backquote($db)
  1230. . ' WHERE Name = \'' . $dbi->escapeString((string) $table) . '\'',
  1231. DatabaseInterface::CONNECT_USER,
  1232. DatabaseInterface::QUERY_STORE
  1233. );
  1234. if ($result != false) {
  1235. if ($dbi->numRows($result) > 0) {
  1236. $tmpres = $dbi->fetchAssoc($result);
  1237. // Here we optionally add the AUTO_INCREMENT next value,
  1238. // but starting with MySQL 5.0.24, the clause is already included
  1239. // in SHOW CREATE TABLE so we'll remove it below
  1240. if (isset($GLOBALS['sql_auto_increment']) && ! empty($tmpres['Auto_increment'])) {
  1241. $autoIncrement .= ' AUTO_INCREMENT='
  1242. . $tmpres['Auto_increment'] . ' ';
  1243. }
  1244. if ($showDates && isset($tmpres['Create_time']) && ! empty($tmpres['Create_time'])) {
  1245. $schemaCreate .= $this->exportComment(
  1246. __('Creation:') . ' '
  1247. . Util::localisedDate(
  1248. strtotime($tmpres['Create_time'])
  1249. )
  1250. );
  1251. $newCrlf = $this->exportComment() . $crlf;
  1252. }
  1253. if ($showDates && isset($tmpres['Update_time']) && ! empty($tmpres['Update_time'])) {
  1254. $schemaCreate .= $this->exportComment(
  1255. __('Last update:') . ' '
  1256. . Util::localisedDate(
  1257. strtotime($tmpres['Update_time'])
  1258. )
  1259. );
  1260. $newCrlf = $this->exportComment() . $crlf;
  1261. }
  1262. if ($showDates && isset($tmpres['Check_time']) && ! empty($tmpres['Check_time'])) {
  1263. $schemaCreate .= $this->exportComment(
  1264. __('Last check:') . ' '
  1265. . Util::localisedDate(
  1266. strtotime($tmpres['Check_time'])
  1267. )
  1268. );
  1269. $newCrlf = $this->exportComment() . $crlf;
  1270. }
  1271. }
  1272. $dbi->freeResult($result);
  1273. }
  1274. $schemaCreate .= $newCrlf;
  1275. if (! empty($sql_drop_table) && $dbi->getTable($db, $table)->isView()) {
  1276. $schemaCreate .= 'DROP VIEW IF EXISTS '
  1277. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
  1278. . $crlf;
  1279. }
  1280. // no need to generate a DROP VIEW here, it was done earlier
  1281. if (! empty($sql_drop_table) && ! $dbi->getTable($db, $table)->isView()) {
  1282. $schemaCreate .= 'DROP TABLE IF EXISTS '
  1283. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
  1284. . $crlf;
  1285. }
  1286. // Complete table dump,
  1287. // Whether to quote table and column names or not
  1288. if ($sql_backquotes) {
  1289. $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 1');
  1290. } else {
  1291. $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 0');
  1292. }
  1293. // I don't see the reason why this unbuffered query could cause problems,
  1294. // because SHOW CREATE TABLE returns only one row, and we free the
  1295. // results below. Nonetheless, we got 2 user reports about this
  1296. // (see bug 1562533) so I removed the unbuffered mode.
  1297. // $result = $dbi->query('SHOW CREATE TABLE ' . backquote($db)
  1298. // . '.' . backquote($table), null, DatabaseInterface::QUERY_UNBUFFERED);
  1299. //
  1300. // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
  1301. // produce a displayable result for the default value of a BIT
  1302. // column, nor does the mysqldump command. See MySQL bug 35796
  1303. $dbi->tryQuery('USE ' . Util::backquote($db));
  1304. $result = $dbi->tryQuery(
  1305. 'SHOW CREATE TABLE ' . Util::backquote($db) . '.'
  1306. . Util::backquote($table)
  1307. );
  1308. // an error can happen, for example the table is crashed
  1309. $tmpError = $dbi->getError();
  1310. if ($tmpError) {
  1311. $message = sprintf(__('Error reading structure for table %s:'), $db . '.' . $table);
  1312. $message .= ' ' . $tmpError;
  1313. if (! defined('TESTSUITE')) {
  1314. trigger_error($message, E_USER_ERROR);
  1315. }
  1316. return $this->exportComment($message);
  1317. }
  1318. // Old mode is stored so it can be restored once exporting is done.
  1319. $oldMode = Context::$MODE;
  1320. $warning = '';
  1321. $row = null;
  1322. if ($result !== false) {
  1323. $row = $dbi->fetchRow($result);
  1324. }
  1325. if ($row) {
  1326. $createQuery = $row[1];
  1327. unset($row);
  1328. // Convert end of line chars to one that we want (note that MySQL
  1329. // doesn't return query it will accept in all cases)
  1330. if (mb_strpos($createQuery, "(\r\n ")) {
  1331. $createQuery = str_replace("\r\n", $crlf, $createQuery);
  1332. } elseif (mb_strpos($createQuery, "(\n ")) {
  1333. $createQuery = str_replace("\n", $crlf, $createQuery);
  1334. } elseif (mb_strpos($createQuery, "(\r ")) {
  1335. $createQuery = str_replace("\r", $crlf, $createQuery);
  1336. }
  1337. /*
  1338. * Drop database name from VIEW creation.
  1339. *
  1340. * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
  1341. * database name, but we don't want name to show up in CREATE VIEW
  1342. * statement.
  1343. */
  1344. if ($view) {
  1345. //TODO: use parser
  1346. $createQuery = preg_replace(
  1347. '/' . preg_quote(Util::backquote($db), '/') . '\./',
  1348. '',
  1349. $createQuery
  1350. );
  1351. $parser = new Parser($createQuery);
  1352. /**
  1353. * `CREATE TABLE` statement.
  1354. *
  1355. * @var CreateStatement
  1356. */
  1357. $statement = $parser->statements[0];
  1358. // exclude definition of current user
  1359. if (isset($GLOBALS['sql_view_current_user'])) {
  1360. $statement->options->remove('DEFINER');
  1361. }
  1362. if (isset($GLOBALS['sql_simple_view_export'])) {
  1363. $statement->options->remove('SQL SECURITY');
  1364. $statement->options->remove('INVOKER');
  1365. $statement->options->remove('ALGORITHM');
  1366. $statement->options->remove('DEFINER');
  1367. }
  1368. $createQuery = $statement->build();
  1369. // whether to replace existing view or not
  1370. if (isset($GLOBALS['sql_or_replace_view'])) {
  1371. $createQuery = preg_replace('/^CREATE/', 'CREATE OR REPLACE', $createQuery);
  1372. }
  1373. }
  1374. // Substitute aliases in `CREATE` query.
  1375. $createQuery = $this->replaceWithAliases($createQuery, $aliases, $db, $table, $flag);
  1376. // One warning per view.
  1377. if ($flag && $view) {
  1378. $warning = $this->exportComment()
  1379. . $this->exportComment(
  1380. __('It appears your database uses views;')
  1381. )
  1382. . $this->exportComment(
  1383. __('alias export may not work reliably in all cases.')
  1384. )
  1385. . $this->exportComment();
  1386. }
  1387. // Adding IF NOT EXISTS, if required.
  1388. if (isset($GLOBALS['sql_if_not_exists'])) {
  1389. $createQuery = (string) preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $createQuery);
  1390. }
  1391. // Making the query MSSQL compatible.
  1392. if ($compat === 'MSSQL') {
  1393. $createQuery = $this->makeCreateTableMSSQLCompatible($createQuery);
  1394. }
  1395. // Views have no constraints, indexes, etc. They do not require any
  1396. // analysis.
  1397. if (! $view) {
  1398. if (empty($sql_backquotes)) {
  1399. // Option "Enclose table and column names with backquotes"
  1400. // was checked.
  1401. Context::$MODE |= Context::SQL_MODE_NO_ENCLOSING_QUOTES;
  1402. }
  1403. // Using appropriate quotes.
  1404. if (($compat === 'MSSQL') || ($sql_backquotes === '"')) {
  1405. Context::$MODE |= Context::SQL_MODE_ANSI_QUOTES;
  1406. }
  1407. }
  1408. /**
  1409. * Parser used for analysis.
  1410. *
  1411. * @var Parser
  1412. */
  1413. $parser = new Parser($createQuery);
  1414. /**
  1415. * `CREATE TABLE` statement.
  1416. *
  1417. * @var CreateStatement
  1418. */
  1419. $statement = $parser->statements[0];
  1420. if (! empty($statement->entityOptions)) {
  1421. $engine = $statement->entityOptions->has('ENGINE');
  1422. } else {
  1423. $engine = '';
  1424. }
  1425. /* Avoid operation on ARCHIVE tables as those can not be altered */
  1426. if (
  1427. (! empty($statement->fields) && is_array($statement->fields))
  1428. && (empty($engine) || strtoupper($engine) !== 'ARCHIVE')
  1429. ) {
  1430. /**
  1431. * Fragments containing definition of each constraint.
  1432. *
  1433. * @var array
  1434. */
  1435. $constraints = [];
  1436. /**
  1437. * Fragments containing definition of each index.
  1438. *
  1439. * @var array
  1440. */
  1441. $indexes = [];
  1442. /**
  1443. * Fragments containing definition of each FULLTEXT index.
  1444. *
  1445. * @var array
  1446. */
  1447. $indexesFulltext = [];
  1448. /**
  1449. * Fragments containing definition of each foreign key that will
  1450. * be dropped.
  1451. *
  1452. * @var array
  1453. */
  1454. $dropped = [];
  1455. /**
  1456. * Fragment containing definition of the `AUTO_INCREMENT`.
  1457. *
  1458. * @var array
  1459. */
  1460. $autoIncrement = [];
  1461. // Scanning each field of the `CREATE` statement to fill the arrays
  1462. // above.
  1463. // If the field is used in any of the arrays above, it is removed
  1464. // from the original definition.
  1465. // Also, AUTO_INCREMENT attribute is removed.
  1466. /** @var CreateDefinition $field */
  1467. foreach ($statement->fields as $key => $field) {
  1468. if ($field->isConstraint) {
  1469. // Creating the parts that add constraints.
  1470. $constraints[] = $field::build($field);
  1471. unset($statement->fields[$key]);
  1472. } elseif (! empty($field->key)) {
  1473. // Creating the parts that add indexes (must not be
  1474. // constraints).
  1475. if ($field->key->type === 'FULLTEXT KEY') {
  1476. $indexesFulltext[] = $field::build($field);
  1477. unset($statement->fields[$key]);
  1478. } else {
  1479. if (empty($GLOBALS['sql_if_not_exists'])) {
  1480. $indexes[] = str_replace(
  1481. 'COMMENT=\'',
  1482. 'COMMENT \'',
  1483. $field::build($field)
  1484. );
  1485. unset($statement->fields[$key]);
  1486. }
  1487. }
  1488. }
  1489. // Creating the parts that drop foreign keys.
  1490. if (! empty($field->key)) {
  1491. if ($field->key->type === 'FOREIGN KEY') {
  1492. $dropped[] = 'FOREIGN KEY ' . Context::escape($field->name);
  1493. unset($statement->fields[$key]);
  1494. }
  1495. }
  1496. // Dropping AUTO_INCREMENT.
  1497. if (empty($field->options)) {
  1498. continue;
  1499. }
  1500. if (! $field->options->has('AUTO_INCREMENT') || ! empty($GLOBALS['sql_if_not_exists'])) {
  1501. continue;
  1502. }
  1503. $autoIncrement[] = $field::build($field);
  1504. $field->options->remove('AUTO_INCREMENT');
  1505. }
  1506. /**
  1507. * The header of the `ALTER` statement (`ALTER TABLE tbl`).
  1508. *
  1509. * @var string
  1510. */
  1511. $alterHeader = 'ALTER TABLE ' .
  1512. Util::backquoteCompat($tableAlias, $compat, $sql_backquotes);
  1513. /**
  1514. * The footer of the `ALTER` statement (usually ';')
  1515. *
  1516. * @var string
  1517. */
  1518. $alterFooter = ';' . $crlf;
  1519. // Generating constraints-related query.
  1520. if (! empty($constraints)) {
  1521. $sql_constraints_query = $alterHeader . $crlf . ' ADD '
  1522. . implode(',' . $crlf . ' ADD ', $constraints)
  1523. . $alterFooter;
  1524. $sql_constraints = $this->generateComment(
  1525. $crlf,
  1526. $sql_constraints,
  1527. __('Constraints for dumped tables'),
  1528. __('Constraints for table'),
  1529. $tableAlias,
  1530. $compat
  1531. ) . $sql_constraints_query;
  1532. }
  1533. // Generating indexes-related query.
  1534. $sql_indexes_query = '';
  1535. if (! empty($indexes)) {
  1536. $sql_indexes_query .= $alterHeader . $crlf . ' ADD '
  1537. . implode(',' . $crlf . ' ADD ', $indexes)
  1538. . $alterFooter;
  1539. }
  1540. if (! empty($indexesFulltext)) {
  1541. // InnoDB supports one FULLTEXT index creation at a time.
  1542. // So FULLTEXT indexes are created one-by-one after other
  1543. // indexes where created.
  1544. $sql_indexes_query .= $alterHeader .
  1545. ' ADD ' . implode($alterFooter . $alterHeader . ' ADD ', $indexesFulltext) . $alterFooter;
  1546. }
  1547. if (! empty($indexes) || ! empty($indexesFulltext)) {
  1548. $sql_indexes = $this->generateComment(
  1549. $crlf,
  1550. $sql_indexes,
  1551. __('Indexes for dumped tables'),
  1552. __('Indexes for table'),
  1553. $tableAlias,
  1554. $compat
  1555. ) . $sql_indexes_query;
  1556. }
  1557. // Generating drop foreign keys-related query.
  1558. if (! empty($dropped)) {
  1559. $sql_drop_foreign_keys = $alterHeader . $crlf . ' DROP '
  1560. . implode(',' . $crlf . ' DROP ', $dropped)
  1561. . $alterFooter;
  1562. }
  1563. // Generating auto-increment-related query.
  1564. if (! empty($autoIncrement) && $updateIndexesIncrements) {
  1565. $sqlAutoIncrementsQuery = $alterHeader . $crlf . ' MODIFY '
  1566. . implode(',' . $crlf . ' MODIFY ', $autoIncrement);
  1567. if (
  1568. isset($GLOBALS['sql_auto_increment'])
  1569. && ($statement->entityOptions->has('AUTO_INCREMENT') !== false)
  1570. ) {
  1571. if (
  1572. ! isset($GLOBALS['table_data'])
  1573. || (isset($GLOBALS['table_data'])
  1574. && in_array($table, $GLOBALS['table_data']))
  1575. ) {
  1576. $sqlAutoIncrementsQuery .= ', AUTO_INCREMENT='
  1577. . $statement->entityOptions->has('AUTO_INCREMENT');
  1578. }
  1579. }
  1580. $sqlAutoIncrementsQuery .= ';' . $crlf;
  1581. $sql_auto_increments = $this->generateComment(
  1582. $crlf,
  1583. $sql_auto_increments,
  1584. __('AUTO_INCREMENT for dumped tables'),
  1585. __('AUTO_INCREMENT for table'),
  1586. $tableAlias,
  1587. $compat
  1588. ) . $sqlAutoIncrementsQuery;
  1589. }
  1590. // Removing the `AUTO_INCREMENT` attribute from the `CREATE TABLE`
  1591. // too.
  1592. if (
  1593. ! empty($statement->entityOptions)
  1594. && (empty($GLOBALS['sql_if_not_exists'])
  1595. || empty($GLOBALS['sql_auto_increment']))
  1596. ) {
  1597. $statement->entityOptions->remove('AUTO_INCREMENT');
  1598. }
  1599. // Rebuilding the query.
  1600. $createQuery = $statement->build();
  1601. }
  1602. $schemaCreate .= $createQuery;
  1603. }
  1604. $dbi->freeResult($result);
  1605. // Restoring old mode.
  1606. Context::$MODE = $oldMode;
  1607. return $warning . $schemaCreate . ($addSemicolon ? ';' . $crlf : '');
  1608. }
  1609. /**
  1610. * Returns $table's comments, relations etc.
  1611. *
  1612. * @param string $db database name
  1613. * @param string $table table name
  1614. * @param string $crlf end of line sequence
  1615. * @param bool $doRelation whether to include relation comments
  1616. * @param bool $doMime whether to include mime comments
  1617. * @param array $aliases Aliases of db/table/columns
  1618. *
  1619. * @return string resulting comments
  1620. */
  1621. private function getTableComments(
  1622. $db,
  1623. $table,
  1624. $crlf,
  1625. $doRelation = false,
  1626. $doMime = false,
  1627. array $aliases = []
  1628. ) {
  1629. global $cfgRelation, $sql_backquotes;
  1630. $dbAlias = $db;
  1631. $tableAlias = $table;
  1632. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1633. $schemaCreate = '';
  1634. // Check if we can use Relations
  1635. [$resRel, $haveRel] = $this->relation->getRelationsAndStatus(
  1636. $doRelation && ! empty($cfgRelation['relation']),
  1637. $db,
  1638. $table
  1639. );
  1640. if ($doMime && $cfgRelation['mimework']) {
  1641. $mimeMap = $this->transformations->getMime($db, $table, true);
  1642. if ($mimeMap === null) {
  1643. unset($mimeMap);
  1644. }
  1645. }
  1646. if (isset($mimeMap) && count($mimeMap) > 0) {
  1647. $schemaCreate .= $this->possibleCRLF()
  1648. . $this->exportComment()
  1649. . $this->exportComment(
  1650. __('MEDIA TYPES FOR TABLE') . ' '
  1651. . Util::backquoteCompat($table, 'NONE', $sql_backquotes) . ':'
  1652. );
  1653. foreach ($mimeMap as $mimeField => $mime) {
  1654. $schemaCreate .= $this->exportComment(
  1655. ' '
  1656. . Util::backquoteCompat($mimeField, 'NONE', $sql_backquotes)
  1657. )
  1658. . $this->exportComment(
  1659. ' '
  1660. . Util::backquoteCompat(
  1661. $mime['mimetype'],
  1662. 'NONE',
  1663. $sql_backquotes
  1664. )
  1665. );
  1666. }
  1667. $schemaCreate .= $this->exportComment();
  1668. }
  1669. if ($haveRel) {
  1670. $schemaCreate .= $this->possibleCRLF()
  1671. . $this->exportComment()
  1672. . $this->exportComment(
  1673. __('RELATIONSHIPS FOR TABLE') . ' '
  1674. . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes)
  1675. . ':'
  1676. );
  1677. foreach ($resRel as $relField => $rel) {
  1678. if ($relField !== 'foreign_keys_data') {
  1679. $relFieldAlias = ! empty(
  1680. $aliases[$db]['tables'][$table]['columns'][$relField]
  1681. ) ? $aliases[$db]['tables'][$table]['columns'][$relField]
  1682. : $relField;
  1683. $schemaCreate .= $this->exportComment(
  1684. ' '
  1685. . Util::backquoteCompat(
  1686. $relFieldAlias,
  1687. 'NONE',
  1688. $sql_backquotes
  1689. )
  1690. )
  1691. . $this->exportComment(
  1692. ' '
  1693. . Util::backquoteCompat(
  1694. $rel['foreign_table'],
  1695. 'NONE',
  1696. $sql_backquotes
  1697. )
  1698. . ' -> '
  1699. . Util::backquoteCompat(
  1700. $rel['foreign_field'],
  1701. 'NONE',
  1702. $sql_backquotes
  1703. )
  1704. );
  1705. } else {
  1706. foreach ($rel as $oneKey) {
  1707. foreach ($oneKey['index_list'] as $index => $field) {
  1708. $relFieldAlias = ! empty(
  1709. $aliases[$db]['tables'][$table]['columns'][$field]
  1710. ) ? $aliases[$db]['tables'][$table]['columns'][$field]
  1711. : $field;
  1712. $schemaCreate .= $this->exportComment(
  1713. ' '
  1714. . Util::backquoteCompat(
  1715. $relFieldAlias,
  1716. 'NONE',
  1717. $sql_backquotes
  1718. )
  1719. )
  1720. . $this->exportComment(
  1721. ' '
  1722. . Util::backquoteCompat(
  1723. $oneKey['ref_table_name'],
  1724. 'NONE',
  1725. $sql_backquotes
  1726. )
  1727. . ' -> '
  1728. . Util::backquoteCompat(
  1729. $oneKey['ref_index_list'][$index],
  1730. 'NONE',
  1731. $sql_backquotes
  1732. )
  1733. );
  1734. }
  1735. }
  1736. }
  1737. }
  1738. $schemaCreate .= $this->exportComment();
  1739. }
  1740. return $schemaCreate;
  1741. }
  1742. /**
  1743. * Outputs a raw query
  1744. *
  1745. * @param string $errorUrl the url to go back in case of error
  1746. * @param string $sqlQuery the rawquery to output
  1747. * @param string $crlf the seperator for a file
  1748. */
  1749. public function exportRawQuery(string $errorUrl, string $sqlQuery, string $crlf): bool
  1750. {
  1751. return $this->export->outputHandler($sqlQuery);
  1752. }
  1753. /**
  1754. * Outputs table's structure
  1755. *
  1756. * @param string $db database name
  1757. * @param string $table table name
  1758. * @param string $crlf the end of line sequence
  1759. * @param string $errorUrl the url to go back in case of error
  1760. * @param string $exportMode 'create_table','triggers','create_view',
  1761. * 'stand_in'
  1762. * @param string $exportType 'server', 'database', 'table'
  1763. * @param bool $relation whether to include relation comments
  1764. * @param bool $comments whether to include the pmadb-style column
  1765. * comments as comments in the structure; this is
  1766. * deprecated but the parameter is left here
  1767. * because /export calls exportStructure()
  1768. * also for other export types which use this
  1769. * parameter
  1770. * @param bool $mime whether to include mime comments
  1771. * @param bool $dates whether to include creation/update/check dates
  1772. * @param array $aliases Aliases of db/table/columns
  1773. */
  1774. public function exportStructure(
  1775. $db,
  1776. $table,
  1777. $crlf,
  1778. $errorUrl,
  1779. $exportMode,
  1780. $exportType,
  1781. $relation = false,
  1782. $comments = false,
  1783. $mime = false,
  1784. $dates = false,
  1785. array $aliases = []
  1786. ): bool {
  1787. global $dbi;
  1788. $dbAlias = $db;
  1789. $tableAlias = $table;
  1790. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1791. if (isset($GLOBALS['sql_compatibility'])) {
  1792. $compat = $GLOBALS['sql_compatibility'];
  1793. } else {
  1794. $compat = 'NONE';
  1795. }
  1796. $formattedTableName = Util::backquoteCompat($tableAlias, $compat, isset($GLOBALS['sql_backquotes']));
  1797. $dump = $this->possibleCRLF()
  1798. . $this->exportComment(str_repeat('-', 56))
  1799. . $this->possibleCRLF()
  1800. . $this->exportComment();
  1801. switch ($exportMode) {
  1802. case 'create_table':
  1803. $dump .= $this->exportComment(
  1804. __('Table structure for table') . ' ' . $formattedTableName
  1805. );
  1806. $dump .= $this->exportComment();
  1807. $dump .= $this->getTableDef($db, $table, $crlf, $errorUrl, $dates, true, false, true, $aliases);
  1808. $dump .= $this->getTableComments($db, $table, $crlf, $relation, $mime, $aliases);
  1809. break;
  1810. case 'triggers':
  1811. $dump = '';
  1812. $delimiter = '$$';
  1813. $triggers = $dbi->getTriggers($db, $table, $delimiter);
  1814. if ($triggers) {
  1815. $dump .= $this->possibleCRLF()
  1816. . $this->exportComment()
  1817. . $this->exportComment(
  1818. __('Triggers') . ' ' . $formattedTableName
  1819. )
  1820. . $this->exportComment();
  1821. $usedAlias = false;
  1822. $triggerQuery = '';
  1823. foreach ($triggers as $trigger) {
  1824. if (! empty($GLOBALS['sql_drop_table'])) {
  1825. $triggerQuery .= $trigger['drop'] . ';' . $crlf;
  1826. }
  1827. $triggerQuery .= 'DELIMITER ' . $delimiter . $crlf;
  1828. $triggerQuery .= $this->replaceWithAliases($trigger['create'], $aliases, $db, $table, $flag);
  1829. if ($flag) {
  1830. $usedAlias = true;
  1831. }
  1832. $triggerQuery .= 'DELIMITER ;' . $crlf;
  1833. }
  1834. // One warning per table.
  1835. if ($usedAlias) {
  1836. $dump .= $this->exportComment(
  1837. __('It appears your table uses triggers;')
  1838. )
  1839. . $this->exportComment(
  1840. __('alias export may not work reliably in all cases.')
  1841. )
  1842. . $this->exportComment();
  1843. }
  1844. $dump .= $triggerQuery;
  1845. }
  1846. break;
  1847. case 'create_view':
  1848. if (empty($GLOBALS['sql_views_as_tables'])) {
  1849. $dump .= $this->exportComment(
  1850. __('Structure for view')
  1851. . ' '
  1852. . $formattedTableName
  1853. )
  1854. . $this->exportComment();
  1855. // delete the stand-in table previously created (if any)
  1856. if ($exportType !== 'table') {
  1857. $dump .= 'DROP TABLE IF EXISTS '
  1858. . Util::backquote($tableAlias) . ';' . $crlf;
  1859. }
  1860. $dump .= $this->getTableDef($db, $table, $crlf, $errorUrl, $dates, true, true, true, $aliases);
  1861. } else {
  1862. $dump .= $this->exportComment(
  1863. sprintf(
  1864. __('Structure for view %s exported as a table'),
  1865. $formattedTableName
  1866. )
  1867. )
  1868. . $this->exportComment();
  1869. // delete the stand-in table previously created (if any)
  1870. if ($exportType !== 'table') {
  1871. $dump .= 'DROP TABLE IF EXISTS '
  1872. . Util::backquote($tableAlias) . ';' . $crlf;
  1873. }
  1874. $dump .= $this->getTableDefForView($db, $table, $crlf, true, $aliases);
  1875. }
  1876. break;
  1877. case 'stand_in':
  1878. $dump .= $this->exportComment(
  1879. __('Stand-in structure for view') . ' ' . $formattedTableName
  1880. )
  1881. . $this->exportComment(
  1882. __('(See below for the actual view)')
  1883. )
  1884. . $this->exportComment();
  1885. // export a stand-in definition to resolve view dependencies
  1886. $dump .= $this->getTableDefStandIn($db, $table, $crlf, $aliases);
  1887. }
  1888. // this one is built by getTableDef() to use in table copy/move
  1889. // but not in the case of export
  1890. unset($GLOBALS['sql_constraints_query']);
  1891. return $this->export->outputHandler($dump);
  1892. }
  1893. /**
  1894. * Outputs the content of a table in SQL format
  1895. *
  1896. * @param string $db database name
  1897. * @param string $table table name
  1898. * @param string $crlf the end of line sequence
  1899. * @param string $errorUrl the url to go back in case of error
  1900. * @param string $sqlQuery SQL query for obtaining data
  1901. * @param array $aliases Aliases of db/table/columns
  1902. */
  1903. public function exportData(
  1904. $db,
  1905. $table,
  1906. $crlf,
  1907. $errorUrl,
  1908. $sqlQuery,
  1909. array $aliases = []
  1910. ): bool {
  1911. global $current_row, $sql_backquotes, $dbi;
  1912. // Do not export data for merge tables
  1913. if ($dbi->getTable($db, $table)->isMerge()) {
  1914. return true;
  1915. }
  1916. $dbAlias = $db;
  1917. $tableAlias = $table;
  1918. $this->initAlias($aliases, $dbAlias, $tableAlias);
  1919. if (isset($GLOBALS['sql_compatibility'])) {
  1920. $compat = $GLOBALS['sql_compatibility'];
  1921. } else {
  1922. $compat = 'NONE';
  1923. }
  1924. $formattedTableName = Util::backquoteCompat($tableAlias, $compat, $sql_backquotes);
  1925. // Do not export data for a VIEW, unless asked to export the view as a table
  1926. // (For a VIEW, this is called only when exporting a single VIEW)
  1927. if ($dbi->getTable($db, $table)->isView() && empty($GLOBALS['sql_views_as_tables'])) {
  1928. $head = $this->possibleCRLF()
  1929. . $this->exportComment()
  1930. . $this->exportComment('VIEW ' . $formattedTableName)
  1931. . $this->exportComment(__('Data:') . ' ' . __('None'))
  1932. . $this->exportComment()
  1933. . $this->possibleCRLF();
  1934. return $this->export->outputHandler($head);
  1935. }
  1936. $result = $dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
  1937. // a possible error: the table has crashed
  1938. $tmpError = $dbi->getError();
  1939. if ($tmpError) {
  1940. $message = sprintf(__('Error reading data for table %s:'), $db . '.' . $table);
  1941. $message .= ' ' . $tmpError;
  1942. if (! defined('TESTSUITE')) {
  1943. trigger_error($message, E_USER_ERROR);
  1944. }
  1945. return $this->export->outputHandler(
  1946. $this->exportComment($message)
  1947. );
  1948. }
  1949. if ($result == false) {
  1950. $dbi->freeResult($result);// This makes no sense
  1951. return true;
  1952. }
  1953. $fieldsCnt = $dbi->numFields($result);
  1954. // Get field information
  1955. /** @var FieldMetadata[] $fieldsMeta */
  1956. $fieldsMeta = $dbi->getFieldsMeta($result);
  1957. $fieldSet = [];
  1958. for ($j = 0; $j < $fieldsCnt; $j++) {
  1959. $colAs = $fieldsMeta[$j]->name;
  1960. if (! empty($aliases[$db]['tables'][$table]['columns'][$colAs])) {
  1961. $colAs = $aliases[$db]['tables'][$table]['columns'][$colAs];
  1962. }
  1963. $fieldSet[$j] = Util::backquoteCompat($colAs, $compat, $sql_backquotes);
  1964. }
  1965. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'UPDATE') {
  1966. // update
  1967. $schemaInsert = 'UPDATE ';
  1968. if (isset($GLOBALS['sql_ignore'])) {
  1969. $schemaInsert .= 'IGNORE ';
  1970. }
  1971. // avoid EOL blank
  1972. $schemaInsert .= Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ' SET';
  1973. } else {
  1974. // insert or replace
  1975. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'REPLACE') {
  1976. $sqlCommand = 'REPLACE';
  1977. } else {
  1978. $sqlCommand = 'INSERT';
  1979. }
  1980. // delayed inserts?
  1981. if (isset($GLOBALS['sql_delayed'])) {
  1982. $insertDelayed = ' DELAYED';
  1983. } else {
  1984. $insertDelayed = '';
  1985. }
  1986. // insert ignore?
  1987. if (isset($GLOBALS['sql_type'], $GLOBALS['sql_ignore']) && $GLOBALS['sql_type'] === 'INSERT') {
  1988. $insertDelayed .= ' IGNORE';
  1989. }
  1990. //truncate table before insert
  1991. if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sqlCommand === 'INSERT') {
  1992. $truncate = 'TRUNCATE TABLE '
  1993. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes) . ';';
  1994. $truncatehead = $this->possibleCRLF()
  1995. . $this->exportComment()
  1996. . $this->exportComment(
  1997. __('Truncate table before insert') . ' '
  1998. . $formattedTableName
  1999. )
  2000. . $this->exportComment()
  2001. . $crlf;
  2002. $this->export->outputHandler($truncatehead);
  2003. $this->export->outputHandler($truncate);
  2004. }
  2005. // scheme for inserting fields
  2006. if ($GLOBALS['sql_insert_syntax'] === 'complete' || $GLOBALS['sql_insert_syntax'] === 'both') {
  2007. $fields = implode(', ', $fieldSet);
  2008. $schemaInsert = $sqlCommand . $insertDelayed . ' INTO '
  2009. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes)
  2010. // avoid EOL blank
  2011. . ' (' . $fields . ') VALUES';
  2012. } else {
  2013. $schemaInsert = $sqlCommand . $insertDelayed . ' INTO '
  2014. . Util::backquoteCompat($tableAlias, $compat, $sql_backquotes)
  2015. . ' VALUES';
  2016. }
  2017. }
  2018. //\x08\\x09, not required
  2019. $current_row = 0;
  2020. $querySize = 0;
  2021. if (
  2022. ($GLOBALS['sql_insert_syntax'] === 'extended'
  2023. || $GLOBALS['sql_insert_syntax'] === 'both')
  2024. && (! isset($GLOBALS['sql_type'])
  2025. || $GLOBALS['sql_type'] !== 'UPDATE')
  2026. ) {
  2027. $separator = ',';
  2028. $schemaInsert .= $crlf;
  2029. } else {
  2030. $separator = ';';
  2031. }
  2032. while ($row = $dbi->fetchRow($result)) {
  2033. if ($current_row == 0) {
  2034. $head = $this->possibleCRLF()
  2035. . $this->exportComment()
  2036. . $this->exportComment(
  2037. __('Dumping data for table') . ' '
  2038. . $formattedTableName
  2039. )
  2040. . $this->exportComment()
  2041. . $crlf;
  2042. if (! $this->export->outputHandler($head)) {
  2043. return false;
  2044. }
  2045. }
  2046. // We need to SET IDENTITY_INSERT ON for MSSQL
  2047. if (
  2048. isset($GLOBALS['sql_compatibility'])
  2049. && $GLOBALS['sql_compatibility'] === 'MSSQL'
  2050. && $current_row == 0
  2051. ) {
  2052. if (
  2053. ! $this->export->outputHandler(
  2054. 'SET IDENTITY_INSERT '
  2055. . Util::backquoteCompat(
  2056. $tableAlias,
  2057. $compat,
  2058. $sql_backquotes
  2059. )
  2060. . ' ON ;' . $crlf
  2061. )
  2062. ) {
  2063. return false;
  2064. }
  2065. }
  2066. $current_row++;
  2067. $values = [];
  2068. for ($j = 0; $j < $fieldsCnt; $j++) {
  2069. // NULL
  2070. if (! isset($row[$j])) {
  2071. $values[] = 'NULL';
  2072. } elseif (
  2073. $fieldsMeta[$j]->isNumeric
  2074. && ! $fieldsMeta[$j]->isMappedTypeTimestamp
  2075. && ! $fieldsMeta[$j]->isBlob
  2076. ) {
  2077. // a number
  2078. // timestamp is numeric on some MySQL 4.1, BLOBs are
  2079. // sometimes numeric
  2080. $values[] = $row[$j];
  2081. } elseif ($fieldsMeta[$j]->isBinary && isset($GLOBALS['sql_hex_for_binary'])) {
  2082. // a true BLOB
  2083. // - mysqldump only generates hex data when the --hex-blob
  2084. // option is used, for fields having the binary attribute
  2085. // no hex is generated
  2086. // - a TEXT field returns type blob but a real blob
  2087. // returns also the 'binary' flag
  2088. // empty blobs need to be different, but '0' is also empty
  2089. // :-(
  2090. if (empty($row[$j]) && $row[$j] != '0') {
  2091. $values[] = '\'\'';
  2092. } else {
  2093. $values[] = '0x' . bin2hex($row[$j]);
  2094. }
  2095. } elseif ($fieldsMeta[$j]->isMappedTypeBit) {
  2096. // detection of 'bit' works only on mysqli extension
  2097. $values[] = "b'" . $dbi->escapeString(
  2098. Util::printableBitValue(
  2099. (int) $row[$j],
  2100. (int) $fieldsMeta[$j]->length
  2101. )
  2102. )
  2103. . "'";
  2104. } elseif ($fieldsMeta[$j]->isMappedTypeGeometry) {
  2105. // export GIS types as hex
  2106. $values[] = '0x' . bin2hex($row[$j]);
  2107. } elseif (! empty($GLOBALS['exporting_metadata']) && $row[$j] === '@LAST_PAGE') {
  2108. $values[] = '@LAST_PAGE';
  2109. } else {
  2110. // something else -> treat as a string
  2111. $values[] = '\''
  2112. . $dbi->escapeString($row[$j])
  2113. . '\'';
  2114. }
  2115. }
  2116. // should we make update?
  2117. if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] === 'UPDATE') {
  2118. $insertLine = $schemaInsert;
  2119. for ($i = 0; $i < $fieldsCnt; $i++) {
  2120. if ($i == 0) {
  2121. $insertLine .= ' ';
  2122. }
  2123. if ($i > 0) {
  2124. // avoid EOL blank
  2125. $insertLine .= ',';
  2126. }
  2127. $insertLine .= $fieldSet[$i] . ' = ' . $values[$i];
  2128. }
  2129. [$tmpUniqueCondition, $tmpClauseIsUnique] = Util::getUniqueCondition(
  2130. $result,
  2131. $fieldsCnt,
  2132. $fieldsMeta,
  2133. $row
  2134. );
  2135. $insertLine .= ' WHERE ' . $tmpUniqueCondition;
  2136. unset($tmpUniqueCondition, $tmpClauseIsUnique);
  2137. } else {
  2138. // Extended inserts case
  2139. if ($GLOBALS['sql_insert_syntax'] === 'extended' || $GLOBALS['sql_insert_syntax'] === 'both') {
  2140. if ($current_row == 1) {
  2141. $insertLine = $schemaInsert . '('
  2142. . implode(', ', $values) . ')';
  2143. } else {
  2144. $insertLine = '(' . implode(', ', $values) . ')';
  2145. $insertLineSize = mb_strlen($insertLine);
  2146. $sqlMaxSize = $GLOBALS['sql_max_query_size'];
  2147. if (isset($sqlMaxSize) && $sqlMaxSize > 0 && $querySize + $insertLineSize > $sqlMaxSize) {
  2148. if (! $this->export->outputHandler(';' . $crlf)) {
  2149. return false;
  2150. }
  2151. $querySize = 0;
  2152. $current_row = 1;
  2153. $insertLine = $schemaInsert . $insertLine;
  2154. }
  2155. }
  2156. $querySize += mb_strlen($insertLine);
  2157. // Other inserts case
  2158. } else {
  2159. $insertLine = $schemaInsert
  2160. . '(' . implode(', ', $values) . ')';
  2161. }
  2162. }
  2163. unset($values);
  2164. if (! $this->export->outputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insertLine)) {
  2165. return false;
  2166. }
  2167. }
  2168. if ($current_row > 0) {
  2169. if (! $this->export->outputHandler(';' . $crlf)) {
  2170. return false;
  2171. }
  2172. }
  2173. // We need to SET IDENTITY_INSERT OFF for MSSQL
  2174. if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'MSSQL' && $current_row > 0) {
  2175. $outputSucceeded = $this->export->outputHandler(
  2176. $crlf . 'SET IDENTITY_INSERT '
  2177. . Util::backquoteCompat(
  2178. $tableAlias,
  2179. $compat,
  2180. $sql_backquotes
  2181. )
  2182. . ' OFF;' . $crlf
  2183. );
  2184. if (! $outputSucceeded) {
  2185. return false;
  2186. }
  2187. }
  2188. $dbi->freeResult($result);
  2189. return true;
  2190. }
  2191. /**
  2192. * Make a create table statement compatible with MSSQL
  2193. *
  2194. * @param string $createQuery MySQL create table statement
  2195. *
  2196. * @return string MSSQL compatible create table statement
  2197. */
  2198. private function makeCreateTableMSSQLCompatible($createQuery)
  2199. {
  2200. // In MSSQL
  2201. // 1. No 'IF NOT EXISTS' in CREATE TABLE
  2202. // 2. DATE field doesn't exists, we will use DATETIME instead
  2203. // 3. UNSIGNED attribute doesn't exist
  2204. // 4. No length on INT, TINYINT, SMALLINT, BIGINT and no precision on
  2205. // FLOAT fields
  2206. // 5. No KEY and INDEX inside CREATE TABLE
  2207. // 6. DOUBLE field doesn't exists, we will use FLOAT instead
  2208. $createQuery = (string) preg_replace('/^CREATE TABLE IF NOT EXISTS/', 'CREATE TABLE', (string) $createQuery);
  2209. // first we need to replace all lines ended with '" DATE ...,\n'
  2210. // last preg_replace preserve us from situation with date text
  2211. // inside DEFAULT field value
  2212. $createQuery = (string) preg_replace(
  2213. "/\" date DEFAULT NULL(,)?\n/",
  2214. '" datetime DEFAULT NULL$1' . "\n",
  2215. $createQuery
  2216. );
  2217. $createQuery = (string) preg_replace("/\" date NOT NULL(,)?\n/", '" datetime NOT NULL$1' . "\n", $createQuery);
  2218. $createQuery = (string) preg_replace(
  2219. '/" date NOT NULL DEFAULT \'([^\'])/',
  2220. '" datetime NOT NULL DEFAULT \'$1',
  2221. $createQuery
  2222. );
  2223. // next we need to replace all lines ended with ') UNSIGNED ...,'
  2224. // last preg_replace preserve us from situation with unsigned text
  2225. // inside DEFAULT field value
  2226. $createQuery = (string) preg_replace("/\) unsigned NOT NULL(,)?\n/", ') NOT NULL$1' . "\n", $createQuery);
  2227. $createQuery = (string) preg_replace(
  2228. "/\) unsigned DEFAULT NULL(,)?\n/",
  2229. ') DEFAULT NULL$1' . "\n",
  2230. $createQuery
  2231. );
  2232. $createQuery = (string) preg_replace(
  2233. '/\) unsigned NOT NULL DEFAULT \'([^\'])/',
  2234. ') NOT NULL DEFAULT \'$1',
  2235. $createQuery
  2236. );
  2237. // we need to replace all lines ended with
  2238. // '" INT|TINYINT([0-9]{1,}) ...,' last preg_replace preserve us
  2239. // from situation with int([0-9]{1,}) text inside DEFAULT field
  2240. // value
  2241. $createQuery = (string) preg_replace(
  2242. '/" (int|tinyint|smallint|bigint)\([0-9]+\) DEFAULT NULL(,)?\n/',
  2243. '" $1 DEFAULT NULL$2' . "\n",
  2244. $createQuery
  2245. );
  2246. $createQuery = (string) preg_replace(
  2247. '/" (int|tinyint|smallint|bigint)\([0-9]+\) NOT NULL(,)?\n/',
  2248. '" $1 NOT NULL$2' . "\n",
  2249. $createQuery
  2250. );
  2251. $createQuery = (string) preg_replace(
  2252. '/" (int|tinyint|smallint|bigint)\([0-9]+\) NOT NULL DEFAULT \'([^\'])/',
  2253. '" $1 NOT NULL DEFAULT \'$2',
  2254. $createQuery
  2255. );
  2256. // we need to replace all lines ended with
  2257. // '" FLOAT|DOUBLE([0-9,]{1,}) ...,'
  2258. // last preg_replace preserve us from situation with
  2259. // float([0-9,]{1,}) text inside DEFAULT field value
  2260. $createQuery = (string) preg_replace(
  2261. '/" (float|double)(\([0-9]+,[0-9,]+\))? DEFAULT NULL(,)?\n/',
  2262. '" float DEFAULT NULL$3' . "\n",
  2263. $createQuery
  2264. );
  2265. $createQuery = (string) preg_replace(
  2266. '/" (float|double)(\([0-9,]+,[0-9,]+\))? NOT NULL(,)?\n/',
  2267. '" float NOT NULL$3' . "\n",
  2268. $createQuery
  2269. );
  2270. return (string) preg_replace(
  2271. '/" (float|double)(\([0-9,]+,[0-9,]+\))? NOT NULL DEFAULT \'([^\'])/',
  2272. '" float NOT NULL DEFAULT \'$3',
  2273. $createQuery
  2274. );
  2275. // @todo remove indexes from CREATE TABLE
  2276. }
  2277. /**
  2278. * replaces db/table/column names with their aliases
  2279. *
  2280. * @param string $sqlQuery SQL query in which aliases are to be substituted
  2281. * @param array $aliases Alias information for db/table/column
  2282. * @param string $db the database name
  2283. * @param string $table the tablename
  2284. * @param string $flag the flag denoting whether any replacement was done
  2285. *
  2286. * @return string query replaced with aliases
  2287. */
  2288. public function replaceWithAliases(
  2289. $sqlQuery,
  2290. array $aliases,
  2291. $db,
  2292. $table = '',
  2293. &$flag = null
  2294. ) {
  2295. $flag = false;
  2296. /**
  2297. * The parser of this query.
  2298. *
  2299. * @var Parser $parser
  2300. */
  2301. $parser = new Parser($sqlQuery);
  2302. if (empty($parser->statements[0])) {
  2303. return $sqlQuery;
  2304. }
  2305. /**
  2306. * The statement that represents the query.
  2307. *
  2308. * @var CreateStatement $statement
  2309. */
  2310. $statement = $parser->statements[0];
  2311. /**
  2312. * Old database name.
  2313. *
  2314. * @var string $oldDatabase
  2315. */
  2316. $oldDatabase = $db;
  2317. // Replacing aliases in `CREATE TABLE` statement.
  2318. if ($statement->options->has('TABLE')) {
  2319. // Extracting the name of the old database and table from the
  2320. // statement to make sure the parameters are correct.
  2321. if (! empty($statement->name->database)) {
  2322. $oldDatabase = $statement->name->database;
  2323. }
  2324. /**
  2325. * Old table name.
  2326. *
  2327. * @var string $oldTable
  2328. */
  2329. $oldTable = $statement->name->table;
  2330. // Finding the aliased database name.
  2331. // The database might be empty so we have to add a few checks.
  2332. $newDatabase = null;
  2333. if (! empty($statement->name->database)) {
  2334. $newDatabase = $statement->name->database;
  2335. if (! empty($aliases[$oldDatabase]['alias'])) {
  2336. $newDatabase = $aliases[$oldDatabase]['alias'];
  2337. }
  2338. }
  2339. // Finding the aliases table name.
  2340. $newTable = $oldTable;
  2341. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['alias'])) {
  2342. $newTable = $aliases[$oldDatabase]['tables'][$oldTable]['alias'];
  2343. }
  2344. // Replacing new values.
  2345. if (($statement->name->database !== $newDatabase) || ($statement->name->table !== $newTable)) {
  2346. $statement->name->database = $newDatabase;
  2347. $statement->name->table = $newTable;
  2348. $statement->name->expr = ''; // Force rebuild.
  2349. $flag = true;
  2350. }
  2351. /** @var CreateDefinition[] $fields */
  2352. $fields = $statement->fields;
  2353. foreach ($fields as $field) {
  2354. // Column name.
  2355. if (! empty($field->type)) {
  2356. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['columns'][$field->name])) {
  2357. $field->name = $aliases[$oldDatabase]['tables'][$oldTable]['columns'][$field->name];
  2358. $flag = true;
  2359. }
  2360. }
  2361. // Key's columns.
  2362. if (! empty($field->key)) {
  2363. foreach ($field->key->columns as $key => $column) {
  2364. if (! isset($column['name'])) {
  2365. // In case the column has no name field
  2366. continue;
  2367. }
  2368. if (empty($aliases[$oldDatabase]['tables'][$oldTable]['columns'][$column['name']])) {
  2369. continue;
  2370. }
  2371. $columnAliases = $aliases[$oldDatabase]['tables'][$oldTable]['columns'];
  2372. $field->key->columns[$key]['name'] = $columnAliases[$column['name']];
  2373. $flag = true;
  2374. }
  2375. }
  2376. // References.
  2377. if (empty($field->references)) {
  2378. continue;
  2379. }
  2380. $refTable = $field->references->table->table;
  2381. // Replacing table.
  2382. if (! empty($aliases[$oldDatabase]['tables'][$refTable]['alias'])) {
  2383. $field->references->table->table = $aliases[$oldDatabase]['tables'][$refTable]['alias'];
  2384. $field->references->table->expr = '';
  2385. $flag = true;
  2386. }
  2387. // Replacing column names.
  2388. foreach ($field->references->columns as $key => $column) {
  2389. if (empty($aliases[$oldDatabase]['tables'][$refTable]['columns'][$column])) {
  2390. continue;
  2391. }
  2392. $field->references->columns[$key] = $aliases[$oldDatabase]['tables'][$refTable]['columns'][$column];
  2393. $flag = true;
  2394. }
  2395. }
  2396. } elseif ($statement->options->has('TRIGGER')) {
  2397. // Extracting the name of the old database and table from the
  2398. // statement to make sure the parameters are correct.
  2399. if (! empty($statement->table->database)) {
  2400. $oldDatabase = $statement->table->database;
  2401. }
  2402. /**
  2403. * Old table name.
  2404. *
  2405. * @var string $oldTable
  2406. */
  2407. $oldTable = $statement->table->table;
  2408. if (! empty($aliases[$oldDatabase]['tables'][$oldTable]['alias'])) {
  2409. $statement->table->table = $aliases[$oldDatabase]['tables'][$oldTable]['alias'];
  2410. $statement->table->expr = ''; // Force rebuild.
  2411. $flag = true;
  2412. }
  2413. }
  2414. if (
  2415. $statement->options->has('TRIGGER')
  2416. || $statement->options->has('PROCEDURE')
  2417. || $statement->options->has('FUNCTION')
  2418. || $statement->options->has('VIEW')
  2419. ) {
  2420. // Replacing the body.
  2421. for ($i = 0, $count = count((array) $statement->body); $i < $count; ++$i) {
  2422. /**
  2423. * Token parsed at this moment.
  2424. *
  2425. * @var Token $token
  2426. */
  2427. $token = $statement->body[$i];
  2428. // Replacing only symbols (that are not variables) and unknown
  2429. // identifiers.
  2430. $isSymbol = $token->type === Token::TYPE_SYMBOL;
  2431. $isKeyword = $token->type === Token::TYPE_KEYWORD;
  2432. $isNone = $token->type === Token::TYPE_NONE;
  2433. $replaceToken = $isSymbol
  2434. && (! ($token->flags & Token::FLAG_SYMBOL_VARIABLE))
  2435. || ($isKeyword
  2436. && (! ($token->flags & Token::FLAG_KEYWORD_RESERVED))
  2437. || $isNone);
  2438. if (! $replaceToken) {
  2439. continue;
  2440. }
  2441. $alias = $this->getAlias($aliases, $token->value);
  2442. if (empty($alias)) {
  2443. continue;
  2444. }
  2445. // Replacing the token.
  2446. $token->token = Context::escape($alias);
  2447. $flag = true;
  2448. }
  2449. }
  2450. return $statement->build();
  2451. }
  2452. /**
  2453. * Generate comment
  2454. *
  2455. * @param string $crlf Carriage return character
  2456. * @param string|null $sqlStatement SQL statement
  2457. * @param string $comment1 Comment for dumped table
  2458. * @param string $comment2 Comment for current table
  2459. * @param string $tableAlias Table alias
  2460. * @param string $compat Compatibility mode
  2461. *
  2462. * @return string
  2463. */
  2464. protected function generateComment(
  2465. $crlf,
  2466. ?string $sqlStatement,
  2467. $comment1,
  2468. $comment2,
  2469. $tableAlias,
  2470. $compat
  2471. ) {
  2472. if (! isset($sqlStatement)) {
  2473. if (isset($GLOBALS['no_constraints_comments'])) {
  2474. $sqlStatement = '';
  2475. } else {
  2476. $sqlStatement = $crlf
  2477. . $this->exportComment()
  2478. . $this->exportComment($comment1)
  2479. . $this->exportComment();
  2480. }
  2481. }
  2482. // comments for current table
  2483. if (! isset($GLOBALS['no_constraints_comments'])) {
  2484. $sqlStatement .= $crlf
  2485. . $this->exportComment()
  2486. . $this->exportComment(
  2487. $comment2 . ' ' . Util::backquoteCompat(
  2488. $tableAlias,
  2489. $compat,
  2490. isset($GLOBALS['sql_backquotes'])
  2491. )
  2492. )
  2493. . $this->exportComment();
  2494. }
  2495. return $sqlStatement;
  2496. }
  2497. }