value can be negative
[phpmyadmin-themes.git] / libraries / import.lib.php
blob24b27db81a254fabda77633e4e7f785728f4b00d
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Library that provides common import functions that are used by import plugins
6 * @version $Id$
7 * @package phpMyAdmin
8 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * We need to know something about user
16 require_once './libraries/check_user_privileges.lib.php';
18 /**
19 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
21 define('PMA_CHK_DROP', 1);
23 /**
24 * Check whether timeout is getting close
26 * @return boolean true if timeout is close
27 * @access public
29 function PMA_checkTimeout()
31 global $timestamp, $maximum_time, $timeout_passed;
32 if ($maximum_time == 0) {
33 return FALSE;
34 } elseif ($timeout_passed) {
35 return TRUE;
36 /* 5 in next row might be too much */
37 } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
38 $timeout_passed = TRUE;
39 return TRUE;
40 } else {
41 return FALSE;
45 /**
46 * Detects what compression filse uses
48 * @param string filename to check
49 * @return string MIME type of compression, none for none
50 * @access public
52 function PMA_detectCompression($filepath)
54 $file = @fopen($filepath, 'rb');
55 if (!$file) {
56 return FALSE;
58 $test = fread($file, 4);
59 $len = strlen($test);
60 fclose($file);
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';
70 return 'none';
73 /**
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
81 * @access public
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;
90 $read_multiply = 1;
91 if (isset($import_run_buffer)) {
92 // Should we skip something?
93 if ($skip_queries > 0) {
94 $skip_queries--;
95 } else {
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']
102 && !$is_superuser
103 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
104 $GLOBALS['message'] = PMA_Message::error('strNoDropDatabases');
105 $error = TRUE;
106 } else {
107 $executed_queries++;
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)
111 )) {
112 $go_sql = TRUE;
113 if (!$sql_query_disabled) {
114 $complete_query = $sql_query;
115 $display_query = $sql_query;
116 } else {
117 $complete_query = '';
118 $display_query = '';
120 $sql_query = $import_run_buffer['sql'];
121 } elseif ($run_query) {
122 if ($controluser) {
123 $result = PMA_query_as_controluser($import_run_buffer['sql']);
124 } else {
125 $result = PMA_DBI_try_query($import_run_buffer['sql']);
127 $msg = '# ';
128 if ($result === FALSE) { // execution failed
129 if (!isset($my_die)) {
130 $my_die = array();
132 $my_die[] = array('sql' => $import_run_buffer['full'], 'error' => PMA_DBI_getError());
134 if ($cfg['VerboseMultiSubmit']) {
135 $msg .= $GLOBALS['strError'];
138 if (!$cfg['IgnoreMultiSubmitErrors']) {
139 $error = TRUE;
140 return;
142 } elseif ($cfg['VerboseMultiSubmit']) {
143 $a_num_rows = (int)@PMA_DBI_num_rows($result);
144 $a_aff_rows = (int)@PMA_DBI_affected_rows();
145 if ($a_num_rows > 0) {
146 $msg .= $GLOBALS['strRows'] . ': ' . $a_num_rows;
147 $last_query_with_results = $import_run_buffer['sql'];
148 } elseif ($a_aff_rows > 0) {
149 $msg .= sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
150 } else {
151 $msg .= $GLOBALS['strEmptyResultSet'];
154 if (!$sql_query_disabled) {
155 $sql_query .= $msg . "\n";
158 // If a 'USE <db>' SQL-clause was found and the query succeeded, set our current $db to the new one
159 if ($result != FALSE && preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $import_run_buffer['sql'], $match)) {
160 $db = trim($match[1]);
161 $db = trim($db,';'); // for example, USE abc;
162 $reload = TRUE;
165 if ($result != FALSE && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])) {
166 $reload = TRUE;
168 } // end run query
169 } // end if not DROP DATABASE
170 } // end non empty query
171 elseif (!empty($import_run_buffer['full'])) {
172 if ($go_sql) {
173 $complete_query .= $import_run_buffer['full'];
174 $display_query .= $import_run_buffer['full'];
175 } else {
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) {
187 $sql_query = '';
188 $sql_query_disabled = TRUE;
190 } else {
191 if (strlen($sql_query) > 10000 || $executed_queries > 10 || $max_sql_len > 500) {
192 $sql_query = '';
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);
203 } else {
204 unset($GLOBALS['import_run_buffer']);
210 * Returns next part of imported file/buffer
212 * @uses $GLOBALS['offset'] read and write
213 * @uses $GLOBALS['import_file'] read only
214 * @uses $GLOBALS['import_text'] read and write
215 * @uses $GLOBALS['finished'] read and write
216 * @uses $GLOBALS['read_limit'] read only
217 * @param integer size of buffer to read (this is maximal size
218 * function will return)
219 * @return string part of file/buffer
220 * @access public
222 function PMA_importGetNextChunk($size = 32768)
224 global $compression, $import_handle, $charset_conversion, $charset_of_file,
225 $charset, $read_multiply;
227 // Add some progression while reading large amount of data
228 if ($read_multiply <= 8) {
229 $size *= $read_multiply;
230 } else {
231 $size *= 8;
233 $read_multiply++;
235 // We can not read too much
236 if ($size > $GLOBALS['read_limit']) {
237 $size = $GLOBALS['read_limit'];
240 if (PMA_checkTimeout()) {
241 return FALSE;
243 if ($GLOBALS['finished']) {
244 return TRUE;
247 if ($GLOBALS['import_file'] == 'none') {
248 // Well this is not yet supported and tested, but should return content of textarea
249 if (strlen($GLOBALS['import_text']) < $size) {
250 $GLOBALS['finished'] = TRUE;
251 return $GLOBALS['import_text'];
252 } else {
253 $r = substr($GLOBALS['import_text'], 0, $size);
254 $GLOBALS['offset'] += $size;
255 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
256 return $r;
260 switch ($compression) {
261 case 'application/bzip2':
262 $result = bzread($import_handle, $size);
263 $GLOBALS['finished'] = feof($import_handle);
264 break;
265 case 'application/gzip':
266 $result = gzread($import_handle, $size);
267 $GLOBALS['finished'] = feof($import_handle);
268 break;
269 case 'application/zip':
270 $result = substr($GLOBALS['import_text'], 0, $size);
271 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
272 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
273 break;
274 case 'none':
275 $result = fread($import_handle, $size);
276 $GLOBALS['finished'] = feof($import_handle);
277 break;
279 $GLOBALS['offset'] += $size;
281 if ($charset_conversion) {
282 return PMA_convert_string($charset_of_file, $charset, $result);
283 } else {
285 * Skip possible byte order marks (I do not think we need more
286 * charsets, but feel free to add more, you can use wikipedia for
287 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
289 * @todo BOM could be used for charset autodetection
291 if ($GLOBALS['offset'] == $size) {
292 // UTF-8
293 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
294 $result = substr($result, 3);
295 // UTF-16 BE, LE
296 } elseif (strncmp($result, "\xFE\xFF", 2) == 0 || strncmp($result, "\xFF\xFE", 2) == 0) {
297 $result = substr($result, 2);
300 return $result;
305 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
307 * This functions uses recursion to build the Excel column name.
309 * The column number (1-26) is converted to the responding ASCII character (A-Z) and returned.
311 * If the column number is bigger than 26 (= num of letters in alfabet),
312 * an extra character needs to be added. To find this extra character, the number is divided by 26
313 * and this value is passed to another instance of the same function (hence recursion).
314 * In that new instance the number is evaluated again, and if it is still bigger than 26, it is divided again
315 * and passed to another instance of the same function. This continues until the number is smaller than 26.
316 * Then the last called function returns the corresponding ASCII character to the function that called it.
317 * Each time a called function ends an extra character is added to the column name.
318 * When the first function is reached, the last character is addded and the complete column name is returned.
320 * @access public
322 * @uses chr()
323 * @param int $num
324 * @return string The column's "Excel" name
326 function PMA_getColumnAlphaName($num)
328 $A = 65; // ASCII value for capital "A"
329 $col_name = "";
331 if ($num > 26) {
332 $div = (int)($num / 26);
333 $remain = (int)($num % 26);
335 // subtract 1 of divided value in case the modulus is 0,
336 // this is necessary because A-Z has no 'zero'
337 if ($remain == 0) {
338 $div--;
341 // recursive function call
342 $col_name = PMA_getColumnAlphaName($div);
343 // use modulus as new column number
344 $num = $remain;
347 if ($num == 0) {
348 // use 'Z' if column number is 0,
349 // this is necessary because A-Z has no 'zero'
350 $col_name .= chr(($A + 26) - 1);
351 } else {
352 // convert column number to ASCII character
353 $col_name .= chr(($A + $num) - 1);
356 return $col_name;
360 * Returns the column number based on the Excel name.
361 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
363 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
364 * It iterates through all characters in the column name and
365 * calculates the corresponding value, based on character value
366 * (A = 1, ..., Z = 26) and position in the string.
368 * @access public
370 * @uses strtoupper()
371 * @uses strlen()
372 * @uses ord()
373 * @param string $name (i.e. "A", or "BC", etc.)
374 * @return int The column number
376 function PMA_getColumnNumberFromName($name) {
377 if (!empty($name)) {
378 $name = strtoupper($name);
379 $num_chars = strlen($name);
380 $column_number = 0;
381 for ($i = 0; $i < $num_chars; ++$i) {
382 // read string from back to front
383 $char_pos = ($num_chars - 1) - $i;
385 // convert capital character to ASCII value
386 // and subtract 64 to get corresponding decimal value
387 // ASCII value of "A" is 65, "B" is 66, etc.
388 // Decimal equivalent of "A" is 1, "B" is 2, etc.
389 $number = (ord($name[$char_pos]) - 64);
391 // base26 to base10 conversion : multiply each number
392 // with corresponding value of the position, in this case
393 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
394 $column_number += $number * pow(26,$i);
396 return $column_number;
397 } else {
398 return 0;
403 * Constants definitions
406 /* MySQL type defs */
407 define("NONE", 0);
408 define("VARCHAR", 1);
409 define("INT", 2);
410 define("DECIMAL", 3);
411 define("BIGINT", 4);
413 /* Decimal size defs */
414 define("M", 0);
415 define("D", 1);
416 define("FULL", 2);
418 /* Table array defs */
419 define("TBL_NAME", 0);
420 define("COL_NAMES", 1);
421 define("ROWS", 2);
423 /* Analysis array defs */
424 define("TYPES", 0);
425 define("SIZES", 1);
428 * Obtains the precision (total # of digits) from a size of type decimal
430 * @author Derek Schaefer (derek.schaefer@gmail.com)
432 * @access public
434 * @uses substr()
435 * @uses strpos()
436 * @param string $last_cumulative_size
437 * @return int Precision of the given decimal size notation
439 function PMA_getM($last_cumulative_size) {
440 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
444 * Obtains the scale (# of digits to the right of the decimal point) from a size of type decimal
446 * @author Derek Schaefer (derek.schaefer@gmail.com)
448 * @access public
450 * @uses substr()
451 * @uses strpos()
452 * @uses strlen()
453 * @param string $last_cumulative_size
454 * @return int Scale of the given decimal size notation
456 function PMA_getD($last_cumulative_size) {
457 return (int)substr($last_cumulative_size, (strpos($last_cumulative_size, ",") + 1), (strlen($last_cumulative_size) - strpos($last_cumulative_size, ",")));
461 * Obtains the decimal size of a given cell
463 * @author Derek Schaefer (derek.schaefer@gmail.com)
465 * @access public
467 * @uses strlen()
468 * @uses strpos()
469 * @param string &$cell
470 * @return array Contains the precision, scale, and full size representation of the given decimal cell
472 function PMA_getDecimalSize(&$cell) {
473 $curr_size = strlen((string)$cell);
474 $decPos = strpos($cell, ".");
475 $decPrecision = ($curr_size - 1) - $decPos;
477 $m = $curr_size - 1;
478 $d = $decPrecision;
480 return array($m, $d, ($m . "," . $d));
484 * Obtains the size of the given cell
486 * @author Derek Schaefer (derek.schaefer@gmail.com)
488 * @todo Handle the error cases more elegantly
490 * @access public
492 * @uses M
493 * @uses D
494 * @uses FULL
495 * @uses VARCHAR
496 * @uses DECIMAL
497 * @uses BIGINT
498 * @uses INT
499 * @uses NONE
500 * @uses strcmp()
501 * @uses strlen()
502 * @uses PMA_getM()
503 * @uses PMA_getD()
504 * @uses PMA_getDecimalSize()
505 * @param string $last_cumulative_size Last cumulative column size
506 * @param int $last_cumulative_type Last cumulative column type (NONE or VARCHAR or DECIMAL or INT or BIGINT)
507 * @param int $curr_type Type of the current cell (NONE or VARCHAR or DECIMAL or INT or BIGINT)
508 * @param string &$cell The current cell
509 * @return string Size of the given cell in the type-appropriate format
511 function PMA_detectSize($last_cumulative_size, $last_cumulative_type, $curr_type, &$cell) {
512 $curr_size = strlen((string)$cell);
515 * If the cell is NULL, don't treat it as a varchar
517 if (! strcmp('NULL', $cell)) {
518 return $last_cumulative_size;
521 * What to do if the current cell is of type VARCHAR
523 elseif ($curr_type == VARCHAR) {
525 * The last cumulative type was VARCHAR
527 if ($last_cumulative_type == VARCHAR) {
528 if ($curr_size >= $last_cumulative_size) {
529 return $curr_size;
530 } else {
531 return $last_cumulative_size;
535 * The last cumulative type was DECIMAL
537 elseif ($last_cumulative_type == DECIMAL) {
538 $oldM = PMA_getM($last_cumulative_size);
540 if ($curr_size >= $oldM) {
541 return $curr_size;
542 } else {
543 return $oldM;
547 * The last cumulative type was BIGINT or INT
549 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
550 if ($curr_size >= $last_cumulative_size) {
551 return $curr_size;
552 } else {
553 return $last_cumulative_size;
557 * This is the first row to be analyzed
559 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
560 return $curr_size;
563 * An error has DEFINITELY occurred
565 else {
567 * TODO: Handle this MUCH more elegantly
570 return -1;
574 * What to do if the current cell is of type DECIMAL
576 elseif ($curr_type == DECIMAL) {
578 * The last cumulative type was VARCHAR
580 if ($last_cumulative_type == VARCHAR) {
581 /* Convert $last_cumulative_size from varchar to decimal format */
582 $size = PMA_getDecimalSize($cell);
584 if ($size[M] >= $last_cumulative_size) {
585 return $size[M];
586 } else {
587 return $last_cumulative_size;
591 * The last cumulative type was DECIMAL
593 elseif ($last_cumulative_type == DECIMAL) {
594 $size = PMA_getDecimalSize($cell);
596 $oldM = PMA_getM($last_cumulative_size);
597 $oldD = PMA_getD($last_cumulative_size);
599 /* New val if M or D is greater than current largest */
600 if ($size[M] > $oldM || $size[D] > $oldD) {
601 /* Take the largest of both types */
602 return (string)((($size[M] > $oldM) ? $size[M] : $oldM) . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
603 } else {
604 return $last_cumulative_size;
608 * The last cumulative type was BIGINT or INT
610 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
611 /* Convert $last_cumulative_size from int to decimal format */
612 $size = PMA_getDecimalSize($cell);
614 if ($size[M] >= $last_cumulative_size) {
615 return $size[FULL];
616 } else {
617 return ($last_cumulative_size.",".$size[D]);
621 * This is the first row to be analyzed
623 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
624 /* First row of the column */
625 $size = PMA_getDecimalSize($cell);
627 return $size[FULL];
630 * An error has DEFINITELY occurred
632 else {
634 * TODO: Handle this MUCH more elegantly
637 return -1;
641 * What to do if the current cell is of type BIGINT or INT
643 elseif ($curr_type == BIGINT || $curr_type == INT) {
645 * The last cumulative type was VARCHAR
647 if ($last_cumulative_type == VARCHAR) {
648 if ($curr_size >= $last_cumulative_size) {
649 return $curr_size;
650 } else {
651 return $last_cumulative_size;
655 * The last cumulative type was DECIMAL
657 elseif ($last_cumulative_type == DECIMAL) {
658 $oldM = PMA_getM($last_cumulative_size);
659 $oldD = PMA_getD($last_cumulative_size);
660 $oldInt = $oldM - $oldD;
661 $newInt = strlen((string)$cell);
663 /* See which has the larger integer length */
664 if ($oldInt >= $newInt) {
665 /* Use old decimal size */
666 return $last_cumulative_size;
667 } else {
668 /* Use $newInt + $oldD as new M */
669 return (($newInt + $oldD) . "," . $oldD);
673 * The last cumulative type was BIGINT or INT
675 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
676 if ($curr_size >= $last_cumulative_size) {
677 return $curr_size;
678 } else {
679 return $last_cumulative_size;
683 * This is the first row to be analyzed
685 elseif (!isset($last_cumulative_type) || $last_cumulative_type == NONE) {
686 return $curr_size;
689 * An error has DEFINITELY occurred
691 else {
693 * TODO: Handle this MUCH more elegantly
696 return -1;
700 * An error has DEFINITELY occurred
702 else {
704 * TODO: Handle this MUCH more elegantly
707 return -1;
712 * Determines what MySQL type a cell is
714 * @author Derek Schaefer (derek.schaefer@gmail.com)
716 * @access public
718 * @uses DECIMAL
719 * @uses BIGINT
720 * @uses INT
721 * @uses VARCHAR
722 * @uses NONE
723 * @uses is_numeric()
724 * @uses strcmp()
725 * @uses strpos()
726 * @uses substr_count()
727 * @param int $last_cumulative_type Last cumulative column type (VARCHAR or INT or BIGINT or DECIMAL or NONE)
728 * @param string &$cell String representation of the cell for which a best-fit type is to be determined
729 * @return int The MySQL type representation (VARCHAR or INT or BIGINT or DECIMAL or NONE)
731 function PMA_detectType($last_cumulative_type, &$cell) {
733 * If numeric, determine if decimal, int or bigint
734 * Else, we call it varchar for simplicity
737 if (! strcmp('NULL', $cell)) {
738 if ($last_cumulative_type === NULL || $last_cumulative_type == NONE) {
739 return NONE;
740 } else {
741 return $last_cumulative_type;
743 } elseif (is_numeric($cell)) {
744 if ($cell == (string)(float)$cell && strpos($cell, ".") !== false && substr_count($cell, ".") == 1) {
745 return DECIMAL;
746 } else {
747 if (abs($cell) > 2147483647) {
748 return BIGINT;
749 } else {
750 return INT;
753 } else {
754 return VARCHAR;
759 * Determines if the column types are int, decimal, or string
761 * @author Derek Schaefer (derek.schaefer@gmail.com)
763 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
765 * @todo Handle the error case more elegantly
767 * @access public
769 * @uses TBL_NAME
770 * @uses COL_NAMES
771 * @uses ROWS
772 * @uses VARCHAR
773 * @uses DECIMAL
774 * @uses BIGINT
775 * @uses INT
776 * @uses NONE
777 * @uses count()
778 * @uses is_array()
779 * @uses PMA_detectType()
780 * @uses PMA_detectSize()
781 * @param &$table array(string $table_name, array $col_names, array $rows)
782 * @return array array(array $types, array $sizes)
784 function PMA_analyzeTable(&$table) {
785 /* Get number of rows in table */
786 $numRows = count($table[ROWS]);
787 /* Get number of columns */
788 $numCols = count($table[COL_NAMES]);
789 /* Current type for each column */
790 $types = array();
791 $sizes = array();
793 /* Initialize $sizes to all 0's */
794 for ($i = 0; $i < $numCols; ++$i) {
795 $sizes[$i] = 0;
798 /* Initialize $types to NONE */
799 for ($i = 0; $i < $numCols; ++$i) {
800 $types[$i] = NONE;
803 /* Temp vars */
804 $curr_type = NONE;
805 $curr_size = 0;
807 /* If the passed array is not of the correct form, do not process it */
808 if (is_array($table) && ! is_array($table[TBL_NAME]) && is_array($table[COL_NAMES]) && is_array($table[ROWS])) {
809 /* Analyze each column */
810 for ($i = 0; $i < $numCols; ++$i) {
811 /* Analyze the column in each row */
812 for ($j = 0; $j < $numRows; ++$j) {
813 /* Determine type of the current cell */
814 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
815 /* Determine size of the current cell */
816 $sizes[$i] = PMA_detectSize($sizes[$i], $types[$i], $curr_type, $table[ROWS][$j][$i]);
819 * If a type for this column has already been declared,
820 * only alter it if it was a number and a varchar was found
822 if ($curr_type != NONE) {
823 if ($curr_type == VARCHAR) {
824 $types[$i] = VARCHAR;
825 } else if ($curr_type == DECIMAL) {
826 if ($types[$i] != VARCHAR) {
827 $types[$i] = DECIMAL;
829 } else if ($curr_type == BIGINT) {
830 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
831 $types[$i] = BIGINT;
833 } else if ($curr_type == INT) {
834 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL && $types[$i] != BIGINT) {
835 $types[$i] = INT;
842 /* Check to ensure that all types are valid */
843 $len = count($types);
844 for ($n = 0; $n < $len; ++$n) {
845 if (! strcmp(NONE, $types[$n])) {
846 $types[$n] = VARCHAR;
847 $sizes[$n] = '10';
851 return array($types, $sizes);
853 else
856 * TODO: Handle this better
859 return false;
863 /* Needed to quell the beast that is PMA_Message */
864 $import_notice = NULL;
867 * Builds and executes SQL statements to create the database and tables
868 * as necessary, as well as insert all the data.
870 * @author Derek Schaefer (derek.schaefer@gmail.com)
872 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
874 * @access public
876 * @uses TBL_NAME
877 * @uses COL_NAMES
878 * @uses ROWS
879 * @uses TYPES
880 * @uses SIZES
881 * @uses strcmp()
882 * @uses count()
883 * @uses preg_match()
884 * @uses preg_replace()
885 * @uses PMA_isView()
886 * @uses PMA_backquote()
887 * @uses PMA_importRunQuery()
888 * @uses PMA_generate_common_url()
889 * @uses PMA_Message::notice()
890 * @param string $db_name Name of the database
891 * @param array &$tables Array of tables for the specified database
892 * @param array &$analyses = NULL Analyses of the tables
893 * @param array &$additional_sql = NULL Additional SQL statements to be executed
894 * @param array $options = NULL Associative array of options
895 * @return void
897 function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL) {
898 /* Take care of the options */
899 if (isset($options['db_collation'])) {
900 $collation = $options['db_collation'];
901 } else {
902 $collation = "utf8_general_ci";
905 if (isset($options['db_charset'])) {
906 $charset = $options['db_charset'];
907 } else {
908 $charset = "utf8";
911 if (isset($options['create_db'])) {
912 $create_db = $options['create_db'];
913 } else {
914 $create_db = true;
917 /* Create SQL code to handle the database */
918 $sql = array();
920 if ($create_db) {
921 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
925 * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
927 * $sql[] = "USE " . PMA_backquote($db_name);
930 /* Execute the SQL statements create above */
931 $sql_len = count($sql);
932 for ($i = 0; $i < $sql_len; ++$i) {
933 PMA_importRunQuery($sql[$i], $sql[$i]);
936 /* No longer needed */
937 unset($sql);
939 /* Run the $additional_sql statements supplied by the caller plug-in */
940 if ($additional_sql != NULL) {
941 /* Clean the SQL first */
942 $additional_sql_len = count($additional_sql);
945 * Only match tables for now, because CREATE IF NOT EXISTS
946 * syntax is lacking or nonexisting for views, triggers,
947 * functions, and procedures.
949 * See: http://bugs.mysql.com/bug.php?id=15287
951 * To the best of my knowledge this is still an issue.
953 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
955 $pattern = '/CREATE .*(TABLE)/';
956 $replacement = 'CREATE \\1 IF NOT EXISTS';
958 /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
959 for ($i = 0; $i < $additional_sql_len; ++$i) {
960 $additional_sql[$i] = preg_replace($pattern, $replacement, $additional_sql[$i]);
961 /* Execute the resulting statements */
962 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
966 if ($analyses != NULL) {
967 $type_array = array(NONE => "NULL", VARCHAR => "varchar", INT => "int", DECIMAL => "decimal", BIGINT => "bigint");
969 /* TODO: Do more checking here to make sure they really are matched */
970 if (count($tables) != count($analyses)) {
971 exit();
974 /* Create SQL code to create the tables */
975 $tempSQLStr = "";
976 $num_tables = count($tables);
977 for ($i = 0; $i < $num_tables; ++$i) {
978 $num_cols = count($tables[$i][COL_NAMES]);
979 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
980 for ($j = 0; $j < $num_cols; ++$j) {
981 $size = $analyses[$i][SIZES][$j];
982 if ((int)$size == 0) {
983 $size = 10;
986 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " " . $type_array[$analyses[$i][TYPES][$j]] . "(" . $size . ")";
988 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
989 $tempSQLStr .= ", ";
992 $tempSQLStr .= ") ENGINE=MyISAM DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
995 * Each SQL statement is executed immediately
996 * after it is formed so that we don't have
997 * to store them in a (possibly large) buffer
999 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1004 * Create the SQL statements to insert all the data
1006 * Only one insert query is formed for each table
1008 $tempSQLStr = "";
1009 $col_count = 0;
1010 $num_tables = count($tables);
1011 for ($i = 0; $i < $num_tables; ++$i) {
1012 $num_cols = count($tables[$i][COL_NAMES]);
1013 $num_rows = count($tables[$i][ROWS]);
1015 $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
1017 for ($m = 0; $m < $num_cols; ++$m) {
1018 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
1020 if ($m != ($num_cols - 1)) {
1021 $tempSQLStr .= ", ";
1025 $tempSQLStr .= ") VALUES ";
1027 for ($j = 0; $j < $num_rows; ++$j) {
1028 $tempSQLStr .= "(";
1030 for ($k = 0; $k < $num_cols; ++$k) {
1031 if ($analyses != NULL) {
1032 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1033 } else {
1034 $is_varchar = !is_numeric($tables[$i][ROWS][$j][$k]);
1037 /* Don't put quotes around NULL fields */
1038 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1039 $is_varchar = false;
1042 $tempSQLStr .= (($is_varchar) ? "'" : "");
1043 $tempSQLStr .= PMA_sqlAddslashes((string)$tables[$i][ROWS][$j][$k]);
1044 $tempSQLStr .= (($is_varchar) ? "'" : "");
1046 if ($k != ($num_cols - 1)) {
1047 $tempSQLStr .= ", ";
1050 if ($col_count == ($num_cols - 1)) {
1051 $col_count = 0;
1052 } else {
1053 $col_count++;
1056 /* Delete the cell after we are done with it */
1057 unset($tables[$i][ROWS][$j][$k]);
1060 $tempSQLStr .= ")";
1062 if ($j != ($num_rows - 1)) {
1063 $tempSQLStr .= ",\n ";
1066 $col_count = 0;
1067 /* Delete the row after we are done with it */
1068 unset($tables[$i][ROWS][$j]);
1071 $tempSQLStr .= ";";
1074 * Each SQL statement is executed immediately
1075 * after it is formed so that we don't have
1076 * to store them in a (possibly large) buffer
1078 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1081 /* No longer needed */
1082 unset($tempSQLStr);
1085 * A work in progress
1088 /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
1090 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1091 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1092 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1094 $regs = array();
1096 $inTables = false;
1098 $additional_sql_len = count($additional_sql);
1099 for ($i = 0; $i < $additional_sql_len; ++$i) {
1100 preg_match($view_pattern, $additional_sql[$i], $regs);
1102 if (count($regs) == 0) {
1103 preg_match($table_pattern, $additional_sql[$i], $regs);
1106 if (count($regs)) {
1107 for ($n = 0; $n < $num_tables; ++$n) {
1108 if (!strcmp($regs[1], $tables[$n][TBL_NAME])) {
1109 $inTables = true;
1110 break;
1114 if (!$inTables) {
1115 $tables[] = array(TBL_NAME => $regs[1]);
1119 /* Reset the array */
1120 $regs = array();
1121 $inTables = false;
1124 $params = array('db' => (string)$db_name);
1125 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1126 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1128 $message = '<br /><br />';
1129 $message .= '<strong>' . $GLOBALS['strImportNoticePt1'] . '</strong><br />';
1130 $message .= '<ul><li>' . $GLOBALS['strImportNoticePt2'] . '</li>';
1131 $message .= '<li>' . $GLOBALS['strImportNoticePt3'] . '</li>';
1132 $message .= '<li>' . $GLOBALS['strImportNoticePt4'] . '</li>';
1133 $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>',
1134 $db_url,
1135 $GLOBALS['strGoToDatabase'] . ': ' . PMA_backquote($db_name),
1136 $db_name,
1137 $db_ops_url,
1138 $GLOBALS['strEdit'] . ' ' . PMA_backquote($db_name) . ' ' . $GLOBALS['strSettings']);
1140 $message .= '<ul>';
1142 unset($params);
1144 $num_tables = count($tables);
1145 for ($i = 0; $i < $num_tables; ++$i)
1147 $params = array('db' => (string)$db_name, 'table' => (string)$tables[$i][TBL_NAME]);
1148 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1149 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1150 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1152 unset($params);
1154 if (! PMA_isView($db_name, $tables[$i][TBL_NAME])) {
1155 $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>',
1156 $tbl_url,
1157 $GLOBALS['strGoToTable'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1158 $tables[$i][TBL_NAME],
1159 $tbl_struct_url,
1160 PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strStructureLC'],
1161 $tbl_ops_url,
1162 $GLOBALS['strEdit'] . ' ' . PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strSettings']);
1163 } else {
1164 $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>',
1165 $tbl_url,
1166 $GLOBALS['strGoToView'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1167 $tables[$i][TBL_NAME]);
1171 $message .= '</ul></ul>';
1173 global $import_notice;
1174 $import_notice = $message;
1176 unset($tables);