BLOB streaming documentation
[phpmyadmin/crack.git] / libraries / export / sql.php
blob0780db202031016b6fbd13152390a793865b2a5d
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 * @version $Id$
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' => 'strSQL',
25 'extension' => 'sql',
26 'mime_type' => 'text/x-sql',
27 'options' => array(
28 array('type' => 'text', 'name' => 'header_comment', 'text' => 'strAddHeaderComment'),
29 array('type' => 'bool', 'name' => 'include_comments', 'text' => 'strComments'),
30 array('type' => 'bool', 'name' => 'use_transaction', 'text' => 'strEncloseInTransaction'),
31 array('type' => 'bool', 'name' => 'disable_fk', 'text' => 'strDisableForeignChecks'),
33 'options_text' => 'strOptions',
35 $compats = PMA_DBI_getCompatibilities();
36 if (count($compats) > 0) {
37 $values = array();
38 foreach($compats as $val) {
39 $values[$val] = $val;
41 $plugin_list['sql']['options'][] =
42 array('type' => 'select', 'name' => 'compatibility', 'text' => 'strSQLCompatibility', 'values' => $values, 'doc' => array('manual_MySQL_Database_Administration', 'Server_SQL_mode'));
43 unset($values);
46 /* Server export options */
47 if ($plugin_param['export_type'] == 'server') {
48 $plugin_list['sql']['options'][] =
49 array('type' => 'bgroup', 'text' => 'strDatabaseExportOptions');
50 $plugin_list['sql']['options'][] =
51 array('type' => 'bool', 'name' => 'drop_database', 'text' => sprintf($GLOBALS['strAddClause'], 'DROP DATABASE'));
52 $plugin_list['sql']['options'][] =
53 array('type' => 'egroup');
56 /* Structure options */
57 if (!$hide_structure) {
58 $plugin_list['sql']['options'][] =
59 array('type' => 'bgroup', 'name' => 'structure', 'text' => 'strStructure', 'force' => 'data');
60 if ($plugin_param['export_type'] == 'table') {
61 if (PMA_Table::isView($GLOBALS['db'], $GLOBALS['table'])) {
62 $drop_clause = 'DROP VIEW';
63 } else {
64 $drop_clause = 'DROP TABLE';
66 } else {
67 $drop_clause = 'DROP TABLE / VIEW / PROCEDURE / FUNCTION';
68 if (PMA_MYSQL_INT_VERSION > 50100) {
69 $drop_clause .= ' / EVENT';
72 $plugin_list['sql']['options'][] =
73 array('type' => 'bool', 'name' => 'drop_table', 'text' => sprintf($GLOBALS['strAddClause'], $drop_clause));
74 $plugin_list['sql']['options'][] =
75 array('type' => 'bool', 'name' => 'if_not_exists', 'text' => sprintf($GLOBALS['strAddClause'], 'IF NOT EXISTS'));
76 $plugin_list['sql']['options'][] =
77 array('type' => 'bool', 'name' => 'auto_increment', 'text' => 'strAddAutoIncrement');
78 $plugin_list['sql']['options'][] =
79 array('type' => 'bool', 'name' => 'backquotes', 'text' => 'strUseBackquotes');
80 $plugin_list['sql']['options'][] =
81 array('type' => 'bool', 'name' => 'procedure_function', 'text' => sprintf($GLOBALS['strAddClause'], 'CREATE PROCEDURE / FUNCTION' . (PMA_MYSQL_INT_VERSION > 50100 ? ' / EVENT' : '')));
83 /* MIME stuff etc. */
84 $plugin_list['sql']['options'][] =
85 array('type' => 'bgroup', 'text' => 'strAddIntoComments');
86 $plugin_list['sql']['options'][] =
87 array('type' => 'bool', 'name' => 'dates', 'text' => 'strCreationDates');
88 if (!empty($GLOBALS['cfgRelation']['relation'])) {
89 $plugin_list['sql']['options'][] =
90 array('type' => 'bool', 'name' => 'relation', 'text' => 'strRelations');
92 if (!empty($GLOBALS['cfgRelation']['mimework'])) {
93 $plugin_list['sql']['options'][] =
94 array('type' => 'bool', 'name' => 'mime', 'text' => 'strMIME_MIMEtype');
96 $plugin_list['sql']['options'][] =
97 array('type' => 'egroup');
99 $plugin_list['sql']['options'][] =
100 array('type' => 'egroup');
103 /* Data */
104 $plugin_list['sql']['options'][] =
105 array('type' => 'bgroup', 'name' => 'data', 'text' => 'strData', 'force' => 'structure');
106 $plugin_list['sql']['options'][] =
107 array('type' => 'bool', 'name' => 'columns', 'text' => 'strCompleteInserts', 'doc' => array('programs', 'mysqldump', 'option_mysqldump_complete-insert-option'));
108 $plugin_list['sql']['options'][] =
109 array('type' => 'bool', 'name' => 'extended', 'text' => 'strExtendedInserts', 'doc' => array('programs', 'mysqldump', 'option_mysqldump_extended-insert-option'));
110 $plugin_list['sql']['options'][] =
111 array('type' => 'text', 'name' => 'max_query_size', 'text' => 'strMaximalQueryLength');
112 $plugin_list['sql']['options'][] =
113 array('type' => 'bool', 'name' => 'delayed', 'text' => 'strDelayedInserts');
114 $plugin_list['sql']['options'][] =
115 array('type' => 'bool', 'name' => 'ignore', 'text' => 'strIgnoreInserts');
116 $plugin_list['sql']['options'][] =
117 array('type' => 'bool', 'name' => 'hex_for_blob', 'text' => 'strHexForBLOB');
118 $plugin_list['sql']['options'][] =
119 array('type' => 'select', 'name' => 'type', 'text' => 'strSQLExportType', 'values' => array('INSERT' => 'INSERT', 'UPDATE' => 'UPDATE', 'REPLACE' => 'REPLACE'));
120 $plugin_list['sql']['options'][] =
121 array('type' => 'egroup');
123 } else {
126 * Avoids undefined variables, use NULL so isset() returns false
128 if (! isset($sql_backquotes)) {
129 $sql_backquotes = null;
133 * Outputs comment
135 * @param string Text of comment
137 * @return string The formatted comment
139 function PMA_exportComment($text = '')
141 if ($GLOBALS['sql_include_comments']) {
142 // see http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-comments.html
143 return '--' . (empty($text) ? '' : ' ') . $text . $GLOBALS['crlf'];
144 } else {
145 return '';
150 * Outputs export footer
152 * @return bool Whether it suceeded
154 * @access public
156 function PMA_exportFooter()
158 global $crlf;
159 global $mysql_charset_map;
161 $foot = '';
163 if (isset($GLOBALS['sql_disable_fk'])) {
164 $foot .= $crlf . 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
167 if (isset($GLOBALS['sql_use_transaction'])) {
168 $foot .= $crlf . 'COMMIT;' . $crlf;
171 // restore connection settings
172 // (not set if $cfg['AllowAnywhereRecoding'] is false)
173 $charset_of_file = isset($GLOBALS['charset_of_file']) ? $GLOBALS['charset_of_file'] : '';
174 if (!empty($GLOBALS['asfile']) && isset($mysql_charset_map[$charset_of_file])) {
175 $foot .= $crlf
176 . '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' . $crlf
177 . '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' . $crlf
178 . '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' . $crlf;
181 return PMA_exportOutputHandler($foot);
185 * Outputs export header
187 * @return bool Whether it suceeded
189 * @access public
191 function PMA_exportHeader()
193 global $crlf;
194 global $cfg;
195 global $mysql_charset_map;
197 if (isset($GLOBALS['sql_compatibility'])) {
198 $tmp_compat = $GLOBALS['sql_compatibility'];
199 if ($tmp_compat == 'NONE') {
200 $tmp_compat = '';
202 PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"');
203 unset($tmp_compat);
205 $head = PMA_exportComment('phpMyAdmin SQL Dump')
206 . PMA_exportComment('version ' . PMA_VERSION)
207 . PMA_exportComment('http://www.phpmyadmin.net')
208 . PMA_exportComment();
209 $head .= empty($cfg['Server']['port']) ? PMA_exportComment($GLOBALS['strHost'] . ': ' . $cfg['Server']['host']) : PMA_exportComment($GLOBALS['strHost'] . ': ' . $cfg['Server']['host'] . ':' . $cfg['Server']['port']);
210 $head .= PMA_exportComment($GLOBALS['strGenTime']
211 . ': ' . PMA_localisedDate())
212 . PMA_exportComment($GLOBALS['strServerVersion'] . ': ' . substr(PMA_MYSQL_INT_VERSION, 0, 1) . '.' . (int) substr(PMA_MYSQL_INT_VERSION, 1, 2) . '.' . (int) substr(PMA_MYSQL_INT_VERSION, 3))
213 . PMA_exportComment($GLOBALS['strPHPVersion'] . ': ' . phpversion());
215 if (isset($GLOBALS['sql_header_comment']) && !empty($GLOBALS['sql_header_comment'])) {
216 // '\n' is not a newline (like "\n" would be), it's the characters
217 // backslash and n, as explained on the export interface
218 $lines = explode('\n', $GLOBALS['sql_header_comment']);
219 $head .= PMA_exportComment();
220 foreach($lines as $one_line) {
221 $head .= PMA_exportComment($one_line);
223 $head .= PMA_exportComment();
226 if (isset($GLOBALS['sql_disable_fk'])) {
227 $head .= $crlf . 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
230 /* We want exported AUTO_INCREMENT fields to have still same value, do this only for recent MySQL exports */
231 if (!isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] == 'NONE') {
232 $head .= $crlf . 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . $crlf;
235 if (isset($GLOBALS['sql_use_transaction'])) {
236 $head .= $crlf .'SET AUTOCOMMIT=0;' . $crlf
237 . 'START TRANSACTION;' . $crlf;
240 $head .= $crlf;
242 if (! empty($GLOBALS['asfile'])) {
243 // we are saving as file, therefore we provide charset information
244 // so that a utility like the mysql client can interpret
245 // the file correctly
246 if (isset($GLOBALS['charset_of_file']) && isset($mysql_charset_map[$GLOBALS['charset_of_file']])) {
247 // $cfg['AllowAnywhereRecoding'] was true so we got a charset from
248 // the export dialog
249 $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']];
250 } else {
251 // by default we use the connection charset
252 $set_names = $mysql_charset_map[$GLOBALS['charset']];
254 $head .= $crlf
255 . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;' . $crlf
256 . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;' . $crlf
257 . '/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;' . $crlf
258 . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf;
261 return PMA_exportOutputHandler($head);
265 * Outputs CREATE DATABASE database
267 * @param string Database name
269 * @return bool Whether it suceeded
271 * @access public
273 function PMA_exportDBCreate($db)
275 global $crlf;
276 if (isset($GLOBALS['sql_drop_database'])) {
277 if (!PMA_exportOutputHandler('DROP DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db) . ';' . $crlf)) {
278 return FALSE;
281 $create_query = 'CREATE DATABASE ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : $db);
282 $collation = PMA_getDbCollation($db);
283 if (strpos($collation, '_')) {
284 $create_query .= ' DEFAULT CHARACTER SET ' . substr($collation, 0, strpos($collation, '_')) . ' COLLATE ' . $collation;
285 } else {
286 $create_query .= ' DEFAULT CHARACTER SET ' . $collation;
288 $create_query .= ';' . $crlf;
289 if (!PMA_exportOutputHandler($create_query)) {
290 return FALSE;
292 if (isset($GLOBALS['sql_backquotes']) && isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'NONE') {
293 return PMA_exportOutputHandler('USE ' . PMA_backquote($db) . ';' . $crlf);
295 return PMA_exportOutputHandler('USE ' . $db . ';' . $crlf);
299 * Outputs database header
301 * @param string Database name
303 * @return bool Whether it suceeded
305 * @access public
307 function PMA_exportDBHeader($db)
309 $head = PMA_exportComment()
310 . PMA_exportComment($GLOBALS['strDatabase'] . ': ' . (isset($GLOBALS['sql_backquotes']) ? PMA_backquote($db) : '\'' . $db . '\''))
311 . PMA_exportComment();
312 return PMA_exportOutputHandler($head);
316 * Outputs database footer
318 * @param string Database name
320 * @return bool Whether it suceeded
322 * @access public
324 function PMA_exportDBFooter($db)
326 global $crlf;
328 $result = TRUE;
329 if (isset($GLOBALS['sql_constraints'])) {
330 $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']);
331 unset($GLOBALS['sql_constraints']);
334 if (isset($GLOBALS['sql_structure']) && isset($GLOBALS['sql_procedure_function'])) {
335 $text = '';
336 $delimiter = '$$';
338 $procedure_names = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE');
339 $function_names = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION');
341 if (PMA_MYSQL_INT_VERSION > 50100) {
342 $event_names = PMA_DBI_fetch_result('SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \'' . PMA_sqlAddslashes($db,true) . '\';');
343 } else {
344 $event_names = array();
347 if ($procedure_names || $function_names || $event_names) {
348 $text .= $crlf
349 . 'DELIMITER ' . $delimiter . $crlf;
352 if ($procedure_names) {
353 $text .=
354 PMA_exportComment()
355 . PMA_exportComment($GLOBALS['strProcedures'])
356 . PMA_exportComment();
358 foreach($procedure_names as $procedure_name) {
359 if (! empty($GLOBALS['sql_drop_table'])) {
360 $text .= 'DROP PROCEDURE IF EXISTS ' . PMA_backquote($procedure_name) . $delimiter . $crlf;
362 $text .= PMA_DBI_get_definition($db, 'PROCEDURE', $procedure_name) . $delimiter . $crlf . $crlf;
366 if ($function_names) {
367 $text .=
368 PMA_exportComment()
369 . PMA_exportComment($GLOBALS['strFunctions'])
370 . PMA_exportComment();
372 foreach($function_names as $function_name) {
373 if (! empty($GLOBALS['sql_drop_table'])) {
374 $text .= 'DROP FUNCTION IF EXISTS ' . PMA_backquote($function_name) . $delimiter . $crlf;
376 $text .= PMA_DBI_get_definition($db, 'FUNCTION', $function_name) . $delimiter . $crlf . $crlf;
380 if ($event_names) {
381 $text .=
382 PMA_exportComment()
383 . PMA_exportComment($GLOBALS['strEvents'])
384 . PMA_exportComment();
386 foreach($event_names as $event_name) {
387 if (! empty($GLOBALS['sql_drop_table'])) {
388 $text .= 'DROP EVENT ' . PMA_backquote($event_name) . $delimiter . $crlf;
390 $text .= PMA_DBI_get_definition($db, 'EVENT', $event_name) . $delimiter . $crlf . $crlf;
393 if ($procedure_names || $function_names || $event_names) {
394 $text .= 'DELIMITER ;' . $crlf;
397 if (! empty($text)) {
398 $result = PMA_exportOutputHandler($text);
401 return $result;
406 * Returns a stand-in CREATE definition to resolve view dependencies
408 * @param string the database name
409 * @param string the vew name
410 * @param string the end of line sequence
412 * @return string resulting definition
414 * @access public
416 function PMA_getTableDefStandIn($db, $view, $crlf) {
417 $create_query = '';
418 if (! empty($GLOBALS['sql_drop_table'])) {
419 $create_query .= 'DROP VIEW IF EXISTS ' . PMA_backquote($view) . ';' . $crlf;
422 $create_query .= 'CREATE TABLE ';
424 if (isset($GLOBALS['sql_if_not_exists']) && $GLOBALS['sql_if_not_exists']) {
425 $create_query .= 'IF NOT EXISTS ';
427 $create_query .= PMA_backquote($view) . ' (' . $crlf;
428 $tmp = array();
429 $columns = PMA_DBI_get_columns_full($db, $view);
430 foreach($columns as $column_name => $definition) {
431 $tmp[] = PMA_backquote($column_name) . ' ' . $definition['Type'] . $crlf;
433 $create_query .= implode(',', $tmp) . ');';
434 return($create_query);
438 * Returns $table's CREATE definition
440 * @param string the database name
441 * @param string the table name
442 * @param string the end of line sequence
443 * @param string the url to go back in case of error
444 * @param boolean whether to include creation/update/check dates
445 * @param boolean whether to add semicolon and end-of-line at the end
447 * @return string resulting schema
449 * @global boolean whether to add 'drop' statements or not
450 * @global boolean whether to use backquotes to allow the use of special
451 * characters in database, table and fields names or not
453 * @access public
455 function PMA_getTableDef($db, $table, $crlf, $error_url, $show_dates = false, $add_semicolon = true)
457 global $sql_drop_table;
458 global $sql_backquotes;
459 global $cfgRelation;
460 global $sql_constraints;
461 global $sql_constraints_query; // just the text of the query
463 $schema_create = '';
464 $auto_increment = '';
465 $new_crlf = $crlf;
467 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
468 $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table) . '\'', null, PMA_DBI_QUERY_STORE);
469 if ($result != FALSE) {
470 if (PMA_DBI_num_rows($result) > 0) {
471 $tmpres = PMA_DBI_fetch_assoc($result);
472 // Here we optionally add the AUTO_INCREMENT next value,
473 // but starting with MySQL 5.0.24, the clause is already included
474 // in SHOW CREATE TABLE so we'll remove it below
475 if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
476 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
479 if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
480 $schema_create .= PMA_exportComment($GLOBALS['strStatCreateTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])));
481 $new_crlf = PMA_exportComment() . $crlf;
484 if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
485 $schema_create .= PMA_exportComment($GLOBALS['strStatUpdateTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])));
486 $new_crlf = PMA_exportComment() . $crlf;
489 if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
490 $schema_create .= PMA_exportComment($GLOBALS['strStatCheckTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])));
491 $new_crlf = PMA_exportComment() . $crlf;
494 PMA_DBI_free_result($result);
497 $schema_create .= $new_crlf;
499 // no need to generate a DROP VIEW here, it was done earlier
500 if (! empty($sql_drop_table) && ! PMA_Table::isView($db,$table)) {
501 $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table, $sql_backquotes) . ';' . $crlf;
504 // Steve Alberty's patch for complete table dump,
505 // Whether to quote table and fields names or not
506 if ($sql_backquotes) {
507 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
508 } else {
509 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
512 // I don't see the reason why this unbuffered query could cause problems,
513 // because SHOW CREATE TABLE returns only one row, and we free the
514 // results below. Nonetheless, we got 2 user reports about this
515 // (see bug 1562533) so I remove the unbuffered mode.
516 //$result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), null, PMA_DBI_QUERY_UNBUFFERED);
518 // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
519 // produce a displayable result for the default value of a BIT
520 // field, nor does the mysqldump command. See MySQL bug 35796
521 $result = PMA_DBI_try_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table));
522 // an error can happen, for example the table is crashed
523 $tmp_error = PMA_DBI_getError();
524 if ($tmp_error) {
525 return PMA_exportComment($GLOBALS['strInUse'] . '(' . $tmp_error . ')');
528 if ($result != FALSE && ($row = PMA_DBI_fetch_row($result))) {
529 $create_query = $row[1];
530 unset($row);
532 // Convert end of line chars to one that we want (note that MySQL doesn't return query it will accept in all cases)
533 if (strpos($create_query, "(\r\n ")) {
534 $create_query = str_replace("\r\n", $crlf, $create_query);
535 } elseif (strpos($create_query, "(\n ")) {
536 $create_query = str_replace("\n", $crlf, $create_query);
537 } elseif (strpos($create_query, "(\r ")) {
538 $create_query = str_replace("\r", $crlf, $create_query);
541 // Should we use IF NOT EXISTS?
542 if (isset($GLOBALS['sql_if_not_exists'])) {
543 $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
546 // are there any constraints to cut out?
547 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
549 // Split the query into lines, so we can easily handle it. We know lines are separated by $crlf (done few lines above).
550 $sql_lines = explode($crlf, $create_query);
551 $sql_count = count($sql_lines);
553 // lets find first line with constraints
554 for ($i = 0; $i < $sql_count; $i++) {
555 if (preg_match('@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', $sql_lines[$i])) {
556 break;
560 // If we really found a constraint
561 if ($i != $sql_count) {
563 // remove , from the end of create statement
564 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
566 // prepare variable for constraints
567 if (!isset($sql_constraints)) {
568 if (isset($GLOBALS['no_constraints_comments'])) {
569 $sql_constraints = '';
570 } else {
571 $sql_constraints = $crlf
572 . PMA_exportComment()
573 . PMA_exportComment($GLOBALS['strConstraintsForDumped'])
574 . PMA_exportComment();
578 // comments for current table
579 if (!isset($GLOBALS['no_constraints_comments'])) {
580 $sql_constraints .= $crlf
581 . PMA_exportComment()
582 . PMA_exportComment($GLOBALS['strConstraintsForTable'] . ' ' . PMA_backquote($table))
583 . PMA_exportComment();
586 // let's do the work
587 $sql_constraints_query .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
588 $sql_constraints .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
590 $first = TRUE;
591 for ($j = $i; $j < $sql_count; $j++) {
592 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $sql_lines[$j])) {
593 if (!$first) {
594 $sql_constraints .= $crlf;
596 if (strpos($sql_lines[$j], 'CONSTRAINT') === FALSE) {
597 $str_tmp = preg_replace('/(FOREIGN[\s]+KEY)/', 'ADD \1', $sql_lines[$j]);
598 $sql_constraints_query .= $str_tmp;
599 $sql_constraints .= $str_tmp;
600 } else {
601 $str_tmp = preg_replace('/(CONSTRAINT)/', 'ADD \1', $sql_lines[$j]);
602 $sql_constraints_query .= $str_tmp;
603 $sql_constraints .= $str_tmp;
605 $first = FALSE;
606 } else {
607 break;
610 $sql_constraints .= ';' . $crlf;
611 $sql_constraints_query .= ';';
613 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
614 unset($sql_lines);
617 $schema_create .= $create_query;
620 // remove a possible "AUTO_INCREMENT = value" clause
621 // that could be there starting with MySQL 5.0.24
622 $schema_create = preg_replace('/AUTO_INCREMENT\s*=\s*([0-9])+/', '', $schema_create);
624 $schema_create .= $auto_increment;
626 PMA_DBI_free_result($result);
627 return $schema_create . ($add_semicolon ? ';' . $crlf : '');
628 } // end of the 'PMA_getTableDef()' function
632 * Returns $table's comments, relations etc.
634 * @param string the database name
635 * @param string the table name
636 * @param string the end of line sequence
637 * @param boolean whether to include relation comments
638 * @param boolean whether to include mime comments
640 * @return string resulting comments
642 * @access public
644 function PMA_getTableComments($db, $table, $crlf, $do_relation = false, $do_mime = false)
646 global $cfgRelation;
647 global $sql_backquotes;
648 global $sql_constraints;
650 $schema_create = '';
652 // Check if we can use Relations (Mike Beck)
653 if ($do_relation && !empty($cfgRelation['relation'])) {
654 // Find which tables are related with the current one and write it in
655 // an array
656 $res_rel = PMA_getForeigners($db, $table);
658 if ($res_rel && count($res_rel) > 0) {
659 $have_rel = TRUE;
660 } else {
661 $have_rel = FALSE;
663 } else {
664 $have_rel = FALSE;
665 } // end if
667 if ($do_mime && $cfgRelation['mimework']) {
668 if (!($mime_map = PMA_getMIME($db, $table, true))) {
669 unset($mime_map);
673 if (isset($mime_map) && count($mime_map) > 0) {
674 $schema_create .= $crlf
675 . PMA_exportComment()
676 . PMA_exportComment($GLOBALS['strMIMETypesForTable']. ' ' . PMA_backquote($table, $sql_backquotes) . ':');
677 @reset($mime_map);
678 foreach ($mime_map AS $mime_field => $mime) {
679 $schema_create .= PMA_exportComment(' ' . PMA_backquote($mime_field, $sql_backquotes))
680 . PMA_exportComment(' ' . PMA_backquote($mime['mimetype'], $sql_backquotes));
682 $schema_create .= PMA_exportComment();
685 if ($have_rel) {
686 $schema_create .= $crlf
687 . PMA_exportComment()
688 . PMA_exportComment($GLOBALS['strRelationsForTable']. ' ' . PMA_backquote($table, $sql_backquotes) . ':');
689 foreach ($res_rel AS $rel_field => $rel) {
690 $schema_create .= PMA_exportComment(' ' . PMA_backquote($rel_field, $sql_backquotes))
691 . PMA_exportComment(' ' . PMA_backquote($rel['foreign_table'], $sql_backquotes)
692 . ' -> ' . PMA_backquote($rel['foreign_field'], $sql_backquotes));
694 $schema_create .= PMA_exportComment();
697 return $schema_create;
699 } // end of the 'PMA_getTableComments()' function
702 * Outputs table's structure
704 * @param string the database name
705 * @param string the table name
706 * @param string the end of line sequence
707 * @param string the url to go back in case of error
708 * @param boolean whether to include relation comments
709 * @param boolean whether to include the pmadb-style column comments
710 * as comments in the structure; this is deprecated
711 * but the parameter is left here because export.php
712 * calls PMA_exportStructure() also for other export
713 * types which use this parameter
714 * @param boolean whether to include mime comments
715 * @param string 'stand_in', 'create_table', 'create_view'
716 * @param string 'server', 'database', 'table'
718 * @return bool Whether it suceeded
720 * @access public
722 function PMA_exportStructure($db, $table, $crlf, $error_url, $relation = FALSE, $comments = FALSE, $mime = FALSE, $dates = FALSE, $export_mode, $export_type)
724 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
725 ? PMA_backquote($table)
726 : '\'' . $table . '\'';
727 $dump = $crlf
728 . PMA_exportComment(str_repeat('-', 56))
729 . $crlf
730 . PMA_exportComment();
732 switch($export_mode) {
733 case 'create_table':
734 $dump .= PMA_exportComment($GLOBALS['strTableStructure'] . ' ' . $formatted_table_name)
735 . PMA_exportComment();
736 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates);
737 $triggers = PMA_DBI_get_triggers($db, $table);
738 if ($triggers) {
739 $dump .= $crlf
740 . PMA_exportComment()
741 . PMA_exportComment($GLOBALS['strTriggers'] . ' ' . $formatted_table_name)
742 . PMA_exportComment();
743 $delimiter = '//';
744 foreach ($triggers as $trigger) {
745 $dump .= $trigger['drop'] . ';' . $crlf;
746 $dump .= 'DELIMITER ' . $delimiter . $crlf;
747 $dump .= $trigger['create'];
748 $dump .= 'DELIMITER ;' . $crlf;
751 break;
752 case 'create_view':
753 $dump .= PMA_exportComment($GLOBALS['strStructureForView'] . ' ' . $formatted_table_name)
754 . PMA_exportComment();
755 // delete the stand-in table previously created (if any)
756 if ($export_type != 'table') {
757 $dump .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table) . ';' . $crlf;
759 $dump .= PMA_getTableDef($db, $table, $crlf, $error_url, $dates);
760 break;
761 case 'stand_in':
762 $dump .= PMA_exportComment($GLOBALS['strStandInStructureForView'] . ' ' . $formatted_table_name)
763 . PMA_exportComment();
764 // export a stand-in definition to resolve view dependencies
765 $dump .= PMA_getTableDefStandIn($db, $table, $crlf);
766 } // end switch
768 $dump .= PMA_getTableComments($db, $table, $crlf, $relation, $mime);
769 // this one is built by PMA_getTableDef() to use in table copy/move
770 // but not in the case of export
771 unset($GLOBALS['sql_constraints_query']);
773 return PMA_exportOutputHandler($dump);
777 * Dispatches between the versions of 'getTableContent' to use depending
778 * on the php version
780 * @param string the database name
781 * @param string the table name
782 * @param string the end of line sequence
783 * @param string the url to go back in case of error
784 * @param string SQL query for obtaining data
786 * @return bool Whether it suceeded
788 * @global boolean whether to use backquotes to allow the use of special
789 * characters in database, table and fields names or not
790 * @global integer the number of records
791 * @global integer the current record position
793 * @access public
795 * @see PMA_getTableContentFast(), PMA_getTableContentOld()
797 * @author staybyte
799 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
801 global $sql_backquotes;
802 global $rows_cnt;
803 global $current_row;
805 $formatted_table_name = (isset($GLOBALS['sql_backquotes']))
806 ? PMA_backquote($table)
807 : '\'' . $table . '\'';
809 // Do not export data for a VIEW
810 // (For a VIEW, this is called only when exporting a single VIEW)
811 if (PMA_Table::isView($db, $table)) {
812 $head = $crlf
813 . PMA_exportComment()
814 . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name)
815 . PMA_exportComment($GLOBALS['strData'] . ': ' . $GLOBALS['strNone'])
816 . PMA_exportComment()
817 . $crlf;
819 if (! PMA_exportOutputHandler($head)) {
820 return FALSE;
822 return true;
825 // it's not a VIEW
826 $head = $crlf
827 . PMA_exportComment()
828 . PMA_exportComment($GLOBALS['strDumpingData'] . ' ' . $formatted_table_name)
829 . PMA_exportComment()
830 . $crlf;
832 if (! PMA_exportOutputHandler($head)) {
833 return FALSE;
836 $buffer = '';
838 // analyze the query to get the true column names, not the aliases
839 // (this fixes an undefined index, also if Complete inserts
840 // are used, we did not get the true column name in case of aliases)
841 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
843 $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
844 // a possible error: the table has crashed
845 $tmp_error = PMA_DBI_getError();
846 if ($tmp_error) {
847 return PMA_exportOutputHandler(PMA_exportComment($GLOBALS['strInUse'] . ' (' . $tmp_error . ')'));
850 if ($result != FALSE) {
851 $fields_cnt = PMA_DBI_num_fields($result);
853 // Get field information
854 $fields_meta = PMA_DBI_get_fields_meta($result);
855 $field_flags = array();
856 for ($j = 0; $j < $fields_cnt; $j++) {
857 $field_flags[$j] = PMA_DBI_field_flags($result, $j);
860 for ($j = 0; $j < $fields_cnt; $j++) {
861 if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
862 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
863 } else {
864 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
868 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
869 // update
870 $schema_insert = 'UPDATE ';
871 if (isset($GLOBALS['sql_ignore'])) {
872 $schema_insert .= 'IGNORE ';
874 // avoid EOL blank
875 $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
876 } else {
877 // insert or replace
878 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
879 $sql_command = 'REPLACE';
880 } else {
881 $sql_command = 'INSERT';
884 // delayed inserts?
885 if (isset($GLOBALS['sql_delayed'])) {
886 $insert_delayed = ' DELAYED';
887 } else {
888 $insert_delayed = '';
891 // insert ignore?
892 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
893 $insert_delayed .= ' IGNORE';
896 // scheme for inserting fields
897 if (isset($GLOBALS['sql_columns'])) {
898 $fields = implode(', ', $field_set);
899 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
900 // avoid EOL blank
901 . ' (' . $fields . ') VALUES';
902 } else {
903 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $sql_backquotes)
904 . ' VALUES';
908 $search = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
909 $replace = array('\0', '\n', '\r', '\Z');
910 $current_row = 0;
911 $query_size = 0;
912 if (isset($GLOBALS['sql_extended']) && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
913 $separator = ',';
914 $schema_insert .= $crlf;
915 } else {
916 $separator = ';';
919 while ($row = PMA_DBI_fetch_row($result)) {
920 $current_row++;
921 for ($j = 0; $j < $fields_cnt; $j++) {
922 // NULL
923 if (!isset($row[$j]) || is_null($row[$j])) {
924 $values[] = 'NULL';
925 // a number
926 // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
927 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp'
928 && ! $fields_meta[$j]->blob) {
929 $values[] = $row[$j];
930 // a true BLOB
931 // - mysqldump only generates hex data when the --hex-blob
932 // option is used, for fields having the binary attribute
933 // no hex is generated
934 // - a TEXT field returns type blob but a real blob
935 // returns also the 'binary' flag
936 } elseif (stristr($field_flags[$j], 'BINARY')
937 && $fields_meta[$j]->blob
938 && isset($GLOBALS['sql_hex_for_blob'])) {
939 // empty blobs need to be different, but '0' is also empty :-(
940 if (empty($row[$j]) && $row[$j] != '0') {
941 $values[] = '\'\'';
942 } else {
943 $values[] = '0x' . bin2hex($row[$j]);
945 // detection of 'bit' works only on mysqli extension
946 } elseif ($fields_meta[$j]->type == 'bit') {
947 $values[] = "b'" . PMA_sqlAddslashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length)) . "'";
948 // something else -> treat as a string
949 } else {
950 $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
951 } // end if
952 } // end for
954 // should we make update?
955 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
957 $insert_line = $schema_insert;
958 for ($i = 0; $i < $fields_cnt; $i++) {
959 if (0 == $i) {
960 $insert_line .= ' ';
962 if ($i > 0) {
963 // avoid EOL blank
964 $insert_line .= ',';
966 $insert_line .= $field_set[$i] . ' = ' . $values[$i];
969 $insert_line .= ' WHERE ' . PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
971 } else {
973 // Extended inserts case
974 if (isset($GLOBALS['sql_extended'])) {
975 if ($current_row == 1) {
976 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
977 } else {
978 $insert_line = '(' . implode(', ', $values) . ')';
979 if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
980 if (!PMA_exportOutputHandler(';' . $crlf)) {
981 return FALSE;
983 $query_size = 0;
984 $current_row = 1;
985 $insert_line = $schema_insert . $insert_line;
988 $query_size += strlen($insert_line);
990 // Other inserts case
991 else {
992 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
995 unset($values);
997 if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
998 return FALSE;
1001 } // end while
1002 if ($current_row > 0) {
1003 if (!PMA_exportOutputHandler(';' . $crlf)) {
1004 return FALSE;
1007 } // end if ($result != FALSE)
1008 PMA_DBI_free_result($result);
1010 return TRUE;
1011 } // end of the 'PMA_exportData()' function