2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Set of functions used to build SQL dumps of tables
6 * @package phpMyAdmin-Export-SQL
8 if (! defined('PHPMYADMIN')) {
15 if (isset($plugin_list)) {
17 $hide_structure = false;
18 if ($plugin_param['export_type'] == 'table' && !$plugin_param['single_table']) {
19 $hide_structure = true;
23 $plugin_list['sql'] = array(
26 'mime_type' => 'text/x-sql',
27 'options' => array());
29 $plugin_list['sql']['options'][] = array('type' => 'begin_group', 'name' => 'general_opts');
32 $plugin_list['sql']['options'][] =
33 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'bool', 'name' => 'include_comments', 'text' => __('Display comments <i>(includes info such as export timestamp, PHP version, and server version)</i>')));
34 $plugin_list['sql']['options'][] =
35 array('type' => 'text', 'name' => 'header_comment', 'text' => __('Additional custom header comment (\n splits lines):'));
36 $plugin_list['sql']['options'][] =
37 array('type' => 'bool', 'name' => 'dates', 'text' => __('Include a timestamp of when databases were created, last updated, and last checked'));
38 if (!empty($GLOBALS['cfgRelation']['relation'])) {
39 $plugin_list['sql']['options'][] =
40 array('type' => 'bool', 'name' => 'relation', 'text' => __('Display foreign key relationships'));
42 if (!empty($GLOBALS['cfgRelation']['mimework'])) {
43 $plugin_list['sql']['options'][] =
44 array('type' => 'bool', 'name' => 'mime', 'text' => __('Display MIME types'));
46 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
49 /* enclose in a transaction */
50 $plugin_list['sql']['options'][] = array('type' => 'bool', 'name' => 'use_transaction', 'text' => __('Enclose export in a transaction'), 'doc' => array('programs', 'mysqldump', 'option_mysqldump_single-transaction'));
52 /* disable foreign key checks */
53 $plugin_list['sql']['options'][] = array('type' => 'bool', 'name' => 'disable_fk', 'text' => __('Disable foreign key checks'), 'doc' => array('manual_MySQL_Database_Administration', 'server-system-variables', 'sysvar_foreign_key_checks'));
55 $plugin_list['sql']['options_text'] = __('Options');
57 /* compatibility maximization */
58 $compats = PMA_DBI_getCompatibilities();
59 if (count($compats) > 0) {
61 foreach($compats as $val) {
64 $plugin_list['sql']['options'][] =
65 array('type' => 'select', 'name' => 'compatibility', 'text' => __('Database system or older MySQL server to maximize output compatibility with:'), 'values' => $values, 'doc' => array('manual_MySQL_Database_Administration', 'Server_SQL_mode'));
69 /* server export options */
70 if ($plugin_param['export_type'] == 'server') {
71 $plugin_list['sql']['options'][] =
72 array('type' => 'bool', 'name' => 'drop_database', 'text' => sprintf(__('Add %s statement'), '<code>DROP DATABASE</code>'));
75 /* what to dump (structure/data/both) */
76 $plugin_list['sql']['options'][] =
77 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'message_only', 'text' => __('Dump table')));
78 $plugin_list['sql']['options'][] =
79 array('type' => 'radio', 'name' => 'structure_or_data', 'values' => array('structure' => __('structure'), 'data' => __('data'), 'structure_and_data' => __('structure and data')));
80 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
82 $plugin_list['sql']['options'][] = array('type' => 'end_group');
84 /* begin Structure options */
85 if (!$hide_structure) {
86 $plugin_list['sql']['options'][] =
87 array('type' => 'begin_group', 'name' => 'structure', 'text' => __('Object creation options'), 'force' => 'data');
89 /* begin SQL Statements */
90 $plugin_list['sql']['options'][] =
91 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'message_only', 'name' => 'add_statements', 'text' => __('Add statements:')));
92 if ($plugin_param['export_type'] == 'table') {
93 if (PMA_Table
::isView($GLOBALS['db'], $GLOBALS['table'])) {
94 $drop_clause = '<code>DROP VIEW</code>';
96 $drop_clause = '<code>DROP TABLE</code>';
99 $drop_clause = '<code>DROP TABLE / VIEW / PROCEDURE / FUNCTION</code>';
100 if (PMA_MYSQL_INT_VERSION
> 50100) {
101 $drop_clause .= '<code> / EVENT</code>';
104 $plugin_list['sql']['options'][] =
105 array('type' => 'bool', 'name' => 'drop_table', 'text' => sprintf(__('Add %s statement'), $drop_clause));
106 $plugin_list['sql']['options'][] =
107 array('type' => 'bool', 'name' => 'procedure_function', 'text' => sprintf(__('Add %s statement'), '<code>CREATE PROCEDURE / FUNCTION' . (PMA_MYSQL_INT_VERSION
> 50100 ?
' / EVENT</code>' : '</code>')));
109 /* begin CREATE TABLE statements*/
110 $plugin_list['sql']['options'][] =
111 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'bool', 'name' => 'create_table_statements', 'text' => __('<code>CREATE TABLE</code> options:')));
112 $plugin_list['sql']['options'][] =
113 array('type' => 'bool', 'name' => 'if_not_exists', 'text' => '<code>IF NOT EXISTS</code>');
114 $plugin_list['sql']['options'][] =
115 array('type' => 'bool', 'name' => 'auto_increment', 'text' => '<code>AUTO_INCREMENT</code>');
116 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
117 /* end CREATE TABLE statements */
119 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
120 /* end SQL statements */
122 $plugin_list['sql']['options'][] =
123 array('type' => 'bool', 'name' => 'backquotes', 'text' => __('Enclose table and field names with backquotes <i>(Protects field and table names formed with special characters or keywords)</i>'));
125 $plugin_list['sql']['options'][] =
126 array('type' => 'end_group');
128 /* end Structure options */
130 /* begin Data options */
131 $plugin_list['sql']['options'][] =
132 array('type' => 'begin_group', 'name' => 'data', 'text' => __('Data dump options'), 'force' => 'structure');
134 /* begin SQL statements */
135 $plugin_list['sql']['options'][] =
136 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'message_only', 'text' => __('Instead of <code>INSERT</code> statements, use:')));
137 $plugin_list['sql']['options'][] =
138 array('type' => 'bool', 'name' => 'delayed', 'text' => __('<code>INSERT DELAYED</code> statements'), 'doc' => array('manual_MySQL_Database_Administration', 'insert_delayed'));
139 $plugin_list['sql']['options'][] =
140 array('type' => 'bool', 'name' => 'ignore', 'text' => __('<code>INSERT IGNORE</code> statements'), 'doc' => array('manual_MySQL_Database_Administration', 'insert'));
141 $plugin_list['sql']['options'][] =
142 array('type' => 'end_subgroup');
143 /* end SQL statements */
145 /* Function to use when dumping data */
146 $plugin_list['sql']['options'][] =
147 array('type' => 'select', 'name' => 'type', 'text' => __('Function to use when dumping data:'), 'values' => array('INSERT' => 'INSERT', 'UPDATE' => 'UPDATE', 'REPLACE' => 'REPLACE'));
149 /* Syntax to use when inserting data */
150 $plugin_list['sql']['options'][] =
151 array('type' => 'begin_subgroup', 'subgroup_header' => array('type' => 'message_only', 'text' => __('Syntax to use when inserting data:')));
152 $plugin_list['sql']['options'][] =
153 array('type' => 'radio', 'name' => 'insert_syntax', 'values' => array(
154 '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>'),
155 '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>'),
156 'both' => __('both of the above<br /> Example: <code>INSERT INTO tbl_name (col_A,col_B) VALUES (1,2,3), (4,5,6), (7,8,9)</code>'),
157 'none' => __('neither of the above<br /> Example: <code>INSERT INTO tbl_name VALUES (1,2,3)</code>')));
158 $plugin_list['sql']['options'][] =
159 array('type' => 'end_subgroup');
161 /* Max length of query */
162 $plugin_list['sql']['options'][] =
163 array('type' => 'text', 'name' => 'max_query_size', 'text' => __('Maximal length of created query'));
165 /* Dump binary columns in hexadecimal */
166 $plugin_list['sql']['options'][] =
167 array('type' => 'bool', 'name' => 'hex_for_blob', 'text' => __('Dump binary columns in hexadecimal notation <i>(for example, "abc" becomes 0x616263)</i>'));
169 /* Dump time in UTC */
170 $plugin_list['sql']['options'][] =
171 array('type' => 'bool', 'name' => 'utc_time', 'text' => __('Dump TIMESTAMP columns in UTC <i>(enables TIMESTAMP columns to be dumped and reloaded between servers in different time zones)</i>'));
173 $plugin_list['sql']['options'][] = array('type' => 'end_group');
174 /* end Data options */
179 * Avoids undefined variables, use NULL so isset() returns false
181 if (! isset($sql_backquotes)) {
182 $sql_backquotes = null;
186 * Possibly outputs comment
188 * @param string Text of comment
190 * @return string The formatted comment
192 function PMA_exportComment($text = '')
194 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
195 // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
196 return '--' . (empty($text) ?
'' : ' ') . $text . $GLOBALS['crlf'];
203 * Possibly outputs CRLF
205 * @return string $crlf or nothing
207 function PMA_possibleCRLF()
210 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
211 return $GLOBALS['crlf'];
218 * Outputs export footer
220 * @return bool Whether it suceeded
224 function PMA_exportFooter()
227 global $mysql_charset_map;
231 if (isset($GLOBALS['sql_disable_fk'])) {
232 $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
235 if (isset($GLOBALS['sql_use_transaction'])) {
236 $foot .= 'COMMIT;' . $crlf;
239 // restore connection settings
240 $charset_of_file = isset($GLOBALS['charset_of_file']) ?
$GLOBALS['charset_of_file'] : '';
241 if (!empty($GLOBALS['asfile']) && isset($mysql_charset_map[$charset_of_file])) {
243 . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' . $crlf
244 . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' . $crlf
245 . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' . $crlf;
248 /* Restore timezone */
249 if ($GLOBALS['sql_utc_time']) {
250 PMA_DBI_query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
253 return PMA_exportOutputHandler($foot);
257 * Outputs export header
259 * @return bool Whether it suceeded
263 function PMA_exportHeader()
267 global $mysql_charset_map;
269 if (isset($GLOBALS['sql_compatibility'])) {
270 $tmp_compat = $GLOBALS['sql_compatibility'];
271 if ($tmp_compat == 'NONE') {
274 PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"');
277 $head = PMA_exportComment('phpMyAdmin SQL Dump')
278 . PMA_exportComment('version ' . PMA_VERSION
)
279 . PMA_exportComment('http://www.phpmyadmin.net')
280 . PMA_exportComment();
281 $head .= empty($cfg['Server']['port']) ?
PMA_exportComment(__('Host') . ': ' . $cfg['Server']['host']) : PMA_exportComment(__('Host') . ': ' . $cfg['Server']['host'] . ':' . $cfg['Server']['port']);
282 $head .= PMA_exportComment(__('Generation Time')
283 . ': ' . PMA_localisedDate())
284 . PMA_exportComment(__('Server version') . ': ' . substr(PMA_MYSQL_INT_VERSION
, 0, 1) . '.' . (int) substr(PMA_MYSQL_INT_VERSION
, 1, 2) . '.' . (int) substr(PMA_MYSQL_INT_VERSION
, 3))
285 . PMA_exportComment(__('PHP Version') . ': ' . phpversion())
286 . PMA_possibleCRLF();
288 if (isset($GLOBALS['sql_header_comment']) && !empty($GLOBALS['sql_header_comment'])) {
289 // '\n' is not a newline (like "\n" would be), it's the characters
290 // backslash and n, as explained on the export interface
291 $lines = explode('\n', $GLOBALS['sql_header_comment']);
292 $head .= PMA_exportComment();
293 foreach($lines as $one_line) {
294 $head .= PMA_exportComment($one_line);
296 $head .= PMA_exportComment();
299 if (isset($GLOBALS['sql_disable_fk'])) {
300 $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
303 /* We want exported AUTO_INCREMENT fields to have still same value, do this only for recent MySQL exports */
304 if (!isset($GLOBALS['sql_compatibility']) ||
$GLOBALS['sql_compatibility'] == 'NONE') {
305 $head .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . $crlf;
308 if (isset($GLOBALS['sql_use_transaction'])) {
309 $head .= 'SET AUTOCOMMIT=0;' . $crlf
310 . 'START TRANSACTION;' . $crlf;
314 /* Change timezone if we should export timestamps in UTC */
315 if ($GLOBALS['sql_utc_time']) {
316 $head .= 'SET time_zone = "+00:00";' . $crlf;
317 $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone');
318 PMA_DBI_query('SET time_zone = "+00:00"');
321 $head .= PMA_possibleCRLF();
323 if (! empty($GLOBALS['asfile'])) {
324 // we are saving as file, therefore we provide charset information
325 // so that a utility like the mysql client can interpret
326 // the file correctly
327 if (isset($GLOBALS['charset_of_file']) && isset($mysql_charset_map[$GLOBALS['charset_of_file']])) {
328 // we got a charset from the export dialog
329 $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']];
331 // by default we use the connection charset
332 $set_names = $mysql_charset_map[$GLOBALS['charset']];
335 . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . $crlf
336 . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . $crlf
337 . '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;' . $crlf
338 . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf;
341 return PMA_exportOutputHandler($head);
345 * Outputs CREATE DATABASE database
347 * @param string Database name
349 * @return bool Whether it suceeded
353 function PMA_exportDBCreate($db)
356 if (isset($GLOBALS['sql_drop_database'])) {
357 if (!PMA_exportOutputHandler('DROP DATABASE ' . (isset($GLOBALS['sql_backquotes']) ?
PMA_backquote($db) : $db) . ';' . $crlf)) {
361 $create_query = 'CREATE DATABASE ' . (isset($GLOBALS['sql_backquotes']) ?
PMA_backquote($db) : $db);
362 $collation = PMA_getDbCollation($db);
363 if (strpos($collation, '_')) {
364 $create_query .= ' DEFAULT CHARACTER SET ' . substr($collation, 0, strpos($collation, '_')) . ' COLLATE ' . $collation;
366 $create_query .= ' DEFAULT CHARACTER SET ' . $collation;
368 $create_query .= ';' . $crlf;
369 if (!PMA_exportOutputHandler($create_query)) {
372 if (isset($GLOBALS['sql_backquotes']) && isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'NONE') {
373 return PMA_exportOutputHandler('USE ' . PMA_backquote($db) . ';' . $crlf);
375 return PMA_exportOutputHandler('USE ' . $db . ';' . $crlf);
379 * Outputs database header
381 * @param string Database name
383 * @return bool Whether it suceeded
387 function PMA_exportDBHeader($db)
389 $head = PMA_exportComment()
390 . PMA_exportComment(__('Database') . ': ' . (isset($GLOBALS['sql_backquotes']) ?
PMA_backquote($db) : '\'' . $db . '\''))
391 . PMA_exportComment();
392 return PMA_exportOutputHandler($head);
396 * Outputs database footer
398 * @param string Database name
400 * @return bool Whether it suceeded
404 function PMA_exportDBFooter($db)
409 if (isset($GLOBALS['sql_constraints'])) {
410 $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']);
411 unset($GLOBALS['sql_constraints']);
414 if (($GLOBALS['sql_structure_or_data'] == 'structure' ||
$GLOBALS['sql_structure_or_data'] == 'structure_and_data') && isset($GLOBALS['sql_procedure_function'])) {
418 $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE');
419 $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION');
421 if (PMA_MYSQL_INT_VERSION
> 50100) {
422 $event_names = PMA_DBI_fetch_result('SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \'' . PMA_sqlAddslashes($db,true) . '\';');
424 $event_names = array();
427 if ($procedure_names ||
$function_names ||
$event_names) {
429 . 'DELIMITER ' . $delimiter . $crlf;
432 if ($procedure_names) {
435 . PMA_exportComment(__('Procedures'))
436 . PMA_exportComment();
438 foreach($procedure_names as $procedure_name) {
439 if (! empty($GLOBALS['sql_drop_table'])) {
440 $text .= 'DROP PROCEDURE IF EXISTS ' . PMA_backquote($procedure_name) . $delimiter . $crlf;
442 $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name) . $delimiter . $crlf . $crlf;
446 if ($function_names) {
449 . PMA_exportComment(__('Functions'))
450 . PMA_exportComment();
452 foreach($function_names as $function_name) {
453 if (! empty($GLOBALS['sql_drop_table'])) {
454 $text .= 'DROP FUNCTION IF EXISTS ' . PMA_backquote($function_name) . $delimiter . $crlf;
456 $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name) . $delimiter . $crlf . $crlf;
463 . PMA_exportComment(__('Events'))
464 . PMA_exportComment();
466 foreach($event_names as $event_name) {
467 if (! empty($GLOBALS['sql_drop_table'])) {
468 $text .= 'DROP EVENT ' . PMA_backquote($event_name) . $delimiter . $crlf;
470 $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) . $delimiter . $crlf . $crlf;
473 if ($procedure_names ||
$function_names ||
$event_names) {
474 $text .= 'DELIMITER ;' . $crlf;
477 if (! empty($text)) {
478 $result = PMA_exportOutputHandler($text);
486 * Returns a stand-in CREATE definition to resolve view dependencies
488 * @param string the database name
489 * @param string the vew name
490 * @param string the end of line sequence
492 * @return string resulting definition
496 function PMA_getTableDefStandIn($db, $view, $crlf) {
498 if (! empty($GLOBALS['sql_drop_table'])) {
499 $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) . ';' . $crlf;
502 $create_query .= 'CREATE TABLE ';
504 if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
505 $create_query .= 'IF NOT EXISTS ';
507 $create_query .= PMA_backquote($view) . ' (' . $crlf;
509 $columns = PMA_DBI_get_columns_full($db, $view);
510 foreach($columns as $column_name => $definition) {
511 $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf;
513 $create_query .= implode(',', $tmp) . ');';
514 return($create_query);
518 * Returns $table's CREATE definition
520 * @param string the database name
521 * @param string the table name
522 * @param string the end of line sequence
523 * @param string the url to go back in case of error
524 * @param boolean whether to include creation/update/check dates
525 * @param boolean whether to add semicolon and end-of-line at the end
526 * @param boolean whether we're handling view
528 * @return string resulting schema
530 * @global boolean whether to add 'drop' statements or not
531 * @global boolean whether to use backquotes to allow the use of special
532 * characters in database, table and fields names or not
536 function PMA_getTableDef($db, $table, $crlf, $error_url, $show_dates = false, $add_semicolon = true, $view = false)
538 global $sql_drop_table;
539 global $sql_backquotes;
541 global $sql_constraints;
542 global $sql_constraints_query; // just the text of the query
543 global $sql_drop_foreign_keys;
546 $auto_increment = '';
549 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
550 $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table) . '\'', null, PMA_DBI_QUERY_STORE
);
551 if ($result != FALSE) {
552 if (PMA_DBI_num_rows($result) > 0) {
553 $tmpres = PMA_DBI_fetch_assoc($result);
554 // Here we optionally add the AUTO_INCREMENT next value,
555 // but starting with MySQL 5.0.24, the clause is already included
556 // in SHOW CREATE TABLE so we'll remove it below
557 if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
558 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
561 if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
562 $schema_create .= PMA_exportComment(__('Creation') . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])));
563 $new_crlf = PMA_exportComment() . $crlf;
566 if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
567 $schema_create .= PMA_exportComment(__('Last update') . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])));
568 $new_crlf = PMA_exportComment() . $crlf;
571 if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
572 $schema_create .= PMA_exportComment(__('Last check') . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])));
573 $new_crlf = PMA_exportComment() . $crlf;
576 PMA_DBI_free_result($result);
579 $schema_create .= $new_crlf;
581 // no need to generate a DROP VIEW here, it was done earlier
582 if (! empty($sql_drop_table) && ! PMA_Table
::isView($db,$table)) {
583 $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table, $sql_backquotes) . ';' . $crlf;
586 // Complete table dump,
587 // Whether to quote table and fields names or not
588 if ($sql_backquotes) {
589 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
591 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
594 // I don't see the reason why this unbuffered query could cause problems,
595 // because SHOW CREATE TABLE returns only one row, and we free the
596 // results below. Nonetheless, we got 2 user reports about this
597 // (see bug 1562533) so I remove the unbuffered mode.
598 //$result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED);
600 // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
601 // produce a displayable result for the default value of a BIT
602 // field, nor does the mysqldump command. See MySQL bug 35796
603 $result = PMA_DBI_try_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table));
604 // an error can happen, for example the table is crashed
605 $tmp_error = PMA_DBI_getError();
607 return PMA_exportComment(__('in use') . '(' . $tmp_error . ')');
610 if ($result != FALSE && ($row = PMA_DBI_fetch_row($result))) {
611 $create_query = $row[1];
614 // Convert end of line chars to one that we want (note that MySQL doesn't return query it will accept in all cases)
615 if (strpos($create_query, "(\r\n ")) {
616 $create_query = str_replace("\r\n", $crlf, $create_query);
617 } elseif (strpos($create_query, "(\n ")) {
618 $create_query = str_replace("\n", $crlf, $create_query);
619 } elseif (strpos($create_query, "(\r ")) {
620 $create_query = str_replace("\r", $crlf, $create_query);
624 * Drop database name from VIEW creation.
626 * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
627 * database name, but we don't want name to show up in CREATE VIEW
631 $create_query = preg_replace('/' . PMA_backquote($db) . '\./', '', $create_query);
634 // Should we use IF NOT EXISTS?
635 if (isset($GLOBALS['sql_if_not_exists'])) {
636 $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
639 // are there any constraints to cut out?
640 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
642 // Split the query into lines, so we can easily handle it. We know lines are separated by $crlf (done few lines above).
643 $sql_lines = explode($crlf, $create_query);
644 $sql_count = count($sql_lines);
646 // lets find first line with constraints
647 for ($i = 0; $i < $sql_count; $i++
) {
648 if (preg_match('@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', $sql_lines[$i])) {
653 // If we really found a constraint
654 if ($i != $sql_count) {
656 // remove , from the end of create statement
657 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
659 // prepare variable for constraints
660 if (!isset($sql_constraints)) {
661 if (isset($GLOBALS['no_constraints_comments'])) {
662 $sql_constraints = '';
664 $sql_constraints = $crlf
665 . PMA_exportComment()
666 . PMA_exportComment(__('Constraints for dumped tables'))
667 . PMA_exportComment();
671 // comments for current table
672 if (!isset($GLOBALS['no_constraints_comments'])) {
673 $sql_constraints .= $crlf
674 . PMA_exportComment()
675 . PMA_exportComment(__('Constraints for table') . ' ' . PMA_backquote($table))
676 . PMA_exportComment();
680 $sql_constraints_query .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
681 $sql_constraints .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
682 $sql_drop_foreign_keys .= 'ALTER TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $crlf;
685 for ($j = $i; $j < $sql_count; $j++
) {
686 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $sql_lines[$j])) {
688 $sql_constraints .= $crlf;
690 if (strpos($sql_lines[$j], 'CONSTRAINT') === FALSE) {
691 $tmp_str = preg_replace('/(FOREIGN[\s]+KEY)/', 'ADD \1', $sql_lines[$j]);
692 $sql_constraints_query .= $tmp_str;
693 $sql_constraints .= $tmp_str;
695 $tmp_str = preg_replace('/(CONSTRAINT)/', 'ADD \1', $sql_lines[$j]);
696 $sql_constraints_query .= $tmp_str;
697 $sql_constraints .= $tmp_str;
698 preg_match('/(CONSTRAINT)([\s])([\S]*)([\s])/', $sql_lines[$j], $matches);
700 $sql_drop_foreign_keys .= ', ';
702 $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' . $matches[3];
709 $sql_constraints .= ';' . $crlf;
710 $sql_constraints_query .= ';';
712 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
716 $schema_create .= $create_query;
719 // remove a possible "AUTO_INCREMENT = value" clause
720 // that could be there starting with MySQL 5.0.24
721 $schema_create = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $schema_create);
723 $schema_create .= $auto_increment;
725 PMA_DBI_free_result($result);
726 return $schema_create . ($add_semicolon ?
';' . $crlf : '');
727 } // end of the 'PMA_getTableDef()' function
731 * Returns $table's comments, relations etc.
733 * @param string the database name
734 * @param string the table name
735 * @param string the end of line sequence
736 * @param boolean whether to include relation comments
737 * @param boolean whether to include mime comments
739 * @return string resulting comments
743 function PMA_getTableComments($db, $table, $crlf, $do_relation = false, $do_mime = false)
746 global $sql_backquotes;
747 global $sql_constraints;
751 // Check if we can use Relations (Mike Beck)
752 if ($do_relation && !empty($cfgRelation['relation'])) {
753 // Find which tables are related with the current one and write it in
755 $res_rel = PMA_getForeigners($db, $table);
757 if ($res_rel && count($res_rel) > 0) {
766 if ($do_mime && $cfgRelation['mimework']) {
767 if (!($mime_map = PMA_getMIME($db, $table, true))) {
772 if (isset($mime_map) && count($mime_map) > 0) {
773 $schema_create .= PMA_possibleCRLF()
774 . PMA_exportComment()
775 . PMA_exportComment(__('MIME TYPES FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
777 foreach ($mime_map AS $mime_field => $mime) {
778 $schema_create .= PMA_exportComment(' ' . PMA_backquote($mime_field, $sql_backquotes))
779 . PMA_exportComment(' ' . PMA_backquote($mime['mimetype'], $sql_backquotes));
781 $schema_create .= PMA_exportComment();
785 $schema_create .= PMA_possibleCRLF()
786 . PMA_exportComment()
787 . PMA_exportComment(__('RELATIONS FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
788 foreach ($res_rel AS $rel_field => $rel) {
789 $schema_create .= PMA_exportComment(' ' . PMA_backquote($rel_field, $sql_backquotes))
790 . PMA_exportComment(' ' . PMA_backquote($rel['foreign_table'], $sql_backquotes)
791 . ' -> ' . PMA_backquote($rel['foreign_field'], $sql_backquotes));
793 $schema_create .= PMA_exportComment();
796 return $schema_create;
798 } // end of the 'PMA_getTableComments()' function
801 * Outputs table's structure
803 * @param string the database name
804 * @param string the table name
805 * @param string the end of line sequence
806 * @param string the url to go back in case of error
807 * @param boolean whether to include relation comments
808 * @param boolean whether to include the pmadb-style column comments
809 * as comments in the structure; this is deprecated
810 * but the parameter is left here because export.php
811 * calls PMA_exportStructure() also for other export
812 * types which use this parameter
813 * @param boolean whether to include mime comments
814 * @param string 'stand_in', 'create_table', 'create_view'
815 * @param string 'server', 'database', 'table'
817 * @return bool Whether it suceeded
821 function PMA_exportStructure($db, $table, $crlf, $error_url, $relation = FALSE, $comments = FALSE, $mime = FALSE, $dates = FALSE, $export_mode, $export_type)
823 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
824 ?
PMA_backquote($table)
825 : '\'' . $table . '\'';
826 $dump = PMA_possibleCRLF()
827 . PMA_exportComment(str_repeat('-', 56))
829 . PMA_exportComment();
831 switch($export_mode) {
833 $dump .= PMA_exportComment(__('Table structure for table') . ' ' . $formatted_table_name)
834 . PMA_exportComment();
835 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates);
836 $dump .= PMA_getTableComments($db, $table, $crlf, $relation, $mime);
840 $triggers = PMA_DBI_get_triggers($db, $table);
842 $dump .= PMA_possibleCRLF()
843 . PMA_exportComment()
844 . PMA_exportComment(__('Triggers') . ' ' . $formatted_table_name)
845 . PMA_exportComment();
847 foreach ($triggers as $trigger) {
848 $dump .= $trigger['drop'] . ';' . $crlf;
849 $dump .= 'DELIMITER ' . $delimiter . $crlf;
850 $dump .= $trigger['create'];
851 $dump .= 'DELIMITER ;' . $crlf;
856 $dump .= PMA_exportComment(__('Structure for view') . ' ' . $formatted_table_name)
857 . PMA_exportComment();
858 // delete the stand-in table previously created (if any)
859 if ($export_type != 'table') {
860 $dump .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table) . ';' . $crlf;
862 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates, true, true);
865 $dump .= PMA_exportComment(__('Stand-in structure for view') . ' ' . $formatted_table_name)
866 . PMA_exportComment();
867 // export a stand-in definition to resolve view dependencies
868 $dump .= PMA_getTableDefStandIn($db, $table, $crlf);
871 // this one is built by PMA_getTableDef() to use in table copy/move
872 // but not in the case of export
873 unset($GLOBALS['sql_constraints_query']);
875 return PMA_exportOutputHandler($dump);
879 * Dispatches between the versions of 'getTableContent' to use depending
882 * @param string the database name
883 * @param string the table name
884 * @param string the end of line sequence
885 * @param string the url to go back in case of error
886 * @param string SQL query for obtaining data
888 * @return bool Whether it suceeded
890 * @global boolean whether to use backquotes to allow the use of special
891 * characters in database, table and fields names or not
892 * @global integer the number of records
893 * @global integer the current record position
897 * @see PMA_getTableContentFast(), PMA_getTableContentOld()
900 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
902 global $sql_backquotes;
906 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
907 ?
PMA_backquote($table)
908 : '\'' . $table . '\'';
910 // Do not export data for a VIEW
911 // (For a VIEW, this is called only when exporting a single VIEW)
912 if (PMA_Table
::isView($db, $table)) {
913 $head = PMA_possibleCRLF()
914 . PMA_exportComment()
915 . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name)
916 . PMA_exportComment(__('Data') . ': ' . __('None'))
917 . PMA_exportComment()
918 . PMA_possibleCRLF();
920 if (! PMA_exportOutputHandler($head)) {
927 $head = PMA_possibleCRLF()
928 . PMA_exportComment()
929 . PMA_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name)
930 . PMA_exportComment();
932 if (! PMA_exportOutputHandler($head)) {
938 // analyze the query to get the true column names, not the aliases
939 // (this fixes an undefined index, also if Complete inserts
940 // are used, we did not get the true column name in case of aliases)
941 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
943 $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED
);
944 // a possible error: the table has crashed
945 $tmp_error = PMA_DBI_getError();
947 return PMA_exportOutputHandler(PMA_exportComment(__('in use') . ' (' . $tmp_error . ')'));
950 if ($result != FALSE) {
951 // emit a single CRLF before the first data statement (produces
952 // an unintended CRLF when there is no data, but I don't see how it
953 // can be avoided, as we are in UNBUFFERED mode)
954 if (! PMA_exportOutputHandler($crlf)) {
958 $fields_cnt = PMA_DBI_num_fields($result);
960 // Get field information
961 $fields_meta = PMA_DBI_get_fields_meta($result);
962 $field_flags = array();
963 for ($j = 0; $j < $fields_cnt; $j++
) {
964 $field_flags[$j] = PMA_DBI_field_flags($result, $j);
967 for ($j = 0; $j < $fields_cnt; $j++
) {
968 if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
969 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
971 $field_set[$j] = PMA_backquote($fields_meta[$j]->name
, $sql_backquotes);
975 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
977 $schema_insert = 'UPDATE ';
978 if (isset($GLOBALS['sql_ignore'])) {
979 $schema_insert .= 'IGNORE ';
982 $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
985 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
986 $sql_command = 'REPLACE';
988 $sql_command = 'INSERT';
992 if (isset($GLOBALS['sql_delayed'])) {
993 $insert_delayed = ' DELAYED';
995 $insert_delayed = '';
999 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
1000 $insert_delayed .= ' IGNORE';
1003 // scheme for inserting fields
1004 if ($GLOBALS['sql_insert_syntax'] == 'complete' ||
$GLOBALS['sql_insert_syntax'] == 'both') {
1005 $fields = implode(', ', $field_set);
1006 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1008 . ' (' . $fields . ') VALUES';
1010 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1015 $search = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
1016 $replace = array('\0', '\n', '\r', '\Z');
1019 if (($GLOBALS['sql_insert_syntax'] == 'extended' ||
$GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) ||
$GLOBALS['sql_type'] != 'UPDATE')) {
1021 $schema_insert .= $crlf;
1026 while ($row = PMA_DBI_fetch_row($result)) {
1028 for ($j = 0; $j < $fields_cnt; $j++
) {
1030 if (!isset($row[$j]) ||
is_null($row[$j])) {
1033 // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
1034 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type
!= 'timestamp'
1035 && ! $fields_meta[$j]->blob
) {
1036 $values[] = $row[$j];
1038 // - mysqldump only generates hex data when the --hex-blob
1039 // option is used, for fields having the binary attribute
1040 // no hex is generated
1041 // - a TEXT field returns type blob but a real blob
1042 // returns also the 'binary' flag
1043 } elseif (stristr($field_flags[$j], 'BINARY')
1044 && $fields_meta[$j]->blob
1045 && isset($GLOBALS['sql_hex_for_blob'])) {
1046 // empty blobs need to be different, but '0' is also empty :-(
1047 if (empty($row[$j]) && $row[$j] != '0') {
1050 $values[] = '0x' . bin2hex($row[$j]);
1052 // detection of 'bit' works only on mysqli extension
1053 } elseif ($fields_meta[$j]->type
== 'bit') {
1054 $values[] = "b'" . PMA_sqlAddslashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length
)) . "'";
1055 // something else -> treat as a string
1057 $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
1061 // should we make update?
1062 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
1064 $insert_line = $schema_insert;
1065 for ($i = 0; $i < $fields_cnt; $i++
) {
1067 $insert_line .= ' ';
1071 $insert_line .= ',';
1073 $insert_line .= $field_set[$i] . ' = ' . $values[$i];
1076 list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
1077 $insert_line .= ' WHERE ' . $tmp_unique_condition;
1078 unset($tmp_unique_condition, $tmp_clause_is_unique);
1082 // Extended inserts case
1083 if ($GLOBALS['sql_insert_syntax'] == 'extended' ||
$GLOBALS['sql_insert_syntax'] == 'both') {
1084 if ($current_row == 1) {
1085 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1087 $insert_line = '(' . implode(', ', $values) . ')';
1088 if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size +
strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
1089 if (!PMA_exportOutputHandler(';' . $crlf)) {
1094 $insert_line = $schema_insert . $insert_line;
1097 $query_size +
= strlen($insert_line);
1099 // Other inserts case
1101 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1106 if (!PMA_exportOutputHandler(($current_row == 1 ?
'' : $separator . $crlf) . $insert_line)) {
1111 if ($current_row > 0) {
1112 if (!PMA_exportOutputHandler(';' . $crlf)) {
1116 } // end if ($result != FALSE)
1117 PMA_DBI_free_result($result);
1120 } // end of the 'PMA_exportData()' function