Hindi translation update
[phpmyadmin-regexreplace.git] / libraries / export / sql.php
blobacfdf11f834c262fc9d1f91fd47e9c39cfe790b1
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Set of functions used to build SQL dumps of tables
6 * @package phpMyAdmin-Export-SQL
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
15 if (isset($plugin_list)) {
16 $hide_sql = false;
17 $hide_structure = false;
18 if ($plugin_param['export_type'] == 'table' && !$plugin_param['single_table']) {
19 $hide_structure = true;
20 $hide_sql = true;
22 if (!$hide_sql) {
23 $plugin_list['sql'] = array(
24 'text' => __('SQL'),
25 'extension' => 'sql',
26 'mime_type' => 'text/x-sql',
27 'options' => array());
29 $plugin_list['sql']['options'][] = array('type' => 'begin_group', 'name' => 'general_opts');
31 /* comments */
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');
47 /* end comments */
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) {
60 $values = array();
61 foreach($compats as $val) {
62 $values[$val] = $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'));
66 unset($values);
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>';
95 } else {
96 $drop_clause = '<code>DROP TABLE</code>';
98 } else {
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 /> &nbsp; &nbsp; &nbsp; 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 /> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO tbl_name VALUES (1,2,3), (4,5,6), (7,8,9)</code>'),
156 'both' => __('both of the above<br /> &nbsp; &nbsp; &nbsp; 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 /> &nbsp; &nbsp; &nbsp; 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 */
176 } else {
179 * Avoids undefined variables, use NULL so isset() returns false
181 if (! isset($sql_backquotes)) {
182 $sql_backquotes = null;
186 * Exports routines (procedures and functions)
188 * @param string $db
190 * @return bool Whether it suceeded
192 function PMA_exportRoutines($db) {
193 global $crlf;
195 $text = '';
196 $delimiter = '$$';
198 $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE');
199 $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION');
201 if ($procedure_names || $function_names) {
202 $text .= $crlf
203 . 'DELIMITER ' . $delimiter . $crlf;
206 if ($procedure_names) {
207 $text .=
208 PMA_exportComment()
209 . PMA_exportComment(__('Procedures'))
210 . PMA_exportComment();
212 foreach($procedure_names as $procedure_name) {
213 if (! empty($GLOBALS['sql_drop_table'])) {
214 $text .= 'DROP PROCEDURE IF EXISTS ' . PMA_backquote($procedure_name) . $delimiter . $crlf;
216 $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name) . $delimiter . $crlf . $crlf;
220 if ($function_names) {
221 $text .=
222 PMA_exportComment()
223 . PMA_exportComment(__('Functions'))
224 . PMA_exportComment();
226 foreach($function_names as $function_name) {
227 if (! empty($GLOBALS['sql_drop_table'])) {
228 $text .= 'DROP FUNCTION IF EXISTS ' . PMA_backquote($function_name) . $delimiter . $crlf;
230 $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name) . $delimiter . $crlf . $crlf;
234 if ($procedure_names || $function_names) {
235 $text .= 'DELIMITER ;' . $crlf;
238 if (! empty($text)) {
239 return PMA_exportOutputHandler($text);
240 } else {
241 return false;
246 * Possibly outputs comment
248 * @param string Text of comment
250 * @return string The formatted comment
252 function PMA_exportComment($text = '')
254 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
255 // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
256 return '--' . (empty($text) ? '' : ' ') . $text . $GLOBALS['crlf'];
257 } else {
258 return '';
263 * Possibly outputs CRLF
265 * @return string $crlf or nothing
267 function PMA_possibleCRLF()
270 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
271 return $GLOBALS['crlf'];
272 } else {
273 return '';
278 * Outputs export footer
280 * @return bool Whether it suceeded
282 * @access public
284 function PMA_exportFooter()
286 global $crlf;
287 global $mysql_charset_map;
289 $foot = '';
291 if (isset($GLOBALS['sql_disable_fk'])) {
292 $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
295 if (isset($GLOBALS['sql_use_transaction'])) {
296 $foot .= 'COMMIT;' . $crlf;
299 // restore connection settings
300 $charset_of_file = isset($GLOBALS['charset_of_file']) ? $GLOBALS['charset_of_file'] : '';
301 if (!empty($GLOBALS['asfile']) && isset($mysql_charset_map[$charset_of_file])) {
302 $foot .= $crlf
303 . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' . $crlf
304 . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' . $crlf
305 . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' . $crlf;
308 /* Restore timezone */
309 if ($GLOBALS['sql_utc_time']) {
310 PMA_DBI_query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
313 return PMA_exportOutputHandler($foot);
317 * Outputs export header
319 * @return bool Whether it suceeded
321 * @access public
323 function PMA_exportHeader()
325 global $crlf;
326 global $cfg;
327 global $mysql_charset_map;
329 if (isset($GLOBALS['sql_compatibility'])) {
330 $tmp_compat = $GLOBALS['sql_compatibility'];
331 if ($tmp_compat == 'NONE') {
332 $tmp_compat = '';
334 PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"');
335 unset($tmp_compat);
337 $head = PMA_exportComment('phpMyAdmin SQL Dump')
338 . PMA_exportComment('version ' . PMA_VERSION)
339 . PMA_exportComment('http://www.phpmyadmin.net')
340 . PMA_exportComment();
341 $head .= empty($cfg['Server']['port']) ? PMA_exportComment(__('Host') . ': ' . $cfg['Server']['host']) : PMA_exportComment(__('Host') . ': ' . $cfg['Server']['host'] . ':' . $cfg['Server']['port']);
342 $head .= PMA_exportComment(__('Generation Time')
343 . ': ' . PMA_localisedDate())
344 . 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))
345 . PMA_exportComment(__('PHP Version') . ': ' . phpversion())
346 . PMA_possibleCRLF();
348 if (isset($GLOBALS['sql_header_comment']) && !empty($GLOBALS['sql_header_comment'])) {
349 // '\n' is not a newline (like "\n" would be), it's the characters
350 // backslash and n, as explained on the export interface
351 $lines = explode('\n', $GLOBALS['sql_header_comment']);
352 $head .= PMA_exportComment();
353 foreach($lines as $one_line) {
354 $head .= PMA_exportComment($one_line);
356 $head .= PMA_exportComment();
359 if (isset($GLOBALS['sql_disable_fk'])) {
360 $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
363 /* We want exported AUTO_INCREMENT fields to have still same value, do this only for recent MySQL exports */
364 if (!isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] == 'NONE') {
365 $head .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . $crlf;
368 if (isset($GLOBALS['sql_use_transaction'])) {
369 $head .= 'SET AUTOCOMMIT=0;' . $crlf
370 . 'START TRANSACTION;' . $crlf;
374 /* Change timezone if we should export timestamps in UTC */
375 if ($GLOBALS['sql_utc_time']) {
376 $head .= 'SET time_zone = "+00:00";' . $crlf;
377 $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone');
378 PMA_DBI_query('SET time_zone = "+00:00"');
381 $head .= PMA_possibleCRLF();
383 if (! empty($GLOBALS['asfile'])) {
384 // we are saving as file, therefore we provide charset information
385 // so that a utility like the mysql client can interpret
386 // the file correctly
387 if (isset($GLOBALS['charset_of_file']) && isset($mysql_charset_map[$GLOBALS['charset_of_file']])) {
388 // we got a charset from the export dialog
389 $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']];
390 } else {
391 // by default we use the connection charset
392 $set_names = $mysql_charset_map[$GLOBALS['charset']];
394 $head .= $crlf
395 . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . $crlf
396 . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . $crlf
397 . '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;' . $crlf
398 . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf;
401 return PMA_exportOutputHandler($head);
405 * Outputs CREATE DATABASE database
407 * @param string Database name
409 * @return bool Whether it suceeded
411 * @access public
413 function PMA_exportDBCreate($db)
415 global $crlf;
416 if (isset($GLOBALS['sql_drop_database'])) {
417 if (!PMA_exportOutputHandler('DROP DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db) . ';' . $crlf)) {
418 return FALSE;
421 $create_query = 'CREATE DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db);
422 $collation = PMA_getDbCollation($db);
423 if (strpos($collation, '_')) {
424 $create_query .= ' DEFAULT CHARACTER SET ' . substr($collation, 0, strpos($collation, '_')) . ' COLLATE ' . $collation;
425 } else {
426 $create_query .= ' DEFAULT CHARACTER SET ' . $collation;
428 $create_query .= ';' . $crlf;
429 if (!PMA_exportOutputHandler($create_query)) {
430 return FALSE;
432 if (isset($GLOBALS['sql_backquotes']) && isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'NONE') {
433 $result = PMA_exportOutputHandler('USE ' . PMA_backquote($db) . ';' . $crlf);
434 } else {
435 $result = PMA_exportOutputHandler('USE ' . $db . ';' . $crlf);
438 return $result;
442 * Outputs database header
444 * @param string Database name
446 * @return bool Whether it suceeded
448 * @access public
450 function PMA_exportDBHeader($db)
452 $head = PMA_exportComment()
453 . PMA_exportComment(__('Database') . ': ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : '\'' . $db . '\''))
454 . PMA_exportComment();
455 return PMA_exportOutputHandler($head);
459 * Outputs database footer
461 * @param string Database name
463 * @return bool Whether it suceeded
465 * @access public
467 function PMA_exportDBFooter($db)
469 global $crlf;
471 $result = TRUE;
472 if (isset($GLOBALS['sql_constraints'])) {
473 $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']);
474 unset($GLOBALS['sql_constraints']);
477 if (($GLOBALS['sql_structure_or_data'] == 'structure' || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') && isset($GLOBALS['sql_procedure_function'])) {
478 $text = '';
479 $delimiter = '$$';
481 if (PMA_MYSQL_INT_VERSION > 50100) {
482 $event_names = PMA_DBI_fetch_result('SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \'' . PMA_sqlAddslashes($db,true) . '\';');
483 } else {
484 $event_names = array();
487 if ($event_names) {
488 $text .= $crlf
489 . 'DELIMITER ' . $delimiter . $crlf;
491 $text .=
492 PMA_exportComment()
493 . PMA_exportComment(__('Events'))
494 . PMA_exportComment();
496 foreach($event_names as $event_name) {
497 if (! empty($GLOBALS['sql_drop_table'])) {
498 $text .= 'DROP EVENT ' . PMA_backquote($event_name) . $delimiter . $crlf;
500 $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) . $delimiter . $crlf . $crlf;
503 $text .= 'DELIMITER ;' . $crlf;
506 if (! empty($text)) {
507 $result = PMA_exportOutputHandler($text);
510 return $result;
515 * Returns a stand-in CREATE definition to resolve view dependencies
517 * @param string the database name
518 * @param string the view name
519 * @param string the end of line sequence
521 * @return string resulting definition
523 * @access public
525 function PMA_getTableDefStandIn($db, $view, $crlf) {
526 $create_query = '';
527 if (! empty($GLOBALS['sql_drop_table'])) {
528 $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) . ';' . $crlf;
531 $create_query .= 'CREATE TABLE ';
533 if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
534 $create_query .= 'IF NOT EXISTS ';
536 $create_query .= PMA_backquote($view) . ' (' . $crlf;
537 $tmp = array();
538 $columns = PMA_DBI_get_columns_full($db, $view);
539 foreach($columns as $column_name => $definition) {
540 $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf;
542 $create_query .= implode(',', $tmp) . ');';
543 return($create_query);
547 * Returns $table's CREATE definition
549 * @param string the database name
550 * @param string the table name
551 * @param string the end of line sequence
552 * @param string the url to go back in case of error
553 * @param boolean whether to include creation/update/check dates
554 * @param boolean whether to add semicolon and end-of-line at the end
555 * @param boolean whether we're handling view
557 * @return string resulting schema
559 * @global boolean whether to add 'drop' statements or not
560 * @global boolean whether to use backquotes to allow the use of special
561 * characters in database, table and fields names or not
563 * @access public
565 function PMA_getTableDef($db, $table, $crlf, $error_url, $show_dates = false, $add_semicolon = true, $view = false)
567 global $sql_drop_table;
568 global $sql_backquotes;
569 global $cfgRelation;
570 global $sql_constraints;
571 global $sql_constraints_query; // just the text of the query
572 global $sql_drop_foreign_keys;
574 $schema_create = '';
575 $auto_increment = '';
576 $new_crlf = $crlf;
578 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
579 $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table) . '\'', null, PMA_DBI_QUERY_STORE);
580 if ($result != FALSE) {
581 if (PMA_DBI_num_rows($result) > 0) {
582 $tmpres = PMA_DBI_fetch_assoc($result);
583 // Here we optionally add the AUTO_INCREMENT next value,
584 // but starting with MySQL 5.0.24, the clause is already included
585 // in SHOW CREATE TABLE so we'll remove it below
586 if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
587 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
590 if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
591 $schema_create .= PMA_exportComment(__('Creation') . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])));
592 $new_crlf = PMA_exportComment() . $crlf;
595 if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
596 $schema_create .= PMA_exportComment(__('Last update') . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])));
597 $new_crlf = PMA_exportComment() . $crlf;
600 if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
601 $schema_create .= PMA_exportComment(__('Last check') . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])));
602 $new_crlf = PMA_exportComment() . $crlf;
605 PMA_DBI_free_result($result);
608 $schema_create .= $new_crlf;
610 // no need to generate a DROP VIEW here, it was done earlier
611 if (! empty($sql_drop_table) && ! PMA_Table::isView($db,$table)) {
612 $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table, $sql_backquotes) . ';' . $crlf;
615 // Complete table dump,
616 // Whether to quote table and fields names or not
617 if ($sql_backquotes) {
618 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
619 } else {
620 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
623 // I don't see the reason why this unbuffered query could cause problems,
624 // because SHOW CREATE TABLE returns only one row, and we free the
625 // results below. Nonetheless, we got 2 user reports about this
626 // (see bug 1562533) so I remove the unbuffered mode.
627 //$result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED);
629 // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
630 // produce a displayable result for the default value of a BIT
631 // field, nor does the mysqldump command. See MySQL bug 35796
632 $result = PMA_DBI_try_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table));
633 // an error can happen, for example the table is crashed
634 $tmp_error = PMA_DBI_getError();
635 if ($tmp_error) {
636 return PMA_exportComment(__('in use') . '(' . $tmp_error . ')');
639 if ($result != FALSE && ($row = PMA_DBI_fetch_row($result))) {
640 $create_query = $row[1];
641 unset($row);
643 // Convert end of line chars to one that we want (note that MySQL doesn't return query it will accept in all cases)
644 if (strpos($create_query, "(\r\n ")) {
645 $create_query = str_replace("\r\n", $crlf, $create_query);
646 } elseif (strpos($create_query, "(\n ")) {
647 $create_query = str_replace("\n", $crlf, $create_query);
648 } elseif (strpos($create_query, "(\r ")) {
649 $create_query = str_replace("\r", $crlf, $create_query);
653 * Drop database name from VIEW creation.
655 * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
656 * database name, but we don't want name to show up in CREATE VIEW
657 * statement.
659 if ($view) {
660 $create_query = preg_replace('/' . PMA_backquote($db) . '\./', '', $create_query);
663 // Should we use IF NOT EXISTS?
664 if (isset($GLOBALS['sql_if_not_exists'])) {
665 $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
668 // are there any constraints to cut out?
669 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
671 // Split the query into lines, so we can easily handle it. We know lines are separated by $crlf (done few lines above).
672 $sql_lines = explode($crlf, $create_query);
673 $sql_count = count($sql_lines);
675 // lets find first line with constraints
676 for ($i = 0; $i < $sql_count; $i++) {
677 if (preg_match('@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', $sql_lines[$i])) {
678 break;
682 // If we really found a constraint
683 if ($i != $sql_count) {
685 // remove , from the end of create statement
686 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
688 // prepare variable for constraints
689 if (!isset($sql_constraints)) {
690 if (isset($GLOBALS['no_constraints_comments'])) {
691 $sql_constraints = '';
692 } else {
693 $sql_constraints = $crlf
694 . PMA_exportComment()
695 . PMA_exportComment(__('Constraints for dumped tables'))
696 . PMA_exportComment();
700 // comments for current table
701 if (!isset($GLOBALS['no_constraints_comments'])) {
702 $sql_constraints .= $crlf
703 . PMA_exportComment()
704 . PMA_exportComment(__('Constraints for table') . ' ' . PMA_backquote($table))
705 . PMA_exportComment();
708 // let's do the work
709 $sql_constraints_query .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
710 $sql_constraints .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
711 $sql_drop_foreign_keys .= 'ALTER TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $crlf;
713 $first = TRUE;
714 for ($j = $i; $j < $sql_count; $j++) {
715 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $sql_lines[$j])) {
716 if (!$first) {
717 $sql_constraints .= $crlf;
719 if (strpos($sql_lines[$j], 'CONSTRAINT') === FALSE) {
720 $tmp_str = preg_replace('/(FOREIGN[\s]+KEY)/', 'ADD \1', $sql_lines[$j]);
721 $sql_constraints_query .= $tmp_str;
722 $sql_constraints .= $tmp_str;
723 } else {
724 $tmp_str = preg_replace('/(CONSTRAINT)/', 'ADD \1', $sql_lines[$j]);
725 $sql_constraints_query .= $tmp_str;
726 $sql_constraints .= $tmp_str;
727 preg_match('/(CONSTRAINT)([\s])([\S]*)([\s])/', $sql_lines[$j], $matches);
728 if (! $first) {
729 $sql_drop_foreign_keys .= ', ';
731 $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' . $matches[3];
733 $first = FALSE;
734 } else {
735 break;
738 $sql_constraints .= ';' . $crlf;
739 $sql_constraints_query .= ';';
741 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
742 unset($sql_lines);
745 $schema_create .= $create_query;
748 // remove a possible "AUTO_INCREMENT = value" clause
749 // that could be there starting with MySQL 5.0.24
750 $schema_create = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $schema_create);
752 $schema_create .= $auto_increment;
754 PMA_DBI_free_result($result);
755 return $schema_create . ($add_semicolon ? ';' . $crlf : '');
756 } // end of the 'PMA_getTableDef()' function
760 * Returns $table's comments, relations etc.
762 * @param string the database name
763 * @param string the table name
764 * @param string the end of line sequence
765 * @param boolean whether to include relation comments
766 * @param boolean whether to include mime comments
768 * @return string resulting comments
770 * @access public
772 function PMA_getTableComments($db, $table, $crlf, $do_relation = false, $do_mime = false)
774 global $cfgRelation;
775 global $sql_backquotes;
776 global $sql_constraints;
778 $schema_create = '';
780 // Check if we can use Relations (Mike Beck)
781 if ($do_relation && !empty($cfgRelation['relation'])) {
782 // Find which tables are related with the current one and write it in
783 // an array
784 $res_rel = PMA_getForeigners($db, $table);
786 if ($res_rel && count($res_rel) > 0) {
787 $have_rel = TRUE;
788 } else {
789 $have_rel = FALSE;
791 } else {
792 $have_rel = FALSE;
793 } // end if
795 if ($do_mime && $cfgRelation['mimework']) {
796 if (!($mime_map = PMA_getMIME($db, $table, true))) {
797 unset($mime_map);
801 if (isset($mime_map) && count($mime_map) > 0) {
802 $schema_create .= PMA_possibleCRLF()
803 . PMA_exportComment()
804 . PMA_exportComment(__('MIME TYPES FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
805 @reset($mime_map);
806 foreach ($mime_map AS $mime_field => $mime) {
807 $schema_create .= PMA_exportComment(' ' . PMA_backquote($mime_field, $sql_backquotes))
808 . PMA_exportComment(' ' . PMA_backquote($mime['mimetype'], $sql_backquotes));
810 $schema_create .= PMA_exportComment();
813 if ($have_rel) {
814 $schema_create .= PMA_possibleCRLF()
815 . PMA_exportComment()
816 . PMA_exportComment(__('RELATIONS FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
817 foreach ($res_rel AS $rel_field => $rel) {
818 $schema_create .= PMA_exportComment(' ' . PMA_backquote($rel_field, $sql_backquotes))
819 . PMA_exportComment(' ' . PMA_backquote($rel['foreign_table'], $sql_backquotes)
820 . ' -> ' . PMA_backquote($rel['foreign_field'], $sql_backquotes));
822 $schema_create .= PMA_exportComment();
825 return $schema_create;
827 } // end of the 'PMA_getTableComments()' function
830 * Outputs table's structure
832 * @param string the database name
833 * @param string the table name
834 * @param string the end of line sequence
835 * @param string the url to go back in case of error
836 * @param boolean whether to include relation comments
837 * @param boolean whether to include the pmadb-style column comments
838 * as comments in the structure; this is deprecated
839 * but the parameter is left here because export.php
840 * calls PMA_exportStructure() also for other export
841 * types which use this parameter
842 * @param boolean whether to include mime comments
843 * @param string 'stand_in', 'create_table', 'create_view'
844 * @param string 'server', 'database', 'table'
846 * @return bool Whether it suceeded
848 * @access public
850 function PMA_exportStructure($db, $table, $crlf, $error_url, $relation = FALSE, $comments = FALSE, $mime = FALSE, $dates = FALSE, $export_mode, $export_type)
852 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
853 ? PMA_backquote($table)
854 : '\'' . $table . '\'';
855 $dump = PMA_possibleCRLF()
856 . PMA_exportComment(str_repeat('-', 56))
857 . PMA_possibleCRLF()
858 . PMA_exportComment();
860 switch($export_mode) {
861 case 'create_table':
862 $dump .= PMA_exportComment(__('Table structure for table') . ' ' . $formatted_table_name)
863 . PMA_exportComment();
864 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates);
865 $dump .= PMA_getTableComments($db, $table, $crlf, $relation, $mime);
866 break;
867 case 'triggers':
868 $dump = '';
869 $triggers = PMA_DBI_get_triggers($db, $table);
870 if ($triggers) {
871 $dump .= PMA_possibleCRLF()
872 . PMA_exportComment()
873 . PMA_exportComment(__('Triggers') . ' ' . $formatted_table_name)
874 . PMA_exportComment();
875 $delimiter = '//';
876 foreach ($triggers as $trigger) {
877 $dump .= $trigger['drop'] . ';' . $crlf;
878 $dump .= 'DELIMITER ' . $delimiter . $crlf;
879 $dump .= $trigger['create'];
880 $dump .= 'DELIMITER ;' . $crlf;
883 break;
884 case 'create_view':
885 $dump .= PMA_exportComment(__('Structure for view') . ' ' . $formatted_table_name)
886 . PMA_exportComment();
887 // delete the stand-in table previously created (if any)
888 if ($export_type != 'table') {
889 $dump .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table) . ';' . $crlf;
891 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates, true, true);
892 break;
893 case 'stand_in':
894 $dump .= PMA_exportComment(__('Stand-in structure for view') . ' ' . $formatted_table_name)
895 . PMA_exportComment();
896 // export a stand-in definition to resolve view dependencies
897 $dump .= PMA_getTableDefStandIn($db, $table, $crlf);
898 } // end switch
900 // this one is built by PMA_getTableDef() to use in table copy/move
901 // but not in the case of export
902 unset($GLOBALS['sql_constraints_query']);
904 return PMA_exportOutputHandler($dump);
908 * Dispatches between the versions of 'getTableContent' to use depending
909 * on the php version
911 * @param string the database name
912 * @param string the table name
913 * @param string the end of line sequence
914 * @param string the url to go back in case of error
915 * @param string SQL query for obtaining data
917 * @return bool Whether it suceeded
919 * @global boolean whether to use backquotes to allow the use of special
920 * characters in database, table and fields names or not
921 * @global integer the number of records
922 * @global integer the current record position
924 * @access public
926 * @see PMA_getTableContentFast(), PMA_getTableContentOld()
929 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
931 global $sql_backquotes;
932 global $rows_cnt;
933 global $current_row;
935 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
936 ? PMA_backquote($table)
937 : '\'' . $table . '\'';
939 // Do not export data for a VIEW
940 // (For a VIEW, this is called only when exporting a single VIEW)
941 if (PMA_Table::isView($db, $table)) {
942 $head = PMA_possibleCRLF()
943 . PMA_exportComment()
944 . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name)
945 . PMA_exportComment(__('Data') . ': ' . __('None'))
946 . PMA_exportComment()
947 . PMA_possibleCRLF();
949 if (! PMA_exportOutputHandler($head)) {
950 return FALSE;
952 return true;
955 // it's not a VIEW
956 $buffer = '';
958 // analyze the query to get the true column names, not the aliases
959 // (this fixes an undefined index, also if Complete inserts
960 // are used, we did not get the true column name in case of aliases)
961 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
963 $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
964 // a possible error: the table has crashed
965 $tmp_error = PMA_DBI_getError();
966 if ($tmp_error) {
967 return PMA_exportOutputHandler(PMA_exportComment(__('in use') . ' (' . $tmp_error . ')'));
970 if ($result != FALSE) {
971 $fields_cnt = PMA_DBI_num_fields($result);
973 // Get field information
974 $fields_meta = PMA_DBI_get_fields_meta($result);
975 $field_flags = array();
976 for ($j = 0; $j < $fields_cnt; $j++) {
977 $field_flags[$j] = PMA_DBI_field_flags($result, $j);
980 for ($j = 0; $j < $fields_cnt; $j++) {
981 if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
982 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
983 } else {
984 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
988 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
989 // update
990 $schema_insert = 'UPDATE ';
991 if (isset($GLOBALS['sql_ignore'])) {
992 $schema_insert .= 'IGNORE ';
994 // avoid EOL blank
995 $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
996 } else {
997 // insert or replace
998 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
999 $sql_command = 'REPLACE';
1000 } else {
1001 $sql_command = 'INSERT';
1004 // delayed inserts?
1005 if (isset($GLOBALS['sql_delayed'])) {
1006 $insert_delayed = ' DELAYED';
1007 } else {
1008 $insert_delayed = '';
1011 // insert ignore?
1012 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
1013 $insert_delayed .= ' IGNORE';
1016 // scheme for inserting fields
1017 if ($GLOBALS['sql_insert_syntax'] == 'complete' || $GLOBALS['sql_insert_syntax'] == 'both') {
1018 $fields = implode(', ', $field_set);
1019 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1020 // avoid EOL blank
1021 . ' (' . $fields . ') VALUES';
1022 } else {
1023 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1024 . ' VALUES';
1028 $search = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
1029 $replace = array('\0', '\n', '\r', '\Z');
1030 $current_row = 0;
1031 $query_size = 0;
1032 if (($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
1033 $separator = ',';
1034 $schema_insert .= $crlf;
1035 } else {
1036 $separator = ';';
1039 while ($row = PMA_DBI_fetch_row($result)) {
1040 if ($current_row == 0) {
1041 $head = PMA_possibleCRLF()
1042 . PMA_exportComment()
1043 . PMA_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name)
1044 . PMA_exportComment()
1045 . $crlf;
1046 if (! PMA_exportOutputHandler($head)) {
1047 return FALSE;
1050 $current_row++;
1051 for ($j = 0; $j < $fields_cnt; $j++) {
1052 // NULL
1053 if (!isset($row[$j]) || is_null($row[$j])) {
1054 $values[] = 'NULL';
1055 // a number
1056 // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
1057 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp'
1058 && ! $fields_meta[$j]->blob) {
1059 $values[] = $row[$j];
1060 // a true BLOB
1061 // - mysqldump only generates hex data when the --hex-blob
1062 // option is used, for fields having the binary attribute
1063 // no hex is generated
1064 // - a TEXT field returns type blob but a real blob
1065 // returns also the 'binary' flag
1066 } elseif (stristr($field_flags[$j], 'BINARY')
1067 && $fields_meta[$j]->blob
1068 && isset($GLOBALS['sql_hex_for_blob'])) {
1069 // empty blobs need to be different, but '0' is also empty :-(
1070 if (empty($row[$j]) && $row[$j] != '0') {
1071 $values[] = '\'\'';
1072 } else {
1073 $values[] = '0x' . bin2hex($row[$j]);
1075 // detection of 'bit' works only on mysqli extension
1076 } elseif ($fields_meta[$j]->type == 'bit') {
1077 $values[] = "b'" . PMA_sqlAddslashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length)) . "'";
1078 // something else -> treat as a string
1079 } else {
1080 $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
1081 } // end if
1082 } // end for
1084 // should we make update?
1085 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
1087 $insert_line = $schema_insert;
1088 for ($i = 0; $i < $fields_cnt; $i++) {
1089 if (0 == $i) {
1090 $insert_line .= ' ';
1092 if ($i > 0) {
1093 // avoid EOL blank
1094 $insert_line .= ',';
1096 $insert_line .= $field_set[$i] . ' = ' . $values[$i];
1099 list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
1100 $insert_line .= ' WHERE ' . $tmp_unique_condition;
1101 unset($tmp_unique_condition, $tmp_clause_is_unique);
1103 } else {
1105 // Extended inserts case
1106 if ($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') {
1107 if ($current_row == 1) {
1108 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1109 } else {
1110 $insert_line = '(' . implode(', ', $values) . ')';
1111 if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
1112 if (!PMA_exportOutputHandler(';' . $crlf)) {
1113 return FALSE;
1115 $query_size = 0;
1116 $current_row = 1;
1117 $insert_line = $schema_insert . $insert_line;
1120 $query_size += strlen($insert_line);
1122 // Other inserts case
1123 else {
1124 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1127 unset($values);
1129 if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
1130 return FALSE;
1133 } // end while
1134 if ($current_row > 0) {
1135 if (!PMA_exportOutputHandler(';' . $crlf)) {
1136 return FALSE;
1139 } // end if ($result != FALSE)
1140 PMA_DBI_free_result($result);
1142 return TRUE;
1143 } // end of the 'PMA_exportData()' function