3 // vim: expandtab sw=4 ts=4 sts=4:
5 * Set of functions used to build SQL dumps of tables
9 * Marker for comments, -- is needed for ANSI SQL.
11 $GLOBALS['comment_marker'] = '-- ';
16 * @param string Text of comment
18 * @return bool Whether it suceeded
20 function PMA_exportComment($text) {
21 return PMA_exportOutputHandler($GLOBALS['comment_marker'] . $text . $GLOBALS['crlf']);
25 * Outputs export footer
27 * @return bool Whether it suceeded
31 function PMA_exportFooter() {
36 if (isset($GLOBALS['disable_fk'])) {
37 $foot .= $crlf . 'SET FOREIGN_KEY_CHECKS=1;' . $crlf;
40 if (isset($GLOBALS['use_transaction'])) {
41 $foot .= $crlf . 'COMMIT;' . $crlf;
44 return PMA_exportOutputHandler($foot);
48 * Outputs export header
50 * @return bool Whether it suceeded
54 function PMA_exportHeader() {
58 if (PMA_MYSQL_INT_VERSION
>= 40100 && isset($GLOBALS['sql_compat']) && $GLOBALS['sql_compat'] != 'NONE') {
59 PMA_DBI_try_query('SET SQL_MODE="' . $GLOBALS['sql_compat'] . '"');
62 $head = $GLOBALS['comment_marker'] . 'phpMyAdmin SQL Dump' . $crlf
63 . $GLOBALS['comment_marker'] . 'version ' . PMA_VERSION
. $crlf
64 . $GLOBALS['comment_marker'] . 'http://www.phpmyadmin.net' . $crlf
65 . $GLOBALS['comment_marker'] . $crlf
66 . $GLOBALS['comment_marker'] . $GLOBALS['strHost'] . ': ' . $cfg['Server']['host'];
67 if (!empty($cfg['Server']['port'])) {
68 $head .= ':' . $cfg['Server']['port'];
71 . $GLOBALS['comment_marker'] . $GLOBALS['strGenTime'] . ': ' . PMA_localisedDate() . $crlf
72 . $GLOBALS['comment_marker'] . $GLOBALS['strServerVersion'] . ': ' . substr(PMA_MYSQL_INT_VERSION
, 0, 1) . '.' . (int) substr(PMA_MYSQL_INT_VERSION
, 1, 2) . '.' . (int) substr(PMA_MYSQL_INT_VERSION
, 3) . $crlf
73 . $GLOBALS['comment_marker'] . $GLOBALS['strPHPVersion'] . ': ' . phpversion() . $crlf;
75 if (isset($GLOBALS['header_comment']) && !empty($GLOBALS['header_comment'])) {
76 $lines = explode('\n', $GLOBALS['header_comment']);
77 $head .= $GLOBALS['comment_marker'] . $crlf
78 . $GLOBALS['comment_marker'] . implode($crlf . $GLOBALS['comment_marker'], $lines) . $crlf
79 . $GLOBALS['comment_marker'] . $crlf;
82 if (isset($GLOBALS['disable_fk'])) {
83 $head .= $crlf . 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
86 if (isset($GLOBALS['use_transaction'])) {
87 $head .= $crlf .'SET AUTOCOMMIT=0;' . $crlf
88 . 'START TRANSACTION;' . $crlf . $crlf;
91 return PMA_exportOutputHandler($head);
95 * Outputs create database database
97 * @param string Database name
99 * @return bool Whether it suceeded
103 function PMA_exportDBCreate($db) {
105 if (isset($GLOBALS['drop_database'])) {
106 if (!PMA_exportOutputHandler('DROP DATABASE ' . (isset($GLOBALS['use_backquotes']) ?
PMA_backquote($db) : $db) . ';' . $crlf)) return FALSE;
108 $create_query = 'CREATE DATABASE ' . (isset($GLOBALS['use_backquotes']) ?
PMA_backquote($db) : $db);
109 if (PMA_MYSQL_INT_VERSION
>= 40101) {
110 $collation = PMA_getDbCollation($db);
111 if (strpos($collation, '_')) {
112 $create_query .= ' DEFAULT CHARACTER SET ' . substr($collation, 0, strpos($collation, '_')) . ' COLLATE ' . $collation;
114 $create_query .= ' DEFAULT CHARACTER SET ' . $collation;
117 $create_query .= ';' . $crlf;
118 if (!PMA_exportOutputHandler($create_query)) return FALSE;
119 return PMA_exportOutputHandler('USE ' . $db . ';' . $crlf);
123 * Outputs database header
125 * @param string Database name
127 * @return bool Whether it suceeded
131 function PMA_exportDBHeader($db) {
133 $head = $GLOBALS['comment_marker'] . $crlf
134 . $GLOBALS['comment_marker'] . $GLOBALS['strDatabase'] . ': ' . (isset($GLOBALS['use_backquotes']) ?
PMA_backquote($db) : '\'' . $db . '\''). $crlf
135 . $GLOBALS['comment_marker'] . $crlf;
136 return PMA_exportOutputHandler($head);
140 * Outputs database footer
142 * @param string Database name
144 * @return bool Whether it suceeded
148 function PMA_exportDBFooter($db) {
150 if (isset($GLOBALS['sql_constraints'])) {
151 $result = PMA_exportOutputHandler($GLOBALS['sql_constraints']);
152 unset($GLOBALS['sql_constraints']);
158 * Returns $table's CREATE definition
160 * @param string the database name
161 * @param string the table name
162 * @param string the end of line sequence
163 * @param string the url to go back in case of error
164 * @param boolean whether to include creation/update/check dates
166 * @return string resulting schema
168 * @global boolean whether to add 'drop' statements or not
169 * @global boolean whether to use backquotes to allow the use of special
170 * characters in database, table and fields names or not
174 function PMA_getTableDef($db, $table, $crlf, $error_url, $show_dates = false)
177 global $use_backquotes;
179 global $sql_constraints;
182 $auto_increment = '';
185 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
186 $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table) . '\'', NULL, PMA_DBI_QUERY_STORE
);
187 if ($result != FALSE) {
188 if (PMA_DBI_num_rows($result) > 0) {
189 $tmpres = PMA_DBI_fetch_assoc($result);
190 if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
191 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
194 if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
195 $schema_create .= $GLOBALS['comment_marker'] . $GLOBALS['strStatCreateTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Create_time'])) . $crlf;
196 $new_crlf = $GLOBALS['comment_marker'] . $crlf . $crlf;
199 if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
200 $schema_create .= $GLOBALS['comment_marker'] . $GLOBALS['strStatUpdateTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Update_time'])) . $crlf;
201 $new_crlf = $GLOBALS['comment_marker'] . $crlf . $crlf;
204 if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
205 $schema_create .= $GLOBALS['comment_marker'] . $GLOBALS['strStatCheckTime'] . ': ' . PMA_localisedDate(strtotime($tmpres['Check_time'])) . $crlf;
206 $new_crlf = $GLOBALS['comment_marker'] . $crlf . $crlf;
209 PMA_DBI_free_result($result);
212 $schema_create .= $new_crlf;
215 $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_backquote($table, $use_backquotes) . ';' . $crlf;
218 // Steve Alberty's patch for complete table dump,
219 // Whether to quote table and fields names or not
220 if ($use_backquotes) {
221 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
223 PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
226 $result = PMA_DBI_query('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), NULL, PMA_DBI_QUERY_UNBUFFERED
);
227 if ($result != FALSE && ($row = PMA_DBI_fetch_row($result))) {
228 $create_query = $row[1];
231 // Convert end of line chars to one that we want (note that MySQL doesn't return query it will accept in all cases)
232 if (strpos($create_query, "(\r\n ")) {
233 $create_query = str_replace("\r\n", $crlf, $create_query);
234 } elseif (strpos($create_query, "(\n ")) {
235 $create_query = str_replace("\n", $crlf, $create_query);
236 } elseif (strpos($create_query, "(\r ")) {
237 $create_query = str_replace("\r", $crlf, $create_query);
240 // Should we use IF NOT EXISTS?
241 if (isset($GLOBALS['if_not_exists'])) {
242 $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
245 // are there any constraints to cut out?
246 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $create_query)) {
248 // Split the query into lines, so we can easily handle it. We know lines are separated by $crlf (done few lines above).
249 $sql_lines = explode($crlf, $create_query);
250 $sql_count = count($sql_lines);
252 // lets find first line with constraints
253 for ($i = 0; $i < $sql_count; $i++
) {
254 if (preg_match('@^[\s]*(CONSTRAINT|FOREIGN[\s]+KEY)@', $sql_lines[$i])) break;
257 // If we really found a constraint
258 if ($i != $sql_count) {
260 // remove , from the end of create statement
261 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
263 // prepare variable for constraints
264 if (!isset($sql_constraints)) {
265 if (isset($GLOBALS['no_constraints_comments'])) {
266 $sql_constraints = '';
268 $sql_constraints = $crlf . $GLOBALS['comment_marker'] .
269 $crlf . $GLOBALS['comment_marker'] . $GLOBALS['strConstraintsForDumped'] .
270 $crlf . $GLOBALS['comment_marker'] . $crlf;
274 // comments for current table
275 if (!isset($GLOBALS['no_constraints_comments'])) {
276 $sql_constraints .= $crlf . $GLOBALS['comment_marker'] .
277 $crlf . $GLOBALS['comment_marker'] . $GLOBALS['strConstraintsForTable'] . ' ' . PMA_backquote($table) .
278 $crlf . $GLOBALS['comment_marker'] . $crlf;
282 $sql_constraints .= 'ALTER TABLE ' . PMA_backquote($table) . $crlf;
285 for($j = $i; $j < $sql_count; $j++
) {
286 if (preg_match('@CONSTRAINT|FOREIGN[\s]+KEY@', $sql_lines[$j])) {
288 $sql_constraints .= $crlf;
290 if (strpos($sql_lines[$j], 'CONSTRAINT') === FALSE) {
291 $sql_constraints .= preg_replace('/(FOREIGN[\s]+KEY)/', 'ADD \1', $sql_lines[$j]);
293 $sql_constraints .= preg_replace('/(CONSTRAINT)/', 'ADD \1', $sql_lines[$j]);
300 $sql_constraints .= ';' . $crlf;
301 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
305 $schema_create .= $create_query;
308 $schema_create .= $auto_increment;
310 PMA_DBI_free_result($result);
311 return $schema_create;
312 } // end of the 'PMA_getTableDef()' function
316 * Returns $table's comments, relations etc.
318 * @param string the database name
319 * @param string the table name
320 * @param string the end of line sequence
321 * @param boolean whether to include relation comments
322 * @param boolean whether to include column comments
323 * @param boolean whether to include mime comments
325 * @return string resulting comments
329 function PMA_getTableComments($db, $table, $crlf, $do_relation = false, $do_comments = false, $do_mime = false)
332 global $use_backquotes;
333 global $sql_constraints;
337 // triggered only for MySQL < 4.1.x (pmadb-style comments)
338 if ($do_comments && $cfgRelation['commwork']) {
339 if (!($comments_map = PMA_getComments($db, $table))) {
340 unset($comments_map);
344 // Check if we can use Relations (Mike Beck)
345 if ($do_relation && !empty($cfgRelation['relation'])) {
346 // Find which tables are related with the current one and write it in
348 $res_rel = PMA_getForeigners($db, $table);
350 if ($res_rel && count($res_rel) > 0) {
360 if ($do_mime && $cfgRelation['mimework']) {
361 if (!($mime_map = PMA_getMIME($db, $table, true))) unset($mime_map);
364 if (isset($comments_map) && count($comments_map) > 0) {
365 $schema_create .= $crlf . $GLOBALS['comment_marker'] . $crlf
366 . $GLOBALS['comment_marker'] . $GLOBALS['strCommentsForTable']. ' ' . PMA_backquote($table, $use_backquotes) . ':' . $crlf;
367 foreach ($comments_map AS $comment_field => $comment) {
368 $schema_create .= $GLOBALS['comment_marker'] . ' ' . PMA_backquote($comment_field, $use_backquotes) . $crlf
369 . $GLOBALS['comment_marker'] . ' ' . PMA_backquote($comment, $use_backquotes) . $crlf;
371 $schema_create .= $GLOBALS['comment_marker'] . $crlf;
374 if (isset($mime_map) && count($mime_map) > 0) {
375 $schema_create .= $crlf . $GLOBALS['comment_marker'] . $crlf
376 . $GLOBALS['comment_marker'] . $GLOBALS['strMIMETypesForTable']. ' ' . PMA_backquote($table, $use_backquotes) . ':' . $crlf;
378 foreach ($mime_map AS $mime_field => $mime) {
379 $schema_create .= $GLOBALS['comment_marker'] . ' ' . PMA_backquote($mime_field, $use_backquotes) . $crlf
380 . $GLOBALS['comment_marker'] . ' ' . PMA_backquote($mime['mimetype'], $use_backquotes) . $crlf;
382 $schema_create .= $GLOBALS['comment_marker'] . $crlf;
386 $schema_create .= $crlf . $GLOBALS['comment_marker'] . $crlf
387 . $GLOBALS['comment_marker'] . $GLOBALS['strRelationsForTable']. ' ' . PMA_backquote($table, $use_backquotes) . ':' . $crlf;
388 foreach ($res_rel AS $rel_field => $rel) {
389 $schema_create .= $GLOBALS['comment_marker'] . ' ' . PMA_backquote($rel_field, $use_backquotes) . $crlf
390 . $GLOBALS['comment_marker'] . ' ' . PMA_backquote($rel['foreign_table'], $use_backquotes)
391 . ' -> ' . PMA_backquote($rel['foreign_field'], $use_backquotes) . $crlf;
393 $schema_create .= $GLOBALS['comment_marker'] . $crlf;
396 return $schema_create;
398 } // end of the 'PMA_getTableComments()' function
401 * Outputs table's structure
403 * @param string the database name
404 * @param string the table name
405 * @param string the end of line sequence
406 * @param string the url to go back in case of error
407 * @param boolean whether to include relation comments
408 * @param boolean whether to include column comments
409 * @param boolean whether to include mime comments
411 * @return bool Whether it suceeded
415 function PMA_exportStructure($db, $table, $crlf, $error_url, $relation = FALSE, $comments = FALSE, $mime = FALSE, $dates = FALSE) {
416 $formatted_table_name = (isset($GLOBALS['use_backquotes']))
417 ?
PMA_backquote($table)
418 : '\'' . $table . '\'';
420 . $GLOBALS['comment_marker'] . '--------------------------------------------------------' . $crlf
421 . $crlf . $GLOBALS['comment_marker'] . $crlf
422 . $GLOBALS['comment_marker'] . $GLOBALS['strTableStructure'] . ' ' . $formatted_table_name . $crlf
423 . $GLOBALS['comment_marker'] . $crlf
424 . PMA_getTableDef($db, $table, $crlf, $error_url, $dates) . ';' . $crlf
425 . PMA_getTableComments($db, $table, $crlf, $relation, $comments, $mime);
428 return PMA_exportOutputHandler($dump);
432 * Dispatches between the versions of 'getTableContent' to use depending
435 * @param string the database name
436 * @param string the table name
437 * @param string the end of line sequence
438 * @param string the url to go back in case of error
439 * @param string SQL query for obtaining data
441 * @return bool Whether it suceeded
443 * @global boolean whether to use backquotes to allow the use of special
444 * characters in database, table and fields names or not
445 * @global integer the number of records
446 * @global integer the current record position
450 * @see PMA_getTableContentFast(), PMA_getTableContentOld()
454 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
456 global $use_backquotes;
460 $formatted_table_name = (isset($GLOBALS['use_backquotes']))
461 ?
PMA_backquote($table)
462 : '\'' . $table . '\'';
464 . $GLOBALS['comment_marker'] . $crlf
465 . $GLOBALS['comment_marker'] . $GLOBALS['strDumpingData'] . ' ' . $formatted_table_name . $crlf
466 . $GLOBALS['comment_marker'] . $crlf .$crlf;
468 if (!PMA_exportOutputHandler($head)) return FALSE;
472 // analyze the query to get the true column names, not the aliases
473 // (this fixes an undefined index, also if Complete inserts
474 // are used, we did not get the true column name in case of aliases)
475 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
477 $result = PMA_DBI_query($sql_query, NULL, PMA_DBI_QUERY_UNBUFFERED
);
478 if ($result != FALSE) {
479 $fields_cnt = PMA_DBI_num_fields($result);
481 // Get field information
482 $fields_meta = PMA_DBI_get_fields_meta($result);
483 $field_flags = array();
484 for ($j = 0; $j < $fields_cnt; $j++
) {
485 $field_flags[$j] = PMA_DBI_field_flags($result, $j);
488 for ($j = 0; $j < $fields_cnt; $j++
) {
489 if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
490 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $use_backquotes);
492 $field_set[$j] = PMA_backquote($fields_meta[$j]->name
, $use_backquotes);
496 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'update') {
498 $schema_insert = 'UPDATE ';
499 if (isset($GLOBALS['sql_ignore']))
500 $schema_insert .= 'IGNORE ';
501 $schema_insert .= PMA_backquote($table, $use_backquotes) . ' SET ';
504 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'replace') {
505 $sql_command = 'REPLACE';
507 $sql_command = 'INSERT';
511 if (isset($GLOBALS['delayed'])) {
512 $insert_delayed = ' DELAYED';
514 $insert_delayed = '';
518 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'insert' && isset($GLOBALS['sql_ignore'])) {
519 $insert_delayed .= ' IGNORE';
522 // scheme for inserting fields
523 if (isset($GLOBALS['showcolumns'])) {
524 $fields = implode(', ', $field_set);
525 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $use_backquotes)
526 . ' (' . $fields . ') VALUES ';
528 $schema_insert = $sql_command . $insert_delayed .' INTO ' . PMA_backquote($table, $use_backquotes)
533 $search = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required
534 $replace = array('\0', '\n', '\r', '\Z');
537 $separator = isset($GLOBALS['extended_ins']) ?
',' : ';';
539 while ($row = PMA_DBI_fetch_row($result)) {
541 for ($j = 0; $j < $fields_cnt; $j++
) {
543 if (!isset($row[$j]) ||
is_null($row[$j])) {
546 // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
547 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type
!= 'timestamp'
548 && ! $fields_meta[$j]->blob
) {
549 $values[] = $row[$j];
551 // Note: with mysqli, under MySQL 4.1.3, we get the flag
552 // "binary" for those field types (I don't know why)
553 } else if (stristr($field_flags[$j], 'BINARY')
554 && isset($GLOBALS['hexforbinary'])
555 && $fields_meta[$j]->type
!= 'datetime'
556 && $fields_meta[$j]->type
!= 'date'
557 && $fields_meta[$j]->type
!= 'time'
558 && $fields_meta[$j]->type
!= 'timestamp'
560 // empty blobs need to be different, but '0' is also empty :-(
561 if (empty($row[$j]) && $row[$j] != '0') {
564 $values[] = '0x' . bin2hex($row[$j]);
566 // something else -> treat as a string
568 $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
572 // should we make update?
573 if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'update') {
575 $insert_line = $schema_insert;
576 for ($i = 0; $i < $fields_cnt; $i++
) {
578 $insert_line .= ', ';
580 $insert_line .= $field_set[$i] . ' = ' . $values[$i];
583 $insert_line .= ' WHERE ' . PMA_getUvaCondition($result, $fields_cnt, $fields_meta, $row);
587 // Extended inserts case
588 if (isset($GLOBALS['extended_ins'])) {
589 if ($current_row == 1) {
590 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
592 $insert_line = '(' . implode(', ', $values) . ')';
593 if (isset($GLOBALS['max_query_size']) && $GLOBALS['max_query_size'] > 0 && $query_size +
strlen($insert_line) > $GLOBALS['max_query_size']) {
594 if (!PMA_exportOutputHandler(';' . $crlf)) return FALSE;
597 $insert_line = $schema_insert . $insert_line;
600 $query_size +
= strlen($insert_line);
602 // Other inserts case
604 $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
609 if (!PMA_exportOutputHandler(($current_row == 1 ?
'' : $separator . $crlf) . $insert_line)) return FALSE;
612 if ($current_row > 0) {
613 if (!PMA_exportOutputHandler(';' . $crlf)) return FALSE;
615 } // end if ($result != FALSE)
616 PMA_DBI_free_result($result);
619 } // end of the 'PMA_exportData()' function