2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Library that provides common import functions that are used by import plugins
6 * @package PhpMyAdmin-Import
8 if (! defined('PHPMYADMIN')) {
13 * We need to know something about user
15 require_once './libraries/check_user_privileges.lib.php';
18 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
20 define('PMA_CHK_DROP', 1);
23 * Checks whether timeout is getting close
25 * @return boolean true if timeout is close
28 function PMA_checkTimeout()
30 global $timestamp, $maximum_time, $timeout_passed;
31 if ($maximum_time == 0) {
33 } elseif ($timeout_passed) {
35 /* 5 in next row might be too much */
36 } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
37 $timeout_passed = true;
45 * Detects what compression filse uses
47 * @param string $filepath 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 * @param string $sql query to run
78 * @param string $full query to display, this might be commented
79 * @param bool $controluser whether to use control user for queries
80 * @param array &$sql_data SQL parse data storage
85 function PMA_importRunQuery($sql = '', $full = '', $controluser = false,
88 global $import_run_buffer, $go_sql, $complete_query, $display_query,
89 $sql_query, $my_die, $error, $reload,
90 $last_query_with_results, $result, $msg,
91 $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
92 $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
94 if (isset($import_run_buffer)) {
95 // Should we skip something?
96 if ($skip_queries > 0) {
99 if (! empty($import_run_buffer['sql'])
100 && trim($import_run_buffer['sql']) != ''
103 // USE query changes the database, son need to track
104 // while running multiple queries
106 = (stripos($import_run_buffer['sql'], "use ") !== false)
110 $max_sql_len = max($max_sql_len, strlen($import_run_buffer['sql']));
111 if (! $sql_query_disabled) {
112 $sql_query .= $import_run_buffer['full'];
114 if (! $cfg['AllowUserDropDatabase']
116 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])
118 $GLOBALS['message'] = PMA_Message
::error(__('"DROP DATABASE" statements are disabled.'));
125 && $GLOBALS['finished']
128 && ((! empty($import_run_buffer['sql'])
129 && preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql']))
130 ||
($executed_queries == 1))
133 if (! $sql_query_disabled) {
134 $complete_query = $sql_query;
135 $display_query = $sql_query;
137 $complete_query = '';
140 $sql_query = $import_run_buffer['sql'];
141 $sql_data['valid_sql'][] = $import_run_buffer['sql'];
142 if (! isset($sql_data['valid_queries'])) {
143 $sql_data['valid_queries'] = 0;
145 $sql_data['valid_queries']++
;
147 // If a 'USE <db>' SQL-clause was found,
148 // set our current $db to the new one
149 list($db, $reload) = PMA_lookForUse(
150 $import_run_buffer['sql'],
154 } elseif ($run_query) {
157 $result = PMA_queryAsControlUser(
158 $import_run_buffer['sql']
161 $result = $GLOBALS['dbi']->tryQuery($import_run_buffer['sql']);
165 if ($result === false) { // execution failed
166 if (! isset($my_die)) {
170 'sql' => $import_run_buffer['full'],
171 'error' => $GLOBALS['dbi']->getError()
176 if (! $cfg['IgnoreMultiSubmitErrors']) {
181 $a_num_rows = (int)@$GLOBALS['dbi']->numRows($result);
182 $a_aff_rows = (int)@$GLOBALS['dbi']->affectedRows();
183 if ($a_num_rows > 0) {
184 $msg .= __('Rows'). ': ' . $a_num_rows;
185 $last_query_with_results = $import_run_buffer['sql'];
186 } elseif ($a_aff_rows > 0) {
187 $message = PMA_Message
::getMessageForAffectedRows($a_aff_rows);
188 $msg .= $message->getMessage();
190 $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
193 if (($a_num_rows > 0) ||
$is_use_query) {
194 $sql_data['valid_sql'][] = $import_run_buffer['sql'];
195 if (! isset($sql_data['valid_queries'])) {
196 $sql_data['valid_queries'] = 0;
198 $sql_data['valid_queries']++
;
202 if (! $sql_query_disabled) {
203 $sql_query .= $msg . "\n";
206 // If a 'USE <db>' SQL-clause was found and the query
207 // succeeded, set our current $db to the new one
208 if ($result != false) {
209 list($db, $reload) = PMA_lookForUse(
210 $import_run_buffer['sql'],
217 && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])
222 } // end if not DROP DATABASE
223 // end non empty query
224 } elseif (! empty($import_run_buffer['full'])) {
226 $complete_query .= $import_run_buffer['full'];
227 $display_query .= $import_run_buffer['full'];
229 if (! $sql_query_disabled) {
230 $sql_query .= $import_run_buffer['full'];
234 // check length of query unless we decided to pass it to sql.php
235 // (if $run_query is false, we are just displaying so show
236 // the complete query in the textarea)
237 if (! $go_sql && $run_query) {
238 if (! empty($sql_query)) {
239 if (strlen($sql_query) > 50000
240 ||
$executed_queries > 50
241 ||
$max_sql_len > 1000
244 $sql_query_disabled = true;
248 } // end do query (no skip)
249 } // end buffer exists
251 // Do we have something to push into buffer?
252 if (! empty($sql) ||
! empty($full)) {
253 $import_run_buffer = array('sql' => $sql, 'full' => $full);
255 unset($GLOBALS['import_run_buffer']);
260 * Looks for the presence of USE to possibly change current db
262 * @param string $buffer buffer to examine
263 * @param string $db current db
264 * @param bool $reload reload
266 * @return array (current or new db, whether to reload)
269 function PMA_lookForUse($buffer, $db, $reload)
271 if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', $buffer, $match)) {
272 $db = trim($match[1]);
273 $db = trim($db, ';'); // for example, USE abc;
275 // $db must not contain the escape characters generated by backquote()
276 // ( used in PMA_buildSQL() as: backquote($db_name), and then called
277 // in PMA_importRunQuery() which in turn calls PMA_lookForUse() )
278 $db = PMA_Util
::unQuote($db);
282 return(array($db, $reload));
287 * Returns next part of imported file/buffer
289 * @param int $size size of buffer to read
290 * (this is maximal size function will return)
292 * @return string part of file/buffer
295 function PMA_importGetNextChunk($size = 32768)
297 global $compression, $import_handle, $charset_conversion, $charset_of_file,
300 // Add some progression while reading large amount of data
301 if ($read_multiply <= 8) {
302 $size *= $read_multiply;
308 // We can not read too much
309 if ($size > $GLOBALS['read_limit']) {
310 $size = $GLOBALS['read_limit'];
313 if (PMA_checkTimeout()) {
316 if ($GLOBALS['finished']) {
320 if ($GLOBALS['import_file'] == 'none') {
321 // Well this is not yet supported and tested,
322 // but should return content of textarea
323 if (strlen($GLOBALS['import_text']) < $size) {
324 $GLOBALS['finished'] = true;
325 return $GLOBALS['import_text'];
327 $r = substr($GLOBALS['import_text'], 0, $size);
328 $GLOBALS['offset'] +
= $size;
329 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
334 switch ($compression) {
335 case 'application/bzip2':
336 $result = bzread($import_handle, $size);
337 $GLOBALS['finished'] = feof($import_handle);
339 case 'application/gzip':
340 $result = gzread($import_handle, $size);
341 $GLOBALS['finished'] = feof($import_handle);
343 case 'application/zip':
344 $result = substr($GLOBALS['import_text'], 0, $size);
345 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
346 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
349 $result = fread($import_handle, $size);
350 $GLOBALS['finished'] = feof($import_handle);
353 $GLOBALS['offset'] +
= $size;
355 if ($charset_conversion) {
356 return PMA_convertString($charset_of_file, 'utf-8', $result);
359 * Skip possible byte order marks (I do not think we need more
360 * charsets, but feel free to add more, you can use wikipedia for
361 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
363 * @todo BOM could be used for charset autodetection
365 if ($GLOBALS['offset'] == $size) {
367 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
368 $result = substr($result, 3);
370 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
371 ||
strncmp($result, "\xFF\xFE", 2) == 0
373 $result = substr($result, 2);
381 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
383 * This functions uses recursion to build the Excel column name.
385 * The column number (1-26) is converted to the responding
386 * ASCII character (A-Z) and returned.
388 * If the column number is bigger than 26 (= num of letters in alfabet),
389 * an extra character needs to be added. To find this extra character,
390 * the number is divided by 26 and this value is passed to another instance
391 * of the same function (hence recursion). In that new instance the number is
392 * evaluated again, and if it is still bigger than 26, it is divided again
393 * and passed to another instance of the same function. This continues until
394 * the number is smaller than 26. Then the last called function returns
395 * the corresponding ASCII character to the function that called it.
396 * Each time a called function ends an extra character is added to the column name.
397 * When the first function is reached, the last character is addded and the complete
398 * column name is returned.
400 * @param int $num the column number
402 * @return string The column's "Excel" name
405 function PMA_getColumnAlphaName($num)
407 $A = 65; // ASCII value for capital "A"
411 $div = (int)($num / 26);
412 $remain = (int)($num %
26);
414 // subtract 1 of divided value in case the modulus is 0,
415 // this is necessary because A-Z has no 'zero'
420 // recursive function call
421 $col_name = PMA_getColumnAlphaName($div);
422 // use modulus as new column number
427 // use 'Z' if column number is 0,
428 // this is necessary because A-Z has no 'zero'
429 $col_name .= chr(($A +
26) - 1);
431 // convert column number to ASCII character
432 $col_name .= chr(($A +
$num) - 1);
439 * Returns the column number based on the Excel name.
440 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
442 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
443 * It iterates through all characters in the column name and
444 * calculates the corresponding value, based on character value
445 * (A = 1, ..., Z = 26) and position in the string.
447 * @param string $name column name(i.e. "A", or "BC", etc.)
449 * @return int The column number
452 function PMA_getColumnNumberFromName($name)
454 if (! empty($name)) {
455 $name = strtoupper($name);
456 $num_chars = strlen($name);
458 for ($i = 0; $i < $num_chars; ++
$i) {
459 // read string from back to front
460 $char_pos = ($num_chars - 1) - $i;
462 // convert capital character to ASCII value
463 // and subtract 64 to get corresponding decimal value
464 // ASCII value of "A" is 65, "B" is 66, etc.
465 // Decimal equivalent of "A" is 1, "B" is 2, etc.
466 $number = (ord($name[$char_pos]) - 64);
468 // base26 to base10 conversion : multiply each number
469 // with corresponding value of the position, in this case
470 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
471 $column_number +
= $number * PMA_Util
::pow(26, $i);
473 return $column_number;
480 * Constants definitions
483 /* MySQL type defs */
485 define("VARCHAR", 1);
487 define("DECIMAL", 3);
489 define("GEOMETRY", 5);
491 /* Decimal size defs */
496 /* Table array defs */
497 define("TBL_NAME", 0);
498 define("COL_NAMES", 1);
501 /* Analysis array defs */
504 define("FORMATTEDSQL", 2);
507 * Obtains the precision (total # of digits) from a size of type decimal
509 * @param string $last_cumulative_size
511 * @return int Precision of the given decimal size notation
514 function PMA_getM($last_cumulative_size)
516 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
520 * Obtains the scale (# of digits to the right of the decimal point)
521 * from a size of type decimal
523 * @param string $last_cumulative_size
525 * @return int Scale of the given decimal size notation
528 function PMA_getD($last_cumulative_size)
531 $last_cumulative_size,
532 (strpos($last_cumulative_size, ",") +
1),
533 (strlen($last_cumulative_size) - strpos($last_cumulative_size, ","))
538 * Obtains the decimal size of a given cell
540 * @param string $cell cell content
542 * @return array Contains the precision, scale, and full size
543 * representation of the given decimal cell
546 function PMA_getDecimalSize($cell)
548 $curr_size = strlen((string)$cell);
549 $decPos = strpos($cell, ".");
550 $decPrecision = ($curr_size - 1) - $decPos;
555 return array($m, $d, ($m . "," . $d));
559 * Obtains the size of the given cell
561 * @param string $last_cumulative_size Last cumulative column size
562 * @param int $last_cumulative_type Last cumulative column type
563 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
564 * @param int $curr_type Type of the current cell
565 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
566 * @param string $cell The current cell
568 * @return string Size of the given cell in the type-appropriate format
571 * @todo Handle the error cases more elegantly
573 function PMA_detectSize($last_cumulative_size, $last_cumulative_type,
576 $curr_size = strlen((string)$cell);
579 * If the cell is NULL, don't treat it as a varchar
581 if (! strcmp('NULL', $cell)) {
582 return $last_cumulative_size;
583 } elseif ($curr_type == VARCHAR
) {
585 * What to do if the current cell is of type VARCHAR
588 * The last cumulative type was VARCHAR
590 if ($last_cumulative_type == VARCHAR
) {
591 if ($curr_size >= $last_cumulative_size) {
594 return $last_cumulative_size;
596 } elseif ($last_cumulative_type == DECIMAL
) {
598 * The last cumulative type was DECIMAL
600 $oldM = PMA_getM($last_cumulative_size);
602 if ($curr_size >= $oldM) {
607 } elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
609 * The last cumulative type was BIGINT or INT
611 if ($curr_size >= $last_cumulative_size) {
614 return $last_cumulative_size;
616 } elseif (! isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
618 * This is the first row to be analyzed
623 * An error has DEFINITELY occurred
626 * TODO: Handle this MUCH more elegantly
631 } elseif ($curr_type == DECIMAL
) {
633 * What to do if the current cell is of type DECIMAL
636 * The last cumulative type was VARCHAR
638 if ($last_cumulative_type == VARCHAR
) {
639 /* Convert $last_cumulative_size from varchar to decimal format */
640 $size = PMA_getDecimalSize($cell);
642 if ($size[M
] >= $last_cumulative_size) {
645 return $last_cumulative_size;
647 } elseif ($last_cumulative_type == DECIMAL
) {
649 * The last cumulative type was DECIMAL
651 $size = PMA_getDecimalSize($cell);
653 $oldM = PMA_getM($last_cumulative_size);
654 $oldD = PMA_getD($last_cumulative_size);
656 /* New val if M or D is greater than current largest */
657 if ($size[M
] > $oldM ||
$size[D
] > $oldD) {
658 /* Take the largest of both types */
659 return (string) ((($size[M
] > $oldM) ?
$size[M
] : $oldM)
660 . "," . (($size[D
] > $oldD) ?
$size[D
] : $oldD));
662 return $last_cumulative_size;
664 } elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
666 * The last cumulative type was BIGINT or INT
668 /* Convert $last_cumulative_size from int to decimal format */
669 $size = PMA_getDecimalSize($cell);
671 if ($size[M
] >= $last_cumulative_size) {
674 return ($last_cumulative_size.",".$size[D
]);
676 } elseif (! isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
678 * This is the first row to be analyzed
680 /* First row of the column */
681 $size = PMA_getDecimalSize($cell);
686 * An error has DEFINITELY occurred
689 * TODO: Handle this MUCH more elegantly
694 } elseif ($curr_type == BIGINT ||
$curr_type == INT) {
696 * What to do if the current cell is of type BIGINT or INT
699 * The last cumulative type was VARCHAR
701 if ($last_cumulative_type == VARCHAR
) {
702 if ($curr_size >= $last_cumulative_size) {
705 return $last_cumulative_size;
707 } elseif ($last_cumulative_type == DECIMAL
) {
709 * The last cumulative type was DECIMAL
711 $oldM = PMA_getM($last_cumulative_size);
712 $oldD = PMA_getD($last_cumulative_size);
713 $oldInt = $oldM - $oldD;
714 $newInt = strlen((string)$cell);
716 /* See which has the larger integer length */
717 if ($oldInt >= $newInt) {
718 /* Use old decimal size */
719 return $last_cumulative_size;
721 /* Use $newInt + $oldD as new M */
722 return (($newInt +
$oldD) . "," . $oldD);
724 } elseif ($last_cumulative_type == BIGINT ||
$last_cumulative_type == INT) {
726 * The last cumulative type was BIGINT or INT
728 if ($curr_size >= $last_cumulative_size) {
731 return $last_cumulative_size;
733 } elseif (! isset($last_cumulative_type) ||
$last_cumulative_type == NONE
) {
735 * This is the first row to be analyzed
740 * An error has DEFINITELY occurred
743 * TODO: Handle this MUCH more elegantly
750 * An error has DEFINITELY occurred
753 * TODO: Handle this MUCH more elegantly
761 * Determines what MySQL type a cell is
763 * @param int $last_cumulative_type Last cumulative column type
764 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
765 * @param string $cell String representation of the cell for which
766 * a best-fit type is to be determined
768 * @return int The MySQL type representation
769 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
772 function PMA_detectType($last_cumulative_type, $cell)
775 * If numeric, determine if decimal, int or bigint
776 * Else, we call it varchar for simplicity
779 if (! strcmp('NULL', $cell)) {
780 if ($last_cumulative_type === null ||
$last_cumulative_type == NONE
) {
783 return $last_cumulative_type;
785 } elseif (is_numeric($cell)) {
786 if ($cell == (string)(float)$cell
787 && strpos($cell, ".") !== false
788 && substr_count($cell, ".") == 1
792 if (abs($cell) > 2147483647) {
804 * Determines if the column types are int, decimal, or string
806 * @param array &$table array(string $table_name, array $col_names, array $rows)
808 * @return array array(array $types, array $sizes)
811 * @link http://wiki.phpmyadmin.net/pma/Import
813 * @todo Handle the error case more elegantly
815 function PMA_analyzeTable(&$table)
817 /* Get number of rows in table */
818 $numRows = count($table[ROWS
]);
819 /* Get number of columns */
820 $numCols = count($table[COL_NAMES
]);
821 /* Current type for each column */
825 /* Initialize $sizes to all 0's */
826 for ($i = 0; $i < $numCols; ++
$i) {
830 /* Initialize $types to NONE */
831 for ($i = 0; $i < $numCols; ++
$i) {
838 /* If the passed array is not of the correct form, do not process it */
840 && ! is_array($table[TBL_NAME
])
841 && is_array($table[COL_NAMES
])
842 && is_array($table[ROWS
])
844 /* Analyze each column */
845 for ($i = 0; $i < $numCols; ++
$i) {
846 /* Analyze the column in each row */
847 for ($j = 0; $j < $numRows; ++
$j) {
848 /* Determine type of the current cell */
849 $curr_type = PMA_detectType($types[$i], $table[ROWS
][$j][$i]);
850 /* Determine size of the current cell */
851 $sizes[$i] = PMA_detectSize(
859 * If a type for this column has already been declared,
860 * only alter it if it was a number and a varchar was found
862 if ($curr_type != NONE
) {
863 if ($curr_type == VARCHAR
) {
864 $types[$i] = VARCHAR
;
865 } else if ($curr_type == DECIMAL
) {
866 if ($types[$i] != VARCHAR
) {
867 $types[$i] = DECIMAL
;
869 } else if ($curr_type == BIGINT
) {
870 if ($types[$i] != VARCHAR
&& $types[$i] != DECIMAL
) {
873 } else if ($curr_type == INT) {
874 if ($types[$i] != VARCHAR
875 && $types[$i] != DECIMAL
876 && $types[$i] != BIGINT
885 /* Check to ensure that all types are valid */
886 $len = count($types);
887 for ($n = 0; $n < $len; ++
$n) {
888 if (! strcmp(NONE
, $types[$n])) {
889 $types[$n] = VARCHAR
;
894 return array($types, $sizes);
897 * TODO: Handle this better
904 /* Needed to quell the beast that is PMA_Message */
905 $import_notice = null;
908 * Builds and executes SQL statements to create the database and tables
909 * as necessary, as well as insert all the data.
911 * @param string $db_name Name of the database
912 * @param array &$tables Array of tables for the specified database
913 * @param array &$analyses Analyses of the tables
914 * @param array &$additional_sql Additional SQL statements to be executed
915 * @param array $options Associative array of options
920 * @link http://wiki.phpmyadmin.net/pma/Import
922 function PMA_buildSQL($db_name, &$tables, &$analyses = null,
923 &$additional_sql = null, $options = null
925 /* Take care of the options */
926 if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
927 $collation = $options['db_collation'];
929 $collation = "utf8_general_ci";
932 if (isset($options['db_charset']) && ! is_null($options['db_charset'])) {
933 $charset = $options['db_charset'];
938 if (isset($options['create_db'])) {
939 $create_db = $options['create_db'];
944 /* Create SQL code to handle the database */
949 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util
::backquote($db_name)
950 . " COLLATE " . $collation;
952 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util
::backquote($db_name)
953 . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
958 * The calling plug-in should include this statement,
959 * if necessary, in the $additional_sql parameter
961 * $sql[] = "USE " . backquote($db_name);
964 /* Execute the SQL statements create above */
965 $sql_len = count($sql);
966 for ($i = 0; $i < $sql_len; ++
$i) {
967 PMA_importRunQuery($sql[$i], $sql[$i]);
970 /* No longer needed */
973 /* Run the $additional_sql statements supplied by the caller plug-in */
974 if ($additional_sql != null) {
975 /* Clean the SQL first */
976 $additional_sql_len = count($additional_sql);
979 * Only match tables for now, because CREATE IF NOT EXISTS
980 * syntax is lacking or nonexisting for views, triggers,
981 * functions, and procedures.
983 * See: http://bugs.mysql.com/bug.php?id=15287
985 * To the best of my knowledge this is still an issue.
987 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
989 $pattern = '/CREATE [^`]*(TABLE)/';
990 $replacement = 'CREATE \\1 IF NOT EXISTS';
992 /* Change CREATE statements to CREATE IF NOT EXISTS to support
993 * inserting into existing structures
995 for ($i = 0; $i < $additional_sql_len; ++
$i) {
996 $additional_sql[$i] = preg_replace(
1001 /* Execute the resulting statements */
1002 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
1006 if ($analyses != null) {
1007 $type_array = array(
1009 VARCHAR
=> "varchar",
1011 DECIMAL
=> "decimal",
1013 GEOMETRY
=> 'geometry'
1016 /* TODO: Do more checking here to make sure they really are matched */
1017 if (count($tables) != count($analyses)) {
1021 /* Create SQL code to create the tables */
1023 $num_tables = count($tables);
1024 for ($i = 0; $i < $num_tables; ++
$i) {
1025 $num_cols = count($tables[$i][COL_NAMES
]);
1026 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_Util
::backquote($db_name)
1027 . '.' . PMA_Util
::backquote($tables[$i][TBL_NAME
]) . " (";
1028 for ($j = 0; $j < $num_cols; ++
$j) {
1029 $size = $analyses[$i][SIZES
][$j];
1030 if ((int)$size == 0) {
1034 $tempSQLStr .= PMA_Util
::backquote($tables[$i][COL_NAMES
][$j]) . " "
1035 . $type_array[$analyses[$i][TYPES
][$j]];
1036 if ($analyses[$i][TYPES
][$j] != GEOMETRY
) {
1037 $tempSQLStr .= "(" . $size . ")";
1040 if ($j != (count($tables[$i][COL_NAMES
]) - 1)) {
1041 $tempSQLStr .= ", ";
1045 . (PMA_DRIZZLE ?
"" : " DEFAULT CHARACTER SET " . $charset)
1046 . " COLLATE " . $collation . ";";
1049 * Each SQL statement is executed immediately
1050 * after it is formed so that we don't have
1051 * to store them in a (possibly large) buffer
1053 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1058 * Create the SQL statements to insert all the data
1060 * Only one insert query is formed for each table
1064 $num_tables = count($tables);
1065 for ($i = 0; $i < $num_tables; ++
$i) {
1066 $num_cols = count($tables[$i][COL_NAMES
]);
1067 $num_rows = count($tables[$i][ROWS
]);
1069 $tempSQLStr = "INSERT INTO " . PMA_Util
::backquote($db_name) . '.'
1070 . PMA_Util
::backquote($tables[$i][TBL_NAME
]) . " (";
1072 for ($m = 0; $m < $num_cols; ++
$m) {
1073 $tempSQLStr .= PMA_Util
::backquote($tables[$i][COL_NAMES
][$m]);
1075 if ($m != ($num_cols - 1)) {
1076 $tempSQLStr .= ", ";
1080 $tempSQLStr .= ") VALUES ";
1082 for ($j = 0; $j < $num_rows; ++
$j) {
1085 for ($k = 0; $k < $num_cols; ++
$k) {
1086 // If fully formatted SQL, no need to enclose
1087 // with aphostrophes, add shalshes etc.
1088 if ($analyses != null
1089 && isset($analyses[$i][FORMATTEDSQL
][$col_count])
1090 && $analyses[$i][FORMATTEDSQL
][$col_count] == true
1092 $tempSQLStr .= (string) $tables[$i][ROWS
][$j][$k];
1094 if ($analyses != null) {
1095 $is_varchar = ($analyses[$i][TYPES
][$col_count] === VARCHAR
);
1097 $is_varchar = ! is_numeric($tables[$i][ROWS
][$j][$k]);
1100 /* Don't put quotes around NULL fields */
1101 if (! strcmp($tables[$i][ROWS
][$j][$k], 'NULL')) {
1102 $is_varchar = false;
1105 $tempSQLStr .= (($is_varchar) ?
"'" : "");
1106 $tempSQLStr .= PMA_Util
::sqlAddSlashes(
1107 (string) $tables[$i][ROWS
][$j][$k]
1109 $tempSQLStr .= (($is_varchar) ?
"'" : "");
1112 if ($k != ($num_cols - 1)) {
1113 $tempSQLStr .= ", ";
1116 if ($col_count == ($num_cols - 1)) {
1122 /* Delete the cell after we are done with it */
1123 unset($tables[$i][ROWS
][$j][$k]);
1128 if ($j != ($num_rows - 1)) {
1129 $tempSQLStr .= ",\n ";
1133 /* Delete the row after we are done with it */
1134 unset($tables[$i][ROWS
][$j]);
1140 * Each SQL statement is executed immediately
1141 * after it is formed so that we don't have
1142 * to store them in a (possibly large) buffer
1144 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1147 /* No longer needed */
1151 * A work in progress
1154 /* Add the viewable structures from $additional_sql
1155 * to $tables so they are also displayed
1157 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1158 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1159 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1165 $additional_sql_len = count($additional_sql);
1166 for ($i = 0; $i < $additional_sql_len; ++
$i) {
1167 preg_match($view_pattern, $additional_sql[$i], $regs);
1169 if (count($regs) == 0) {
1170 preg_match($table_pattern, $additional_sql[$i], $regs);
1174 for ($n = 0; $n < $num_tables; ++
$n) {
1175 if (! strcmp($regs[1], $tables[$n][TBL_NAME
])) {
1182 $tables[] = array(TBL_NAME
=> $regs[1]);
1186 /* Reset the array */
1191 $params = array('db' => (string)$db_name);
1192 $db_url = 'db_structure.php' . PMA_URL_getCommon($params);
1193 $db_ops_url = 'db_operations.php' . PMA_URL_getCommon($params);
1195 $message = '<br /><br />';
1196 $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
1197 $message .= '<ul><li>' . __("View a structure's contents by clicking on its name") . '</li>';
1198 $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link') . '</li>';
1199 $message .= '<li>' . __('Edit structure by following the "Structure" link') . '</li>';
1200 $message .= sprintf(
1201 '<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1203 sprintf(__('Go to database: %s'), htmlspecialchars(PMA_Util
::backquote($db_name))),
1204 htmlspecialchars($db_name),
1206 sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_Util
::backquote($db_name)))
1213 $num_tables = count($tables);
1214 for ($i = 0; $i < $num_tables; ++
$i) {
1216 'db' => (string) $db_name,
1217 'table' => (string) $tables[$i][TBL_NAME
]
1219 $tbl_url = 'sql.php' . PMA_URL_getCommon($params);
1220 $tbl_struct_url = 'tbl_structure.php' . PMA_URL_getCommon($params);
1221 $tbl_ops_url = 'tbl_operations.php' . PMA_URL_getCommon($params);
1225 if (! PMA_Table
::isView($db_name, $tables[$i][TBL_NAME
])) {
1226 $message .= sprintf(
1227 '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1229 sprintf(__('Go to table: %s'), htmlspecialchars(PMA_Util
::backquote($tables[$i][TBL_NAME
]))),
1230 htmlspecialchars($tables[$i][TBL_NAME
]),
1232 sprintf(__('Structure of %s'), htmlspecialchars(PMA_Util
::backquote($tables[$i][TBL_NAME
]))),
1234 sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_Util
::backquote($tables[$i][TBL_NAME
])))
1237 $message .= sprintf(
1238 '<li><a href="%s" title="%s">%s</a></li>',
1240 sprintf(__('Go to view: %s'), htmlspecialchars(PMA_Util
::backquote($tables[$i][TBL_NAME
]))),
1241 htmlspecialchars($tables[$i][TBL_NAME
])
1246 $message .= '</ul></ul>';
1248 global $import_notice;
1249 $import_notice = $message;