/libraries/classes/Plugins/Export/ExportSql.php
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
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Set of functions used to build SQL dumps of tables
- */
- declare(strict_types=1);
- namespace PhpMyAdmin\Plugins\Export;
- use PhpMyAdmin\Charsets;
- use PhpMyAdmin\DatabaseInterface;
- use PhpMyAdmin\FieldMetadata;
- use PhpMyAdmin\Plugins\ExportPlugin;
- use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
- use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
- use PhpMyAdmin\Properties\Options\Groups\OptionsPropertySubgroup;
- use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
- use PhpMyAdmin\Properties\Options\Items\MessageOnlyPropertyItem;
- use PhpMyAdmin\Properties\Options\Items\NumberPropertyItem;
- use PhpMyAdmin\Properties\Options\Items\RadioPropertyItem;
- use PhpMyAdmin\Properties\Options\Items\SelectPropertyItem;
- use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
- use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
- use PhpMyAdmin\SqlParser\Components\CreateDefinition;
- use PhpMyAdmin\SqlParser\Context;
- use PhpMyAdmin\SqlParser\Parser;
- use PhpMyAdmin\SqlParser\Statements\CreateStatement;
- use PhpMyAdmin\SqlParser\Token;
- use PhpMyAdmin\Util;
- use PhpMyAdmin\Version;
- use function __;
- use function bin2hex;
- use function count;
- use function defined;
- use function explode;
- use function implode;
- use function in_array;
- use function intval;
- use function is_array;
- use function mb_strlen;
- use function mb_strpos;
- use function mb_substr;
- use function preg_quote;
- use function preg_replace;
- use function preg_split;
- use function sprintf;
- use function str_repeat;
- use function str_replace;
- use function strtotime;
- use function strtoupper;
- use function trigger_error;
- use const E_USER_ERROR;
- use const PHP_VERSION;
- /**
- * Handles the export for the SQL class
- */
- class ExportSql extends ExportPlugin
- {
- /**
- * Whether charset header was sent.
- *
- * @var bool
- */
- private $sentCharset = false;
- protected function init(): void
- {
- // Avoids undefined variables, use NULL so isset() returns false
- if (isset($GLOBALS['sql_backquotes'])) {
- return;
- }
- $GLOBALS['sql_backquotes'] = null;
- }
- /**
- * @psalm-return non-empty-lowercase-string
- */
- public function getName(): string
- {
- return 'sql';
- }
- protected function setProperties(): ExportPluginProperties
- {
- global $plugin_param, $dbi;
- $hideSql = false;
- $hideStructure = false;
- if ($plugin_param['export_type'] === 'table' && ! $plugin_param['single_table']) {
- $hideStructure = true;
- $hideSql = true;
- }
- // In case we have `raw_query` parameter set,
- // we initialize SQL option
- if (isset($_REQUEST['raw_query'])) {
- $hideStructure = false;
- $hideSql = false;
- }
- $exportPluginProperties = new ExportPluginProperties();
- $exportPluginProperties->setText('SQL');
- $exportPluginProperties->setExtension('sql');
- $exportPluginProperties->setMimeType('text/x-sql');
- if ($hideSql) {
- return $exportPluginProperties;
- }
- $exportPluginProperties->setOptionsText(__('Options'));
- // create the root group that will be the options field for
- // $exportPluginProperties
- // this will be shown as "Format specific options"
- $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
- // general options main group
- $generalOptions = new OptionsPropertyMainGroup('general_opts');
- // comments
- $subgroup = new OptionsPropertySubgroup('include_comments');
- $leaf = new BoolPropertyItem(
- 'include_comments',
- __(
- 'Display comments <i>(includes info such as export timestamp, PHP version, and server version)</i>'
- )
- );
- $subgroup->setSubgroupHeader($leaf);
- $leaf = new TextPropertyItem(
- 'header_comment',
- __('Additional custom header comment (\n splits lines):')
- );
- $subgroup->addProperty($leaf);
- $leaf = new BoolPropertyItem(
- 'dates',
- __(
- 'Include a timestamp of when databases were created, last updated, and last checked'
- )
- );
- $subgroup->addProperty($leaf);
- if (! empty($GLOBALS['cfgRelation']['relation'])) {
- $leaf = new BoolPropertyItem(
- 'relation',
- __('Display foreign key relationships')
- );
- $subgroup->addProperty($leaf);
- }
- if (! empty($GLOBALS['cfgRelation']['mimework'])) {
- $leaf = new BoolPropertyItem(
- 'mime',
- __('Display media types')
- );
- $subgroup->addProperty($leaf);
- }
- $generalOptions->addProperty($subgroup);
- // enclose in a transaction
- $leaf = new BoolPropertyItem(
- 'use_transaction',
- __('Enclose export in a transaction')
- );
- $leaf->setDoc(
- [
- 'programs',
- 'mysqldump',
- 'option_mysqldump_single-transaction',
- ]
- );
- $generalOptions->addProperty($leaf);
- // disable foreign key checks
- $leaf = new BoolPropertyItem(
- 'disable_fk',
- __('Disable foreign key checks')
- );
- $leaf->setDoc(
- [
- 'manual_MySQL_Database_Administration',
- 'server-system-variables',
- 'sysvar_foreign_key_checks',
- ]
- );
- $generalOptions->addProperty($leaf);
- // export views as tables
- $leaf = new BoolPropertyItem(
- 'views_as_tables',
- __('Export views as tables')
- );
- $generalOptions->addProperty($leaf);
- // export metadata
- $leaf = new BoolPropertyItem(
- 'metadata',
- __('Export metadata')
- );
- $generalOptions->addProperty($leaf);
- // compatibility maximization
- $compats = $dbi->getCompatibilities();
- if (count($compats) > 0) {
- $values = [];
- foreach ($compats as $val) {
- $values[$val] = $val;
- }
- $leaf = new SelectPropertyItem(
- 'compatibility',
- __(
- 'Database system or older MySQL server to maximize output compatibility with:'
- )
- );
- $leaf->setValues($values);
- $leaf->setDoc(
- [
- 'manual_MySQL_Database_Administration',
- 'Server_SQL_mode',
- ]
- );
- $generalOptions->addProperty($leaf);
- unset($values);
- }
- // what to dump (structure/data/both)
- $subgroup = new OptionsPropertySubgroup(
- 'dump_table',
- __('Dump table')
- );
- $leaf = new RadioPropertyItem('structure_or_data');
- $leaf->setValues(
- [
- 'structure' => __('structure'),
- 'data' => __('data'),
- 'structure_and_data' => __('structure and data'),
- ]
- );
- $subgroup->setSubgroupHeader($leaf);
- $generalOptions->addProperty($subgroup);
- // add the main group to the root group
- $exportSpecificOptions->addProperty($generalOptions);
- // structure options main group
- if (! $hideStructure) {
- $structureOptions = new OptionsPropertyMainGroup(
- 'structure',
- __('Object creation options')
- );
- $structureOptions->setForce('data');
- // begin SQL Statements
- $subgroup = new OptionsPropertySubgroup();
- $leaf = new MessageOnlyPropertyItem(
- 'add_statements',
- __('Add statements:')
- );
- $subgroup->setSubgroupHeader($leaf);
- // server export options
- if ($plugin_param['export_type'] === 'server') {
- $leaf = new BoolPropertyItem(
- 'drop_database',
- sprintf(__('Add %s statement'), '<code>DROP DATABASE IF EXISTS</code>')
- );
- $subgroup->addProperty($leaf);
- }
- if ($plugin_param['export_type'] === 'database') {
- $createClause = '<code>CREATE DATABASE / USE</code>';
- $leaf = new BoolPropertyItem(
- 'create_database',
- sprintf(__('Add %s statement'), $createClause)
- );
- $subgroup->addProperty($leaf);
- }
- if ($plugin_param['export_type'] === 'table') {
- $dropClause = $dbi->getTable($GLOBALS['db'], $GLOBALS['table'])->isView()
- ? '<code>DROP VIEW</code>'
- : '<code>DROP TABLE</code>';
- } else {
- $dropClause = '<code>DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT</code>';
- }
- $dropClause .= '<code> / TRIGGER</code>';
- $leaf = new BoolPropertyItem(
- 'drop_table',
- sprintf(__('Add %s statement'), $dropClause)
- );
- $subgroup->addProperty($leaf);
- $subgroupCreateTable = new OptionsPropertySubgroup();
- // Add table structure option
- $leaf = new BoolPropertyItem(
- 'create_table',
- sprintf(__('Add %s statement'), '<code>CREATE TABLE</code>')
- );
- $subgroupCreateTable->setSubgroupHeader($leaf);
- $leaf = new BoolPropertyItem(
- 'if_not_exists',
- '<code>IF NOT EXISTS</code> ' . __(
- '(less efficient as indexes will be generated during table creation)'
- )
- );
- $subgroupCreateTable->addProperty($leaf);
- $leaf = new BoolPropertyItem(
- 'auto_increment',
- sprintf(__('%s value'), '<code>AUTO_INCREMENT</code>')
- );
- $subgroupCreateTable->addProperty($leaf);
- $subgroup->addProperty($subgroupCreateTable);
- // Add view option
- $subgroupCreateView = new OptionsPropertySubgroup();
- $leaf = new BoolPropertyItem(
- 'create_view',
- sprintf(__('Add %s statement'), '<code>CREATE VIEW</code>')
- );
- $subgroupCreateView->setSubgroupHeader($leaf);
- $leaf = new BoolPropertyItem(
- 'simple_view_export',
- /* l10n: Allow simplifying exported view syntax to only "CREATE VIEW" */
- __('Use simple view export')
- );
- $subgroupCreateView->addProperty($leaf);
- $leaf = new BoolPropertyItem(
- 'view_current_user',
- __('Exclude definition of current user')
- );
- $subgroupCreateView->addProperty($leaf);
- $leaf = new BoolPropertyItem(
- 'or_replace_view',
- sprintf(__('%s view'), '<code>OR REPLACE</code>')
- );
- $subgroupCreateView->addProperty($leaf);
- $subgroup->addProperty($subgroupCreateView);
- $leaf = new BoolPropertyItem(
- 'procedure_function',
- sprintf(
- __('Add %s statement'),
- '<code>CREATE PROCEDURE / FUNCTION / EVENT</code>'
- )
- );
- $subgroup->addProperty($leaf);
- // Add triggers option
- $leaf = new BoolPropertyItem(
- 'create_trigger',
- sprintf(__('Add %s statement'), '<code>CREATE TRIGGER</code>')
- );
- $subgroup->addProperty($leaf);
- $structureOptions->addProperty($subgroup);
- $leaf = new BoolPropertyItem(
- 'backquotes',
- __(
- 'Enclose table and column names with backquotes '
- . '<i>(Protects column and table names formed with'
- . ' special characters or keywords)</i>'
- )
- );
- $structureOptions->addProperty($leaf);
- // add the main group to the root group
- $exportSpecificOptions->addProperty($structureOptions);
- }
- // begin Data options
- $dataOptions = new OptionsPropertyMainGroup(
- 'data',
- __('Data creation options')
- );
- $dataOptions->setForce('structure');
- $leaf = new BoolPropertyItem(
- 'truncate',
- __('Truncate table before insert')
- );
- $dataOptions->addProperty($leaf);
- // begin SQL Statements
- $subgroup = new OptionsPropertySubgroup();
- $leaf = new MessageOnlyPropertyItem(
- __('Instead of <code>INSERT</code> statements, use:')
- );
- $subgroup->setSubgroupHeader($leaf);
- $leaf = new BoolPropertyItem(
- 'delayed',
- __('<code>INSERT DELAYED</code> statements')
- );
- $leaf->setDoc(
- [
- 'manual_MySQL_Database_Administration',
- 'insert_delayed',
- ]
- );
- $subgroup->addProperty($leaf);
- $leaf = new BoolPropertyItem(
- 'ignore',
- __('<code>INSERT IGNORE</code> statements')
- );
- $leaf->setDoc(
- [
- 'manual_MySQL_Database_Administration',
- 'insert',
- ]
- );
- $subgroup->addProperty($leaf);
- $dataOptions->addProperty($subgroup);
- // Function to use when dumping dat
- $leaf = new SelectPropertyItem(
- 'type',
- __('Function to use when dumping data:')
- );
- $leaf->setValues(
- [
- 'INSERT' => 'INSERT',
- 'UPDATE' => 'UPDATE',
- 'REPLACE' => 'REPLACE',
- ]
- );
- $dataOptions->addProperty($leaf);
- /* Syntax to use when inserting data */
- $subgroup = new OptionsPropertySubgroup();
- $leaf = new MessageOnlyPropertyItem(
- null,
- __('Syntax to use when inserting data:')
- );
- $subgroup->setSubgroupHeader($leaf);
- $leaf = new RadioPropertyItem(
- 'insert_syntax',
- __('<code>INSERT IGNORE</code> statements')
- );
- $leaf->setValues(
- [
- 'complete' => __(
- 'include column names in every <code>INSERT</code> statement'
- . ' <br> Example: <code>INSERT INTO'
- . ' tbl_name (col_A,col_B,col_C) VALUES (1,2,3)</code>'
- ),
- 'extended' => __(
- 'insert multiple rows in every <code>INSERT</code> statement'
- . '<br> Example: <code>INSERT INTO'
- . ' tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)</code>'
- ),
- 'both' => __(
- 'both of the above<br> Example:'
- . ' <code>INSERT INTO tbl_name (col_A,col_B,col_C) VALUES'
- . ' (1,2,3), (4,5,6), (7,8,9)</code>'
- ),
- 'none' => __(
- 'neither of the above<br> Example:'
- . ' <code>INSERT INTO tbl_name VALUES (1,2,3)</code>'
- ),
- ]
- );
- $subgroup->addProperty($leaf);
- $dataOptions->addProperty($subgroup);
- // Max length of query
- $leaf = new NumberPropertyItem(
- 'max_query_size',
- __('Maximal length of created query')
- );
- $dataOptions->addProperty($leaf);
- // Dump binary columns in hexadecimal
- $leaf = new BoolPropertyItem(
- 'hex_for_binary',
- __(
- 'Dump binary columns in hexadecimal notation <i>(for example, "abc" becomes 0x616263)</i>'
- )
- );
- $dataOptions->addProperty($leaf);
- // Dump time in UTC
- $leaf = new BoolPropertyItem(
- 'utc_time',
- __(
- 'Dump TIMESTAMP columns in UTC <i>(enables TIMESTAMP columns'
- . ' to be dumped and reloaded between servers in different'
- . ' time zones)</i>'
- )
- );
- $dataOptions->addProperty($leaf);
- // add the main group to the root group
- $exportSpecificOptions->addProperty($dataOptions);
- // set the options for the export plugin property item
- $exportPluginProperties->setOptions($exportSpecificOptions);
- return $exportPluginProperties;
- }
- /**
- * Generates SQL for routines export
- *
- * @param string $db Database
- * @param array $aliases Aliases of db/table/columns
- * @param string $type Type of exported routine
- * @param string $name Verbose name of exported routine
- * @param array $routines List of routines to export
- * @param string $delimiter Delimiter to use in SQL
- *
- * @return string SQL query
- */
- protected function exportRoutineSQL(
- $db,
- array $aliases,
- $type,
- $name,
- array $routines,
- $delimiter
- ) {
- global $crlf, $dbi;
- $text = $this->exportComment()
- . $this->exportComment($name)
- . $this->exportComment();
- $usedAlias = false;
- $procQuery = '';
- foreach ($routines as $routine) {
- if (! empty($GLOBALS['sql_drop_table'])) {
- $procQuery .= 'DROP ' . $type . ' IF EXISTS '
- . Util::backquote($routine)
- . $delimiter . $crlf;
- }
- $createQuery = $this->replaceWithAliases(
- $dbi->getDefinition($db, $type, $routine),
- $aliases,
- $db,
- '',
- $flag
- );
- // One warning per database
- if ($flag) {
- $usedAlias = true;
- }
- $procQuery .= $createQuery . $delimiter . $crlf . $crlf;
- }
- if ($usedAlias) {
- $text .= $this->exportComment(
- __('It appears your database uses routines;')
- )
- . $this->exportComment(
- __('alias export may not work reliably in all cases.')
- )
- . $this->exportComment();
- }
- $text .= $procQuery;
- return $text;
- }
- /**
- * Exports routines (procedures and functions)
- *
- * @param string $db Database
- * @param array $aliases Aliases of db/table/columns
- */
- public function exportRoutines($db, array $aliases = []): bool
- {
- global $crlf, $dbi;
- $dbAlias = $db;
- $this->initAlias($aliases, $dbAlias);
- $text = '';
- $delimiter = '$$';
- $procedureNames = $dbi->getProceduresOrFunctions($db, 'PROCEDURE');
- $functionNames = $dbi->getProceduresOrFunctions($db, 'FUNCTION');
- if ($procedureNames || $functionNames) {
- $text .= $crlf
- . 'DELIMITER ' . $delimiter . $crlf;
- if ($procedureNames) {
- $text .= $this->exportRoutineSQL(
- $db,
- $aliases,
- 'PROCEDURE',
- __('Procedures'),
- $procedureNames,
- $delimiter
- );
- }
- if ($functionNames) {
- $text .= $this->exportRoutineSQL(
- $db,
- $aliases,
- 'FUNCTION',
- __('Functions'),
- $functionNames,
- $delimiter
- );
- }
- $text .= 'DELIMITER ;' . $crlf;
- }
- if (! empty($text)) {
- return $this->export->outputHandler($text);
- }
- return false;
- }
- /**
- * Possibly outputs comment
- *
- * @param string $text Text of comment
- *
- * @return string The formatted comment
- */
- private function exportComment($text = '')
- {
- if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
- // see https://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
- if (empty($text)) {
- return '--' . $GLOBALS['crlf'];
- }
- $lines = preg_split("/\\r\\n|\\r|\\n/", $text);
- if ($lines === false) {
- return '--' . $GLOBALS['crlf'];
- }
- $result = [];
- foreach ($lines as $line) {
- $result[] = '-- ' . $line . $GLOBALS['crlf'];
- }
- return implode('', $result);
- }
- return '';
- }
- /**
- * Possibly outputs CRLF
- *
- * @return string crlf or nothing
- */
- private function possibleCRLF()
- {
- if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
- return $GLOBALS['crlf'];
- }
- return '';
- }
- /**
- * Outputs export footer
- */
- public function exportFooter(): bool
- {
- global $crlf, $dbi;
- $foot = '';
- if (isset($GLOBALS['sql_disable_fk'])) {
- $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
- }
- if (isset($GLOBALS['sql_use_transaction'])) {
- $foot .= 'COMMIT;' . $crlf;
- }
- // restore connection settings
- if ($this->sentCharset) {
- $foot .= $crlf
- . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;'
- . $crlf
- . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;'
- . $crlf
- . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;'
- . $crlf;
- $this->sentCharset = false;
- }
- /* Restore timezone */
- if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
- $dbi->query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
- }
- return $this->export->outputHandler($foot);
- }
- /**
- * Outputs export header. It is the first method to be called, so all
- * the required variables are initialized here.
- */
- public function exportHeader(): bool
- {
- global $crlf, $cfg, $dbi;
- if (isset($GLOBALS['sql_compatibility'])) {
- $tmpCompat = $GLOBALS['sql_compatibility'];
- if ($tmpCompat === 'NONE') {
- $tmpCompat = '';
- }
- $dbi->tryQuery('SET SQL_MODE="' . $tmpCompat . '"');
- unset($tmpCompat);
- }
- $head = $this->exportComment('phpMyAdmin SQL Dump')
- . $this->exportComment('version ' . Version::VERSION)
- . $this->exportComment('https://www.phpmyadmin.net/')
- . $this->exportComment();
- $hostString = __('Host:') . ' ' . $cfg['Server']['host'];
- if (! empty($cfg['Server']['port'])) {
- $hostString .= ':' . $cfg['Server']['port'];
- }
- $head .= $this->exportComment($hostString);
- $head .= $this->exportComment(
- __('Generation Time:') . ' '
- . Util::localisedDate()
- )
- . $this->exportComment(
- __('Server version:') . ' ' . $dbi->getVersionString()
- )
- . $this->exportComment(__('PHP Version:') . ' ' . PHP_VERSION)
- . $this->possibleCRLF();
- if (isset($GLOBALS['sql_header_comment']) && ! empty($GLOBALS['sql_header_comment'])) {
- // '\n' is not a newline (like "\n" would be), it's the characters
- // backslash and n, as explained on the export interface
- $lines = explode('\n', $GLOBALS['sql_header_comment']);
- $head .= $this->exportComment();
- foreach ($lines as $oneLine) {
- $head .= $this->exportComment($oneLine);
- }
- $head .= $this->exportComment();
- }
- if (isset($GLOBALS['sql_disable_fk'])) {
- $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
- }
- // We want exported AUTO_INCREMENT columns to have still same value,
- // do this only for recent MySQL exports
- if (! isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] === 'NONE') {
- $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf;
- }
- if (isset($GLOBALS['sql_use_transaction'])) {
- $head .= 'START TRANSACTION;' . $crlf;
- }
- /* Change timezone if we should export timestamps in UTC */
- if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
- $head .= 'SET time_zone = "+00:00";' . $crlf;
- $GLOBALS['old_tz'] = $dbi
- ->fetchValue('SELECT @@session.time_zone');
- $dbi->query('SET time_zone = "+00:00"');
- }
- $head .= $this->possibleCRLF();
- if (! empty($GLOBALS['asfile'])) {
- // we are saving as file, therefore we provide charset information
- // so that a utility like the mysql client can interpret
- // the file correctly
- if (isset($GLOBALS['charset'], Charsets::$mysqlCharsetMap[$GLOBALS['charset']])) {
- // we got a charset from the export dialog
- $setNames = Charsets::$mysqlCharsetMap[$GLOBALS['charset']];
- } else {
- // by default we use the connection charset
- $setNames = Charsets::$mysqlCharsetMap['utf-8'];
- }
- if ($setNames === 'utf8' && $dbi->getVersion() > 50503) {
- $setNames = 'utf8mb4';
- }
- $head .= $crlf
- . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT='
- . '@@CHARACTER_SET_CLIENT */;' . $crlf
- . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS='
- . '@@CHARACTER_SET_RESULTS */;' . $crlf
- . '/*!40101 SET @OLD_COLLATION_CONNECTION='
- . '@@COLLATION_CONNECTION */;' . $crlf
- . '/*!40101 SET NAMES ' . $setNames . ' */;' . $crlf . $crlf;
- $this->sentCharset = true;
- }
- return $this->export->outputHandler($head);
- }
- /**
- * Outputs CREATE DATABASE statement
- *
- * @param string $db Database name
- * @param string $exportType 'server', 'database', 'table'
- * @param string $dbAlias Aliases of db
- */
- public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
- {
- global $crlf, $dbi;
- if (empty($dbAlias)) {
- $dbAlias = $db;
- }
- if (isset($GLOBALS['sql_compatibility'])) {
- $compat = $GLOBALS['sql_compatibility'];
- } else {
- $compat = 'NONE';
- }
- if (isset($GLOBALS['sql_drop_database'])) {
- if (
- ! $this->export->outputHandler(
- 'DROP DATABASE IF EXISTS '
- . Util::backquoteCompat(
- $dbAlias,
- $compat,
- isset($GLOBALS['sql_backquotes'])
- )
- . ';' . $crlf
- )
- ) {
- return false;
- }
- }
- if ($exportType === 'database' && ! isset($GLOBALS['sql_create_database'])) {
- return true;
- }
- $createQuery = 'CREATE DATABASE IF NOT EXISTS '
- . Util::backquoteCompat($dbAlias, $compat, isset($GLOBALS['sql_backquotes']));
- $collation = $dbi->getDbCollation($db);
- if (mb_strpos($collation, '_')) {
- $createQuery .= ' DEFAULT CHARACTER SET '
- . mb_substr(
- $collation,
- 0,
- (int) mb_strpos($collation, '_')
- )
- . ' COLLATE ' . $collation;
- } else {
- $createQuery .= ' DEFAULT CHARACTER SET ' . $collation;
- }
- $createQuery .= ';' . $crlf;
- if (! $this->export->outputHandler($createQuery)) {
- return false;
- }
- return $this->exportUseStatement($dbAlias, $compat);
- }
- /**
- * Outputs USE statement
- *
- * @param string $db db to use
- * @param string $compat sql compatibility
- */
- private function exportUseStatement($db, $compat): bool
- {
- global $crlf;
- if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] === 'NONE') {
- $result = $this->export->outputHandler(
- 'USE '
- . Util::backquoteCompat(
- $db,
- $compat,
- isset($GLOBALS['sql_backquotes'])
- )
- . ';' . $crlf
- );
- } else {
- $result = $this->export->outputHandler('USE ' . $db . ';' . $crlf);
- }
- return $result;
- }
- /**
- * Outputs database header
- *
- * @param string $db Database name
- * @param string $dbAlias Alias of db
- */
- public function exportDBHeader($db, $dbAlias = ''): bool
- {
- if (empty($dbAlias)) {
- $dbAlias = $db;
- }
- if (isset($GLOBALS['sql_compatibility'])) {
- $compat = $GLOBALS['sql_compatibility'];
- } else {
- $compat = 'NONE';
- }
- $head = $this->exportComment()
- . $this->exportComment(
- __('Database:') . ' '
- . Util::backquoteCompat(
- $dbAlias,
- $compat,
- isset($GLOBALS['sql_backquotes'])
- )
- )
- . $this->exportComment();
- return $this->export->outputHandler($head);
- }
- /**
- * Outputs database footer
- *
- * @param string $db Database name
- */
- public function exportDBFooter($db): bool
- {
- global $crlf;
- $result = true;
- //add indexes to the sql dump file
- if (isset($GLOBALS['sql_indexes'])) {
- $result = $this->export->outputHandler($GLOBALS['sql_indexes']);
- unset($GLOBALS['sql_indexes']);
- }
- //add auto increments to the sql dump file
- if (isset($GLOBALS['sql_auto_increments'])) {
- $result = $this->export->outputHandler($GLOBALS['sql_auto_increments']);
- unset($GLOBALS['sql_auto_increments']);
- }
- //add constraints to the sql dump file
- if (isset($GLOBALS['sql_constraints'])) {
- $result = $this->export->outputHandler($GLOBALS['sql_constraints']);
- unset($GLOBALS['sql_constraints']);
- }
- return $result;
- }
- /**
- * Exports events
- *
- * @param string $db Database
- */
- public function exportEvents($db): bool
- {
- global $crlf, $dbi;
- $text = '';
- $delimiter = '$$';
- $eventNames = $dbi->fetchResult(
- 'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE'
- . " EVENT_SCHEMA= '" . $dbi->escapeString($db)
- . "';"
- );
- if ($eventNames) {
- $text .= $crlf
- . 'DELIMITER ' . $delimiter . $crlf;
- $text .= $this->exportComment()
- . $this->exportComment(__('Events'))
- . $this->exportComment();
- foreach ($eventNames as $eventName) {
- if (! empty($GLOBALS['sql_drop_table'])) {
- $text .= 'DROP EVENT IF EXISTS '
- . Util::backquote($eventName)
- . $delimiter . $crlf;
- }
- $text .= $dbi->getDefinition($db, 'EVENT', $eventName)
- . $delimiter . $crlf . $crlf;
- }
- $text .= 'DELIMITER ;' . $crlf;
- }
- if (! empty($text)) {
- return $this->export->outputHandler($text);
- }
- return false;
- }
- /**
- * Exports metadata from Configuration Storage
- *
- * @param string $db database being exported
- * @param string|array $tables table(s) being exported
- * @param array $metadataTypes types of metadata to export
- */
- public function exportMetadata(
- $db,
- $tables,
- array $metadataTypes
- ): bool {
- $cfgRelation = $this->relation->getRelationsParam();
- if (! isset($cfgRelation['db'])) {
- return true;
- }
- $comment = $this->possibleCRLF()
- . $this->possibleCRLF()
- . $this->exportComment()
- . $this->exportComment(__('Metadata'))
- . $this->exportComment();
- if (! $this->export->outputHandler($comment)) {
- return false;
- }
- if (! $this->exportUseStatement($cfgRelation['db'], $GLOBALS['sql_compatibility'])) {
- return false;
- }
- $r = 1;
- if (is_array($tables)) {
- // export metadata for each table
- foreach ($tables as $table) {
- $r &= (int) $this->exportConfigurationMetadata($db, $table, $metadataTypes);
- }
- // export metadata for the database
- $r &= (int) $this->exportConfigurationMetadata($db, null, $metadataTypes);
- } else {
- // export metadata for single table
- $r &= (int) $this->exportConfigurationMetadata($db, $tables, $metadataTypes);
- }
- return (bool) $r;
- }
- /**
- * Exports metadata from Configuration Storage
- *
- * @param string $db database being exported
- * @param string|null $table table being exported
- * @param array $metadataTypes types of metadata to export
- */
- private function exportConfigurationMetadata(
- $db,
- $table,
- array $metadataTypes
- ): bool {
- global $dbi;
- $cfgRelation = $this->relation->getRelationsParam();
- if (isset($table)) {
- $types = [
- 'column_info' => 'db_name',
- 'table_uiprefs' => 'db_name',
- 'tracking' => 'db_name',
- ];
- } else {
- $types = [
- 'bookmark' => 'dbase',
- 'relation' => 'master_db',
- 'pdf_pages' => 'db_name',
- 'savedsearches' => 'db_name',
- 'central_columns' => 'db_name',
- ];
- }
- $aliases = [];
- $comment = $this->possibleCRLF()
- . $this->exportComment();
- if (isset($table)) {
- $comment .= $this->exportComment(
- sprintf(
- __('Metadata for table %s'),
- $table
- )
- );
- } else {
- $comment .= $this->exportComment(
- sprintf(
- __('Metadata for database %s'),
- $db
- )
- );
- }
- $comment .= $this->exportComment();
- if (! $this->export->outputHandler($comment)) {
- return false;
- }
- foreach ($types as $type => $dbNameColumn) {
- if (! in_array($type, $metadataTypes) || ! isset($cfgRelation[$type])) {
- continue;
- }
- // special case, designer pages and their coordinates
- if ($type === 'pdf_pages') {
- $sqlQuery = 'SELECT `page_nr`, `page_descr` FROM '
- . Util::backquote($cfgRelation['db'])
- . '.' . Util::backquote($cfgRelation[$type])
- . ' WHERE ' . Util::backquote($dbNameColumn)
- . " = '" . $dbi->escapeString($db) . "'";
- $result = $dbi->fetchResult($sqlQuery, 'page_nr', 'page_descr');
- foreach ($result as $page => $name) {
- // insert row for pdf_page
- $sqlQueryRow = 'SELECT `db_name`, `page_descr` FROM '
- . Util::backquote($cfgRelation['db'])
- . '.' . Util::backquote($cfgRelation[$type])
- . ' WHERE ' . Util::backquote($dbNameColumn)
- . " = '" . $dbi->escapeString($db) . "'"
- . " AND `page_nr` = '" . intval($page) . "'";
- if (
- ! $this->exportData(
- $cfgRelation['db'],
- $cfgRelation[$type],
- $GLOBALS['crlf'],
- '',
- $sqlQueryRow,
- $aliases
- )
- ) {
- return false;
- }
- $lastPage = $GLOBALS['crlf']
- . 'SET @LAST_PAGE = LAST_INSERT_ID();'
- . $GLOBALS['crlf'];
- if (! $this->export->outputHandler($lastPage)) {
- return false;
- }
- $sqlQueryCoords = 'SELECT `db_name`, `table_name`, '
- . "'@LAST_PAGE' AS `pdf_page_number`, `x`, `y` FROM "
- . Util::backquote($cfgRelation['db'])
- . '.' . Util::backquote($cfgRelation['table_coords'])
- . " WHERE `pdf_page_number` = '" . $page . "'";
- $GLOBALS['exporting_metadata'] = true;
- if (
- ! $this->exportData(
- $cfgRelation['db'],
- $cfgRelation['table_coords'],
- $GLOBALS['crlf'],
- '',
- $sqlQueryCoords,
- $aliases
- )
- ) {
- $GLOBALS['exporting_metadata'] = false;
- return false;
- }
- $GLOBALS['exporting_metadata'] = false;
- }
- continue;
- }
- // remove auto_incrementing id field for some tables
- if ($type === 'bookmark') {
- $sqlQuery = 'SELECT `dbase`, `user`, `label`, `query` FROM ';
- } elseif ($type === 'column_info') {
- $sqlQuery = 'SELECT `db_name`, `table_name`, `column_name`,'
- . ' `comment`, `mimetype`, `transformation`,'
- . ' `transformation_options`, `input_transformation`,'
- . ' `input_transformation_options` FROM';
- } elseif ($type === 'savedsearches') {
- $sqlQuery = 'SELECT `username`, `db_name`, `search_name`, `search_data` FROM';
- } else {
- $sqlQuery = 'SELECT * FROM ';
- }
- $sqlQuery .= Util::backquote($cfgRelation['db'])
- . '.' . Util::backquote($cfgRelation[$type])
- . ' WHERE ' . Util::backquote($dbNameColumn)
- . " = '" . $dbi->escapeString($db) . "'";
- if (isset($table)) {
- $sqlQuery .= " AND `table_name` = '"
- . $dbi->escapeString($table) . "'";
- }
- if (
- ! $this->exportData(
- $cfgRelation['db'],
- $cfgRelation[$type],
- $GLOBALS['crlf'],
- '',
- $sqlQuery,
- $aliases
- )
- ) {
- return false;
- }
- }
- return true;
- }
- /**
- * Returns a stand-in CREATE definition to resolve view dependencies
- *
- * @param string $db the database name
- * @param string $view the view name
- * @param string $crlf the end of line sequence
- * @param array $aliases Aliases of db/table/columns
- *
- * @return string resulting definition
- */
- public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
- {
- global $dbi;
- $dbAlias = $db;
- $viewAlias = $view;
- $this->initAlias($aliases, $dbAlias, $viewAlias);
- $createQuery = '';
- if (! empty($GLOBALS['sql_drop_table'])) {
- $createQuery .= 'DROP VIEW IF EXISTS '
- . Util::backquote($viewAlias)
- . ';' . $crlf;
- }
- $createQuery .= 'CREATE TABLE ';
- if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
- $createQuery .= 'IF NOT EXISTS ';
- }
- $createQuery .= Util::backquote($viewAlias) . ' (' . $crlf;
- $tmp = [];
- $columns = $dbi->getColumnsFull($db, $view);
- foreach ($columns as $columnName => $definition) {
- $colAlias = $columnName;
- if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
- $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
- }
- $tmp[] = Util::backquote($colAlias) . ' ' .
- $definition['Type'] . $crlf;
- }
- return $createQuery . implode(',', $tmp) . ');' . $crlf;
- }
- /**
- * Returns CREATE definition that matches $view's structure
- *
- * @param string $db the database name
- * @param string $view the view name
- * @param string $crlf the end of line sequence
- * @param bool $addSemicolon whether to add semicolon and end-of-line at
- * the end
- * @param array $aliases Aliases of db/table/columns
- *
- * @return string resulting schema
- */
- private function getTableDefForView(
- $db,
- $view,
- $crlf,
- $addSemicolon = true,
- array $aliases = []
- ) {
- global $dbi;
- $dbAlias = $db;
- $viewAlias = $view;
- $this->initAlias($aliases, $dbAlias, $viewAlias);
- $createQuery = 'CREATE TABLE';
- if (isset($GLOBALS['sql_if_not_exists'])) {
- $createQuery .= ' IF NOT EXISTS ';
- }
- $createQuery .= Util::backquote($viewAlias) . '(' . $crlf;
- $columns = $dbi->getColumns($db, $view, null, true);
- $firstCol = true;
- foreach ($columns as $column) {
- $colAlias = $column['Field'];
- if (! empty($aliases[$db]['tables'][$view]['columns'][$colAlias])) {
- $colAlias = $aliases[$db]['tables'][$view]['columns'][$colAlias];
- }
- $extractedColumnspec = Util::extractColumnSpec($column['Type']);
- if (! $firstCol) {
- $createQuery .= ',' . $crlf;
- }
- $createQuery .= ' ' . Util::backquote($colAlias);
- $createQuery .= ' ' . $column['Type'];
- if ($extractedColumnspec['can_contain_collation'] && ! empty($column['Collation'])) {
- $createQuery .= ' COLLATE ' . $column['Collation'];
- }
- if ($column['Null'] === 'NO') {
- $createQuery .= ' NOT NULL';
- }
- if (isset($column['Default'])) {
- $createQuery .= " DEFAULT '"
- . $dbi->escapeString($column['Default']) . "'";
- } else {
- if ($column['Null'] === 'YES') {
- $createQuery .= ' DEFAULT NULL';
- }
- }
- if (! empty($column['Comment'])) {
- $createQuery .= " COMMENT '"
- . $dbi->escapeString($column['Comment']) . "'";
- }
- $firstCol = false;
- }
- $createQuery .= $crlf . ')' . ($addSemicolon ? ';' : '') . $crlf;
- if (isset($GLOBALS['sql_compatibility'])) {
- $compat = $GLOBALS['sql_compatibility'];
- } else {
- $compat = 'NONE';
- }
- if ($compat === 'MSSQL') {
- $createQuery = $this->makeCreateTableMSSQLCompatible($createQuery);
- }
- return $createQuery;
- }
- /**
- * Returns $table's CREATE definition
- *
- * @param string $db the database name
- * @param string $table the table name
- * @param string $crlf the end of line sequence
- * @param string $errorUrl the url to go back in case
- * of error
- * @param bool $showDates whether to include creation/
- * update/check dates
- * @param bool $addSemicolon whether to add semicolon and
- * end-of-line at the end
- * @param bool $view whether we're handling a view
- * @param bool $updateIndexesIncrements whether we need to update
- * two global variables
- * @param array $aliases Aliases of db/table/columns
- *
- * @return string resulting schema
- */
- public function getTableDef(
- $db,
- $table,
- $crlf,
- $errorUrl,
- $showDates = false,
- $addSemicolon = true,
- $view = false,
- $updateIndexesIncrements = true,
- array $aliases = []
- ) {
- global $sql_drop_table, $sql_backquotes, $sql_constraints,
- $sql_constraints_query, $sql_indexes, $sql_indexes_query,
- $sql_auto_increments, $sql_drop_foreign_keys, $dbi;
- $dbAlias = $db;
- $tableAlias = $table;
- $this->initAlias($aliases, $dbAlias, $tableAlias);
- $schemaCreate = '';
- $autoIncrement = '';
- $newCrlf = $crlf;
- if (isset($GLOBALS['sql_compatibility'])) {
- $compat = $GLOBALS['sql_compatibility'];
- } else {
- $compat = 'NONE';
- }
- // need to use PhpMyAdmin\DatabaseInterface::QUERY_STORE
- // with $dbi->numRows() in mysqli
- $result = $dbi->tryQuery(
- 'SHOW TABLE STATUS FROM ' . Util::backquote($db)
- . ' WHERE Name = \'' . $dbi->escapeString((string) $table) . '\'',
- DatabaseInterface::CONNECT_USER,
- DatabaseInterface::QUERY_STORE
- );
- if ($result != false) {
- if ($dbi->numRows($result) > 0) {
- $tmpres = $dbi->fetchAssoc($result);
- // Here we optionally add the AUTO_INCREMENT next value,
- // but starting with MySQL 5.0.24, the clause is already included
- // in SHOW CREATE TABLE so we'll remove it below
- if (isset($GLOBALS['sql_auto_increment']) && ! empty($tmpres['Auto_increment'])) {
- $autoIncrement .= ' AUTO_INCREMENT='
- . $tmpres['Auto_increment'] . ' ';
- }
- if ($showDates && isset($tmpres['Create_time']) && ! empty($tmpres['Create_time'])) {
- $schemaCreate .= $this->exportComment(
- __('Creation:') . ' '
- . Util::localisedDate(
- strtotime($tmpres['Create_time'])
- )
- );
- $newCrlf = $this->exportComment() . $crlf;
- }
- if ($showDates && isset($tmpres['Update_time']) && ! empty($tmpres['Update_time'])) {
- $schemaCreate .= $this->exportComment(
- __('Last update:') . ' '
- . Util::localisedDate(
- strtotime($tmpres['Update_time'])
- )
- );
- $newCrlf = $this->exportComment() . $crlf;
- }
- if ($showDates && isset($tmpres['Check_time']) && ! empty($tmpres['Check_time'])) {
- $schemaCreate .= $this->exportComment(
- __('Last check:') . ' '
- . Util::localisedDate(
- strtotime($tmpres['Check_time'])
- )
- );
- $newCrlf = $this->exportComment() . $crlf;
- }
- }
- $dbi->freeResult($result);
- }
- $schemaCreate .= $newCrlf;
- if (! empty($sql_drop_table) && $dbi->getTable($db, $table)->isView()) {
- $schemaCreate .= 'DROP VIEW IF EXISTS '
- . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
- . $crlf;
- }
- // no need to generate a DROP VIEW here, it was done earlier
- if (! empty($sql_drop_table) && ! $dbi->getTable($db, $table)->isView()) {
- $schemaCreate .= 'DROP TABLE IF EXISTS '
- . Util::backquoteCompat($tableAlias, 'NONE', $sql_backquotes) . ';'
- . $crlf;
- }
- // Complete table dump,
- // Whether to quote table and column names or not
- if ($sql_backquotes) {
- $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 1');
- } else {
- $dbi->query('SET SQL_QUOTE_SHOW_CREATE = 0');
- }
- // I don't see the reason why this unbuffered query could cause problems,
- // because SHOW CREATE TABLE returns only one row, and we free the
- // results below. Nonetheless, we got 2 user reports about this
- // (see bug 1562533) so I removed the unbuffered mode.
- // $result = $dbi->query('SHOW CREATE TABLE ' . backquote($db)
- // . '.' . backquote($table), null, DatabaseInterface::QUERY_UNBUFFERED);
- //
- // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
- // produce a displayable result for the default value…
Large files files are truncated, but you can click here to view the full file