2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Library that provides common import functions that are used by import plugins
9 if (! defined('PHPMYADMIN')) {
14 * We need to know something about user
16 require_once './libraries/check_user_privileges.lib.php';
19 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
21 define('PMA_CHK_DROP', 1);
24 * Check whether timeout is getting close
26 * @return boolean true if timeout is close
29 function PMA_checkTimeout()
31 global $timestamp, $maximum_time, $timeout_passed;
32 if ($maximum_time == 0) {
34 } elseif ($timeout_passed) {
36 /* 5 in next row might be too much */
37 } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
38 $timeout_passed = TRUE;
46 * Detects what compression filse uses
48 * @param string filename to check
49 * @return string MIME type of compression, none for none
52 function PMA_detectCompression($filepath)
54 $file = @fopen
($filepath, 'rb');
58 $test = fread($file, 4);
61 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
62 return 'application/gzip';
64 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
65 return 'application/bzip2';
67 if ($len >= 4 && $test == "PK\003\004") {
68 return 'application/zip';
74 * Runs query inside import buffer. This is needed to allow displaying
75 * of last SELECT, SHOW or HANDLER results and similar nice stuff.
77 * @uses $GLOBALS['finished'] read and write
78 * @param string query to run
79 * @param string query to display, this might be commented
80 * @param bool whether to use control user for queries
83 function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
85 global $import_run_buffer, $go_sql, $complete_query, $display_query,
86 $sql_query, $my_die, $error, $reload,
87 $last_query_with_results,
88 $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
89 $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
91 if (isset($import_run_buffer)) {
92 // Should we skip something?
93 if ($skip_queries > 0) {
96 if (!empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
97 $max_sql_len = max($max_sql_len, strlen($import_run_buffer['sql']));
98 if (!$sql_query_disabled) {
99 $sql_query .= $import_run_buffer['full'];
101 if (!$cfg['AllowUserDropDatabase']
103 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
104 $GLOBALS['message'] = PMA_Message
::error('strNoDropDatabases');
108 if ($run_query && $GLOBALS['finished'] && empty($sql) && !$error && (
109 (!empty($import_run_buffer['sql']) && preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
110 ($executed_queries == 1)
113 if (!$sql_query_disabled) {
114 $complete_query = $sql_query;
115 $display_query = $sql_query;
117 $complete_query = '';
120 $sql_query = $import_run_buffer['sql'];
121 // If a 'USE <db>' SQL-clause was found, set our current $db to the new one
122 list($db, $reload) = PMA_lookForUse($import_run_buffer['sql'], $db, $reload);
123 } elseif ($run_query) {
125 $result = PMA_query_as_controluser($import_run_buffer['sql']);
127 $result = PMA_DBI_try_query($import_run_buffer['sql']);
130 if ($result === FALSE) { // execution failed
131 if (!isset($my_die)) {
134 $my_die[] = array('sql' => $import_run_buffer['full'], 'error' => PMA_DBI_getError());
136 if ($cfg['VerboseMultiSubmit']) {
137 $msg .= $GLOBALS['strError'];
140 if (!$cfg['IgnoreMultiSubmitErrors']) {
144 } elseif ($cfg['VerboseMultiSubmit']) {
145 $a_num_rows = (int)@PMA_DBI_num_rows
($result);
146 $a_aff_rows = (int)@PMA_DBI_affected_rows
();
147 if ($a_num_rows > 0) {
148 $msg .= $GLOBALS['strRows'] . ': ' . $a_num_rows;
149 $last_query_with_results = $import_run_buffer['sql'];
150 } elseif ($a_aff_rows > 0) {
151 $msg .= sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
153 $msg .= $GLOBALS['strEmptyResultSet'];
156 if (!$sql_query_disabled) {
157 $sql_query .= $msg . "\n";
160 // If a 'USE <db>' SQL-clause was found and the query succeeded, set our current $db to the new one
161 if ($result != FALSE) {
162 list($db, $reload) = PMA_lookForUse($import_run_buffer['sql'], $db, $reload);
165 if ($result != FALSE && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])) {
169 } // end if not DROP DATABASE
170 } // end non empty query
171 elseif (!empty($import_run_buffer['full'])) {
173 $complete_query .= $import_run_buffer['full'];
174 $display_query .= $import_run_buffer['full'];
176 if (!$sql_query_disabled) {
177 $sql_query .= $import_run_buffer['full'];
181 // check length of query unless we decided to pass it to sql.php
182 // (if $run_query is false, we are just displaying so show
183 // the complete query in the textarea)
184 if (! $go_sql && $run_query) {
185 if ($cfg['VerboseMultiSubmit'] && ! empty($sql_query)) {
186 if (strlen($sql_query) > 50000 ||
$executed_queries > 50 ||
$max_sql_len > 1000) {
188 $sql_query_disabled = TRUE;
191 if (strlen($sql_query) > 10000 ||
$executed_queries > 10 ||
$max_sql_len > 500) {
193 $sql_query_disabled = TRUE;
197 } // end do query (no skip)
198 } // end buffer exists
200 // Do we have something to push into buffer?
201 if (!empty($sql) ||
!empty($full)) {
202 $import_run_buffer = array('sql' => $sql, 'full' => $full);
204 unset($GLOBALS['import_run_buffer']);
209 * Looks for the presence of USE to possibly change current db
211 * @param string buffer to examine
212 * @param string current db
213 * @param boolean reload
214 * @return array (current or new db, whether to reload)
217 function PMA_lookForUse($buffer, $db, $reload)
219 if (preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $buffer, $match)) {
220 $db = trim($match[1]);
221 $db = trim($db,';'); // for example, USE abc;
224 return(array($db, $reload));
229 * Returns next part of imported file/buffer
231 * @uses $GLOBALS['offset'] read and write
232 * @uses $GLOBALS['import_file'] read only
233 * @uses $GLOBALS['import_text'] read and write
234 * @uses $GLOBALS['finished'] read and write
235 * @uses $GLOBALS['read_limit'] read only
236 * @param integer size of buffer to read (this is maximal size
237 * function will return)
238 * @return string part of file/buffer
241 function PMA_importGetNextChunk($size = 32768)
243 global $compression, $import_handle, $charset_conversion, $charset_of_file,
244 $charset, $read_multiply;
246 // Add some progression while reading large amount of data
247 if ($read_multiply <= 8) {
248 $size *= $read_multiply;
254 // We can not read too much
255 if ($size > $GLOBALS['read_limit']) {
256 $size = $GLOBALS['read_limit'];
259 if (PMA_checkTimeout()) {
262 if ($GLOBALS['finished']) {
266 if ($GLOBALS['import_file'] == 'none') {
267 // Well this is not yet supported and tested, but should return content of textarea
268 if (strlen($GLOBALS['import_text']) < $size) {
269 $GLOBALS['finished'] = TRUE;
270 return $GLOBALS['import_text'];
272 $r = substr($GLOBALS['import_text'], 0, $size);
273 $GLOBALS['offset'] +
= $size;
274 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
279 switch ($compression) {
280 case 'application/bzip2':
281 $result = bzread($import_handle, $size);
282 $GLOBALS['finished'] = feof($import_handle);
284 case 'application/gzip':
285 $result = gzread($import_handle, $size);
286 $GLOBALS['finished'] = feof($import_handle);
288 case 'application/zip':
289 $result = substr($GLOBALS['import_text'], 0, $size);
290 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
291 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
294 $result = fread($import_handle, $size);
295 $GLOBALS['finished'] = feof($import_handle);
298 $GLOBALS['offset'] +
= $size;
300 if ($charset_conversion) {
301 return PMA_convert_string($charset_of_file, $charset, $result);
304 * Skip possible byte order marks (I do not think we need more
305 * charsets, but feel free to add more, you can use wikipedia for
306 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
308 * @todo BOM could be used for charset autodetection
310 if ($GLOBALS['offset'] == $size) {
312 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
313 $result = substr($result, 3);
315 } elseif (strncmp($result, "\xFE\xFF", 2) == 0 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
316 $result = substr($result, 2);
324 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
326 * This functions uses recursion to build the Excel column name.
328 * The column number (1-26) is converted to the responding ASCII character (A-Z) and returned.
330 * If the column number is bigger than 26 (= num of letters in alfabet),
331 * an extra character needs to be added. To find this extra character, the number is divided by 26
332 * and this value is passed to another instance of the same function (hence recursion).
333 * In that new instance the number is evaluated again, and if it is still bigger than 26, it is divided again
334 * and passed to another instance of the same function. This continues until the number is smaller than 26.
335 * Then the last called function returns the corresponding ASCII character to the function that called it.
336 * Each time a called function ends an extra character is added to the column name.
337 * When the first function is reached, the last character is addded and the complete column name is returned.
343 * @return string The column's "Excel" name
345 function PMA_getColumnAlphaName($num)
347 $A = 65; // ASCII value for capital "A"
351 $div = (int)($num / 26);
352 $remain = (int)($num %
26);
354 // subtract 1 of divided value in case the modulus is 0,
355 // this is necessary because A-Z has no 'zero'
360 // recursive function call
361 $col_name = PMA_getColumnAlphaName($div);
362 // use modulus as new column number
367 // use 'Z' if column number is 0,
368 // this is necessary because A-Z has no 'zero'
369 $col_name .= chr(($A +
26) - 1);
371 // convert column number to ASCII character
372 $col_name .= chr(($A +
$num) - 1);
379 * Returns the column number based on the Excel name.
380 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
382 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
383 * It iterates through all characters in the column name and
384 * calculates the corresponding value, based on character value
385 * (A = 1, ..., Z = 26) and position in the string.
392 * @param string $name (i.e. "A", or "BC", etc.)
393 * @return int The column number
395 function PMA_getColumnNumberFromName($name) {
397 $name = strtoupper($name);
398 $num_chars = strlen($name);
400 for ($i = 0; $i < $num_chars; ++
$i) {
401 // read string from back to front
402 $char_pos = ($num_chars - 1) - $i;
404 // convert capital character to ASCII value
405 // and subtract 64 to get corresponding decimal value
406 // ASCII value of "A" is 65, "B" is 66, etc.
407 // Decimal equivalent of "A" is 1, "B" is 2, etc.
408 $number = (ord($name[$char_pos]) - 64);
410 // base26 to base10 conversion : multiply each number
411 // with corresponding value of the position, in this case
412 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
413 $column_number +
= $number * pow(26,$i);
415 return $column_number;
422 * Constants definitions
425 /* MySQL type defs */
427 define("VARCHAR", 1);
429 define("DECIMAL", 3);
432 /* Decimal size defs */
437 /* Table array defs */
438 define("TBL_NAME", 0);
439 define("COL_NAMES", 1);
442 /* Analysis array defs */
447 * Obtains the precision (total # of digits) from a size of type decimal
449 * @author Derek Schaefer (derek.schaefer@gmail.com)
455 * @param string $last_cumulative_size
456 * @return int Precision of the given decimal size notation
458 function PMA_getM($last_cumulative_size) {
459 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
463 * Obtains the scale (# of digits to the right of the decimal point) from a size of type decimal
465 * @author Derek Schaefer (derek.schaefer@gmail.com)
472 * @param string $last_cumulative_size
473 * @return int Scale of the given decimal size notation
475 function PMA_getD($last_cumulative_size) {
476 return (int)substr($last_cumulative_size, (strpos($last_cumulative_size, ",") +
1), (strlen($last_cumulative_size) - strpos($last_cumulative_size, ",")));
480 * Obtains the decimal size of a given cell
482 * @author Derek Schaefer (derek.schaefer@gmail.com)
488 * @param string &$cell
489 * @return array Contains the precision, scale, and full size representation of the given decimal cell
491 function PMA_getDecimalSize(&$cell) {
492 $curr_size = strlen((string)$cell);
493 $decPos = strpos($cell, ".");
494 $decPrecision = ($curr_size - 1) - $decPos;
499 return array($m, $d, ($m . "," . $d));
503 * Obtains the size of the given cell
505 * @author Derek Schaefer (derek.schaefer@gmail.com)
507 * @todo Handle the error cases more elegantly
523 * @uses PMA_getDecimalSize()
524 * @param string $last_cumulative_size Last cumulative column size
525 * @param int $last_cumulative_type Last cumulative column type (NONE or VARCHAR or DECIMAL or INT or BIGINT)
526 * @param int $curr_type Type of the current cell (NONE or VARCHAR or DECIMAL or INT or BIGINT)
527 * @param string &$cell The current cell
528 * @return string Size of the given cell in the type-appropriate format
530 function PMA_detectSize($last_cumulative_size, $last_cumulative_type, $curr_type, &$cell) {
531 $curr_size = strlen((string)$cell);
534 * If the cell is NULL, don't treat it as a varchar
536 if (! strcmp('NULL', $cell)) {
537 return $last_cumulative_size;
540 * What to do if the current cell is of type VARCHAR
542 elseif ($curr_type == VARCHAR
) {
544 * The last cumulative type was VARCHAR
546 if ($last_cumulative_type == VARCHAR
) {
547 if ($curr_size >= $last_cumulative_size) {
550 return $last_cumulative_size;
554 * The last cumulative type was DECIMAL
556 elseif ($last_cumulative_type == DECIMAL
) {
557 $oldM = PMA_getM($last_cumulative_size);
559 if ($curr_size >= $oldM) {
566 * The last cumulative type was BIGINT or INT
568 elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
569 if ($curr_size >= $last_cumulative_size) {
572 return $last_cumulative_size;
576 * This is the first row to be analyzed
578 elseif (! isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
582 * An error has DEFINITELY occurred
586 * TODO: Handle this MUCH more elegantly
593 * What to do if the current cell is of type DECIMAL
595 elseif ($curr_type == DECIMAL
) {
597 * The last cumulative type was VARCHAR
599 if ($last_cumulative_type == VARCHAR
) {
600 /* Convert $last_cumulative_size from varchar to decimal format */
601 $size = PMA_getDecimalSize($cell);
603 if ($size[M
] >= $last_cumulative_size) {
606 return $last_cumulative_size;
610 * The last cumulative type was DECIMAL
612 elseif ($last_cumulative_type == DECIMAL
) {
613 $size = PMA_getDecimalSize($cell);
615 $oldM = PMA_getM($last_cumulative_size);
616 $oldD = PMA_getD($last_cumulative_size);
618 /* New val if M or D is greater than current largest */
619 if ($size[M
] > $oldM ||
$size[D
] > $oldD) {
620 /* Take the largest of both types */
621 return (string)((($size[M
] > $oldM) ?
$size[M
] : $oldM) . "," . (($size[D
] > $oldD) ?
$size[D
] : $oldD));
623 return $last_cumulative_size;
627 * The last cumulative type was BIGINT or INT
629 elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
630 /* Convert $last_cumulative_size from int to decimal format */
631 $size = PMA_getDecimalSize($cell);
633 if ($size[M
] >= $last_cumulative_size) {
636 return ($last_cumulative_size.",".$size[D
]);
640 * This is the first row to be analyzed
642 elseif (! isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
643 /* First row of the column */
644 $size = PMA_getDecimalSize($cell);
649 * An error has DEFINITELY occurred
653 * TODO: Handle this MUCH more elegantly
660 * What to do if the current cell is of type BIGINT or INT
662 elseif ($curr_type == BIGINT ||
$curr_type == INT) {
664 * The last cumulative type was VARCHAR
666 if ($last_cumulative_type == VARCHAR
) {
667 if ($curr_size >= $last_cumulative_size) {
670 return $last_cumulative_size;
674 * The last cumulative type was DECIMAL
676 elseif ($last_cumulative_type == DECIMAL
) {
677 $oldM = PMA_getM($last_cumulative_size);
678 $oldD = PMA_getD($last_cumulative_size);
679 $oldInt = $oldM - $oldD;
680 $newInt = strlen((string)$cell);
682 /* See which has the larger integer length */
683 if ($oldInt >= $newInt) {
684 /* Use old decimal size */
685 return $last_cumulative_size;
687 /* Use $newInt + $oldD as new M */
688 return (($newInt +
$oldD) . "," . $oldD);
692 * The last cumulative type was BIGINT or INT
694 elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
695 if ($curr_size >= $last_cumulative_size) {
698 return $last_cumulative_size;
702 * This is the first row to be analyzed
704 elseif (!isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
708 * An error has DEFINITELY occurred
712 * TODO: Handle this MUCH more elegantly
719 * An error has DEFINITELY occurred
723 * TODO: Handle this MUCH more elegantly
731 * Determines what MySQL type a cell is
733 * @author Derek Schaefer (derek.schaefer@gmail.com)
745 * @uses substr_count()
746 * @param int $last_cumulative_type Last cumulative column type (VARCHAR or INT or BIGINT or DECIMAL or NONE)
747 * @param string &$cell String representation of the cell for which a best-fit type is to be determined
748 * @return int The MySQL type representation (VARCHAR or INT or BIGINT or DECIMAL or NONE)
750 function PMA_detectType($last_cumulative_type, &$cell) {
752 * If numeric, determine if decimal, int or bigint
753 * Else, we call it varchar for simplicity
756 if (! strcmp('NULL', $cell)) {
757 if ($last_cumulative_type === NULL ||
$last_cumulative_type == NONE
) {
760 return $last_cumulative_type;
762 } elseif (is_numeric($cell)) {
763 if ($cell == (string)(float)$cell && strpos($cell, ".") !== false && substr_count($cell, ".") == 1) {
766 if (abs($cell) > 2147483647) {
778 * Determines if the column types are int, decimal, or string
780 * @author Derek Schaefer (derek.schaefer@gmail.com)
782 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
784 * @todo Handle the error case more elegantly
798 * @uses PMA_detectType()
799 * @uses PMA_detectSize()
800 * @param &$table array(string $table_name, array $col_names, array $rows)
801 * @return array array(array $types, array $sizes)
803 function PMA_analyzeTable(&$table) {
804 /* Get number of rows in table */
805 $numRows = count($table[ROWS
]);
806 /* Get number of columns */
807 $numCols = count($table[COL_NAMES
]);
808 /* Current type for each column */
812 /* Initialize $sizes to all 0's */
813 for ($i = 0; $i < $numCols; ++
$i) {
817 /* Initialize $types to NONE */
818 for ($i = 0; $i < $numCols; ++
$i) {
826 /* If the passed array is not of the correct form, do not process it */
827 if (is_array($table) && ! is_array($table[TBL_NAME
]) && is_array($table[COL_NAMES
]) && is_array($table[ROWS
])) {
828 /* Analyze each column */
829 for ($i = 0; $i < $numCols; ++
$i) {
830 /* Analyze the column in each row */
831 for ($j = 0; $j < $numRows; ++
$j) {
832 /* Determine type of the current cell */
833 $curr_type = PMA_detectType($types[$i], $table[ROWS
][$j][$i]);
834 /* Determine size of the current cell */
835 $sizes[$i] = PMA_detectSize($sizes[$i], $types[$i], $curr_type, $table[ROWS
][$j][$i]);
838 * If a type for this column has already been declared,
839 * only alter it if it was a number and a varchar was found
841 if ($curr_type != NONE
) {
842 if ($curr_type == VARCHAR
) {
843 $types[$i] = VARCHAR
;
844 } else if ($curr_type == DECIMAL
) {
845 if ($types[$i] != VARCHAR
) {
846 $types[$i] = DECIMAL
;
848 } else if ($curr_type == BIGINT
) {
849 if ($types[$i] != VARCHAR
&& $types[$i] != DECIMAL
) {
852 } else if ($curr_type == INT) {
853 if ($types[$i] != VARCHAR
&& $types[$i] != DECIMAL
&& $types[$i] != BIGINT
) {
861 /* Check to ensure that all types are valid */
862 $len = count($types);
863 for ($n = 0; $n < $len; ++
$n) {
864 if (! strcmp(NONE
, $types[$n])) {
865 $types[$n] = VARCHAR
;
870 return array($types, $sizes);
875 * TODO: Handle this better
882 /* Needed to quell the beast that is PMA_Message */
883 $import_notice = NULL;
886 * Builds and executes SQL statements to create the database and tables
887 * as necessary, as well as insert all the data.
889 * @author Derek Schaefer (derek.schaefer@gmail.com)
891 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
903 * @uses preg_replace()
905 * @uses PMA_backquote()
906 * @uses PMA_importRunQuery()
907 * @uses PMA_generate_common_url()
908 * @uses PMA_Message::notice()
909 * @param string $db_name Name of the database
910 * @param array &$tables Array of tables for the specified database
911 * @param array &$analyses = NULL Analyses of the tables
912 * @param array &$additional_sql = NULL Additional SQL statements to be executed
913 * @param array $options = NULL Associative array of options
916 function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL) {
917 /* Take care of the options */
918 if (isset($options['db_collation'])) {
919 $collation = $options['db_collation'];
921 $collation = "utf8_general_ci";
924 if (isset($options['db_charset'])) {
925 $charset = $options['db_charset'];
930 if (isset($options['create_db'])) {
931 $create_db = $options['create_db'];
936 /* Create SQL code to handle the database */
940 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
944 * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
946 * $sql[] = "USE " . PMA_backquote($db_name);
949 /* Execute the SQL statements create above */
950 $sql_len = count($sql);
951 for ($i = 0; $i < $sql_len; ++
$i) {
952 PMA_importRunQuery($sql[$i], $sql[$i]);
955 /* No longer needed */
958 /* Run the $additional_sql statements supplied by the caller plug-in */
959 if ($additional_sql != NULL) {
960 /* Clean the SQL first */
961 $additional_sql_len = count($additional_sql);
964 * Only match tables for now, because CREATE IF NOT EXISTS
965 * syntax is lacking or nonexisting for views, triggers,
966 * functions, and procedures.
968 * See: http://bugs.mysql.com/bug.php?id=15287
970 * To the best of my knowledge this is still an issue.
972 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
974 $pattern = '/CREATE .*(TABLE)/';
975 $replacement = 'CREATE \\1 IF NOT EXISTS';
977 /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
978 for ($i = 0; $i < $additional_sql_len; ++
$i) {
979 $additional_sql[$i] = preg_replace($pattern, $replacement, $additional_sql[$i]);
980 /* Execute the resulting statements */
981 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
985 if ($analyses != NULL) {
986 $type_array = array(NONE
=> "NULL", VARCHAR
=> "varchar", INT => "int", DECIMAL
=> "decimal", BIGINT
=> "bigint");
988 /* TODO: Do more checking here to make sure they really are matched */
989 if (count($tables) != count($analyses)) {
993 /* Create SQL code to create the tables */
995 $num_tables = count($tables);
996 for ($i = 0; $i < $num_tables; ++
$i) {
997 $num_cols = count($tables[$i][COL_NAMES
]);
998 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME
]) . " (";
999 for ($j = 0; $j < $num_cols; ++
$j) {
1000 $size = $analyses[$i][SIZES
][$j];
1001 if ((int)$size == 0) {
1005 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES
][$j]) . " " . $type_array[$analyses[$i][TYPES
][$j]] . "(" . $size . ")";
1007 if ($j != (count($tables[$i][COL_NAMES
]) - 1)) {
1008 $tempSQLStr .= ", ";
1011 $tempSQLStr .= ") ENGINE=MyISAM DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
1014 * Each SQL statement is executed immediately
1015 * after it is formed so that we don't have
1016 * to store them in a (possibly large) buffer
1018 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1023 * Create the SQL statements to insert all the data
1025 * Only one insert query is formed for each table
1029 $num_tables = count($tables);
1030 for ($i = 0; $i < $num_tables; ++
$i) {
1031 $num_cols = count($tables[$i][COL_NAMES
]);
1032 $num_rows = count($tables[$i][ROWS
]);
1034 $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME
]) . " (";
1036 for ($m = 0; $m < $num_cols; ++
$m) {
1037 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES
][$m]);
1039 if ($m != ($num_cols - 1)) {
1040 $tempSQLStr .= ", ";
1044 $tempSQLStr .= ") VALUES ";
1046 for ($j = 0; $j < $num_rows; ++
$j) {
1049 for ($k = 0; $k < $num_cols; ++
$k) {
1050 if ($analyses != NULL) {
1051 $is_varchar = ($analyses[$i][TYPES
][$col_count] === VARCHAR
);
1053 $is_varchar = !is_numeric($tables[$i][ROWS
][$j][$k]);
1056 /* Don't put quotes around NULL fields */
1057 if (! strcmp($tables[$i][ROWS
][$j][$k], 'NULL')) {
1058 $is_varchar = false;
1061 $tempSQLStr .= (($is_varchar) ?
"'" : "");
1062 $tempSQLStr .= PMA_sqlAddslashes((string)$tables[$i][ROWS
][$j][$k]);
1063 $tempSQLStr .= (($is_varchar) ?
"'" : "");
1065 if ($k != ($num_cols - 1)) {
1066 $tempSQLStr .= ", ";
1069 if ($col_count == ($num_cols - 1)) {
1075 /* Delete the cell after we are done with it */
1076 unset($tables[$i][ROWS
][$j][$k]);
1081 if ($j != ($num_rows - 1)) {
1082 $tempSQLStr .= ",\n ";
1086 /* Delete the row after we are done with it */
1087 unset($tables[$i][ROWS
][$j]);
1093 * Each SQL statement is executed immediately
1094 * after it is formed so that we don't have
1095 * to store them in a (possibly large) buffer
1097 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1100 /* No longer needed */
1104 * A work in progress
1107 /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
1109 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1110 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1111 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1117 $additional_sql_len = count($additional_sql);
1118 for ($i = 0; $i < $additional_sql_len; ++
$i) {
1119 preg_match($view_pattern, $additional_sql[$i], $regs);
1121 if (count($regs) == 0) {
1122 preg_match($table_pattern, $additional_sql[$i], $regs);
1126 for ($n = 0; $n < $num_tables; ++
$n) {
1127 if (!strcmp($regs[1], $tables[$n][TBL_NAME
])) {
1134 $tables[] = array(TBL_NAME
=> $regs[1]);
1138 /* Reset the array */
1143 $params = array('db' => (string)$db_name);
1144 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1145 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1147 $message = '<br /><br />';
1148 $message .= '<strong>' . $GLOBALS['strImportNoticePt1'] . '</strong><br />';
1149 $message .= '<ul><li>' . $GLOBALS['strImportNoticePt2'] . '</li>';
1150 $message .= '<li>' . $GLOBALS['strImportNoticePt3'] . '</li>';
1151 $message .= '<li>' . $GLOBALS['strImportNoticePt4'] . '</li>';
1152 $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>',
1154 $GLOBALS['strGoToDatabase'] . ': ' . PMA_backquote($db_name),
1157 $GLOBALS['strEdit'] . ' ' . PMA_backquote($db_name) . ' ' . $GLOBALS['strSettings']);
1163 $num_tables = count($tables);
1164 for ($i = 0; $i < $num_tables; ++
$i)
1166 $params = array('db' => (string)$db_name, 'table' => (string)$tables[$i][TBL_NAME
]);
1167 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1168 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1169 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1173 if (! PMA_isView($db_name, $tables[$i][TBL_NAME
])) {
1174 $message .= sprintf('<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strStructure'] . '</a>) (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>',
1176 $GLOBALS['strGoToTable'] . ': ' . PMA_backquote($tables[$i][TBL_NAME
]),
1177 $tables[$i][TBL_NAME
],
1179 PMA_backquote($tables[$i][TBL_NAME
]) . ' ' . $GLOBALS['strStructureLC'],
1181 $GLOBALS['strEdit'] . ' ' . PMA_backquote($tables[$i][TBL_NAME
]) . ' ' . $GLOBALS['strSettings']);
1183 $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>',
1185 $GLOBALS['strGoToView'] . ': ' . PMA_backquote($tables[$i][TBL_NAME
]),
1186 $tables[$i][TBL_NAME
]);
1190 $message .= '</ul></ul>';
1192 global $import_notice;
1193 $import_notice = $message;