Translation update done using Pootle.
[phpmyadmin/ammaryasirr.git] / libraries / export / sql.php
blob40efc2b7b60ea7405792b7634c2746070f7f730b
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
7 * @subpackage SQL
8 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
16 if (isset($plugin_list)) {
17 $hide_sql = false;
18 $hide_structure = false;
19 if ($plugin_param['export_type'] == 'table' && !$plugin_param['single_table']) {
20 $hide_structure = true;
21 $hide_sql = true;
23 if (!$hide_sql) {
24 $plugin_list['sql'] = array(
25 'text' => __('SQL'),
26 'extension' => 'sql',
27 'mime_type' => 'text/x-sql',
28 'options' => array());
30 $plugin_list['sql']['options'][] = array(
31 'type' => 'begin_group',
32 'name' => 'general_opts');
34 /* comments */
35 $plugin_list['sql']['options'][] = array(
36 'type' => 'begin_subgroup',
37 'subgroup_header' => array(
38 'type' => 'bool',
39 'name' => 'include_comments',
40 'text' => __('Display comments <i>(includes info such as export timestamp, PHP version, and server version)</i>')
41 ));
42 $plugin_list['sql']['options'][] = array(
43 'type' => 'text',
44 'name' => 'header_comment',
45 'text' => __('Additional custom header comment (\n splits lines):')
47 $plugin_list['sql']['options'][] = array(
48 'type' => 'bool',
49 'name' => 'dates',
50 'text' => __('Include a timestamp of when databases were created, last updated, and last checked')
52 if (!empty($GLOBALS['cfgRelation']['relation'])) {
53 $plugin_list['sql']['options'][] = array(
54 'type' => 'bool',
55 'name' => 'relation',
56 'text' => __('Display foreign key relationships')
59 if (!empty($GLOBALS['cfgRelation']['mimework'])) {
60 $plugin_list['sql']['options'][] = array(
61 'type' => 'bool',
62 'name' => 'mime',
63 'text' => __('Display MIME types')
66 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
67 /* end comments */
69 /* enclose in a transaction */
70 $plugin_list['sql']['options'][] = array(
71 'type' => 'bool',
72 'name' => 'use_transaction',
73 'text' => __('Enclose export in a transaction'),
74 'doc' => array('programs', 'mysqldump', 'option_mysqldump_single-transaction')
77 /* disable foreign key checks */
78 $plugin_list['sql']['options'][] = array(
79 'type' => 'bool',
80 'name' => 'disable_fk',
81 'text' => __('Disable foreign key checks'),
82 'doc' => array(
83 'manual_MySQL_Database_Administration',
84 'server-system-variables',
85 'sysvar_foreign_key_checks')
88 $plugin_list['sql']['options_text'] = __('Options');
90 /* compatibility maximization */
91 $compats = PMA_DBI_getCompatibilities();
92 if (count($compats) > 0) {
93 $values = array();
94 foreach ($compats as $val) {
95 $values[$val] = $val;
97 $plugin_list['sql']['options'][] = array(
98 'type' => 'select',
99 'name' => 'compatibility',
100 'text' => __('Database system or older MySQL server to maximize output compatibility with:'),
101 'values' => $values,
102 'doc' => array(
103 'manual_MySQL_Database_Administration',
104 'Server_SQL_mode')
106 unset($values);
109 /* server export options */
110 if ($plugin_param['export_type'] == 'server') {
111 $plugin_list['sql']['options'][] = array(
112 'type' => 'bool',
113 'name' => 'drop_database',
114 'text' => sprintf(__('Add %s statement'), '<code>DROP DATABASE</code>')
118 /* what to dump (structure/data/both) */
119 $plugin_list['sql']['options'][] = array(
120 'type' => 'begin_subgroup',
121 'subgroup_header' => array(
122 'type' => 'message_only',
123 'text' => __('Dump table')
125 $plugin_list['sql']['options'][] = array(
126 'type' => 'radio',
127 'name' => 'structure_or_data',
128 'values' => array(
129 'structure' => __('structure'),
130 'data' => __('data'),
131 'structure_and_data' => __('structure and data')
133 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
135 $plugin_list['sql']['options'][] = array('type' => 'end_group');
137 /* begin Structure options */
138 if (!$hide_structure) {
139 $plugin_list['sql']['options'][] = array(
140 'type' => 'begin_group',
141 'name' => 'structure',
142 'text' => __('Object creation options'),
143 'force' => 'data'
146 /* begin SQL Statements */
147 $plugin_list['sql']['options'][] = array(
148 'type' => 'begin_subgroup',
149 'subgroup_header' => array(
150 'type' => 'message_only',
151 'name' => 'add_statements',
152 'text' => __('Add statements:')
154 if ($plugin_param['export_type'] == 'table') {
155 if (PMA_Table::isView($GLOBALS['db'], $GLOBALS['table'])) {
156 $drop_clause = '<code>DROP VIEW</code>';
157 } else {
158 $drop_clause = '<code>DROP TABLE</code>';
160 } else {
161 $drop_clause = '<code>DROP TABLE / VIEW / PROCEDURE / FUNCTION</code>';
162 if (PMA_MYSQL_INT_VERSION > 50100) {
163 $drop_clause .= '<code> / EVENT</code>';
166 $plugin_list['sql']['options'][] = array(
167 'type' => 'bool',
168 'name' => 'drop_table',
169 'text' => sprintf(__('Add %s statement'), $drop_clause)
171 $plugin_list['sql']['options'][] = array(
172 'type' => 'bool',
173 'name' => 'procedure_function',
174 'text' => sprintf(__('Add %s statement'), '<code>CREATE PROCEDURE / FUNCTION' . (PMA_MYSQL_INT_VERSION > 50100 ? ' / EVENT</code>' : '</code>'))
177 /* begin CREATE TABLE statements*/
178 $plugin_list['sql']['options'][] = array(
179 'type' => 'begin_subgroup',
180 'subgroup_header' => array(
181 'type' => 'bool',
182 'name' => 'create_table_statements',
183 'text' => __('<code>CREATE TABLE</code> options:')
185 $plugin_list['sql']['options'][] = array(
186 'type' => 'bool',
187 'name' => 'if_not_exists',
188 'text' => '<code>IF NOT EXISTS</code>'
190 $plugin_list['sql']['options'][] = array(
191 'type' => 'bool',
192 'name' => 'auto_increment',
193 'text' => '<code>AUTO_INCREMENT</code>'
195 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
196 /* end CREATE TABLE statements */
198 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
199 /* end SQL statements */
201 $plugin_list['sql']['options'][] = array(
202 'type' => 'bool',
203 'name' => 'backquotes',
204 'text' => __('Enclose table and field names with backquotes <i>(Protects field and table names formed with special characters or keywords)</i>')
207 $plugin_list['sql']['options'][] = array('type' => 'end_group');
209 /* end Structure options */
211 /* begin Data options */
212 $plugin_list['sql']['options'][] = array(
213 'type' => 'begin_group',
214 'name' => 'data',
215 'text' => __('Data dump options'),
216 'force' => 'structure'
219 /* begin SQL statements */
220 $plugin_list['sql']['options'][] = array(
221 'type' => 'begin_subgroup',
222 'subgroup_header' => array(
223 'type' => 'message_only',
224 'text' => __('Instead of <code>INSERT</code> statements, use:')
226 $plugin_list['sql']['options'][] = array(
227 'type' => 'bool',
228 'name' => 'delayed',
229 'text' => __('<code>INSERT DELAYED</code> statements'),
230 'doc' => array('manual_MySQL_Database_Administration', 'insert_delayed')
232 $plugin_list['sql']['options'][] = array(
233 'type' => 'bool',
234 'name' => 'ignore',
235 'text' => __('<code>INSERT IGNORE</code> statements'),
236 'doc' => array('manual_MySQL_Database_Administration', 'insert')
238 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
239 /* end SQL statements */
241 /* Function to use when dumping data */
242 $plugin_list['sql']['options'][] = array(
243 'type' => 'select',
244 'name' => 'type',
245 'text' => __('Function to use when dumping data:'),
246 'values' => array(
247 'INSERT' => 'INSERT',
248 'UPDATE' => 'UPDATE',
249 'REPLACE' => 'REPLACE'
253 /* Syntax to use when inserting data */
254 $plugin_list['sql']['options'][] = array(
255 'type' => 'begin_subgroup',
256 'subgroup_header' => array(
257 'type' => 'message_only',
258 'text' => __('Syntax to use when inserting data:')
260 $plugin_list['sql']['options'][] = array(
261 'type' => 'radio',
262 'name' => 'insert_syntax',
263 'values' => array(
264 '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>'),
265 '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>'),
266 '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>'),
267 'none' => __('neither of the above<br /> &nbsp; &nbsp; &nbsp; Example: <code>INSERT INTO tbl_name VALUES (1,2,3)</code>')
269 $plugin_list['sql']['options'][] = array('type' => 'end_subgroup');
271 /* Max length of query */
272 $plugin_list['sql']['options'][] = array(
273 'type' => 'text',
274 'name' => 'max_query_size',
275 'text' => __('Maximal length of created query')
278 /* Dump binary columns in hexadecimal */
279 $plugin_list['sql']['options'][] = array(
280 'type' => 'bool',
281 'name' => 'hex_for_blob',
282 'text' => __('Dump binary columns in hexadecimal notation <i>(for example, "abc" becomes 0x616263)</i>')
285 /* Dump time in UTC */
286 $plugin_list['sql']['options'][] = array(
287 'type' => 'bool',
288 'name' => 'utc_time',
289 'text' => __('Dump TIMESTAMP columns in UTC <i>(enables TIMESTAMP columns to be dumped and reloaded between servers in different time zones)</i>')
292 $plugin_list['sql']['options'][] = array('type' => 'end_group');
293 /* end Data options */
295 } else {
298 * Avoids undefined variables, use NULL so isset() returns false
300 if (! isset($GLOBALS['sql_backquotes'])) {
301 $GLOBALS['sql_backquotes'] = null;
305 * Exports routines (procedures and functions)
307 * @param string $db
308 * @return bool Whether it suceeded
310 * @access public
312 function PMA_exportRoutines($db) {
313 global $crlf;
315 $text = '';
316 $delimiter = '$$';
318 $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE');
319 $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION');
321 if ($procedure_names || $function_names) {
322 $text .= $crlf
323 . 'DELIMITER ' . $delimiter . $crlf;
326 if ($procedure_names) {
327 $text .=
328 PMA_exportComment()
329 . PMA_exportComment(__('Procedures'))
330 . PMA_exportComment();
332 foreach ($procedure_names as $procedure_name) {
333 if (! empty($GLOBALS['sql_drop_table'])) {
334 $text .= 'DROP PROCEDURE IF EXISTS '
335 . PMA_backquote($procedure_name)
336 . $delimiter . $crlf;
338 $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name)
339 . $delimiter . $crlf . $crlf;
343 if ($function_names) {
344 $text .=
345 PMA_exportComment()
346 . PMA_exportComment(__('Functions'))
347 . PMA_exportComment();
349 foreach ($function_names as $function_name) {
350 if (! empty($GLOBALS['sql_drop_table'])) {
351 $text .= 'DROP FUNCTION IF EXISTS '
352 . PMA_backquote($function_name)
353 . $delimiter . $crlf;
355 $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name)
356 . $delimiter . $crlf . $crlf;
360 if ($procedure_names || $function_names) {
361 $text .= 'DELIMITER ;' . $crlf;
364 if (! empty($text)) {
365 return PMA_exportOutputHandler($text);
366 } else {
367 return false;
372 * Possibly outputs comment
374 * @param string $text Text of comment
375 * @return string The formatted comment
377 * @access private
379 function PMA_exportComment($text = '')
381 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
382 // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
383 return '--' . (empty($text) ? '' : ' ') . $text . $GLOBALS['crlf'];
384 } else {
385 return '';
390 * Possibly outputs CRLF
392 * @return string $crlf or nothing
394 * @access private
396 function PMA_possibleCRLF()
398 if (isset($GLOBALS['sql_include_comments']) && $GLOBALS['sql_include_comments']) {
399 return $GLOBALS['crlf'];
400 } else {
401 return '';
406 * Outputs export footer
408 * @return bool Whether it suceeded
410 * @access public
412 function PMA_exportFooter()
414 global $crlf;
415 global $mysql_charset_map;
417 $foot = '';
419 if (isset($GLOBALS['sql_disable_fk'])) {
420 $foot .= 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
423 if (isset($GLOBALS['sql_use_transaction'])) {
424 $foot .= 'COMMIT;' . $crlf;
427 // restore connection settings
428 $charset_of_file = isset($GLOBALS['charset_of_file']) ? $GLOBALS['charset_of_file'] : '';
429 if (!empty($GLOBALS['asfile']) && isset($mysql_charset_map[$charset_of_file])) {
430 $foot .= $crlf
431 . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' . $crlf
432 . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' . $crlf
433 . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' . $crlf;
436 /* Restore timezone */
437 if ($GLOBALS['sql_utc_time']) {
438 PMA_DBI_query('SET time_zone = "' . $GLOBALS['old_tz'] . '"');
441 return PMA_exportOutputHandler($foot);
445 * Outputs export header
447 * @return bool Whether it suceeded
449 * @access public
451 function PMA_exportHeader()
453 global $crlf;
454 global $cfg;
455 global $mysql_charset_map;
457 if (isset($GLOBALS['sql_compatibility'])) {
458 $tmp_compat = $GLOBALS['sql_compatibility'];
459 if ($tmp_compat == 'NONE') {
460 $tmp_compat = '';
462 PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"');
463 unset($tmp_compat);
465 $head = PMA_exportComment('phpMyAdmin SQL Dump')
466 . PMA_exportComment('version ' . PMA_VERSION)
467 . PMA_exportComment('http://www.phpmyadmin.net')
468 . PMA_exportComment();
469 $host_string = __('Host') . ': ' . $cfg['Server']['host'];
470 if (!empty($cfg['Server']['port'])) {
471 $host_string .= ':' . $cfg['Server']['port'];
473 $head .= PMA_exportComment($host_string);
474 $head .= PMA_exportComment(__('Generation Time')
475 . ': ' . PMA_localisedDate())
476 . PMA_exportComment(__('Server version') . ': ' . PMA_MYSQL_STR_VERSION)
477 . PMA_exportComment(__('PHP Version') . ': ' . phpversion())
478 . PMA_possibleCRLF();
480 if (isset($GLOBALS['sql_header_comment']) && !empty($GLOBALS['sql_header_comment'])) {
481 // '\n' is not a newline (like "\n" would be), it's the characters
482 // backslash and n, as explained on the export interface
483 $lines = explode('\n', $GLOBALS['sql_header_comment']);
484 $head .= PMA_exportComment();
485 foreach ($lines as $one_line) {
486 $head .= PMA_exportComment($one_line);
488 $head .= PMA_exportComment();
491 if (isset($GLOBALS['sql_disable_fk'])) {
492 $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
495 /* We want exported AUTO_INCREMENT fields to have still same value, do this only for recent MySQL exports */
496 if (!isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] == 'NONE') {
497 $head .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . $crlf;
500 if (isset($GLOBALS['sql_use_transaction'])) {
501 $head .= 'SET AUTOCOMMIT=0;' . $crlf
502 . 'START TRANSACTION;' . $crlf;
506 /* Change timezone if we should export timestamps in UTC */
507 if ($GLOBALS['sql_utc_time']) {
508 $head .= 'SET time_zone = "+00:00";' . $crlf;
509 $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone');
510 PMA_DBI_query('SET time_zone = "+00:00"');
513 $head .= PMA_possibleCRLF();
515 if (! empty($GLOBALS['asfile'])) {
516 // we are saving as file, therefore we provide charset information
517 // so that a utility like the mysql client can interpret
518 // the file correctly
519 if (isset($GLOBALS['charset_of_file']) && isset($mysql_charset_map[$GLOBALS['charset_of_file']])) {
520 // we got a charset from the export dialog
521 $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']];
522 } else {
523 // by default we use the connection charset
524 $set_names = $mysql_charset_map['utf-8'];
526 $head .= $crlf
527 . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . $crlf
528 . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . $crlf
529 . '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;' . $crlf
530 . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf;
533 return PMA_exportOutputHandler($head);
537 * Outputs CREATE DATABASE statement
539 * @param string $db Database name
540 * @return bool Whether it suceeded
542 * @access public
544 function PMA_exportDBCreate($db)
546 global $crlf;
547 if (isset($GLOBALS['sql_drop_database'])) {
548 if (!PMA_exportOutputHandler('DROP DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db) . ';' . $crlf)) {
549 return false;
552 $create_query = 'CREATE DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db);
553 $collation = PMA_getDbCollation($db);
554 if (strpos($collation, '_')) {
555 $create_query .= ' DEFAULT CHARACTER SET ' . substr($collation, 0, strpos($collation, '_')) . ' COLLATE ' . $collation;
556 } else {
557 $create_query .= ' DEFAULT CHARACTER SET ' . $collation;
559 $create_query .= ';' . $crlf;
560 if (!PMA_exportOutputHandler($create_query)) {
561 return false;
563 if (isset($GLOBALS['sql_backquotes']) && isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'NONE') {
564 $result = PMA_exportOutputHandler('USE ' . PMA_backquote($db) . ';' . $crlf);
565 } else {
566 $result = PMA_exportOutputHandler('USE ' . $db . ';' . $crlf);
569 return $result;
573 * Outputs database header
575 * @param string $db Database name
576 * @return bool Whether it suceeded
578 * @access public
580 function PMA_exportDBHeader($db)
582 $head = PMA_exportComment()
583 . PMA_exportComment(__('Database') . ': ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : '\'' . $db . '\''))
584 . PMA_exportComment();
585 return PMA_exportOutputHandler($head);
589 * Outputs database footer
591 * @param string $db Database name
592 * @return bool Whether it suceeded
594 * @access public
596 function PMA_exportDBFooter($db)
598 global $crlf;
600 $result = true;
601 if (isset($GLOBALS['sql_constraints'])) {
602 $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']);
603 unset($GLOBALS['sql_constraints']);
606 if (($GLOBALS['sql_structure_or_data'] == 'structure' || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') && isset($GLOBALS['sql_procedure_function'])) {
607 $text = '';
608 $delimiter = '$$';
610 if (PMA_MYSQL_INT_VERSION > 50100) {
611 $event_names = PMA_DBI_fetch_result('SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \'' . PMA_sqlAddSlashes($db,true) . '\';');
612 } else {
613 $event_names = array();
616 if ($event_names) {
617 $text .= $crlf
618 . 'DELIMITER ' . $delimiter . $crlf;
620 $text .=
621 PMA_exportComment()
622 . PMA_exportComment(__('Events'))
623 . PMA_exportComment();
625 foreach ($event_names as $event_name) {
626 if (! empty($GLOBALS['sql_drop_table'])) {
627 $text .= 'DROP EVENT ' . PMA_backquote($event_name) . $delimiter . $crlf;
629 $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) . $delimiter . $crlf . $crlf;
632 $text .= 'DELIMITER ;' . $crlf;
635 if (! empty($text)) {
636 $result = PMA_exportOutputHandler($text);
639 return $result;
643 * Returns a stand-in CREATE definition to resolve view dependencies
645 * @param string $db the database name
646 * @param string $view the view name
647 * @param string $crlf the end of line sequence
648 * @return string resulting definition
650 * @access public
652 function PMA_getTableDefStandIn($db, $view, $crlf) {
653 $create_query = '';
654 if (! empty($GLOBALS['sql_drop_table'])) {
655 $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) . ';' . $crlf;
658 $create_query .= 'CREATE TABLE ';
660 if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
661 $create_query .= 'IF NOT EXISTS ';
663 $create_query .= PMA_backquote($view) . ' (' . $crlf;
664 $tmp = array();
665 $columns = PMA_DBI_get_columns_full($db, $view);
666 foreach ($columns as $column_name => $definition) {
667 $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf;
669 $create_query .= implode(',', $tmp) . ');';
670 return($create_query);
674 * Returns $table's CREATE definition
676 * @param string $db the database name
677 * @param string $table the table name
678 * @param string $crlf the end of line sequence
679 * @param string $error_url the url to go back in case of error
680 * @param bool $show_dates whether to include creation/update/check dates
681 * @param bool $add_semicolon whether to add semicolon and end-of-line at the end
682 * @param bool $view whether we're handling a view
683 * @return string resulting schema
685 * @access public
687 function PMA_getTableDef($db, $table, $crlf, $error_url, $show_dates = false, $add_semicolon = true, $view = false)
689 global $sql_drop_table;
690 global $sql_backquotes;
691 global $sql_constraints_query; // just the text of the query
692 global $sql_drop_foreign_keys;
694 $schema_create = '';
695 $auto_increment = '';
696 $new_crlf = $crlf;
698 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
699 $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddSlashes($table, true) . '\'', null, PMA_DBI_QUERY_STORE);
700 if ($result != false) {
701 if (PMA_DBI_num_rows($result) > 0) {
702 $tmpres = PMA_DBI_fetch_assoc($result);
703 // Here we optionally add the AUTO_INCREMENT next value,
704 // but starting with MySQL 5.0.24, the clause is already included
705 // in SHOW CREATE TABLE so we'll remove it below
706 if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
707 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
710 if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
711 $schema_create .= PMA_exportComment(__('Creation') . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])));
712 $new_crlf = PMA_exportComment() . $crlf;
715 if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
716 $schema_create .= PMA_exportComment(__('Last update') . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])));
717 $new_crlf = PMA_exportComment() . $crlf;
720 if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
721 $schema_create .= PMA_exportComment(__('Last check') . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])));
722 $new_crlf = PMA_exportComment() . $crlf;
725 PMA_DBI_free_result($result);
728 $schema_create .= $new_crlf;
730 // no need to generate a DROP VIEW here, it was done earlier
731 if (! empty($sql_drop_table) && ! PMA_Table::isView($db,$table)) {
732 $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table, $sql_backquotes) . ';' . $crlf;
735 // Complete table dump,
736 // Whether to quote table and fields names or not
737 if ($sql_backquotes) {
738 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
739 } else {
740 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
743 // I don't see the reason why this unbuffered query could cause problems,
744 // because SHOW CREATE TABLE returns only one row, and we free the
745 // results below. Nonetheless, we got 2 user reports about this
746 // (see bug 1562533) so I remove the unbuffered mode.
747 //$result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED);
749 // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
750 // produce a displayable result for the default value of a BIT
751 // field, nor does the mysqldump command. See MySQL bug 35796
752 $result = PMA_DBI_try_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table));
753 // an error can happen, for example the table is crashed
754 $tmp_error = PMA_DBI_getError();
755 if ($tmp_error) {
756 return PMA_exportComment(__('in use') . '(' . $tmp_error . ')');
759 if ($result != false && ($row = PMA_DBI_fetch_row($result))) {
760 $create_query = $row[1];
761 unset($row);
763 // Convert end of line chars to one that we want (note that MySQL doesn't return query it will accept in all cases)
764 if (strpos($create_query, "(\r\n ")) {
765 $create_query = str_replace("\r\n", $crlf, $create_query);
766 } elseif (strpos($create_query, "(\n ")) {
767 $create_query = str_replace("\n", $crlf, $create_query);
768 } elseif (strpos($create_query, "(\r ")) {
769 $create_query = str_replace("\r", $crlf, $create_query);
773 * Drop database name from VIEW creation.
775 * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
776 * database name, but we don't want name to show up in CREATE VIEW
777 * statement.
779 if ($view) {
780 $create_query = preg_replace('/' . PMA_backquote($db) . '\./', '', $create_query);
783 // Should we use IF NOT EXISTS?
784 if (isset($GLOBALS['sql_if_not_exists'])) {
785 $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
788 // are there any constraints to cut out?
789 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
791 // Split the query into lines, so we can easily handle it. We know lines are separated by $crlf (done few lines above).
792 $sql_lines = explode($crlf, $create_query);
793 $sql_count = count($sql_lines);
795 // lets find first line with constraints
796 for ($i = 0; $i < $sql_count; $i++) {
797 if (preg_match('@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', $sql_lines[$i])) {
798 break;
802 // If we really found a constraint
803 if ($i != $sql_count) {
805 // remove , from the end of create statement
806 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
808 // prepare variable for constraints
809 if (!isset($sql_constraints)) {
810 if (isset($GLOBALS['no_constraints_comments'])) {
811 $sql_constraints = '';
812 } else {
813 $sql_constraints = $crlf
814 . PMA_exportComment()
815 . PMA_exportComment(__('Constraints for dumped tables'))
816 . PMA_exportComment();
820 // comments for current table
821 if (!isset($GLOBALS['no_constraints_comments'])) {
822 $sql_constraints .= $crlf
823 . PMA_exportComment()
824 . PMA_exportComment(__('Constraints for table') . ' ' . PMA_backquote($table))
825 . PMA_exportComment();
828 // let's do the work
829 $sql_constraints_query .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
830 $sql_constraints .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
831 $sql_drop_foreign_keys .= 'ALTER TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table) . $crlf;
833 $first = true;
834 for ($j = $i; $j < $sql_count; $j++) {
835 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $sql_lines[$j])) {
836 if (!$first) {
837 $sql_constraints .= $crlf;
839 if (strpos($sql_lines[$j], 'CONSTRAINT') === false) {
840 $tmp_str = preg_replace('/(FOREIGN[\s]+KEY)/', 'ADD \1', $sql_lines[$j]);
841 $sql_constraints_query .= $tmp_str;
842 $sql_constraints .= $tmp_str;
843 } else {
844 $tmp_str = preg_replace('/(CONSTRAINT)/', 'ADD \1', $sql_lines[$j]);
845 $sql_constraints_query .= $tmp_str;
846 $sql_constraints .= $tmp_str;
847 preg_match('/(CONSTRAINT)([\s])([\S]*)([\s])/', $sql_lines[$j], $matches);
848 if (! $first) {
849 $sql_drop_foreign_keys .= ', ';
851 $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' . $matches[3];
853 $first = false;
854 } else {
855 break;
858 $sql_constraints .= ';' . $crlf;
859 $sql_constraints_query .= ';';
861 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
862 unset($sql_lines);
865 $schema_create .= $create_query;
868 // remove a possible "AUTO_INCREMENT = value" clause
869 // that could be there starting with MySQL 5.0.24
870 $schema_create = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $schema_create);
872 $schema_create .= $auto_increment;
874 PMA_DBI_free_result($result);
875 return $schema_create . ($add_semicolon ? ';' . $crlf : '');
876 } // end of the 'PMA_getTableDef()' function
879 * Returns $table's comments, relations etc.
881 * @param string $db database name
882 * @param string $table table name
883 * @param string $crlf end of line sequence
884 * @param bool $do_relation whether to include relation comments
885 * @param bool $do_mime whether to include mime comments
886 * @return string resulting comments
888 * @access private
890 function PMA_getTableComments($db, $table, $crlf, $do_relation = false, $do_mime = false)
892 global $cfgRelation;
893 global $sql_backquotes;
894 global $sql_constraints;
896 $schema_create = '';
898 // Check if we can use Relations
899 if ($do_relation && !empty($cfgRelation['relation'])) {
900 // Find which tables are related with the current one and write it in
901 // an array
902 $res_rel = PMA_getForeigners($db, $table);
904 if ($res_rel && count($res_rel) > 0) {
905 $have_rel = true;
906 } else {
907 $have_rel = false;
909 } else {
910 $have_rel = false;
911 } // end if
913 if ($do_mime && $cfgRelation['mimework']) {
914 if (!($mime_map = PMA_getMIME($db, $table, true))) {
915 unset($mime_map);
919 if (isset($mime_map) && count($mime_map) > 0) {
920 $schema_create .= PMA_possibleCRLF()
921 . PMA_exportComment()
922 . PMA_exportComment(__('MIME TYPES FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
923 @reset($mime_map);
924 foreach ($mime_map AS $mime_field => $mime) {
925 $schema_create .= PMA_exportComment(' ' . PMA_backquote($mime_field, $sql_backquotes))
926 . PMA_exportComment(' ' . PMA_backquote($mime['mimetype'], $sql_backquotes));
928 $schema_create .= PMA_exportComment();
931 if ($have_rel) {
932 $schema_create .= PMA_possibleCRLF()
933 . PMA_exportComment()
934 . PMA_exportComment(__('RELATIONS FOR TABLE'). ' ' . PMA_backquote($table, $sql_backquotes) . ':');
935 foreach ($res_rel AS $rel_field => $rel) {
936 $schema_create .= PMA_exportComment(' ' . PMA_backquote($rel_field, $sql_backquotes))
937 . PMA_exportComment(' ' . PMA_backquote($rel['foreign_table'], $sql_backquotes)
938 . ' -> ' . PMA_backquote($rel['foreign_field'], $sql_backquotes));
940 $schema_create .= PMA_exportComment();
943 return $schema_create;
945 } // end of the 'PMA_getTableComments()' function
948 * Outputs table's structure
950 * @param string $db database name
951 * @param string $table table name
952 * @param string $crlf the end of line sequence
953 * @param string $error_url the url to go back in case of error
954 * @param bool $relation whether to include relation comments
955 * @param bool $comments whether to include the pmadb-style column comments
956 * as comments in the structure; this is deprecated
957 * but the parameter is left here because export.php
958 * calls PMA_exportStructure() also for other export
959 * types which use this parameter
960 * @param bool $mime whether to include mime comments
961 * @param bool $dates whether to include creation/update/check dates
962 * @param string $export_mode 'create_table', 'triggers', 'create_view', 'stand_in'
963 * @param string $export_type 'server', 'database', 'table'
964 * @return bool Whether it suceeded
966 * @access public
968 function PMA_exportStructure($db, $table, $crlf, $error_url, $relation = false, $comments = false, $mime = false, $dates = false, $export_mode, $export_type)
970 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
971 ? PMA_backquote($table)
972 : '\'' . $table . '\'';
973 $dump = PMA_possibleCRLF()
974 . PMA_exportComment(str_repeat('-', 56))
975 . PMA_possibleCRLF()
976 . PMA_exportComment();
978 switch($export_mode) {
979 case 'create_table':
980 $dump .= PMA_exportComment(__('Table structure for table') . ' ' . $formatted_table_name);
981 $dump .= PMA_exportComment();
982 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates);
983 $dump .= PMA_getTableComments($db, $table, $crlf, $relation, $mime);
984 break;
985 case 'triggers':
986 $dump = '';
987 $triggers = PMA_DBI_get_triggers($db, $table);
988 if ($triggers) {
989 $dump .= PMA_possibleCRLF()
990 . PMA_exportComment()
991 . PMA_exportComment(__('Triggers') . ' ' . $formatted_table_name)
992 . PMA_exportComment();
993 $delimiter = '//';
994 foreach ($triggers as $trigger) {
995 $dump .= $trigger['drop'] . ';' . $crlf;
996 $dump .= 'DELIMITER ' . $delimiter . $crlf;
997 $dump .= $trigger['create'];
998 $dump .= 'DELIMITER ;' . $crlf;
1001 break;
1002 case 'create_view':
1003 $dump .= PMA_exportComment(__('Structure for view') . ' ' . $formatted_table_name)
1004 . PMA_exportComment();
1005 // delete the stand-in table previously created (if any)
1006 if ($export_type != 'table') {
1007 $dump .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table) . ';' . $crlf;
1009 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates, true, true);
1010 break;
1011 case 'stand_in':
1012 $dump .= PMA_exportComment(__('Stand-in structure for view') . ' ' . $formatted_table_name)
1013 . PMA_exportComment();
1014 // export a stand-in definition to resolve view dependencies
1015 $dump .= PMA_getTableDefStandIn($db, $table, $crlf);
1016 } // end switch
1018 // this one is built by PMA_getTableDef() to use in table copy/move
1019 // but not in the case of export
1020 unset($GLOBALS['sql_constraints_query']);
1022 return PMA_exportOutputHandler($dump);
1026 * Outputs the content of a table in SQL format
1028 * @param string $db database name
1029 * @param string $table table name
1030 * @param string $crlf the end of line sequence
1031 * @param string $error_url the url to go back in case of error
1032 * @param string $sql_query SQL query for obtaining data
1033 * @return bool Whether it suceeded
1035 * @access public
1037 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
1039 global $sql_backquotes;
1040 global $current_row;
1042 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
1043 ? PMA_backquote($table)
1044 : '\'' . $table . '\'';
1046 // Do not export data for a VIEW
1047 // (For a VIEW, this is called only when exporting a single VIEW)
1048 if (PMA_Table::isView($db, $table)) {
1049 $head = PMA_possibleCRLF()
1050 . PMA_exportComment()
1051 . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name)
1052 . PMA_exportComment(__('Data') . ': ' . __('None'))
1053 . PMA_exportComment()
1054 . PMA_possibleCRLF();
1056 if (! PMA_exportOutputHandler($head)) {
1057 return false;
1059 return true;
1062 // analyze the query to get the true column names, not the aliases
1063 // (this fixes an undefined index, also if Complete inserts
1064 // are used, we did not get the true column name in case of aliases)
1065 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
1067 $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
1068 // a possible error: the table has crashed
1069 $tmp_error = PMA_DBI_getError();
1070 if ($tmp_error) {
1071 return PMA_exportOutputHandler(PMA_exportComment(__('Error reading data:') . ' (' . $tmp_error . ')'));
1074 if ($result != false) {
1075 $fields_cnt = PMA_DBI_num_fields($result);
1077 // Get field information
1078 $fields_meta = PMA_DBI_get_fields_meta($result);
1079 $field_flags = array();
1080 for ($j = 0; $j < $fields_cnt; $j++) {
1081 $field_flags[$j] = PMA_DBI_field_flags($result, $j);
1084 for ($j = 0; $j < $fields_cnt; $j++) {
1085 if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
1086 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
1087 } else {
1088 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
1092 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
1093 // update
1094 $schema_insert = 'UPDATE ';
1095 if (isset($GLOBALS['sql_ignore'])) {
1096 $schema_insert .= 'IGNORE ';
1098 // avoid EOL blank
1099 $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
1100 } else {
1101 // insert or replace
1102 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
1103 $sql_command = 'REPLACE';
1104 } else {
1105 $sql_command = 'INSERT';
1108 // delayed inserts?
1109 if (isset($GLOBALS['sql_delayed'])) {
1110 $insert_delayed = ' DELAYED';
1111 } else {
1112 $insert_delayed = '';
1115 // insert ignore?
1116 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
1117 $insert_delayed .= ' IGNORE';
1120 // scheme for inserting fields
1121 if ($GLOBALS['sql_insert_syntax'] == 'complete' || $GLOBALS['sql_insert_syntax'] == 'both') {
1122 $fields = implode(', ', $field_set);
1123 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1124 // avoid EOL blank
1125 . ' (' . $fields . ') VALUES';
1126 } else {
1127 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
1128 . ' VALUES';
1132 $search = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
1133 $replace = array('\0', '\n', '\r', '\Z');
1134 $current_row = 0;
1135 $query_size = 0;
1136 if (($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
1137 $separator = ',';
1138 $schema_insert .= $crlf;
1139 } else {
1140 $separator = ';';
1143 while ($row = PMA_DBI_fetch_row($result)) {
1144 if ($current_row == 0) {
1145 $head = PMA_possibleCRLF()
1146 . PMA_exportComment()
1147 . PMA_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name)
1148 . PMA_exportComment()
1149 . $crlf;
1150 if (! PMA_exportOutputHandler($head)) {
1151 return false;
1154 $current_row++;
1155 for ($j = 0; $j < $fields_cnt; $j++) {
1156 // NULL
1157 if (!isset($row[$j]) || is_null($row[$j])) {
1158 $values[] = 'NULL';
1159 // a number
1160 // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
1161 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp'
1162 && ! $fields_meta[$j]->blob) {
1163 $values[] = $row[$j];
1164 // a true BLOB
1165 // - mysqldump only generates hex data when the --hex-blob
1166 // option is used, for fields having the binary attribute
1167 // no hex is generated
1168 // - a TEXT field returns type blob but a real blob
1169 // returns also the 'binary' flag
1170 } elseif (stristr($field_flags[$j], 'BINARY')
1171 && $fields_meta[$j]->blob
1172 && isset($GLOBALS['sql_hex_for_blob'])) {
1173 // empty blobs need to be different, but '0' is also empty :-(
1174 if (empty($row[$j]) && $row[$j] != '0') {
1175 $values[] = '\'\'';
1176 } else {
1177 $values[] = '0x' . bin2hex($row[$j]);
1179 // detection of 'bit' works only on mysqli extension
1180 } elseif ($fields_meta[$j]->type == 'bit') {
1181 $values[] = "b'" . PMA_sqlAddSlashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length)) . "'";
1182 // something else -> treat as a string
1183 } else {
1184 $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddSlashes($row[$j])) . '\'';
1185 } // end if
1186 } // end for
1188 // should we make update?
1189 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
1191 $insert_line = $schema_insert;
1192 for ($i = 0; $i < $fields_cnt; $i++) {
1193 if (0 == $i) {
1194 $insert_line .= ' ';
1196 if ($i > 0) {
1197 // avoid EOL blank
1198 $insert_line .= ',';
1200 $insert_line .= $field_set[$i] . ' = ' . $values[$i];
1203 list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
1204 $insert_line .= ' WHERE ' . $tmp_unique_condition;
1205 unset($tmp_unique_condition, $tmp_clause_is_unique);
1207 } else {
1209 // Extended inserts case
1210 if ($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') {
1211 if ($current_row == 1) {
1212 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1213 } else {
1214 $insert_line = '(' . implode(', ', $values) . ')';
1215 if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
1216 if (!PMA_exportOutputHandler(';' . $crlf)) {
1217 return false;
1219 $query_size = 0;
1220 $current_row = 1;
1221 $insert_line = $schema_insert . $insert_line;
1224 $query_size += strlen($insert_line);
1226 // Other inserts case
1227 else {
1228 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
1231 unset($values);
1233 if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
1234 return false;
1237 } // end while
1238 if ($current_row > 0) {
1239 if (!PMA_exportOutputHandler(';' . $crlf)) {
1240 return false;
1243 } // end if ($result != false)
1244 PMA_DBI_free_result($result);
1246 return true;
1247 } // end of the 'PMA_exportData()' function